branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep># ResRNN
Implementation of a two path ResRNN architecture (Circle-RNN was invented).
### This repository is an implementation of our IPMI 2017 paper:
<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. (2017) Direct Estimation of Regional Wall Thicknesses via Residual Recurrent Neural Network. In: Information Processing in Medical Imaging. IPMI 2017. Lecture Notes in Computer Science, vol 10265. Springer.
https://link.springer.com/chapter/10.1007/978-3-319-59050-9_40 or https://arxiv.org/pdf/1705.09728.pdf
Two RNN modules are deployed for temporal dynamic modeling and spatial context modeling.


### ON implementation of Circle-RNN
To implement Circle-RNN,the following modifications to the caffe toolbox are required:
1. add 'circle_lstm_layer.hpp' to '/caffe/include/caffe/layers', add 'circle_lstm_layer.cpp' to '/caffe/src/caffe/layers';
2. In *caffe.proto*, add the following line to `message RecurrentParameter`:
`optional uint32 depth = 6 [default = 0];`
Note: LSTM units is employed in Circle-RNN.
#### Example of Circle-RNN
~~~
layer {
name: "lstm1"
type: "CircleLSTM"
bottom: "ip1_permute"
bottom: "clip_permute"
top: "wt_lstm1"
recurrent_param {
num_output: 6
weight_filler {
type: "uniform"
min: -0.05
max: 0.05
}
bias_filler {
type: "constant"
value: 0
}
depth: 0
}
}
~~~
The parameters *depth* indicates how many rounds the RNN network is unrolled.
* *depth=0* : the number of rounds equals the number of time steps of the sequences.
* *depth=1* : the RNN network is unrolled once. This is equivalent to the original RNN in caffe with LSTM unit;
<file_sep>LOGDIR=./log
CAFFE=/opt/caffe_new/build/tools/caffe
SOLVER=./lstm_cardiac_solver.prototxt
GLOG_log_dir=$LOGDIR $CAFFE train -solver $SOLVER
<file_sep>Ground truth of the RWT are stored in HDF5 format.
test file:
cmrmid145_test_5fold1.hdf5
cmrmid145_test_5fold2.hdf5
cmrmid145_test_5fold3.hdf5
cmrmid145_test_5fold4.hdf5
cmrmid145_test_5fold5.hdf5
train file:
cmrmid145_train_5fold1.hdf5
cmrmid145_train_5fold2.hdf5
cmrmid145_train_5fold3.hdf5
cmrmid145_train_5fold4.hdf5
cmrmid145_train_5fold5.hdf5
|
2b01bcca89b495be919f0b847a075744844a4bf5
|
[
"Markdown",
"Text",
"Shell"
] | 3
|
Markdown
|
xwolfs/ResRNN
|
5f2618d08c3843246c5adc24cbd92908655b25cf
|
f2c9c08b063f268143d4f4acf9520fae6b266d34
|
refs/heads/master
|
<repo_name>mgreenbe/jslatex-old<file_sep>/src/tokenize.test.js
let { tokenize } = require('./tokenize.js');
let { regexes } = require('./regexes.js');
let { matchText, parse } = require('./parse.js');
let str = `
Hi, mom!
\\section{Dude section}
Yo, dude!
Yo, man!
\\subsection{Blah blah}
Subsection content.
\\subsection{Bleh bleh}
Second subsection
content.
\\section{Dude, again}
Dude!
`;
let ts = tokenize(regexes, str);
console.log(JSON.stringify(ts));
let nodes = parse(ts);
console.log(`Nodes: ${JSON.stringify(nodes, null, 2)}`);
<file_sep>/src/parse.js
let divisions = ['subsection', 'section', 'part'];
let terminators = {};
for (let i = 0; i < divisions.length; i++) {
terminators[divisions[i]] = divisions.slice(i);
}
let shiftSpace = ts => {
while (ts[0] && ts[0].type === 'SPACE') {
ts.shift();
}
};
let shiftSpaceAndPar = ts => {
while (ts[0] && (ts[0].type === 'SPACE' || ts[0].type === 'PAR')) {
ts.shift();
}
};
let matchText = ts => {
let content = '';
while (ts[0] && (ts[0].type === 'CHAR' || ts[0].type === 'SPACE')) {
content += ts[0].type === 'CHAR' ? ts[0].value : ' ';
ts.shift();
}
return { type: 'text', content };
};
let matchGroup = ts => {
console.assert(
ts[0].type === 'LBRACE',
'matchGroup expected first token to be LBRACE.'
);
ts.shift();
shiftSpace(ts);
console.assert(
ts[0].type === 'CHAR' || ts[0].type === 'RBRACE',
'matchGroup expected group to be empty or to begin with CHAR.'
);
let node = ts[0].type === 'CHAR' ? matchText(ts) : { type: 'empty' };
ts.shift();
return node;
};
let matchSubsection = ts => {
console.assert(
ts[0].type === 'SUBSECTION',
'matchSubsection expected first token to be SUBSECTION.'
);
ts.shift();
shiftSpaceAndPar(ts);
let { content: title } = matchGroup(ts);
let children = [];
while (ts[0]) {
let node;
switch (ts[0].type) {
case 'SECTION':
case 'SUBSECTION':
return {
type: 'subsection',
title,
children
};
case 'CHAR':
node = matchText(ts);
children.push(node);
break;
case 'SPACE':
case 'PAR':
ts.shift();
break;
default:
throw new Error(
`Unexpected token type in matchSubsection: ${ts[0].type}`
);
}
}
return { type: 'subsection', title, children };
};
let matchSection = ts => {
console.assert(
ts[0].type === 'SECTION',
'matchSection expected first token to be SECTION.'
);
ts.shift();
shiftSpaceAndPar(ts);
let { content: title } = matchGroup(ts);
let children = [];
while (ts[0]) {
let node;
switch (ts[0].type) {
case 'SECTION':
return { type: 'section', title, children };
case 'SUBSECTION':
node = matchSubsection(ts);
children.push(node);
break;
case 'CHAR':
node = matchText(ts);
children.push(node);
break;
case 'SPACE':
case 'PAR':
ts.shift();
break;
default:
throw new Error(`Unexpected token type in matchSection: ${ts[0].type}`);
}
}
return { type: 'section', title, children };
};
let parse = ts => {
shiftSpaceAndPar(ts);
children = [];
while (ts[0]) {
let node;
console.log(ts[0]);
switch (ts[0].type) {
case 'SECTION':
node = matchSection(ts);
children.push(node);
break;
case 'SUBSECTION':
node = matchSection(ts);
children.push(node);
break;
case 'CHAR':
node = matchText(ts);
children.push(node);
break;
case 'SPACE':
case 'PAR':
shiftSpaceAndPar(ts);
}
}
return { type: 'document', children };
};
module.exports = { parse };
<file_sep>/src/parse_.js
let matchText = tokenQueue => {
let text = "";
do {
let token = tokenQueue.shift();
if (token.type == "CHAR") {
text += token.value;
} else if (token.type == "WHITESPACE") {
text += " ";
} else {
throw new Error("Parse error: Expected CHAR or WHITESPACE token.");
}
} while (
tokenQueue.length >= 1 &&
(tokenQueue[0].type == "CHAR" || tokenQueue[0].type == "WHITESPACE")
);
return text;
};
let matchGroup = tokenQueue => {
let token = tokenQueue.shift();
switch (token.type) {
case "WHITESPACE":
return matchGroup(tokenQueue);
case "CHAR":
return [token.value];
case "LBRACE":
return parse(tokenQueue, "RBRACE");
default:
throw new Error("Parse error: A group must begin with CHAR or LBRACE.");
}
};
let parse = (tokenQueue, terminator = "EOI" /* End Of Input */) => {
let nodes = [];
while (tokenQueue.length >= 1) {
let peek = tokenQueue[0];
console.log(`Next token: ${JSON.stringify(peek)}`);
switch (peek.type) {
case "COMMAND":
let token = tokenQueue.shift();
console.log(`Parsing command: ${JSON.stringify(token)}`);
while (tokenQueue[0].type == "WHITESPACE") {
tokenQueue.shift();
}
console.log(`Next token: ${JSON.stringify(tokenQueue[0])}`);
if (tokenQueue[0].type == "LBRACE") {
tokenQueue.shift();
let arg = parse(tokenQueue, "RBRACE");
console.log(`Arg: ${JSON.stringify(arg)}`);
nodes.push({ type: "COMMAND", id: token.id, arg });
} else {
throw new Error("Parse error: Missing argument.");
}
break;
case "CHAR":
case "WHITESPACE":
let text = matchText(tokenQueue);
let node = { type: "TEXT", text };
nodes.push(node);
break;
case "LBRACE":
tokenQueue.shift();
let group = parse(tokenQueue, "RBRACE");
nodes.push(group);
break;
case "RBRACE":
if (terminator == "RBRACE") {
tokenQueue.shift();
return nodes;
} else {
throw new Error("Parse error: Unmatched RBRACE.");
}
return nodes;
default:
throw new Error(`Parse error: Unrecognized token type ${peek.type}.`);
}
}
if (terminator !== "EOI" /* End Of Input */) {
throw new Error("Parse error: Unexpected end of input.");
}
return nodes;
};
module.exports = { matchText, parse };
<file_sep>/src/commands.js
let commands = {
part: {
requiredArgs: ['title'],
nOptionalArgs: ['toctitle'],
defaultValues: requiredArgs => requiredArgs
},
section: {
requiredArgs: ['title'],
nOptionalArgs: ['toctitle'],
defaultValues: requiredArgs => requiredArgs
},
subsection: {
requiredArgs: ['title'],
nOptionalArgs: ['toctitle'],
defaultValues: requiredArgs => requiredArgs
},
textbf: {
requiredArgs: ['text'],
optionalArgs: []
},
textit: {
nRequiredArgs: ['text'],
nOptionalArgs: []
}
};
let sectioning = ['part', 'section', 'subsection'];
|
75ab0de7f79f90b2bb1a49d026d13706a6453b04
|
[
"JavaScript"
] | 4
|
JavaScript
|
mgreenbe/jslatex-old
|
222360a90c9c6eb9ede9f3149e1bf2512cfb8d5e
|
1adea65ae79a16ed78535b3ee225be71050d98d4
|
refs/heads/main
|
<repo_name>kodzzzima/pulttaxi-test<file_sep>/app/src/main/java/com/example/testapp/util/Utils.kt
package com.example.testapp.util
import android.graphics.Color
import android.view.View
import androidx.fragment.app.Fragment
import com.google.android.material.snackbar.Snackbar
fun Fragment.handleApiError(
failure: Resource.Failure,
) {
when {
failure.isNetworkError -> requireView().snackBar(
"Проверьте Интернет соединение"
)
failure.errorCode == 400 -> {
requireView().snackBar("Вы ввели некорректный номер")
}
failure.errorCode == 401 -> {
requireView().snackBar("Ошибка авторизации")
}
else -> {
val error = failure.errorBody?.string().toString()
requireView().snackBar(error)
}
}
}
fun View.snackBar(message: String, action: (() -> Unit)? = null) {
val snackBar = Snackbar.make(this, message, Snackbar.LENGTH_LONG)
snackBar.setBackgroundTint(Color.WHITE)
snackBar.setTextColor(Color.parseColor("#047BF8"))
action?.let {
snackBar.setAction("Retry") {
it()
}
}
snackBar.show()
}
fun String.removeElements(elements: List<String>): String {
var newString = this
elements.forEach {
newString = newString.replace(it, "")
}
return newString
}
<file_sep>/app/src/main/java/com/example/testapp/ui/inputCode/InputCodeFragmentViewModel.kt
package com.example.testapp.ui.inputCode
import android.os.CountDownTimer
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.testapp.data.model.TokenResponse
import com.example.testapp.data.repository.AppRepository
import com.example.testapp.util.Resource
import kotlinx.coroutines.launch
class InputCodeFragmentViewModel(
private val repository: AppRepository,
) : ViewModel() {
private val _tokenResponse: MutableLiveData<Resource<TokenResponse>> = MutableLiveData()
val tokenResponse: LiveData<Resource<TokenResponse>>
get() = _tokenResponse
private val _timerFlag = MutableLiveData(false)
val timerFlag: LiveData<Boolean>
get() = _timerFlag
var timer: CountDownTimer? = null
init {
startTimer()
}
fun enterCode(phoneNumber: String, smsCode: String) {
viewModelScope.launch {
_tokenResponse.value = Resource.Loading
_tokenResponse.value = repository.getToken(phoneNumber, smsCode)
}
}
fun repeatSmsCode() {
viewModelScope.launch {
loadUserPhone()?.let { repository.getSmsCode(it) }
}
}
suspend fun saveUserToken(token: String) {
repository.saveUserToken(token)
}
suspend fun loadUserPhone(): String? {
return repository.loadUserPhone()
}
fun startTimer() {
_timerFlag.value = false
timer = object : CountDownTimer(15000, 1000) {
override fun onTick(p0: Long) {}
override fun onFinish() {
_timerFlag.value = true
}
}.start()
}
}<file_sep>/app/src/main/java/com/example/testapp/ui/inputNumber/InputNumberFragmentViewModel.kt
package com.example.testapp.ui.inputNumber
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.testapp.data.model.SmsCodeResponse
import com.example.testapp.data.repository.AppRepository
import com.example.testapp.util.Resource
import kotlinx.coroutines.launch
class InputNumberFragmentViewModel(
private val repository: AppRepository,
) : ViewModel() {
private val _smsCodeResponse: MutableLiveData<Resource<SmsCodeResponse>> = MutableLiveData()
val smsCodeResponse: LiveData<Resource<SmsCodeResponse>>
get() = _smsCodeResponse
fun enterNumber(phoneNumber: String) {
viewModelScope.launch {
_smsCodeResponse.value = Resource.Loading
_smsCodeResponse.value = repository.getSmsCode(phoneNumber)
}
}
suspend fun saveUserPhone(phoneNumber: String) {
repository.saveUserPhone(phoneNumber)
}
}<file_sep>/app/src/main/java/com/example/testapp/ui/inputCode/InputCodeFragment.kt
package com.example.testapp.ui.inputCode
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.testapp.R
import com.example.testapp.data.api.RetrofitBuilder
import com.example.testapp.data.repository.AppRepositoryImpl
import com.example.testapp.databinding.FragmentInputCodeBinding
import com.example.testapp.ui.ViewModelFactory
import com.example.testapp.util.Resource
import com.example.testapp.util.handleApiError
import com.example.testapp.util.snackBar
import kotlinx.coroutines.launch
class InputCodeFragment : Fragment(R.layout.fragment_input_code) {
private lateinit var binding: FragmentInputCodeBinding
private val viewModel by viewModels<InputCodeFragmentViewModel> {
ViewModelFactory(appRepository = AppRepositoryImpl(RetrofitBuilder.apiService))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentInputCodeBinding.bind(view)
binding.progressbar.isVisible = false
setupObservers()
binding.inputCode1.addTextChangedListener {
if (binding.inputCode1.text.length == 1) {
binding.inputCode2.requestFocus()
}
}
binding.inputCode2.addTextChangedListener {
if (binding.inputCode2.text.length == 1) {
binding.inputCode3.requestFocus()
} else if (binding.inputCode2.text.isEmpty()) {
binding.inputCode1.requestFocus()
}
}
binding.inputCode3.addTextChangedListener {
if (binding.inputCode3.text.length == 1) {
binding.inputCode4.requestFocus()
} else if (binding.inputCode3.text.isEmpty()) {
binding.inputCode2.requestFocus()
}
}
binding.inputCode4.addTextChangedListener {
if (binding.inputCode4.text.length == 1) {
binding.inputCode4.clearFocus()
} else if (binding.inputCode4.text.isEmpty()) {
binding.inputCode3.requestFocus()
}
}
binding.buttonDone.setOnClickListener {
if (binding.inputCode1.text.isNotEmpty()
&& binding.inputCode2.text.isNotEmpty()
&& binding.inputCode3.text.isNotEmpty()
&& binding.inputCode4.text.isNotEmpty()
) {
enterCode()
}
}
binding.buttonRepeatSmsCode.setOnClickListener {
sendSmsCode()
}
}
private fun setupObservers() {
viewModel.tokenResponse.observe(viewLifecycleOwner, {
binding.progressbar.isVisible = it is Resource.Loading
when (it) {
is Resource.Success -> {
if (it.value.status == "error") {
requireView().snackBar("Неверный код")
} else {
lifecycleScope.launch {
viewModel.saveUserToken(
it.value.token!!,
)
findNavController().navigate(R.id.action_inputCodeFragment_to_userInfoDialogFragment)
}
}
}
is Resource.Failure -> handleApiError(it)
}
})
viewModel.timerFlag.observe(viewLifecycleOwner, {
if (it == true) {
binding.buttonRepeatSmsCode.visibility = View.VISIBLE
binding.repeatSmsCode.visibility = View.GONE
} else {
binding.buttonRepeatSmsCode.visibility = View.GONE
binding.repeatSmsCode.visibility = View.VISIBLE
}
})
}
private fun sendSmsCode() {
viewModel.repeatSmsCode()
viewModel.startTimer()
}
private fun enterCode() {
val smsCode = binding.inputCode1.text.toString() +
binding.inputCode2.text.toString() +
binding.inputCode3.text.toString() +
binding.inputCode4.text.toString()
lifecycleScope.launch {
val phoneNum = viewModel.loadUserPhone()!!
viewModel.enterCode(phoneNum, smsCode)
}
}
override fun onDestroyView() {
super.onDestroyView()
if (viewModel.timer != null) viewModel.timer!!.cancel()
}
}<file_sep>/app/src/main/java/com/example/testapp/ui/inputNumber/InputNumberFragment.kt
package com.example.testapp.ui.inputNumber
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.testapp.R
import com.example.testapp.data.api.RetrofitBuilder
import com.example.testapp.data.repository.AppRepositoryImpl
import com.example.testapp.databinding.FragmentInputNumberBinding
import com.example.testapp.ui.ViewModelFactory
import com.example.testapp.util.PhoneNumberFormatting
import com.example.testapp.util.Resource
import com.example.testapp.util.handleApiError
import kotlinx.coroutines.launch
class InputNumberFragment : Fragment(R.layout.fragment_input_number) {
private lateinit var binding: FragmentInputNumberBinding
private val viewModel by viewModels<InputNumberFragmentViewModel> {
ViewModelFactory(appRepository = AppRepositoryImpl(RetrofitBuilder.apiService))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentInputNumberBinding.bind(view)
binding.progressbar.isVisible = false
binding.buttonContinue.isEnabled = false
setupObserver()
binding.editText.doOnTextChanged { _, _, _, _ ->
PhoneNumberFormatting
when {
PhoneNumberFormatting.countNumber ?: 0 > 10 -> {
binding.buttonContinue.isEnabled = false
binding.textInputLayout.error = " Ошибка"
}
PhoneNumberFormatting.countNumber ?: 0 < 10 -> {
binding.buttonContinue.isEnabled = false
binding.textInputLayout.error = null
}
PhoneNumberFormatting.countNumber ?: 0 == 10 ->
binding.buttonContinue.isEnabled = true
}
}
binding.editText.addTextChangedListener(PhoneNumberFormatting)
binding.buttonContinue.setOnClickListener {
enterNumber()
binding.editText.clearFocus()
}
}
private fun setupObserver() {
viewModel.smsCodeResponse.observe(viewLifecycleOwner, {
binding.progressbar.isVisible = it is Resource.Loading
when (it) {
is Resource.Success -> {
lifecycleScope.launch {
viewModel.saveUserPhone("7" +
PhoneNumberFormatting.unFormattedNumber.toString())
findNavController()
.navigate(R.id.action_inputNumberFragment_to_inputCodeFragment)
}
}
is Resource.Failure -> handleApiError(it)
}
})
}
private fun enterNumber() {
val phoneNumber = "7" + PhoneNumberFormatting.unFormattedNumber.toString()
viewModel.enterNumber(phoneNumber)
}
}<file_sep>/app/src/main/java/com/example/testapp/ui/userInfo/UserInfoDialogFragmentViewModel.kt
package com.example.testapp.ui.userInfo
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.testapp.data.model.UserResponse
import com.example.testapp.data.repository.AppRepository
import com.example.testapp.util.Resource
import kotlinx.coroutines.launch
class UserInfoDialogFragmentViewModel(
private val repository: AppRepository,
) : ViewModel() {
private val _userResponse: MutableLiveData<Resource<UserResponse>> = MutableLiveData()
val userResponse: LiveData<Resource<UserResponse>>
get() = _userResponse
init {
getUserFromToken()
}
private fun getUserFromToken() {
viewModelScope.launch {
val token = loadUserToken()
if (token != null) {
getUserInfo(token)
}
}
}
private fun getUserInfo(token: String) {
viewModelScope.launch {
_userResponse.value = Resource.Loading
_userResponse.value = repository.getUser(token)
}
}
private suspend fun loadUserToken(): String? {
return repository.loadUserToken()
}
}<file_sep>/app/src/main/java/com/example/testapp/data/repository/AppRepository.kt
package com.example.testapp.data.repository
import com.example.testapp.data.model.SmsCodeResponse
import com.example.testapp.data.model.TokenResponse
import com.example.testapp.data.model.UserResponse
import com.example.testapp.util.Resource
interface AppRepository {
suspend fun getSmsCode(phoneNumber: String): Resource<SmsCodeResponse>
suspend fun getToken(phone_number: String, password: String): Resource<TokenResponse>
suspend fun getUser(token: String): Resource<UserResponse>
suspend fun saveUserPhone(phone_number: String) {}
suspend fun loadUserPhone(): String?
suspend fun saveUserToken(token: String)
suspend fun loadUserToken(): String?
}<file_sep>/app/src/main/java/com/example/testapp/data/model/TokenResponse.kt
package com.example.testapp.data.model
data class TokenResponse(
val token: String?,
val status: String?,
)<file_sep>/app/src/main/java/com/example/testapp/data/api/ApiService.kt
package com.example.testapp.data.api
import com.example.testapp.data.model.UserResponse
import com.example.testapp.data.model.SmsCodeResponse
import com.example.testapp.data.model.TokenResponse
import retrofit2.http.*
interface ApiService {
@FormUrlEncoded
@POST("api/authenticateClients")
suspend fun getToken(
@Field("phone_number") phone_number: String,
@Field("password") password: String,
): TokenResponse
@GET("api/requestSMSCodeClient")
suspend fun getSmsCode(
@Query("phone_number") phone_number: String,
): SmsCodeResponse
@GET("api/client/getInfo")
suspend fun getUser(
@Query("token") token: String,
): UserResponse
}<file_sep>/app/src/main/java/com/example/testapp/ui/ViewModelFactory.kt
package com.example.testapp.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.testapp.data.repository.AppRepository
import com.example.testapp.ui.inputCode.InputCodeFragmentViewModel
import com.example.testapp.ui.inputNumber.InputNumberFragmentViewModel
import com.example.testapp.ui.userInfo.UserInfoDialogFragmentViewModel
class ViewModelFactory(private val appRepository: AppRepository) :
ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(InputNumberFragmentViewModel::class.java)) {
return InputNumberFragmentViewModel(appRepository) as T
}
if (modelClass.isAssignableFrom(InputCodeFragmentViewModel::class.java)) {
return InputCodeFragmentViewModel(appRepository) as T
}
if (modelClass.isAssignableFrom(UserInfoDialogFragmentViewModel::class.java)) {
return UserInfoDialogFragmentViewModel(appRepository) as T
}
throw IllegalArgumentException("Unknown class name")
}
}<file_sep>/app/src/main/java/com/example/testapp/ui/userInfo/UserInfoDialogFragment.kt
package com.example.testapp.ui.userInfo
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.example.testapp.R
import com.example.testapp.data.api.RetrofitBuilder
import com.example.testapp.data.repository.AppRepositoryImpl
import com.example.testapp.databinding.DialogUserInfoBinding
import com.example.testapp.ui.ViewModelFactory
import com.example.testapp.util.Resource
import com.example.testapp.util.handleApiError
import com.example.testapp.util.snackBar
class UserInfoDialogFragment : DialogFragment() {
private var _binding: DialogUserInfoBinding? = null
private val binding
get() = _binding!!
private val viewModel by viewModels<UserInfoDialogFragmentViewModel> {
ViewModelFactory(appRepository = AppRepositoryImpl(RetrofitBuilder.apiService))
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = DialogUserInfoBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.progressbar.isVisible = true
binding.layoutInfo.visibility = View.GONE
setupObserver()
binding.buttonOk.setOnClickListener {
findNavController().navigate(R.id.action_userInfoDialogFragment_to_inputCodeFragment)
}
}
private fun setupObserver() {
viewModel.userResponse.observe(viewLifecycleOwner, { response ->
binding.progressbar.isVisible = response is Resource.Loading
binding.layoutInfo.isVisible = response !is Resource.Loading
when (response) {
is Resource.Success -> {
if (response.value.status == "error") {
requireView().snackBar("Неверный код")
} else {
response.value.let { user ->
binding.nameValue.text = user.name ?: "-"
binding.sexValue.text = user.sex ?: "-"
binding.phoneNumberValue.text = user.phone_number
binding.emailValue.text = user.email ?: "-"
binding.birthdayValue.text = user.birth_day ?: "-"
binding.cityValue.text = user.city ?: "-"
binding.ratingValue.text = user.rating ?: "-"
}
}
}
is Resource.Failure -> handleApiError(response)
}
})
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}<file_sep>/app/src/main/java/com/example/testapp/data/model/UserResponse.kt
package com.example.testapp.data.model
data class UserResponse(
val active_order: String?,
val birth_day: String?,
val city: String?,
val email: String?,
val id: Int,
val name: String?,
val need_registration: Boolean,
val organization_id: Int?,
val phone_number: String?,
val rating: String?,
val sex: String?,
val status: String,
)
<file_sep>/app/src/main/java/com/example/testapp/data/repository/AppRepositoryImpl.kt
package com.example.testapp.data.repository
import com.example.testapp.data.api.ApiService
import com.example.testapp.data.api.SafeApiCall
import com.example.testapp.data.model.UserResponse
import com.example.testapp.util.Resource
import com.example.testapp.util.UserPreferences
class AppRepositoryImpl(
private val apiService: ApiService,
) : SafeApiCall, AppRepository {
override suspend fun getSmsCode(phoneNumber: String) =
safeApiCall { apiService.getSmsCode(phoneNumber) }
override suspend fun getToken(phone_number: String, password: String) =
safeApiCall { apiService.getToken(phone_number, password) }
override suspend fun getUser(token: String): Resource<UserResponse> =
safeApiCall { apiService.getUser(token) }
override suspend fun saveUserPhone(phone_number: String) {
UserPreferences.setUserPhone(phone_number)
}
override suspend fun loadUserPhone(): String? {
return UserPreferences.getUserPhone()
}
override suspend fun saveUserToken(token: String) {
UserPreferences.setUserToken(token)
}
override suspend fun loadUserToken(): String? {
return UserPreferences.getUserToken()
}
}<file_sep>/app/src/main/java/com/example/testapp/data/model/SmsCodeResponse.kt
package com.example.testapp.data.model
data class SmsCodeResponse(
val status: String?,
)<file_sep>/app/src/main/java/com/example/testapp/util/UserPreferences.kt
package com.example.testapp.util
import android.content.Context
import android.content.SharedPreferences
object UserPreferences {
private const val NAME_PREF = "preference"
private const val PHONE_NUMBER = "phoneNumber"
private const val USER_TOKEN = "userToken"
private lateinit var preferences: SharedPreferences
fun getPreference(context: Context): SharedPreferences {
preferences = context.getSharedPreferences(NAME_PREF, Context.MODE_PRIVATE)
return preferences
}
fun getUserPhone(): String? {
return preferences.getString(PHONE_NUMBER, "")
}
fun setUserPhone(phoneNumber: String) {
preferences.edit()
.putString(PHONE_NUMBER, phoneNumber)
.apply()
}
fun getUserToken(): String? {
return preferences.getString(USER_TOKEN, "")
}
fun setUserToken(token: String) {
preferences.edit()
.putString(USER_TOKEN, token)
.apply()
}
}<file_sep>/README.md
Задача: сделать небольшое мобильное приложение, которое будет состоять из двух
экранов и выполнять запросы по API, делать авторизацию клиента и выводить
информацию о нём в диалоговом окне, после ввода кода из СМС. Номер телефон должен
содержать маску и быть только российским номером, код страны +7 пользователю
вводить не нужно (т.к. есть уже на экране). Приложение должно также обрабатывать
ошибки при неверном коде.
## Скриншоты
<table>
<thead>
<tr>
<th align="center">Номер телефона</th>
<th align="center">Код из смс</th>
<th align="center">Информация о пользователе</th>
</tr>
</thead>
<tbody>
<tr>
<td> <img src="https://github.com/kodzzzima/pulttaxi-test/blob/main/screenshots/screen1.jpg" ></td>
<td> <img src="https://github.com/kodzzzima/pulttaxi-test/blob/main/screenshots/screen3.jpg"" ></td>
<td> <img src="https://github.com/kodzzzima/pulttaxi-test/blob/main/screenshots/screen4.jpg" ></td>
</tr>
<tr>
|
2553ba52d16c9bcb3b68ab80f0c2d8ee78f078c4
|
[
"Markdown",
"Kotlin"
] | 16
|
Kotlin
|
kodzzzima/pulttaxi-test
|
a0d858bb2aa855d775504c9709ade9ba124faf94
|
21b9cba2be3895a4a68026444cd51272977b5bce
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Valve.VR;
using Valve.VR.InteractionSystem;
public class GameBook : MonoBehaviour
{
[Header("Action")]
// a reference to the action
public SteamVR_Action_Boolean menu;
// a reference to the hand
public SteamVR_Input_Sources left;
public SteamVR_Input_Sources right;
[Header("Teleportation")]
public GameObject VR_Camera;
[Range(0f, 1f)]
public float yOffset = 0.1f;
[Range(0f, 5f)]
public float distance = 0.5f;
[Header("Text")]
public Text body;
void Start()
{
menu.AddOnStateDownListener(MenuUp, left);
menu.AddOnStateUpListener(MenuDown, left);
menu.AddOnStateDownListener(MenuUp, right);
menu.AddOnStateUpListener(MenuDown, right);
Storage.gameBook = this;
}
public void MenuUp(SteamVR_Action_Boolean fromAction, SteamVR_Input_Sources fromSource)
{
Debug.Log("Called menu!");
Vector3 pos = VR_Camera.transform.position + VR_Camera.transform.forward * distance;
pos.y -= yOffset;
transform.position = pos;
GetComponent<Rigidbody>().useGravity = false;
GetComponent<Rigidbody>().velocity = Vector3.zero;
GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
Vector3 targetDirection = VR_Camera.transform.position - transform.position;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, 360f, 360f);
Debug.DrawRay(transform.position, newDirection, Color.red);
transform.rotation = Quaternion.LookRotation(newDirection);
}
public void MenuDown(SteamVR_Action_Boolean fromAction, SteamVR_Input_Sources fromSource)
{
}
public void Next()
{
Debug.Log("[GameBook] Next");
}
public void UpdateMission(Mission mission)
{
if (mission.maxProgress != 1) body.text = mission.text + " (прогресс: " + mission.progress + ")";
else body.text = mission.text;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
public static class Storage
{
public static GameBook gameBook;
public static List<Mission> missions { get; set; }
private static int missionId;
public static int MissionId
{
get { return missionId; }
set
{
missionId = value;
gameBook.UpdateMission(missions[value]);
}
}
public static int addMission(Mission mission)
{
try { missions.Add(mission); }
catch (NullReferenceException) {
missions = new List<Mission>();
missions.Add(mission);
};
return missions.Count - 1;
}
private static int evidenceCount;
public static int EvidenceCount
{
get {
evidenceCount++;
return evidenceCount;
}
}
}
public class Mission
{
public string text;
public int maxProgress = 1;
public int progress = 0;
public MissionObject missionObject;
public Mission(MissionObject missionObject, string text)
{
this.text = text;
this.missionObject = missionObject;
}
public Mission(MissionObject missionObject, string text, int maxProgress)
{
this.text = text;
this.maxProgress = maxProgress;
this.missionObject = missionObject;
}
public void AddProgress()
{
progress++;
Storage.gameBook.UpdateMission(this);
if (progress >= maxProgress)
{
missionObject.EndMission();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR.InteractionSystem;
using System;
using UnityEngine.UI;
public class EvidenceFound : MonoBehaviour
{
public GameObject point;
public GameObject notePrefab;
[Space]
public string evidenceExplontation;
public Overlay overlay;
[Space]
public MissionObject missionObject;
private bool isDetected;
private void OnTriggerEnter(Collider other)
{
try
{
if (!GetComponent<MeshRenderer>().enabled) return;
if (!GetComponentInChildren<MeshRenderer>().enabled) return;
} catch (MissingComponentException)
{
}
//Debug.Log(other);
GameObject hand;
try
{
hand = other.GetComponentInParent<HandCollider>().hand.gameObject;
} catch (NullReferenceException)
{
try
{
hand = other.GetComponentInParent<Interactable>().attachedToHand.gameObject;
} catch (NullReferenceException)
{
return;
}
}
if(hand != null && !isDetected)
{
Debug.Log("[Evidence] " + hand.GetComponent<Hand>() + " interact with " + gameObject);
GameObject note = Instantiate(notePrefab, point.transform.position, point.transform.rotation);
note.GetComponent<NoteLink>().text.text = Storage.EvidenceCount.ToString();
overlay.SetText(evidenceExplontation, "Улика найденна:");
missionObject.mission.AddProgress();
isDetected = true;
}
}
public IEnumerator HideOverlay(GameObject overlay)
{
yield return new WaitForSeconds(5f);
overlay.SetActive(false);
yield return true;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MissionObject : MonoBehaviour
{
public Mission mission;
public string missionText;
public bool activateNow = false;
public int missionId { get; private set; }
[Space]
public MissionObject nextMission;
[Space]
public bool isProgress;
public int maxProgress;
[Space]
public Overlay overlay;
// Start is called before the first frame update
void Start()
{
if (isProgress) mission = new Mission(this, missionText, maxProgress);
else mission = new Mission(this, missionText);
missionId = Storage.addMission(mission);
Debug.Log("[MissionManager] Added mission '" + mission.text + "' (" + missionId + ")");
if (activateNow)
{
Debug.Log("[MissionManager] Activated mission '" + mission.text + "' (" + missionId + ")");
overlay.SetText(mission.text, "Текущая миссия:");
Storage.MissionId = missionId;
}
}
public void EndMission()
{
if (!enabled) return;
Debug.Log("[MissionManager] End mission '" + mission.text + "' (" + missionId + ")");
overlay.SetText(mission.text, "Миссия завершенна:");
enabled = false;
if (nextMission != null)
{
Storage.MissionId = Storage.missions.IndexOf(nextMission.mission);
}
else
{
Storage.MissionId = Storage.addMission(new Mission(this, "Конец!"));
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR.InteractionSystem;
using Valve.VR;
using System.Linq;
using UnityEngine.Events;
using System;
public class Slot : MonoBehaviour
{
GameObject objectToStorage;
UnityAction action;
private Color startColor;
public Color storageColor;
// Start is called before the first frame update
void Start()
{
startColor = gameObject.GetComponent<MeshRenderer>().material.color;
}
// Update is called once per frame
void Update()
{
}
void OnHandHoverBegin(Hand hand)
{
//Debug.Log("Interactive");
Interactable[] myItems = FindObjectsOfType(typeof(Interactable)) as Interactable[];
myItems = myItems.Where(val => val != gameObject.GetComponent<Interactable>()).ToArray();
SphereCollider sphereCollider = GetComponent<SphereCollider>();
float radius = Mathf.Max(sphereCollider.transform.lossyScale.x, sphereCollider.transform.lossyScale.x, sphereCollider.transform.lossyScale.x) * sphereCollider.radius - 0.00f;
try { objectToStorage = Utility.GetNearestInteractable<Interactable>(hand.gameObject.transform.position, myItems, radius).gameObject; }
catch (NullReferenceException) { return; }
try { objectToStorage.GetComponent<Rigidbody>(); }
catch (MissingComponentException) { return; }
if (objectToStorage == gameObject) return;
Debug.Log("Storage object " + objectToStorage);
objectToStorage.GetComponent<Rigidbody>().isKinematic = true;
objectToStorage.transform.SetParent(transform);
objectToStorage.transform.localPosition = new Vector3(0, 0, 0);
sphereCollider.enabled = false;
gameObject.GetComponent<MeshRenderer>().material.color = storageColor;
action = delegate { onUse(objectToStorage, action, gameObject); };
objectToStorage.GetComponent<Throwable>().onPickUp.AddListener(action);
}
void OnHandHoverEnd(Hand hand)
{
}
void onUse(GameObject gameObject, UnityAction action, GameObject slot)
{
gameObject.GetComponent<Rigidbody>().isKinematic = false;
gameObject.transform.SetParent(null);
gameObject.GetComponent<Throwable>().onPickUp.RemoveListener(action);
slot.GetComponent<SphereCollider>().enabled = true;
slot.GetComponent<MeshRenderer>().material.color = startColor;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR.InteractionSystem;
public static class Utility
{
public static T GetNearestInteractable<T>(Vector3 origin, Interactable[] collection, float maxDistance)
where T : Interactable
{
T nearest = null;
float minDistance = float.MaxValue;
float distance = 0.0f;
// For each object we are touching
foreach (T entity in collection)
{
if (!entity)
continue;
if (entity.tag == "Dont Inventory")
continue;
/*
if (!entity.GetAvailability())
continue;
*/
distance = (entity.gameObject.transform.position - origin).sqrMagnitude;
if (distance > maxDistance) continue;
if (distance < minDistance)
{
minDistance = distance;
nearest = entity;
}
}
return nearest;
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Slots : MonoBehaviour
{
public GameObject VrCamera;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = new Vector3(VrCamera.transform.position.x, 0f, VrCamera.transform.position.z);
var angles = transform.rotation.eulerAngles;
angles.y = VrCamera.transform.eulerAngles.y;
transform.rotation = Quaternion.Euler(angles);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class Overlay : MonoBehaviour
{
public Text body;
public Text header;
Queue<string> bodyW;
Queue<string> headerW;
public void SetText(string bodyS, string headerS)
{
try
{
bodyW.Enqueue(bodyS);
headerW.Enqueue(headerS);
} catch (NullReferenceException)
{
bodyW = new Queue<string>();
headerW = new Queue<string>();
bodyW.Enqueue(bodyS);
headerW.Enqueue(headerS);
}
if (!gameObject.activeSelf)
{
Display();
}
}
public IEnumerator HideOverlay(GameObject overlay)
{
yield return new WaitForSeconds(5f);
overlay.SetActive(false);
Display();
yield return true;
}
private void Display()
{
body.text = bodyW.Dequeue();
header.text = headerW.Dequeue();
gameObject.SetActive(true);
StartCoroutine("HideOverlay", gameObject);
}
}
<file_sep>using System;
using System.Collections;
using UnityEngine;
using Valve.VR;
using Valve.VR.InteractionSystem;
public class SimpleShoot : MonoBehaviour
{
public SteamVR_Action_Boolean fireAction;
public SteamVR_Action_Boolean removeTheMagazineAction;
public GameObject bulletPrefab;
public GameObject casingPrefab;
public GameObject muzzleFlashPrefab;
public Transform barrelLocation;
public Transform casingExitLocation;
[SerializeField]
private GameObject magazineReceiver;
private Transform magazine;
private Interactable interactable;
public float shotPower = 3333f;
public float bulletLifeTime = 10f;
private short bulletsInTheMagazine;
void Start()
{
if (barrelLocation == null)
barrelLocation = transform;
interactable = GetComponent<Interactable>();
foreach (Transform child in transform)
{
if (child.tag == "Magazine")
{
magazine = child;
bulletsInTheMagazine = magazine.GetComponent<MagazinStorage>().bulletAmmout;
break;
}
}
}
void Update()
{
if (interactable.attachedToHand != null)
{
SteamVR_Input_Sources source = interactable.attachedToHand.handType;
if (fireAction[source].stateDown) Shoot();
if (removeTheMagazineAction[source].stateDown) RemoveTheMagazine();
}
}
void Shoot()
{
if (bulletsInTheMagazine != 0)
{
GameObject bullet;
GameObject tempFlash;
bulletsInTheMagazine--;
bullet = Instantiate(bulletPrefab, barrelLocation.position, barrelLocation.rotation);
bullet.GetComponent<Rigidbody>().AddForce(barrelLocation.forward * shotPower);
tempFlash = Instantiate(muzzleFlashPrefab, barrelLocation.position, barrelLocation.rotation);
Destroy(bullet, bulletLifeTime);
Destroy(tempFlash, 0.5f);
}
}
/// <summary>
/// Без малейшего понятия чё это
/// </summary>
void CasingRelease()
{
GameObject casing;
casing = Instantiate(casingPrefab, casingExitLocation.position, casingExitLocation.rotation) as GameObject;
casing.GetComponent<Rigidbody>().AddExplosionForce(550f, (casingExitLocation.position - casingExitLocation.right * 0.3f - casingExitLocation.up * 0.6f), 1f);
casing.GetComponent<Rigidbody>().AddTorque(new Vector3(0, UnityEngine.Random.Range(100f, 500f), UnityEngine.Random.Range(10f, 1000f)), ForceMode.Impulse);
}
void RemoveTheMagazine()
{
//GameObject.FindGameObjectsWithTag?
Rigidbody rigidbody = magazine.GetComponent<Rigidbody>();
rigidbody.isKinematic = false;
rigidbody.useGravity = true;
if (bulletsInTheMagazine == 0 && magazine.GetChild(0) == null) Destroy(magazine.GetChild(0).gameObject);
magazine.GetComponent<MagazinStorage>().bulletAmmout = bulletsInTheMagazine;
bulletsInTheMagazine = 0;
magazine.GetComponent<Interactable>().enabled = true;
StartCoroutine(TurnOnCollisionMagazine());
}
IEnumerator TurnOnCollisionMagazine()
{
magazine.transform.Translate(0, -0.15f, 0);
yield return new WaitForSeconds(0.02f); // xз зачем:/
magazine.GetComponent<MeshCollider>().isTrigger = false;
magazine.transform.parent = null;
magazine = null;
}
void OnTriggerEnter(Collider other)
{
Debug.Log(other);
if (other.tag == "Magazine" && magazine == null) InsertTheMagazine(other);
}
void InsertTheMagazine(Collider magazineCollider)
{
magazine = magazineCollider.transform;
MeshCollider mcm = magazine.GetComponent<MeshCollider>();
Rigidbody rigidbody = magazine.GetComponent<Rigidbody>();
magazine.GetComponent<Interactable>().enabled = false;
if (mcm.isTrigger == true) return; // Если он уже успел выпасть, то код продолжается
mcm.isTrigger = true;
rigidbody.isKinematic = true;
rigidbody.useGravity = false;
magazine.transform.parent = this.gameObject.transform;
magazine.transform.localPosition = new Vector3(-0.0005000038f, 0.055f, 0.033f);
magazine.transform.localRotation = Quaternion.Euler(0, 90, 11);
bulletsInTheMagazine = magazine.GetComponent<MagazinStorage>().bulletAmmout;
}
}<file_sep>using System;
public static class CoolDataBase
{
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MagazinStorage : MonoBehaviour
{
public short bulletAmmout = 7;
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR;
using Valve.VR.InteractionSystem;
using System;
public class KeyCheck : MonoBehaviour
{
public GameObject key;
public GameObject door;
public MissionObject missionObject;
private bool isDoorOpen = false;
void Update()
{
if(isDoorOpen && GetComponent<AudioSource>().isPlaying == false)
{
door.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
GetComponent<KeyCheck>().enabled = false;
if (missionObject != null) missionObject.EndMission();
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject == key && isDoorOpen == false)
{
isDoorOpen = true;
GetComponent<AudioSource>().Play();
}
}
}
<file_sep>using UnityEngine;
public class UVArea : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
if (other.tag == "UV") other.gameObject.GetComponentInChildren<MeshRenderer>().enabled = true; // Показываем улику
}
void OnTriggerExit(Collider other)
{
if (other.tag == "UV") other.gameObject.GetComponentInChildren<MeshRenderer>().enabled = false; // Скрываем
}
}
|
4d29ceb8b81253ca2cdc3394a4a9c57d76ef386d
|
[
"C#"
] | 13
|
C#
|
Senteris/detectiveVR
|
06113de3b3debdf54aaeab5badae5fa56f6b9493
|
13702b493df60edf5b862d4031e3c118ce8480a5
|
refs/heads/main
|
<repo_name>sonOfArent/Simple-Zombie-AI<file_sep>/SimpleZombieAI.py
import random
########################################################## Classes #################################################################
class Zombie():
def __init__(self):
self.character = "Z"
self.location = None
self.fromBrain = None
def __repr__(self):
return "Z"
def __str__(self):
return "zombie"
class Brain():
def __init__(self):
self.location = None
self.character = "@"
self.fromBrain = 0
def __repr__(self):
return "@"
def __str__(self):
return "brain"
class Cell():
def __init__(self):
self.fromBrain = None
self.contains = None
self.character = "-"
def __repr__(self):
return "-"
def __str__(self):
if self.contains == None:
return "Empty"
return self.contains
############################################################ Map ###################################################################
def SimpleZombieAI():
map = [Cell() for num in range(144)]
def addEntities(zombieNum, brainNum): # Automatically adding entities to the map.
# I need it to choose a random index in map, not what's in it.
for num in range(int(zombieNum)): # Choose a random number. Then, pop it and insert a zombie/brain there.
randomNum = random.choice(range(len(map)))
if map[randomNum].contains == None: # I need to make this a loop, rerandomizing the number over and over again if map[currentNum] isn't None.
map.pop(randomNum)
map.insert(randomNum, Zombie())
map[randomNum].contains = "zombie"
for num in range(int(brainNum)):
randomNum = random.choice(range(len(map)))
if map[randomNum].contains == None:
map.pop(randomNum)
map.insert(randomNum, Brain())
map[randomNum].contains = "brain"
addEntities(1, 1)
######################################################### Functions ################################################################
def checkMapSquareSize(): # Checking what size of square the map is.
numsList = [num for num in range(len(map))]
numsList.reverse()
for num in numsList:
if len(map) - (num ** 2) == 0: # prolly coulda used sqrRoot or some shit but ah well
return num
return "Not a perfect square."
def findBrain():
temp = None
for cell in map:
if type(cell) == Brain:
temp = cell
return map.index(temp)
def findZombie():
temp = None
for cell in map:
if type(cell) == Zombie:
temp = cell
return map.index(temp)
def updateFromBrainDistances(): # I don't actually remember what this function was intended for. A small consequence of leaving your work!
staticBrainLocation = findBrain()
iteration = 1
sqrt = checkMapSquareSize()
# Alright, I'll have it radial search from the brain; the first cells it finds will be given a tag of "1". Second wave will be "2", etc.
while iteration < sqrt:
for horizontal in range(-iteration, iteration + 1):
for vertical in range(-iteration, iteration + 1):
currentCell = staticBrainLocation + horizontal + (vertical * sqrt)
try:
if currentCell >= 0 and map[currentCell].fromBrain == None:
map[currentCell].fromBrain = iteration
# if iteration == 1:
# # print(f"{currentCell} is {iteration} cell away.")
# else:
# # print(f"{currentCell} is {iteration} cells away.")
except:
pass
iteration += 1
updateFromBrainDistances()
def terminalFormatting(): # So that my terminal is way cleaner to look at from a human perspective.
# I want it to add a newline as it prints, depending on what the square root is.
# A way I can think of is to turn a maplist into a string, insert a \n after so many characters, and print the string instead.
sqrt = checkMapSquareSize()
concatCount = 0
mapString = ""
for cell in map:
mapString += cell.character + " "
concatCount += 1
if concatCount == sqrt:
concatCount = 0
mapString += "\n"
return mapString
print(terminalFormatting())
for cell in map:
if type(cell) == Zombie:
if cell.fromBrain != 1:
print(f"There is a zombie currently {cell.fromBrain} spots away.\n")
else:
print(f"There is a zombie currently {cell.fromBrain} spot away.\n")
# Now, I just need to make the Zombie object take the closest path. This can be done by checking around it for the lowest fromBrain
# property, then switching spots with that cell. I will have my program update every cycle so that the fromBrain properties get fixed.
def findNextStone():
sqrt = checkMapSquareSize()
zombieLocation = findZombie()
leastDistance = 50
nextStoneIndex = None
for horizontal in range(-1, 2):
for vertical in range(-1, 2):
currentCell = zombieLocation + horizontal + (vertical * sqrt)
try:
if map[currentCell].fromBrain < leastDistance:
leastDistance = map[currentCell].fromBrain
nextStoneIndex = currentCell
except:
pass
return nextStoneIndex
def swapCells(fromCell, toCell): # If I want to use zombie or brain specifically, I have to comb through/find the zombie and brain, and assign temporary variables to them.
fromCellIndex = map.index(fromCell)
toCellIndex = map.index(toCell)
if toCell.contains == None:
map.pop(toCellIndex) # toCell = fromCell
map.insert(toCellIndex, fromCell)
map.pop(fromCellIndex) # fromCell = toCell
map.insert(fromCellIndex, toCell)
else:
map.pop(toCellIndex) # toCell = fromCell
map.insert(toCellIndex, fromCell)
map.pop(fromCellIndex) # different this time, fromCell becomes vacant.
map.insert(fromCellIndex, Cell())
def brainRemaining():
for cell in map:
if type(cell) == Brain:
return True
return False
# Lastly (I think), I need to build the While loop, so my level keeps operating.
turnCounter = 0
while (brainRemaining()):
print(terminalFormatting())
turnCounter += 1
zombieLocation = findZombie()
nextStoneIndex = findNextStone()
swapCells(map[zombieLocation], map[nextStoneIndex])
print("It found the brain!")
if __name__ == "__main__":
SimpleZombieAI()<file_sep>/README.md
# Simple-Zombie-AI
This is my first "complicated" project, having a Zombie object find the Brain object in the quickest manner it can.
Currently, all it can do is find it. In the future, I plan to add:
- Terrain, for needing to weave around
- Line of sight, so that it must be within range of Brain to detect it
- Movement for Brain, so the zombie must weave efficiently to catch it.
|
87cae267677c3b111b964c926164b1061615f27e
|
[
"Markdown",
"Python"
] | 2
|
Python
|
sonOfArent/Simple-Zombie-AI
|
098dcffd37ab206bc2e66417365ae573f3db163e
|
f0aaba1b3cd44acf40cee6f2316354963d5ee26d
|
refs/heads/master
|
<file_sep># dogecoin-serverless-tracker
Store price history and get current USD price of Dogecoin using AWS and Serverless framework.

<file_sep>'use strict';
const Coinmarketcap = require('node-coinmarketcap-api');
const AWS = require('aws-sdk');
const coinmarketcap = new Coinmarketcap();
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const ASSET_ID = 'dogecoin';
const priceInfo = (priceUsd) => {
const timestamp = new Date().getTime();
return {
priceUsd,
createdAt: timestamp
};
};
// Insert individual price row
const submitPriceP = (price) => {
console.log('Submitting price');
const priceInsert = {
TableName: process.env.DOGE_PRICE_TABLE,
Item: price
};
return dynamoDb.put(priceInsert).promise();
};
// Insert ticker results into new price entries
const updatePrices = (prices) => {
console.log(`prices ${JSON.stringify(prices)}`);
const priceUpdates = [];
prices.forEach((price) => {
priceUpdates.push(submitPriceP(priceInfo(parseFloat(price.price_usd))));
});
return Promise.all(priceUpdates);
};
const getLatestPrice = (assetId) => {
const params = {
TableName: process.env.DOGE_PRICE_TABLE,
Limit: 1,
ScanIndexForward: false,
ProjectionExpression: 'priceUsd'
};
return dynamoDb.scan(params).promise();
};
module.exports.updatePrice = (event, context) => {
console.log('Running dogecoin-tracker updatePrice');
console.log(`event ${JSON.stringify(event)}`);
console.log(`context ${JSON.stringify(context)}`);
const promises = [[ASSET_ID], coinmarketcap.ticker(null, null, 0)];
coinmarketcap.ticker(null, null, 0)
.then((prices) => {
return prices.filter(price => price.id === ASSET_ID);
})
.then(prices => updatePrices(prices))
.then(() => console.log('Successfully updated each price'))
.catch(err => console.log('coinmarketcap ticker:', err));
};
module.exports.getPrice = (event, context, callback) => {
getLatestPrice(ASSET_ID).then(result => {
const priceUsd = (result.Items.length > 0) ? result.Items[0].priceUsd : 0;
const response = {
statusCode: 200,
body: JSON.stringify({
price: priceUsd,
}),
};
callback(null, response);
}).catch(err => console.log('get price error:', err));
};
|
abc481ed6e2741938fdea43035dcf87cabd721f1
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
ShawnAukstak/dogecoin-serverless-tracker
|
da4f0f3eba4a22925307c271d726934a7323b697
|
10600e5e498853d12446b938f6c6916cdd4490b2
|
refs/heads/master
|
<file_sep>package etsmtl.gti785.musicserver;
import android.content.res.AssetFileDescriptor;
import android.media.MediaMetadataRetriever;
import android.util.Base64;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;
import etsmtl.gti785.bean.Song;
import fi.iki.elonen.NanoHTTPD;
import static fi.iki.elonen.NanoHTTPD.newChunkedResponse;
public class StreamService {
public MainActivity mainActivity;
public ArrayList<Song> playList;
public StreamService(MainActivity mainActivity) {
this.mainActivity = mainActivity;
this.playList = createPlaylist();
}
public ArrayList<Song> getPlayList() {
return playList;
}
public ArrayList<Song> createPlaylist() {
ArrayList<Song> playList = new ArrayList<>();
Field[] fields = R.raw.class.getFields();
for (int count = 0; count < fields.length; count++) {
Song song = createSongFromFileName(fields[count].getName());
playList.add(song);
}
return playList;
}
public NanoHTTPD.Response initPlayer(){
return generateResponse(getPlayList().get(0).getTitle());
}
public NanoHTTPD.Response getNextSong(String currentSong){
int currentSongIndex = 0;
Song nextSong;
// TODO: change contains for equals after cleaning the url params String
for (Song song: playList) {
if(currentSong.contains(song.getTitle())){
currentSongIndex = playList.indexOf(song);
}
}
if(currentSongIndex == playList.size()-1){
nextSong = playList.get(0);
}
else{
nextSong = playList.get(currentSongIndex+1);
}
return generateResponse(nextSong.getTitle());
}
public NanoHTTPD.Response getPreviousSong(String currentSong){
int currentSongIndex = 0;
Song previousSong;
// TODO: change contains for equals after cleaning the url params String
for (Song song: playList) {
if(currentSong.contains(song.getTitle())){
currentSongIndex = playList.indexOf(song);
}
}
if(currentSongIndex == 0){
previousSong = playList.get(playList.size()-1);
}
else{
previousSong = playList.get(currentSongIndex-1);
}
return generateResponse(previousSong.getTitle());
}
// TODO: make sure that the selected song is not the one that is playing already
public NanoHTTPD.Response getRandomSong(){
int randomNum = ThreadLocalRandom.current().nextInt(0, playList.size());
return generateResponse(playList.get(randomNum).getTitle());
}
public NanoHTTPD.Response generateResponse(String songName){
int songIndex = 0;
for (Song song: playList) {
if(songName == song.getTitle()){
songIndex = playList.indexOf(song);
}
}
JsonObject songMetadata = retrieveSongMetadata(playList.get(songIndex));
Gson gson = new GsonBuilder().create();
String jsonSongMetadata = gson.toJson(songMetadata);
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.ACCEPTED,"application/json", jsonSongMetadata);
}
public NanoHTTPD.Response getFileStream(String uri){
String fileName = uri.substring(5,uri.length()-4);
int resID = mainActivity.getResources().getIdentifier(fileName, "raw", mainActivity.getPackageName());
String path = getPathWithSongId(resID);
AssetFileDescriptor assetFileDescriptor = mainActivity.getResources().openRawResourceFd(resID);
try {
FileInputStream fis = assetFileDescriptor.createInputStream();
return newChunkedResponse(NanoHTTPD.Response.Status.OK, "audio/mpeg",fis);
} catch (Exception e) {
e.printStackTrace();
}
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.BAD_REQUEST, "application/text", "File Problem");
}
public JsonObject retrieveSongMetadata(Song song){
JsonObject songMetadata = new JsonObject();
songMetadata.addProperty("title", song.title);
songMetadata.addProperty("artist", song.artist);
songMetadata.addProperty("album", song.album);
songMetadata.addProperty("albumArt", song.albumArt);
songMetadata.addProperty("duration", song.duration);
songMetadata.addProperty("path", song.path);
return songMetadata;
}
public Song createSongFromFileName(String songFileName){
int resID = mainActivity.getResources().getIdentifier(songFileName, "raw", mainActivity.getPackageName());
String path = getPathWithSongId(resID);
String[] parts = path.split("/");
path = parts[parts.length-1];
// on initialise le metadataretriever avec un assetfiledescriptor pour l'aider a traiter le fichier
// source: http://book2s.com/java/api/android/media/mediametadataretriever/setdatasource-3.html
AssetFileDescriptor assetFileDescriptor = mainActivity.getResources().openRawResourceFd(resID);
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
String artist = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
String album = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
String title = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
// encoder l'image en base64 pour la faire passer en string
// source: https://stackoverflow.com/questions/36492084/how-to-convert-an-image-to-base64-string-in-java
byte[] artByteArray;
String artString;
if( mediaMetadataRetriever.getEmbeddedPicture() == null){
artString = null; }
else{
artByteArray = mediaMetadataRetriever.getEmbeddedPicture();
artString = Base64.encodeToString(artByteArray,0);
}
Song song = new Song(title, artist, album, artString, duration, path);
return song;
}
public String getPathWithSongId(int id){
return mainActivity.getResources().getResourceName(id);
}
}
<file_sep>package etsmtl.gti785.musicserver;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "IP";
public static final int PORT = 8765;
private static MyServer server;
TextView txtIpAddress;
TextView txtPortNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
server = new MyServer(PORT,this);
this.txtIpAddress = (TextView)this.findViewById(R.id.textView_ip);
this.txtPortNumber = (TextView)this.findViewById(R.id.textView_port);
server.start();
this.txtIpAddress.setText(getLocalIpAddress());
} catch (IOException e) {
e.printStackTrace();
}
}
public String getLocalIpAddress() {
WifiManager wifiMan = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
int ipAddress = wifiInf.getIpAddress();
String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
return ip;
}
}
|
be1b5fa0df9190be499b45751287167f9dbdbe72
|
[
"Java"
] | 2
|
Java
|
EricBarry99/MusicServer
|
471bcf560b5cb5b9b172d2cd51580bf24a7e4cc3
|
6c29d65bd8c3c72b24e622c80002a16c76c4be12
|
refs/heads/master
|
<file_sep># Generated by Django 3.0 on 2020-11-23 10:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0007_post_sidebar'),
]
operations = [
migrations.AddField(
model_name='post',
name='footer',
field=models.BooleanField(default=False),
),
]
<file_sep>[uwsgi]
http = 0.0.0.0:7000
master = true
memory-report = false
processes = 1
uid = root
gid = root
wsgi-file=voabrasil/wsgi.py
static-map=/static=blog/static/
static-map=/imagens=blog/static/imagens/
pidfile=/tmp/blog-master.pid
<file_sep>FROM python:3
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirement.txt /code/
RUN pip install https://github.com/darklow/django-suit/tarball/v2 & pip install -r requirement.txt
COPY . /code/
EXPOSE 7000
CMD ["/code/run.sh"]
<file_sep>#!/bin/bash
cd /code
uwsgi --ini blog.ini
#./manage.py runserver 0.0.0.0:7000 --insecure
<file_sep>from django.db import models
from django.contrib.auth.models import User
from django.db.models import signals
from django.db.models.signals import post_save,post_delete
import funcoes
from bs4 import BeautifulSoup
class Menu(models.Model):
name = models.CharField(max_length=80)
active = models.BooleanField(default=False)
def __str__(self):
return self.name
STATUS = (
(0,"Draft"),
(1,"Publish"),
(2,"Internal")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
resume = models.CharField(max_length=200, unique=False,default='')
menu = models.ForeignKey(Menu,on_delete=models.CASCADE,blank=True,null=True)
author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
detach = models.BooleanField(default=False)
sidebar = models.BooleanField(default=False)
footer=models.BooleanField(default=False)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
class Image(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=False,default='')
image = models.ImageField(upload_to='images')
def __str__(self):
return self.title
class File(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=False,default='')
file = models.FileField(upload_to='images')
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.name)
def Comment_save(signal, instance, sender, **kwargs):
post=''.join(BeautifulSoup(Post.objects.get(title=instance.post).content, "html.parser").stripped_strings)
if funcoes.similarity(instance.body,post) > 0.0 :
instance.active=True
else:
instance.active=False
signals.pre_save.connect(Comment_save, sender=Comment)
<file_sep># Generated by Django 3.0 on 2020-11-20 14:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_image_slug'),
]
operations = [
migrations.AddField(
model_name='post',
name='resume',
field=models.CharField(default='', max_length=200),
),
]
<file_sep>pip install https://github.com/darklow/django-suit/tarball/v2
docker run -p 7000:7000 -v /opt/blog/planabrasil/blog/static/imagens/:/code/blog/static/imagens/ blogplanabrasil
<file_sep>asgiref==3.3.1
beautifulsoup4==4.9.3
click==7.1.2
Django==3.0
django-crispy-forms==1.11.1
django-suit==2.0a1
django-summernote==0.8.11.6
joblib==1.0.1
nltk==3.5
numpy==1.20.1
Pillow==8.0.1
pytz==2020.4
regex==2020.11.13
scikit-learn==0.24.1
scipy==1.6.1
sklearn==0.0
soupsieve==2.2
sqlparse==0.4.1
threadpoolctl==2.1.0
tqdm==4.59.0
uWSGI==2.0.19.1
<file_sep>from django.shortcuts import render
from django.http import HttpResponse,HttpRequest
# Create your views here.
from django.views import generic
from .models import Post,Image,Menu
from django.shortcuts import render, get_object_or_404
from .forms import CommentForm
from django.contrib import messages
from django.contrib.auth import authenticate, login
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1,detach=False,sidebar=False,footer=False).order_by('-created_on')
template_name = 'index.html'
paginate_by = 3
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['dados'] = Post.objects.filter(detach=True,status=1,footer=False).order_by('-created_on')
context['menu'] = Menu.objects.filter(active=True)
context['submenu'] = Post.objects.filter(status__gt=0).order_by('-created_on')
context['sidebar'] = Post.objects.filter(sidebar=True,status=1,footer=False).order_by('-created_on')
context['footer'] = Post.objects.get(footer=True,status=1).content
context['logo'] = Image.objects.get(slug='logo').image
return context
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['dados'] = Post.objects.filter(detach=True,status=1,footer=False).order_by('-created_on')
context['menu'] = Menu.objects.filter(active=True)
context['submenu'] = Post.objects.filter(status__gt=0).order_by('-created_on')
context['sidebar'] = Post.objects.filter(sidebar=True,status=1,footer=False).order_by('-created_on')
context['footer'] = Post.objects.get(footer=True,status=1).content
context['logo'] = Image.objects.get(slug='logo').image
return context
class PostSearch(generic.ListView):
queryset = Post.objects.filter(status=1,detach=False,sidebar=False,footer=False).order_by('-created_on')
template_name = 'search.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
try:
search=self.request.GET.get('search' )
if not search == '':
context['pesquisa'] = Post.objects.filter(status=1,detach=False,sidebar=False,footer=False,content__contains=search)[:3]
except:
search="null"
context['dados'] = Post.objects.filter(detach=True,status=1,footer=False).order_by('-created_on')
context['sidebar'] = Post.objects.filter(sidebar=True,status=1,footer=False).order_by('-created_on')
context['menu'] = Menu.objects.filter(active=True)
context['submenu'] = Post.objects.filter(status__gt=0).order_by('-created_on')
context['footer'] = Post.objects.get(footer=True,status=1).content
context['logo'] = Image.objects.get(slug='logo').image
return context
def post_detail(request, slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
dados = Post.objects.filter(detach=True,status=1,footer=False).order_by('-created_on')
menu = Menu.objects.filter(active=True)
submenu = Post.objects.filter(status__gt=0).order_by('-created_on')
sidebar = Post.objects.filter(sidebar=True,status=1,footer=False).order_by('-created_on')
footer = Post.objects.get(footer=True,status=1).content
logo = Image.objects.get(slug='logo').image
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request, template_name, {
'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form,
'dados':dados,
'menu':menu,
'submenu':submenu,
'sidebar':sidebar,
'footer':footer,
'logo':logo,
})
<file_sep># Generated by Django 3.0 on 2020-11-23 08:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_post_detach'),
]
operations = [
migrations.AddField(
model_name='post',
name='sidebar',
field=models.BooleanField(default=False),
),
]
<file_sep>import nltk
import warnings
from nltk.corpus import stopwords
warnings.filterwarnings("ignore")
import numpy as np
import random
import string
nltk.download('stopwords')
nltk.download('rslp')
nltk.download('punkt')
import threading
language='portuguese'
def LemTokens(tokens):
#lemmer = nltk.stem.WordNetLemmatizer()
lemmer = nltk.stem.RSLPStemmer()
# return [lemmer.lemmatize(token) for token in tokens]
return [lemmer.stem(token) for token in tokens]
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
def LemNormalize(text):
return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))
def similarity(user_response,text):
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
sent_tokens = nltk.sent_tokenize(text, language=language)
sent_tokens.append(user_response.lower())
TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words=stopwords.words(language))
tfidf = TfidfVec.fit_transform(sent_tokens)
vals = cosine_similarity(tfidf[-1], tfidf)
idx=vals.argsort()[0][-2]
flat = vals.flatten()
flat.sort()
req_tfidf = flat[-2]
#sent_tokens.remove(user_response.lower())
return req_tfidf
|
2779f93f93bc2fbfefcd73c43e7af8b657dd56b7
|
[
"Markdown",
"INI",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 11
|
Python
|
fabiocax/glob
|
bd1c57abbe171bc7d79f644037c1a1ee94fe6d85
|
6e7b7235207dda34634bb88438757d8c45bad15d
|
refs/heads/master
|
<repo_name>EMalley/YouNameIt<file_sep>/schema.sql
CREATE DATABASE users;
USE users;
CREATE TABLE `userInfo` (
`id` INT (11) AUTO_INCREMENT NOT NULL,
`userName` VARCHAR (255) NOT NULL,
'email' VARCHAR (255) NOT NULL,
'phone' int(10) NOT NULL,
PRIMARY KEY (`id`)
)
|
cb0151d3012191fdcbe0e285b6bdb58e33bfa758
|
[
"SQL"
] | 1
|
SQL
|
EMalley/YouNameIt
|
7700f3f5af7cc35a413dded862ffa019cd1919ea
|
ddecb9c7cbd741927ca304be3b1ba91e778c91bb
|
refs/heads/master
|
<file_sep># Countdown
In a Countdown letters game, contestants form the longest anagram they can from a scramble of nine somewhat random letters (including at least three vowels and four consonants). No letter may be used more often than it appears in the scramble. More information on the rules (and controversies!) of the game can be found [here](https://en.wikipedia.org/wiki/Countdown_(game_show)#Letters_round) and [here](http://wiki.apterous.org/Letters_game). This script takes a nine letter string from the user and prints out a list of anagrams for the longest three lengths. For example, for the input `qwertyuio` the script prints:
```
7 letter words: quoiter, torquey
6 letter words: equity, quiety, quoter, requit, roquet, ryotei, torque, towery
5 letter words: ourey, ourie, outer, outie, outre, owrie, query, quiet, quire, quirt, quite, quoit, quote, rioty, roque, rouet, route, rowet, royet, ruote, ryoti, toque, tower, towie, uteri, write, wrote
Time taken: 0.3727662639994378s
```
## Word list
The dictionary used in this script contains 122160 unique words sourced from the spreadsheet [here](https://countdownresources.wordpress.com/2018/10/13/complete-list-of-words-ordered-by-how-useful-they-are-for-countdown/). A copy of that 32.6 MB spreadsheet is also available in this repository, called [dictionary-original.xlsx](dictionary-original.xlsx). A second 17.2 MB spreadsheet, [dictionary.xlsx](dictionary.xlsx) has had redundant worksheets removed leaving only the `overall` worksheet. Even so, the [lookup.py](lookup.py) script still takes over 15 seconds to produce the word list file, [dictionary.txt](dictionary.txt), but this isn't too much of a problem because it only needed to be ran once.
The [lookup.py](lookup.py) script iterates over the rows in a column and adds them to the `words` list. In the spreadsheet words that are anagrams are stored in the same cell. For example, the `C9` cell has value `RODENTIA/RATIONED/ORDINATE/NADORITE/DERATION`, the script separates this into the lowercase set: `{'rodentia', 'rationed', 'ordinate', 'nadorite', 'deration'}` and appends these values to the `words` list. The script then adds all the list to [dictionary.txt](dictionary.txt).<file_sep>from timeit import default_timer
import re
def is_match(scramble, word):
word = list(word)
for letter in scramble:
if letter in word:
word.remove(letter)
if len(word) == 0:
return True
return False
def parse_dictionary(filename, scramble):
anagrams = list(list() for i in range(len(scramble) - 1))
with open(filename) as dictionary:
for word in dictionary:
word = word.rstrip()
if len(scramble) >= len(word):
if is_match(scramble, word):
anagrams[len(word) - 2].append(word)
return anagrams
def main():
scramble = input("Enter up to nine letters: ")
if not scramble.isalpha():
print("Enter letters only.")
return
if len(scramble) > 9:
print("Enter up to nine letters only.")
return
start = default_timer()
anagrams = parse_dictionary("dictionary.txt", scramble)
end = default_timer()
j = 0
for i in range(len(anagrams) - 1, -1, -1):
if j < 3:
if anagrams[i]:
j += 1
print(i + 2, "letter words:", ', '.join(anagrams[i]))
if j == 0:
print("There were no anagrams found for those letters.")
else:
print("Time taken: {}{}".format(end - start, 's'))
if __name__ == "__main__":
main()<file_sep>from openpyxl import load_workbook
import re
dictionary = list()
for row in load_workbook("dictionary.xlsx", read_only=True)["overall"].iter_rows(min_row=4, min_col=3, max_col=3):
for cell in row:
dictionary.extend(set(cell.value.lower().split('/')))
dictionary = sorted(dictionary)
open("dictionary.txt", 'w').write('\n'.join(word for word in dictionary))
|
b7f3e4b336102c629f768c39979c0a2b142badd3
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
oliver-brenner/Countdown
|
d6a641c0b0f26c7ea9fd1140f7f7fef35884c6ad
|
7175d324b51ec6c0aa60da9a1e3dcab990cc444b
|
refs/heads/master
|
<file_sep>driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1/test_db
username=root
password=<PASSWORD><file_sep>package com.sxx.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sxx.dao.UserMapper;
import com.sxx.entity.User;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public void saveUser(User user) {
// TODO Auto-generated method stub
userMapper.saveUser(user);
}
}
<file_sep>package com.sxx.dao;
import com.sxx.entity.User;
public interface UserMapper {
public User getUserById(int id);
public void saveUser(User user);
public void updateUser(User user);
public void delUser(int id);
}
|
071b67728f0402e251f4c60e7f970396b82e6bd1
|
[
"Java",
"INI"
] | 3
|
INI
|
sunxiaoxu0124/MavenDemo
|
f9e0ce65e7ce8608c0e6873902fa21284e606041
|
2d11292fa2636d72b846b2db6d06388672b623cb
|
refs/heads/master
|
<repo_name>Shawnuke/node-snake-game<file_sep>/public/assets/js/script.js
// type apple =
// {
// context: HTMLElement,
// color: string
// position: location
// }
class Apple {
constructor(_options) {
this.context = _options.context;
this.color = _options.color;
this.position =
{
x: _options.x,
y: _options.y
};
this.isEaten = false;
this.canvasSizes = _options.canvasSizes;
}
relocate() {
this.isEaten = false;
this.position =
{
x: Math.floor(Math.random() * this.canvasSizes.width / 20),
y: Math.floor(Math.random() * this.canvasSizes.width / 20),
};
}
draw() {
this.context.fillStyle = this.color;
this.context.beginPath();
this.context.arc(this.position.x * 20 + 10, // x
this.position.y * 20 + 10, // y
1 * 8, // radius
0, // start angle
Math.PI * 2 // theta
);
this.context.fill();
}
}
class Snake {
constructor(_options) {
this.context = _options.context;
// this.x = _options.x
// this.y = _options.y
this.color = _options.color;
this.apples = _options.apples;
this.head =
{
x: _options.x,
y: _options.y
};
this.direction =
{
x: _options.direction.x,
y: _options.direction.y
};
this.body = [];
this.isAlive = true;
this.ate = false;
this.scale = _options.scale;
this.grow();
this.grow();
this.grow();
}
updatePosition() {
// keep trace of previous head position (for collision management)
this.head.previousX = this.head.x;
this.head.previousY = this.head.y;
// update head position relative to direction
this.head.x += this.direction.x;
this.head.y += this.direction.y;
this.body.push({ x: this.head.x, y: this.head.y }); // add a block ahead of the snake
this.body.shift(); // remove the last block of its tail
}
outerRingCollision(_canvas) {
if (this.head.x <= 0) {
this.head.x = 0;
this.direction.x = 0;
}
else if (this.head.x >= 11) {
this.head.x = 11;
this.direction.x = 0;
}
if (this.head.y <= 0) {
this.head.y = 0;
this.direction.y = 0;
}
else if (this.head.y >= 19) {
this.head.y = 19;
this.direction.y = 0;
}
}
fatalCollisionDetection(_canvas) {
/* outer ring */
if (this.head.x < 0
|| this.head.x > (_canvas.width - this.scale) / this.scale
|| this.head.y < 0
|| this.head.y > (_canvas.height - this.scale) / this.scale)
this.isAlive = false;
/* self collision detection */
if (this.body.length <= 4)
return; // no need to test self-collision if snake length < 4
const max = this.body.length - 4;
const verifyArray = this.body.slice(0, max);
for (const _bodyPart of verifyArray) {
if (this.head.x == _bodyPart.x && this.head.y == _bodyPart.y) {
this.isAlive = false;
}
}
}
appleCollisionDetection(list) {
this.apples = list;
for (const _apple of this.apples) {
if (this.head.x == _apple.position.x && this.head.y == _apple.position.y) {
this.ate = true;
_apple.isEaten = true;
}
}
return this.apples;
}
draw() {
/* draw the snake */
this.context.fillStyle = this.color;
this.context.beginPath();
for (const _bodyPart of this.body) {
const x = _bodyPart.x * this.scale;
const y = _bodyPart.y * this.scale;
const width = 1 * this.scale;
const height = 1 * this.scale;
this.context.fillRect(x, y, width, height);
}
/* color the head when the snake dies */
if (!this.isAlive) {
this.context.fillStyle = 'red';
const x = this.head.x * this.scale;
const y = this.head.y * this.scale;
const width = 1 * this.scale;
const height = 1 * this.scale;
this.context.fillRect(x, y, width, height);
}
const centerOf = (_cell, _scale) => {
return _cell * _scale + _scale / 2;
};
// highlight the head
// create gradient
this.context.beginPath();
const gradient = context.createRadialGradient(centerOf(this.head.x, this.scale), // inner x
centerOf(this.head.y, this.scale), // inner y
0, // inner radius
centerOf(this.head.x, this.scale), // outer x
centerOf(this.head.y, this.scale), // outer y
2 * this.scale // outer radius
);
if (this.isAlive) {
gradient.addColorStop(0, '#32CE3699');
gradient.addColorStop(1, '#32CE3600');
}
else {
gradient.addColorStop(0, '#CE323699');
gradient.addColorStop(1, '#CE323600');
}
/* draw the gradient */
this.context.fillStyle = gradient;
this.context.arc(centerOf(this.head.x, this.scale), // x
centerOf(this.head.y, this.scale), // y
10 * this.scale, // radius
0, // start angle
Math.PI * 2 // theta
);
this.context.fill();
}
setDirectionTo(input) {
switch (input) {
case 0:
this.direction.x = 0;
this.direction.y = -1;
break;
case 1:
this.direction.x = 1;
this.direction.y = 0;
break;
case 2:
this.direction.x = 0;
this.direction.y = 1;
break;
case 3:
this.direction.x = -1;
this.direction.y = 0;
break;
default:
break;
}
}
grow() {
this.body.push({ x: this.head.x, y: this.head.y });
}
}
const $button = document.querySelector('.js-invite');
const url = new URL(window.location.href);
const path = url.pathname.substring(1);
// const multiCountdown = () =>
// {
// let sec = 3
// const countdown = setInterval(() =>
// {
// console.log(sec)
// sec--
// if (sec == 0)
// {
// window.clearInterval(countdown)
// }
// }, 1000)
// }
// let multiRunning = false
const connect = () => {
const socket = io();
// controls
const keyboardInput = (_event) => {
let input = 5;
switch (_event.key) {
case 'ArrowUp':
case 'z':
// if (snake.head.x == snake.head.previousX) return
input = 0;
break;
case 'ArrowRight':
case 'd':
// if (snake.head.y == snake.head.previousY) return
input = 1;
break;
case 'ArrowDown':
case 's':
// if (snake.head.x == snake.head.previousX) return
input = 2;
break;
case 'ArrowLeft':
case 'q':
// if (snake.head.y == snake.head.previousY) return
input = 3;
break;
case 'g':
snake.grow();
break;
}
if (input < 5) {
socket.emit('input', input);
snake.setDirectionTo(input);
}
};
document.addEventListener('keydown', keyboardInput);
// if (!path) // 1st player
// {
// console.log('give this link to your friend')
// }
socket.on('chat message', (msg) => {
console.log(msg);
});
// socket.on('snakeParam', (param) => // assign snake initial position
// {
// snake.head.x = param.posX
// snake.head.x = param.posY
// snake.direction.x = param.dirX
// snake.direction.x = param.dirY
// snakes.push(snake)
// })
// socket.on('enemyParam', (param) => // assign snake initial position
// {
// const enemy = new Snake(
// {
// context: context,
// x: 3,
// y: 10,
// direction:
// {
// x: 1,
// y: 0
// },
// color: '#5C25C2',
// apples: apples,
// scale: frame.scale
// })
// enemy.head.x = param.posX
// enemy.head.x = param.posY
// enemy.direction.x = param.dirX
// enemy.direction.x = param.dirY
// snakes.push(enemy)
// })
// let silentDisconnexion = false
// socket.on('errorMsg', (msg: string) =>
// {
// switch (msg)
// {
// case '1':
// console.log('Sorry, but the party you\'re trying to join is either full or empty. Make sure you wrote the address right, or please ask your friend to try again.')
// break;
// default:
// console.log(msg)
// break;
// }
// silentDisconnexion = true
// })
// socket.on('disconnect', () =>
// {
// if (!silentDisconnexion) console.log('oops, you were disconnected. Please verify the quality of your connection')
// })
// socket.on('gameStatus', (status) =>
// {
// switch (status)
// {
// case 'start':
// // multiRunning = true
// // multiCountdown()
// document.addEventListener('keydown', multiControls)
// break
// case 'stop':
// break
// default:
// break
// }
// })
const useEnemyInput = (direction) => {
console.log('enemyDirection:', direction);
snakes[1].setDirectionTo(direction);
};
socket.on('enemyInput', useEnemyInput);
};
connect();
// $button.addEventListener('click', () =>
// {
// connect()
// })
// if (path)
// {
// connect()
// }
/// <reference path="Snake.ts" />
/// <reference path="Apple.ts" />
/// <reference path="client.ts" />
/* Set up */
const $wrapper = document.querySelector('.wrapper');
const $canvas = document.querySelector('.js-canvas');
const context = $canvas.getContext('2d');
$canvas.focus();
/* Resize */
const frame = {
width: $canvas.width,
height: $canvas.height,
scale: 20
};
let apples = [];
const apple = new Apple({
context: context,
color: 'white',
x: 2,
y: 2,
canvasSizes: frame
});
apples.push(apple);
let snakes = [];
const snake = new Snake({
context: context,
x: 5,
y: 3,
direction: {
x: 0,
y: 1
},
color: '#32CE36',
apples: apples,
scale: frame.scale
});
snakes.push(snake);
const enemy = new Snake({
context: context,
x: 5,
y: 3,
direction: {
x: 0,
y: 1
},
color: '#5C25C2',
apples: apples,
scale: frame.scale
});
snakes.push(enemy);
let localGame = true;
// controls
// const controls = (_event: KeyboardEvent) =>
// {
// console.log(_event)
// switch (_event.key)
// {
// case 'ArrowUp':
// case 'z':
// // if (snake.direction.y == 1) return // prevent the player from going straight back in the opposite direction
// // if (snake.head.x == snake.body[length-1].x && snake.head.y == snake.body[length-1].y + 1) return // works, but ugly
// if (snake.head.x == snake.head.previousX) return
// snake.setDirectionTo(0, -1)
// break
// case 'ArrowRight':
// case 'd':
// // if (snake.direction.x == -1) return
// if (snake.head.y == snake.head.previousY) return
// snake.setDirectionTo(1, 0)
// break
// case 'ArrowDown':
// case 's':
// // if (snake.direction.y == -1) return
// if (snake.head.x == snake.head.previousX) return
// snake.setDirectionTo(0, 1)
// break
// case 'ArrowLeft':
// case 'q':
// // if (snake.direction.x == 1) return
// if (snake.head.y == snake.head.previousY) return
// snake.setDirectionTo(-1, 0)
// break
// case 'g':
// snake.grow()
// break
// }
// }
// document.addEventListener('keydown', controls)
const drawGrid = (_canvas, _color) => {
context.strokeStyle = _color;
context.beginPath();
for (var x = 0; x <= _canvas.width; x += _canvas.scale) {
context.moveTo(x, 0);
context.lineTo(x, _canvas.height);
}
for (var y = 0; y <= _canvas.height; y += _canvas.scale) {
context.moveTo(0, y);
context.lineTo(_canvas.height, y);
}
context.stroke();
};
const drawCheckeredBackground = (_canvas, _color) => {
context.fillStyle = _color;
let w = _canvas.width;
let h = _canvas.height;
const nCol = w / _canvas.scale;
const nRow = h / _canvas.scale;
w /= nCol; // width of a block
h /= nRow; // height of a block
context.beginPath();
for (let i = 0; i < nRow; ++i) {
for (let j = 0, col = nCol / 2; j < col; ++j) {
context.rect(2 * j * w + (i % 2 ? 0 : w), i * h, w, h);
}
}
context.fill();
};
const fps = 12;
const loop = () => {
setTimeout(() => {
const game = window.requestAnimationFrame(loop);
/**
* Update Phase
*/
for (const _snake of snakes) {
// update snakes positions
_snake.updatePosition();
_snake.outerRingCollision(frame);
// // resolve snakes collisions
// _snake.fatalCollisionDetection(frame)
// if (!_snake.isAlive)
// {
// window.cancelAnimationFrame(game)
// document.removeEventListener('keydown', controls)
// console.log('you died. max length:', _snake.body.length)
// }
// // resolve snake-apple collisions
// apples = _snake.appleCollisionDetection(apples)
// if (_snake.ate)
// {
// _snake.ate = false
// _snake.grow()
// }
}
/**
* Drawing phase
*/
/* Clear canvas */
context.clearRect(0, 0, frame.width, frame.height);
/* Draw */
for (const _snake of snakes) {
_snake.draw();
}
drawCheckeredBackground(frame, '#FFFFFF22');
}, 1000 / fps);
};
loop();
// const loop = () =>
// {
// setTimeout(() =>
// {
// const game = window.requestAnimationFrame(loop)
// // Maths
// for (const _snake of snakes)
// {
// // update snakes positions
// _snake.updatePosition()
// // resolve snakes collisions
// _snake.fatalCollisionDetection(frame)
// if (!_snake.isAlive)
// {
// window.cancelAnimationFrame(game)
// document.removeEventListener('keydown', controls)
// console.log('you died. max length:', _snake.body.length)
// }
// // resolve snake-apple collisions
// apples = _snake.appleCollisionDetection(apples)
// if (_snake.ate)
// {
// _snake.ate = false
// _snake.grow()
// }
// // Clear canvas
// context.clearRect(0, 0, frame.width, frame.height)
// // Draw
// _snake.draw()
// }
// for (const _apple of apples)
// {
// if (_apple.isEaten)
// {
// _apple.relocate()
// }
// _apple.draw()
// }
// /* style the map */
// // drawGrid(frame, 'black')
// drawCheckeredBackground(frame, '#FFFFFF22')
// }, 1000/fps)
// }
// loop()
// const $restart: Element = document.querySelector('.js-restart')
// $restart.addEventListener('click', () =>
// {
// document.removeEventListener('keydown', controls)
// snakes.forEach(_snake =>
// {
// snake.isAlive = true
// snake.body = []
// snake.grow()
// snake.grow()
// snake.grow()
// snake.head.x = 9
// snake.head.y = 3
// snake.direction.x = 0
// snake.direction.y = 1
// })
// // console.log(snakes)
// $canvas.focus()
// // snakes.splice(0, 1)
// // console.log(snakes)
// // const snake = new Snake(
// // {
// // context: context,
// // x: 9,
// // y: 3,
// // direction:
// // {
// // x: 0,
// // y: 1
// // },
// // color: '#32CE36',
// // apples: apples,
// // scale: frame.scale
// // })
// // snakes.push(snake)
// // console.log(snakes)
// document.addEventListener('keydown', controls)
// loop()
// })
<file_sep>/src/ts/server.ts
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
const http = require('http').createServer(app)
const io = require('socket.io')(http)
// Make the files in the public folder available to the world
app.use(express.static(__dirname + '/public/'))
http.listen(port, () =>
{
console.log('running on http://localhost:' + port)
})
/**
* Routes management
*/
/* no need for app.get('/') since default convention is to redirect to index.html */
app.get('/:room', function(req, res)
{
// console.log('req.params.room=', req.params.room)
res.sendFile(__dirname + '/public/index.html')
})
/**
* Function to assign a room to a client depending of its URL
*/
const assignRoom = (requestedRoom: string) =>
{
console.log('requestedRoom is', requestedRoom? requestedRoom : 'none')
if (!requestedRoom) // first player entering the room
{
// if roomValue is taken, take next room
if (io.nsps['/'].adapter.rooms[roomValue]) roomValue++
// if roomValue is empty
return roomValue
}
else // 2nd or 3rd player entering the room
{
// const roomTested = io.nsps['/'].adapter.rooms[requestedRoom]
// if (roomTested && roomTested.length == 1) // if room exists and is not full
// {
// return requestedRoom
// }
// else // in any other cases, whether it exists but is full, or empty, or doesn't exist
// {
// console.log('already full/totally empty/doesnt exist')
// return null
// }
return requestedRoom
}
}
let roomValue: number = 0
/**
* Socket connection management
*/
const newConnection = (socket) =>
{
console.log('new connection:', socket.id)
/**
* Rooms management
*/
const origin: string = socket.handshake.headers.referer // url of client
// global.URL = require('url').URL
// const url = new URL(origin)
// const path = url.pathname.substring(1)
const url = socket.handshake.headers.referer
const newURL = url.substring(url.lastIndexOf("/") + 1, url.length)
const currentRoom = assignRoom(newURL) // assign a room to the client
console.log('the room assigned is', currentRoom)
if (currentRoom == null) // if joining a room failed
{
socket.emit('errorMsg', '1')
socket.disconnect()
console.log('socket was disconnected by force')
}
socket.join(currentRoom)
// socket.emit('snakeParam', { posX: 9, posY: 3, dirX: 0, dirY: 1})
// socket.emit('enemyParam', { posX: 3, posY: 9, dirX: 0, dirY: -1})
/**
* A room is now filled with 2 players
*/
if (io.nsps['/'].adapter.rooms[currentRoom].length == 2)
{
io.emit('chat message', 'connected with player 2')
console.log('players are connected')
// socket.broadcast.emit('snakeParam', { posX: 3, posY: 9, dirX: 0, dirY: -1})
// socket.broadcast.emit('enemyParam', { posX: 9, posY: 3, dirX: 0, dirY: 1})
// if room is full, socket = x:9, y: 3, the other something else
const inputData = (direction) =>
{
console.log('direction received:', direction)
socket.broadcast.emit('enemyInput', direction)
}
socket.on('input', inputData)
}
// socket.on('disconnect', (reason) =>
// {
// console.log('socket disconnected from room#' + currentRoom)
// console.log('reason: ', reason)
// // io.sockets.in(roomValue).emit('chat message', 'your friend abandonned you')
// socket.broadcast.emit('chat message', 'your friend left the party')
// })
}
io.on('connection', newConnection)<file_sep>/tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"outDir": "public/assets/js/",
"outFile": "public/assets/js/script.js"
},
"exclude": ["node_modules", "src/ts/server.ts"]
}
<file_sep>/README.md
node-snake-game
========
This project is a snake game using WebSockets, allowing 2 players to play together.
# Table of Contents
* [Overview](#overview)
* [Current Features](#current-features)
* [Browser Support](#browser-support)
* [Project Demo](#project-demo)
* [Todo](#todo)
* [Known Issues](#known-issues)
* [Built With](#built-with)
* [Author](#author)
* [License](#license)
# Overview
# Current Features
*
# Browser Support
All current browsers are fully supported.
* Chrome 83
* Firefox 76
* Edge 83
* Safari 13.1
* Opera 68
# Project Demo
A live demo of the project can be found at [this address](https://node-snake-game.herokuapp.com/).
# Todo
- add smartphone controls to play
- add favicon
- use cache to keep trace of scores
- generate canvas color scheme on page load
# Known Issues
- in multiplayer game, if one of the players have internet issues, snakes positions could possibly be different in both clients ; it comes from the fact that server send to clients ***directions*** and not ***positions***. It might be done in an upcoming version.
- Multiple hits on the "restart" button increases the framerate, then gets back to normal after game over.
- canvas visual proportions are document-size dependent (it can currently shrink because of right side buttons)
# Built With
* [Node.js](http://nodejs.org/)
* [Express](https://expressjs.com/)
* [Socket.io](https://socket.io/)
# Author
* **<NAME>** - [Shawnuke](https://github.com/Shawnuke)
# Forked from
* [jamesward/hello-node_js-express](https:/github.com/jamesward/hello-node_js-express)
# License
[MIT](LICENSE) © <NAME>
This project is licensed under the terms of the [MIT](LICENSE) license.<br>
See the [LICENSE.md]() file for more information.
|
382fc12d0f403a52268631e43e56b3e22508afcd
|
[
"JavaScript",
"TypeScript",
"JSON with Comments",
"Markdown"
] | 4
|
JavaScript
|
Shawnuke/node-snake-game
|
91c26b3e4442ff2bd2e62109f2244ebc0c8cf666
|
366c5dc9303ad91cdfe837804550d70c2dab8a9d
|
refs/heads/master
|
<repo_name>briannoogin/Neural-Network-Science-Fair-Research<file_sep>/normalityTest.R
mardiaTest <-
function (data, cov = TRUE, qqplot = FALSE)
{
dataframe=as.data.frame(data)
dname <- deparse(substitute(data))
data <- as.matrix(data)
n <- dim(data)[1]
p <- dim(data)[2]
data.org <- data
data <- scale(data, scale = FALSE)
if (cov) {
S <- ((n - 1)/n) * cov(data)
}
else {
S <- cov(data)
}
D <- data %*% solve(S) %*% t(data)
g1p <- sum(D^3)/n^2
g2p <- sum(diag((D^2)))/n
df <- p * (p + 1) * (p + 2)/6
k <- (p + 1) * (n + 1) * (n + 3)/(n * ((n + 1) * (p + 1) -
6))
small.skew <- n * k * g1p/6
skew <- n * g1p/6
kurt <- (g2p - p * (p + 2)) * sqrt(n/(8 * p * (p + 2)))
p.skew <- pchisq(skew, df, lower.tail = FALSE)
p.small <- pchisq(small.skew, df, lower.tail = FALSE)
p.kurt <- 2 * (1 - pnorm(abs(kurt)))
if (qqplot) {
d <- diag(D)
r <- rank(d)
chi2q <- qchisq((r - 0.5)/n, p)
df = data.frame(d, chi2q)
qqPlotPrint = ggplot(df, aes(d, chi2q),environment = environment())+geom_point(shape=16, size=4)+
geom_abline(intercept =0, slope =1,color="black",size=2)+
xlab("Squared Mahalanobis Distance")+
ylab("Chi-Square Quantile")+
ggtitle("Chi-Square Q-Q Plot")+
theme(plot.title = element_text(lineheight=.8, face="bold"))
print(qqPlotPrint)
}
result <- new("mardia", g1p = g1p, chi.skew = skew, p.value.skew = p.skew,
chi.small.skew = small.skew, p.value.small = p.small, g2p = g2p,
z.kurtosis = kurt, p.value.kurt = p.kurt, dname = dname, dataframe = dataframe)
result
}
mydata = read.xls("breastCancerKaggle.xlsx")
y <- mardiaTest(breastCancerKaggle, cov = TRUE, qqplot = FALSE)
<file_sep>/README.md
# Neural-Network-Science-Fair-Research
Machine Learning Research Summer 2016
This repostiory contains all of my work that I have done during the summer.
|
6b7286e14b3830fd9cbe57bd49056a68babab052
|
[
"Markdown",
"R"
] | 2
|
R
|
briannoogin/Neural-Network-Science-Fair-Research
|
8232bc6abea8d670736ac2d0d21d04fb10842694
|
2c450b9889b8a1517db7ea6f6150cd0c93b30f8c
|
HEAD
|
<repo_name>webpioneer/rien3<file_sep>/utils_app/views.py
from django.contrib.auth.models import User
from django.contrib.messages import info
from django.core import mail
from django.core.mail import EmailMessage
from django.shortcuts import get_object_or_404, redirect
from django.utils.translation import ugettext_lazy as _
from mezzanine.utils.views import render
from gigs.models import Application
from utils_app.forms import ResumeForm, PeopleForm, TeamForm
from utils_app.models import EmailedResume, GroupWithType, Team
def unslugify(value):
return value.replace('-', ' ')
def email_resume(request, attach, template_name = 'utils_app/email_resume.html'):
app = Application.objects.get(id = request.POST.get('application_id'))
if request.method == 'POST':
resume_form = ResumeForm(request.POST)
if resume_form.is_valid():
post_data = resume_form.cleaned_data
emailed_resume = EmailedResume()
emailed_resume.recipients = post_data.get('recipients')
emailed_resume.subject = post_data.get('subject')
emailed_resume.body = post_data.get('body')
emailed_resume.sender = request.user
emailed_resume.application = app
emailed_resume.save()
# send the email(s)
connection = mail.get_connection()
connection.open()
print emailed_resume.recipients.split(',')
if ',' in emailed_resume.recipients:
print 'in'
emails = [ mail.EmailMessage(emailed_resume.subject,
emailed_resume.body, emailed_resume.sender.email,
[recipient])
for recipient in emailed_resume.recipients.split(',') ]
for email in emails:
email.attach_file(app.resume.file.path)
#print emails[0].attach_file(app.resume.file.path)
#emails_attached = [ email.attach_file(app.resume.file.path) for email in emails ]
#print emails_attached
connection.send_messages(emails)
connection.close()
else:
print 'not in '
message = EmailMessage(emailed_resume.subject, emailed_resume.body, emailed_resume.sender.email, [emailed_resume.recipients])
if attach == 'True':
message.attach_file(app.resume.file.path)
message.send()
if attach == 'True':
message = _("The applicant's resume was emailed to the <strong>%s</strong>." %
emailed_resume.recipients)
else:
message = _('Feedback on <strong>%s</strong> requested from <strong>%s</strong>'
% (app.sender.last_name.capitalize(), emailed_resume.recipients))
info(request, message, extra_tags='success')
return redirect(app.get_absolute_url())
else:
resume_form = ResumeForm()
context = {
'resume_form' : resume_form,
'application' : app,
}
if attach == 'True':
context['attach'] = True
return render(request, template_name, context)
def people(request, template_name = 'utils_app/people.html'):
# retrieve user (owner) as it is need in POST and GET
owner = request.user
#people_groups = [ (user, user.groups.all()[0].groupwithtype.group_type) for group in owner.groupwithtypes.all()
# for user in group.user_set.all().order_by('-date_joined') ]
if request.method == 'POST':
people_form = PeopleForm(request.POST)
team_form = TeamForm(request.POST)
if people_form.is_valid():
#retrieve post data
post_data = request.POST.copy()
print post_data
account_type = post_data['account_type']
email = post_data['email']
last_name = post_data['last_name']
first_name = post_data['first_name']
# check if group type already exists, otherwise create a new group type
group_type, group_type_created = GroupWithType.objects.get_or_create(
name = '%s_%s' % (account_type, owner.id), group_type = account_type, user = owner)
print group_type, group_type_created
# create a new user
new_user_password = User.objects.make_random_password()
new_user = User.objects.create_user(username = email, email = email,
password = <PASSWORD>)
new_user.last_name = last_name
new_user.first_name = first_name
new_user.save()
# add the new user to the group type
new_user.groups.add(group_type)
# send email to the new user with a randomly generated password and link
# send message
message = _('User <strong>%s</strong> (%s) account was created. An email is sent to <strong>%s</strong> to notify him'
% (new_user, group_type.group_type, email))
info(request, message, extra_tags='success')
return redirect(request.META['HTTP_REFERER'])
else:
context ={
'people_form' : people_form,
'people_form' : people_form,
}
if team_form.is_valid():
#create a group if it does not exist
post_data = request.POST.copy()
team_name = post_data['team_name']
#team, team_created = Team.objects.get_or_create(
# name = team_name, user = owner)
# send message
message = _('Team <strong>%s</strong> was created' % team_name)
info(request, message, extra_tags='success')
return redirect(request.META['HTTP_REFERER'])
else:
context = {
'team_form' : team_form,
'people_form' : people_form,
}
else:
people_form = PeopleForm()
team_form = TeamForm()
context = {
'people_form' : people_form,
'team_form' : team_form,
}
#context['people_groups'] = people_groups
return render(request, template_name, context)
<file_sep>/utils_app/forms.py
from django import forms
#from django.contrib.auth.forms import UserCreationForm
from django.core.validators import validate_email
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from utils_app.models import EmailContentBase, EmailedResume
class ResumeForm(ModelForm):
body = forms.CharField(widget=forms.Textarea(attrs = {'rows': '5'}))
class Meta:
model = EmailedResume
fields = ['recipients', 'subject', 'body',]
def clean_recipients(self):
recipients = self.cleaned_data['recipients']
print type(recipients)
if ',' not in recipients:
validate_email(recipients)
else:
recipients_list = recipients.split(',')
for recipient in recipients_list:
validate_email(recipient)
return recipients
TYPE_CHOICES = (
('INTERVIEWER', _('Interviewer')),
('RECRUITER', _('Recruiter')),
#('ADMIN', _('Administrator')),
)
class PeopleForm(forms.Form):
account_type = forms.ChoiceField(widget = forms.Select(), choices = TYPE_CHOICES,
initial = TYPE_CHOICES[0][0])
first_name = forms.CharField(_('First Name'))
last_name = forms.CharField(_('Last Name'))
email = forms.EmailField(_('Email'))
class TeamForm(forms.Form):
team_name = forms.CharField(_('Team'))
<file_sep>/gigs/templates/gigs/applier/related_jobs.html
{% load i18n mezzanine_tags %}
{% if related_jobs %}
<aside>
<div class="headline">
<h4>{% trans 'People Also viewed' %}</h4>
</div>
<ul class="media-list">
{% for job in related_jobs %}
<li class="media">
<a class="pull-left" href="#">
<img class="media-object" data-src="holder.js/64x64">
{% if job.company.twitter_username %}
<img class="media-object" src="http://twitter.com/api/users/profile_image/{{ job.company.twitter_username }}?size=bigger" width="27" height="27">
{% elif job.company.profile_picture_choice %}
<img class="media-object" src="{{ MEDIA_URL }}{% thumbnail request.user.company.profile_picture 25 25 %}">
{% endif %}
</a>
<div class="media-body">
<h5 class="media-heading">
<a href="{{ job.get_absolute_url }}">{{ job.title|capfirst }}</a></h5>
<p>{{ job.location }}</p>
</div>
</li>
{% endfor %}
</ul>
</aside>
{% endif %}<file_sep>/gigs/admin.py
from django.contrib import admin
from gigs.models import (Category, ChildStatus, Company, Gig,
GigSocial, GigType, JobSeekerProfile, SocialLinks)
from gigs.signals import gig_is_validated
class JobSeekerProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'twitter_username',)
class CategoryAdmin(admin.ModelAdmin):
list_display = ('title','pub_date',)
class GigTypeAdmin(admin.ModelAdmin):
list_display = ('type', 'description', 'price',)
class CompanyAdmin(admin.ModelAdmin):
list_display = ('title', 'email',)
class GigAdmin(admin.ModelAdmin):
list_display = ('title', 'job_type', 'site', 'valid', 'processed', 'by_us',)
def response_change(self, request, obj):
if obj.valid == True:
#send signal
gig_is_validated.send(sender = 'response_change', gig = obj)
return super(GigAdmin, self).response_change(request, obj)
class GigSocialAdmin(admin.ModelAdmin):
list_display = ('social_network', 'gig', 'link_to_post',)
class ChildStatusAdmin(admin.ModelAdmin):
list_display = ('name', 'date', 'user')
class SocialLinksAdmin(admin.ModelAdmin):
list_display = ('user', 'twitter_link', 'linkedin_link',
'facebook_link', 'github_link',)
admin.site.register(Category, CategoryAdmin)
admin.site.register(GigType, GigTypeAdmin)
admin.site.register(Company, CompanyAdmin)
admin.site.register(Gig, GigAdmin)
admin.site.register(GigSocial, GigSocialAdmin)
admin.site.register(ChildStatus, ChildStatusAdmin)
admin.site.register(JobSeekerProfile, JobSeekerProfileAdmin)
admin.site.register(SocialLinks, SocialLinksAdmin)
<file_sep>/contact/models.py
from django.db import models
from django.contrib.auth.models import User
class Contact(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField()
subject = models.CharField(max_length=255)
message = models.TextField()
user = models.ForeignKey(User, blank=True, null=True)
sent_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return '{0} : {1} by {2}'.format(self.email, self.subject, self.user)
<file_sep>/sitemaps.py
from django.contrib.sitemaps import Sitemap
from django.contrib.sites.models import Site
from django.db.models import get_model
from django.core import urlresolvers, paginator
from django.core.exceptions import ImproperlyConfigured
import urllib
from mezzanine.conf import settings
from mezzanine.core.models import Displayable
from mezzanine.utils.sites import current_site_id
from mezzanine.utils.urls import home_slug
from gigs.models import Gig, Company
#from planet.models import Feed, Post
blog_installed = "mezzanine.blog" in settings.INSTALLED_APPS
if blog_installed:
from mezzanine.blog.models import BlogPost
class CustomSitemap(object):
# This limit is defined by Google. See the index documentation at
# http://sitemaps.org/protocol.php#index.
limit = 50000
# If protocol is None, the URLs in the sitemap will use the protocol
# with which the sitemap was requested.
protocol = None
def __get(self, name, obj, default=None):
try:
attr = getattr(self, name)
except AttributeError:
return default
if callable(attr):
return attr(obj)
return attr
def items(self):
return []
def location(self, obj):
return obj.get_absolute_url()
def _get_paginator(self):
return paginator.Paginator(self.items(), self.limit)
paginator = property(_get_paginator)
def get_urls(self, page=1, site=None, protocol=None):
# Determine protocol
if self.protocol is not None:
protocol = self.protocol
if protocol is None:
protocol = 'http'
# Determine domain
site=Site.objects.get(id=current_site_id())
#if site is None:
# if Site._meta.installed:
# try:
# site = Site.objects.get_current()
# except Site.DoesNotExist:
# pass
# if site is None:
# raise ImproperlyConfigured("To use sitemaps, either enable the sites framework or pass a Site/RequestSite object in your view.")
domain = site.domain
urls = []
for item in self.paginator.page(page).object_list:
loc = "%s://%s%s" % (protocol, domain, self.__get('location', item))
priority = self.__get('priority', item, None)
url_info = {
'item': item,
'location': loc,
'lastmod': self.__get('lastmod', item, None),
'changefreq': self.__get('changefreq', item, None),
'priority': str(priority is not None and priority or ''),
}
urls.append(url_info)
return urls
class JobSitemap(CustomSitemap):
priority = 1
changefreq = 'hourly'
def items(self):
return Gig.objects.filter(site=current_site_id()).\
filter(valid=True).order_by('-publish_date')
def lastmod(self, obj):
return obj.publish_date
class CompanySitemap(CustomSitemap):
priority = 1
changefreq = 'hourly'
def items(self):
return Company.objects.filter(site=current_site_id()).\
filter(valid=True).order_by('-publish_date')
def lastmod(self, obj):
return obj.publish_date
#class CommunitySitemap(CustomSitemap):
# priority = 1
# changefreq = 'hourly'
# def items(self):
# feeds = Feed.objects.filter(site=current_site_id())
# posts_ids = [ post.id for feed in feeds for post in feed.post_set.all()]
# return Post.objects.filter(id__in=posts_ids).order_by('-date_created')
# def lastmod(self, obj):
# return obj.date_created
class BlogSitemap(CustomSitemap):
priority = 1
changefreq = 'daily'
def items(self):
return BlogPost.objects.filter(site=current_site_id())
def lastmod(self, obj):
return obj.publish_date
SITEMAP_MODELS = [
'pages.models.Page',
'pages.models.RichTextPage',
'pages.models.Link',
]
class CustomDisplayableSitemap(Sitemap):
"""
Sitemap class for Django's sitemaps framework that returns
all published items for models that subclass ``Displayable``.
"""
priority = 1
changefreq = 'hourly'
def items(self):
"""
Return all published items for models that subclass
``Displayable``, excluding those that point to external sites.
"""
# Fake homepage object.
home = Displayable()
setattr(home, "get_absolute_url", home_slug)
items = {home.get_absolute_url(): home}
for path in SITEMAP_MODELS:
model = get_model(app_label = path.split('.')[0], model_name = path.split('.')[-1])
for item in (model.objects.published().filter(in_sitemap=True)
.exclude(slug__startswith="http://")
.exclude(slug__startswith="https://")):
items[item.get_absolute_url()] = item
return items.values()
def lastmod(self, obj):
return obj.publish_date
def get_urls(self, **kwargs):
"""
Ensure the correct host by injecting the current site.
"""
kwargs["site"] = Site.objects.get(id=current_site_id())
return super(CustomDisplayableSitemap, self).get_urls(**kwargs)
<file_sep>/gigs/models.py
import moneyed
from django.contrib.auth.models import User
from django.contrib.contenttypes import generic
from django.contrib.sites.models import Site
from django.core.validators import RegexValidator
from django.db import models
from django.db.models.signals import post_save
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
import settings
from cartridge.shop.models import Product, OrderItem
from mezzanine.core.managers import DisplayableManager
from mezzanine.core.models import Slugged, Displayable, Ownable, RichText
from mezzanine.core.fields import FileField, RichTextField
from mezzanine.generic.fields import CommentsField, RatingField
from mezzanine.utils.models import upload_to
from mezzanine.utils.timezone import now
from django_messages.models import Message
from djmoney.models.fields import MoneyField
from feedb.models import Feedback
from stats.utils import get_metricitem_set
def get_app_mother(message):
""" returns the mother app if any """
print message.id, message.body
if message.parent_msg == None:
print message.id, message.body
return message
get_app_mother(message.parent_msg)
class Resume(models.Model):
file = models.FileField(upload_to = 'resumes')
user = models.ForeignKey(User)
created_at = now()
is_enabled = models.BooleanField(default = True)
def __unicode__(self):
return ('{0} {1} {2}').format(self.file, self.user, self.created_at)
def get_filename(self):
return self.file.file.name.split('/')[-1].capitalize()
class ChildStatus(models.Model):
STATUS_CHOICES = (
('NEW', _('New')),
('Active Statuses', (
('REVIEWED', _('Reviewed')),
('PHONE_SCREENED', _('Phone Screened')),
('INTERVIEW_SCHEDULED', _('Interview Scheduled')),
('INTERVIEWED', _('Interviewed')),
('PUT_ON_HOLD', _('Put on Hold')),
('MADE_OFFER', _('Made Offer')),
)
),
('Hired Statuses', (
('HIRED_FULL_TIME', _('Hired Full-Time')),
('CONTRACTED', _('Contracted')),
)
),
('Not Hired Statuses', (
('NOT_A_FIT', _('Not a fit')),
('NOT_QUALIFIED', _('Not Qualified')),
('OVER_QUALIFIED', _('Over Qualified')),
)
),
)
name = models.CharField(max_length = 15, choices = STATUS_CHOICES, default = STATUS_CHOICES[0][0])
#parent_status = models.ForeignKey(ParentStatus)
date = now()
user = models.ForeignKey(User)
def __unicode__(self):
return '{0} > {1} by {2}'.format(self.name, self.date, self.user)
class Note(Displayable, Ownable, RichText):
""" Notes related to a particular application"""
application = models.ForeignKey('Application')
def __unicode__(self):
return '%s %s %s' % (self.user, self.application, self.publish_date)
class Application(Message):
"""Reprsents an application from an applier regarding a gig """
#message = models.OneToOneField(Message)
gig = models.ForeignKey('Gig', null = True, blank = True)
favorited_at = models.DateTimeField(null = True, blank = True)
rejected_at = models.DateTimeField(null = True, blank = True)
printed_at = models.DateTimeField(null = True, blank = True)
resume = models.ForeignKey(Resume)
status = models.ManyToManyField(ChildStatus)
feedbacks = generic.GenericRelation(Feedback)
is_read_by_sender = models.NullBooleanField(default=False)
#def __unicode__(self):
# return "{0} {1} {2}".format(self.sender, self.recipient, self.resume)
@models.permalink
def get_absolute_url(self):
url_name = 'application_detail'
#mother_app = get_app_mother(self)
#print mother_app
kwargs = {"message_id" : self.id}
return (url_name, (), kwargs)
def is_application(self):
if self.__class__.__name__ == 'Application':
return True
def get_mother_app(self, **kwargs):
if self.parent_msg is None:
return self
self.get_mother_app(**kwargs)
@property
def get_resume(self):
return self.resume.file
@property
def get_resume_name(self):
return self.resume.file.name.split('/')[1]
@property
def get_status(self):
"""return the last status of the app if any"""
return self.status.select_related()[0].name
@property
def rated_feedbacks(self):
"""
returns the rated feedbacks
"""
feedbacks = self.feedbacks.all()
if feedbacks:
return [ f.rating for f in feedbacks if f.rating is not None]
@property
def average_rating(self):
"""
returns the average of feedbacks_rating
"""
feedbacks_ratings = self.rated_feedbacks
if feedbacks_ratings:
return round(sum(feedbacks_ratings) / len(feedbacks_ratings), 2)
@property
def last_status(self):
"""returns the application status if any """
if self.status:
return self.status.latest('id')
@property
def notes(self):
if self.note_set.all():
return self.note_set.all().order_by('-publish_date')
def inbox_count_for(user):
"""
returns the number of unread messages for the given user but does not
mark them seen and the message IS NOT an application
"""
return Message.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True, application__isnull=True).count()
class Category(models.Model):
"""
Job Category
"""
title = models.CharField(max_length=250)
pub_date = models.DateTimeField(auto_now_add = True)
description = models.CharField(max_length = 50, null = True, blank = True)
is_custom = models.BooleanField()
on_site = models.ForeignKey(Site)
order = models.IntegerField(null=True, blank=True)
class Meta:
verbose_name = _("Job Category")
verbose_name_plural = _("Categories")
def __unicode__(self):
return ("%s") % (self.title)
@models.permalink
def get_absolute_url(self):
return ('gigs_list_category',(),{'slug':self.slug})
@property
def description_list(self):
return self.description.split(',')
COMPANY_LOGO_DEFAULT = getattr(settings, 'COMPANY_LOGO_DEFAULT',
'company_logos/.thumbnails/employer_default.png')
APPLIER_PICTURE_DEFAULT = getattr(settings, 'APPLIER_PICTURE_DEFAULT',
'job_seekers_pictures/.thumbnails/job_seeker_picture.png')
class Company(Displayable):
"""
Company Model
"""
COMPANY_TYPES = (
('STARTUP', "Startup"),
('STUDIO', "Studio"),
('SMALL_BUSINESS', "Small Business"),
('MID_SIZED_BUSINESS', "Mid Sized Business"),
('LARGE_ORGANIZATION', "Large Organization"),
('EDUCATIONAL_INSTITUTION', "Educational Institution"),
('NON_PROFIT', "Non-profit"),
)
PROFILE_PICTURE_SOURCE = (
('NO_PICTURE', _('No picture')),
('TWITTER_PICTURE', _('Use Twitter profile picture (recommended)')),
('OWN_PICTURE', _('Upload a picture')),
)
company_name = models.CharField(_('Company name'), max_length = 500)
#type = models.CharField(max_length = 200, choices = COMPANY_TYPES,
# verbose_name = _('Company type'))
title_is_confidential = models.NullBooleanField(verbose_name = _("Company name is Confidential?"))
url = models.URLField(verbose_name = _("Company URL"), null=True, blank=True)
email = models.EmailField()
# figure out upload_to function and its 2 arguments
profile_picture_choice = models.CharField(max_length = 60,
choices = PROFILE_PICTURE_SOURCE, default = PROFILE_PICTURE_SOURCE[0][1])
profile_picture = models.ImageField(verbose_name= _('Profile Picture'),
upload_to = 'company_logos', max_length=255,
null = True, blank = True, default = COMPANY_LOGO_DEFAULT)
twitter_username = models.CharField(max_length = 50, null= True, blank = True)
valid = models.BooleanField(default = False)
ip_address = models.GenericIPAddressField()
user = models.OneToOneField(User)
### Profile fields
# description field is part of Displayable
about_the_company = models.TextField(blank=True, null=True,
verbose_name=_('About the Company'))
elevator_pitch = models.TextField(blank=True, null=True,
verbose_name = _("Elevator pitch"),
help_text=_("What s your company about (i.e. tag line)"))
#founded = models.PositiveIntegerField(blank=True, null=True, default=1970)
size = models.PositiveIntegerField(blank=True, null=True,
help_text=_('Number of Employees'))
# profile background picture
# Benefits
# Location
# Social services (Any user can social services/contacts, either a company or
# a JobSeeker)
# Picture Gallery
# Video Gallery
###
class Meta:
verbose_name_plural = _("Companies")
def save(self, *args, **kwargs):
if 'force_update' in kwargs.keys():
print 'update force %s ' % kwargs['force_update']
company_password = User.objects.make_random_password()
print 'company password : %s' % company_password
if 'force_update' not in kwargs.keys():
#User.objects.get_or_create(username = self.email, email = self.email,
# password = <PASSWORD>)
#self.user = User.objects.get_or_create(username = self.email, email = self.email,
# password = <PASSWORD>)
self.user = User.objects.create_user(username = self.email, email = self.email,
password = <PASSWORD>)
if self.profile_picture_choice == 'NO_PICTURE':
self.profile_picture = COMPANY_LOGO_DEFAULT
print 'profile picture : %s' % self.profile_picture_choice
super(Company, self).save(*args, **kwargs)
return company_password
def __unicode__(self):
return ("{0} {1} {2} {3}").format(self.company_name, self.email, self.url, self.profile_picture)
@models.permalink
def get_absolute_url(self):
url_name = 'company_profile'
kwargs = {"slug" : self.slug}
return (url_name, (), kwargs)
def number_posted_gigs(self):
return self.gig_set.count()
def company_gigs(self):
return self.gig_set.all().order_by('-publish_date')
def gigs(self):
return self.gig_set.all()
@property
def get_keywords(self):
return ','.join(self.gigs()[0].get_tags())
class SocialLinks(models.Model):
twitter_link = models.URLField(blank=True,null=True,
default='http://www.twitter.com/<login>',
help_text=_("Your twitter username"))
linkedin_link = models.URLField(blank=True,null=True,
default='http://www.linkedin.com/<login>')
facebook_link = models.URLField(blank=True,null=True,
default='http://www.facebook.com/<login>')
github_link = models.URLField(blank=True,null=True,
default='http://www.github.com/<login>',
help_text=_('Your Github username'))
user = models.OneToOneField(User)
def __unicode__(self):
return ('[%s - %s - %s]') % \
(self.twitter_link, self.linkedin_link, self.github_link)
class JobSeekerProfile(Displayable):
PROFILE_PICTURE_SOURCE = (
('NO_PICTURE', _('No picture')),
('TWITTER_PICTURE', _('Use Twitter profile picture (recommended)')),
('OWN_PICTURE', _('Upload a picture')),
)
profile_picture_choice = models.CharField(max_length = 60,
choices = PROFILE_PICTURE_SOURCE, default = PROFILE_PICTURE_SOURCE[0][1])
profile_picture = models.ImageField(verbose_name= _('Profile Picture'),
upload_to = 'applier_pictures', max_length=255,
null = True, blank = True, default = APPLIER_PICTURE_DEFAULT)
twitter_username = models.CharField(max_length = 50, null= True, blank = True)
ip_address = models.GenericIPAddressField()
location = models.CharField(max_length = 200, null=True, blank=True,
verbose_name = _("Location"),
help_text=_("Examples: San Francisco, CA; Seattle; Anywhere"))
latitude = models.CharField(max_length = 25, null = True, blank = True)
longitude = models.CharField(max_length = 25, null = True, blank = True)
area_level1 = models.CharField(max_length = 20, blank = True, null = True)
area_level2 = models.CharField(max_length = 20, blank = True, null = True)
area_level3 = models.CharField(max_length = 20, blank = True, null = True)
area_level4 = models.CharField(max_length = 20, blank = True, null = True)
# resume : an applier can have one or more resumes
#resume = models.FileField(verbose_name=_("Resume"), blank=True,
# upload_to=upload_to("gigs.Applier.resume", "resumes"), help_text=_("Upload your resume"))
is_relocation = models.NullBooleanField(verbose_name = _("Ready to relocate"), null = True, blank = True, default = True)
is_looking = models.NullBooleanField(null = True, blank = True, default = True)
#phone_number refers to https://github.com/daviddrysdale/python-phonenumbers
#about_me = description
# experience, education many to many field
# social networks Foreign Key
user = models.OneToOneField(User)
# Profile meta
# title comes from Displayable
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format:'+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=15, blank=True,
help_text=_("hello there"))
about = models.TextField(blank=True, null=True,
help_text=_("Describe your title, experience, skills and what you are looking for"),
verbose_name='About me')
# linkedin like fields
is_linkedin = models.NullBooleanField(default=False)
linkedin_profile_picture = models.URLField(null=True, blank=True)
skills = models.CharField(max_length=255)
def __unicode__(self):
return '%s - %s' % (self.user, self.user.email)
class GigType(models.Model):
"""
Gig Type
"""
type = models.CharField(max_length = 20)
description = models.CharField(max_length = 200)
price = MoneyField(max_digits=10, decimal_places=2, default_currency='USD')
on_site = models.ForeignKey(Site)
def __unicode__(self):
return ("%s %s") % (self.type, self.price)
class Gig(Product):
"""
Gig Model
Gig(job_type, location, latitude, longitude, is_relocation, is_onsite, descr,
perks, how_to_apply, via_email, via_url. apply_instructions, is_filled,
categories, company)
"""
HOW_TO_APPLY_CHOICES = (
('VIA_EMAIL','by Email'),
('VIA_URL', 'via URL'),
)
job_type = models.ForeignKey('GigType', verbose_name = _('Job Type'))
valid = models.BooleanField(default = False, help_text='Check if the Job is not Spam')
by_us = models.BooleanField(default=False,
help_text = _('Check If the Job is posted by us'))
processed = models.NullBooleanField(default = False,
help_text='Check if the Company payed the fee')
location = models.CharField(max_length = 200, verbose_name = _('Job Location'),
help_text=_("Examples: San Francisco, CA; Seattle; Anywhere"))
latitude = models.CharField(max_length = 25)
longitude = models.CharField(max_length = 25)
area_level1 = models.CharField(max_length = 25, blank = True, null = True)
area_level2 = models.CharField(max_length = 25, blank = True, null = True)
area_level3 = models.CharField(max_length = 25, blank = True, null = True)
area_level4 = models.CharField(max_length = 25, blank = True, null = True)
is_relocation = models.BooleanField(verbose_name = _("Relocation assistance offered\
for this opposition"))
is_remote = models.BooleanField(verbose_name = _("Work can be done from anywhere \
(i.e. telecommuting)"))
perks = models.TextField(verbose_name = _("Job Perks"), blank = True,
null = True, help_text = _("Sell your position! If you're willing \
to relocate, mention it here. If you've got great benefits, bonuses\
, paid trips to conferences, free food, discounts, etc., talk it up."))
how_to_apply = models.CharField(max_length = 15, choices = HOW_TO_APPLY_CHOICES,
default = HOW_TO_APPLY_CHOICES[0][0], verbose_name = _('How to apply'))
tags = models.CharField(max_length = 100, null = True, blank = True)
hidden_tags = models.CharField(max_length = 100, null = True, blank = True)
via_email = models.EmailField(blank = True, null = True)
via_url = models.URLField(blank = True, null = True)
apply_instructions = models.TextField(null = True, blank = True,
verbose_name = _('Add instructions(optional)'))
is_filled = models.BooleanField(verbose_name = _("Filled"))
gig_categories = models.ManyToManyField('Category')
company = models.ForeignKey('Company')
product = models.OneToOneField(Product)
on_site = models.ManyToManyField(Site)
class Meta:
verbose_name = "Gig"
verbose_name_plural = "Jobs"
def __unicode__(self):
return '[%s] %s %s, %s' % (self.company, self.title, self.status, self.publish_date)
@models.permalink
def get_absolute_url(self):
url_name = 'get_gig'
kwargs = {"slug" : self.slug}
return (url_name, (), kwargs)
def is_processed(self):
try:
status = True if OrderItem.objects.filter(sku = self.product.variations.all()[0].sku)[0].order.status == 2 else False
return status
except IndexError:
return False
def applications(self):
return self.application_set.filter(gig__isnull= False)
def num_applications(self):
return self.application_set.count()
def get_tags(self):
return self.hidden_tags.split(',') if self.hidden_tags else False
def num_views(self):
return get_metricitem_set(obj=self,metric_name='num_views',
excluded_owner=self.company.user).count()
def top_referrers(self):
referrers_data = get_metricitem_set(obj=self, metric_name='num_views',
excluded_owner=self.company.user).values('referrer').annotate(models.Count('referrer'))\
.order_by('-referrer__count')
return [ (i['referrer'].replace('https://','').replace('http://','') , i['referrer__count']) for i in referrers_data][:10]
def num_views_per_day(self):
num_views_per_day = get_metricitem_set(obj=self,metric_name='num_views',
excluded_owner=self.company.user).values('publish_date')\
.annotate(models.Count('publish_date'))
return [ (i['publish_date__count'],i['publish_date']) for i in num_views_per_day if i['publish_date'] is not None][:30]
@property
def social_posts(self):
return self.gigsocial_set.all()
class GigSocial(models.Model):
SOCIAL_NETWORK_CHOICES = (
('FACEBOOK', 'Facebook',),
('TWITTER', 'Twitter',),
('LINKEDIN', 'LinkedIn',),
)
social_network = models.CharField(max_length=200, choices=SOCIAL_NETWORK_CHOICES)
link_to_post = models.URLField(blank=True, null=True)
code_to_embed = models.TextField()
gig = models.ForeignKey(Gig)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return '%s' % self.social_network
class GigStat(models.Model):
"""
Stats about a given Gig
"""
views = models.IntegerField(verbose_name = _("Number of Views"))
clicked_apply = models.IntegerField(verbose_name = _("Clicked Apply"))
notified_users = models.IntegerField(verbose_name = _("Notified Users"))
class Meta:
verbose_name = 'Job Stats'
<file_sep>/fts/tests.py
from django.test import LiveServerTestCase
from selenium import webdriver
class NavigateTestCase(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def _navigate_to_homepage(self):
self.browser.get(self.live_server_url)
body = self.browser.find_element_by_tag_name('body')
return body
class GigTest(NavigateTestCase):
def test_post_a_job(self):
#navigate to post_job
body = self.browser.get(self.live_server_url + '/post_job')
#user fill out the form and preview it
body = self.browser.find_element_by_tag_name('body')
self.assertIn('Create Your Job Listing', body.text)
# select a job type
#type_chosen = self.browser.find_element_by_css_selector(
# "input[value='1']"
#)
#type_chosen.click()
# select a job category
category_chosen = self.browser.find_elements_by_css_selector(
"option[value='1']"
)
category_chosen.click()
# fill out the title
title = self.browser.find_element_by_id("id_title")
<file_sep>/marketing/models.py
from django.db import models
from django.contrib.sites.models import Site
class PreLaunch(models.Model):
"""
Model for email collection before site prelaunch
"""
email = models.EmailField()
publish_date = models.DateTimeField(auto_now_add=True)
site = models.ForeignKey(Site)
def __unicode__(self):
return self.email, self.publish_date, self.site
<file_sep>/gigs/templates/gigs/includes/sell_point.html
{% load i18n %}
<h3>{{ settings.SITE_TAGLINE }}</h3>
<p><img class="pull-right" src="{{ STATIC_URL }}images/satisfaction-guaranteed.png" alt="{{ settings.SITE_TITLE }} satisfaction guaranteed" />{{ settings.SITE_TITLE }}{% blocktrans %} <span class="muted">is where companies and creative professionals meet to make a better web. Since 2010, qualified candidates have been applying for great opportunities at Apple, Facebook, ESPN, Sony, The New York Times, and many other companies big and small.</span> {% endblocktrans %}</p>
<p class="text-right">
<a href="/about/" class="btn btn-u btn-sm">{% trans 'Learn more' %} <i class="icon-circle-arrow-right icon-white"></i></a>
</p>
<file_sep>/gigs/utils.py
from django.http import HttpResponse
from django.utils import simplejson
from cartridge.shop.models import ProductVariation
def get_gig_info(request, sku):
"""
Returns gig object from sku
"""
gig = ProductVariation.objects.filter(sku = sku)[0].product.gig
response = simplejson.dumps({
'gig_type' : gig.job_type.type,
'gig_picture' : gig.company.twitter_username or gig.company.profile_picture.name,
'gig_twitter_username' : gig.company.twitter_username,
})
return HttpResponse(response, content_type='application/javascript')
<file_sep>/gigs/context_processors.py
from django.db.models import Min
from mezzanine.utils.sites import current_site_id
from gigs.models import inbox_count_for, GigType
from gigs.utils.views import application_count_for, read_applications, unread_applications
def inbox(request):
if request.user.is_authenticated():
return {
'messages_inbox_count': inbox_count_for(request.user),
'applications_inbox_count' : application_count_for(request.user),
'unread_applications' : unread_applications(request.user),
'read_applications' : read_applications(request.user),
}
else:
return {}
def whole_site(request):
site_id = current_site_id()
context = {
'starting_price':GigType.objects.filter(on_site=site_id).aggregate(Min('price'))['price__min'],
}
return context
<file_sep>/gigs/views.py
from operator import __or__ as OR
from django.contrib.auth.models import User, Group
from django.contrib.auth import authenticate, login
from django.contrib.messages import info
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.db.models.signals import post_save
from django.db.models import Min, Q
from django.dispatch import receiver
from django.http import Http404
from django.shortcuts import HttpResponse, get_object_or_404, render_to_response, redirect
from django.template import Context, RequestContext, loader
from django.utils import simplejson
from django.utils.translation import ugettext_lazy as _
from cartridge.shop.forms import AddProductForm
from cartridge.shop.models import (Cart, CartItem, Product,
ProductImage, ProductVariation)
from cartridge.shop.views import cart, product as product_view
from mezzanine.accounts import get_profile_form
from mezzanine.conf import settings
from mezzanine.utils.views import paginate, render
from mezzanine.utils.sites import current_site_id
from mezzanine.utils.timezone import now
from mezzanine.utils.urls import slugify
from django_messages.models import Message
from notification.models import NoticeSetting
import twitter
from gigs.forms import (ApplicationStatusForm, ApplyForm, ChildStatus,
CompanyForm, PostJobForm, ProfileForm2, ProfilePictureForm, ReplyForm,
CompanyProfileForm, SocialLinksForm, JobseekerProfileForm)
from gigs.models import Category, Gig, GigType, Application, \
JobSeekerProfile, Note, Resume, SocialLinks
from gigs.signals import (user_added_to_group, gig_is_validated,
company_posted_job, user_apply, gig_is_visited, company_read_application)
from utils_app.tasks import notification_send_now_task
from gigs.utils.views import application_messages
from searchapp.forms import GigSearchForm
from searchapp.search import store, get_results
from stats.models import Metric, MetricItem
from stats.utils import save_metric_item
from utils_app.forms import ResumeForm
from utils_app.views import unslugify
if "notification" in settings.INSTALLED_APPS:
from notification import models as notification
else:
notification = None
def all_gigs(request, template_name = 'gigs/index.html'):
"""
Returns gigs on the home page
"""
# gigs need to be filtred based on order processed
# based on site_id,etc by creating a models.Manager
settings.use_editable()
site_id = current_site_id()
related_sites = settings.RELATED_SITE[ site_id - 1]
# If site is not active
if not settings.SITE_IS_ACTIVE:
template_name = 'gigs/not_active_index.html'
context = {
'site_id' : current_site_id(),
}
return render(request, template_name, context)
# search form
gig_search_form = GigSearchForm()
categories = Category.objects.all().filter(on_site=site_id)
# for search and filtering
gig_types = GigType.objects.filter(on_site=site_id)
results = []
#starting_price = GigType.get_starting_price()
starting_price = GigType.objects.all().aggregate(Min('price'))['price__min']
if request.method == 'GET':
#print 'call Get Method'
#print [Q(on_site__id=related_site_id) for related_site_id in related_sites]
search_include_tag = settings.SITE_SEARCH_INCLUDE_TAG
if related_sites is not None:
Q_related_site_ids = [ Q(on_site__id=related_site_id) for related_site_id in related_sites]
Q_related_site_ids.append(Q(site_id=site_id))
results = Gig.objects.filter(reduce(OR, Q_related_site_ids))
results = results.distinct().filter(valid = True).order_by('-publish_date')
else:
results = Gig.objects.filter(site_id=site_id).filter(valid = True).order_by('-publish_date')
#results = results.filter(Q(location__icontains=search_include_tag)|
# Q(area_level2__iexact=search_include_tag)|
# Q(area_level3__iexact=search_include_tag))
#results = Gig.objects.filter(valid=True)
#if related_sites is not None:
# for related_site in related_sites:
# results.filter(site_id=related_site)
#results.filter
gigs = paginate(results, request.GET.get("page", 1),
settings.GIGS_PER_PAGE,
settings.MAX_PAGING_LINKS)
context = {
'gigs' : gigs,
'categories' : categories,
'gig_types' : gig_types,
'starting_price' : starting_price,
'gig_search_form' : gig_search_form,
}
return render(request, template_name, context)
elif request.method == 'POST' and gig_search_form.is_valid():
print 'call POST Method'
what = gig_search_form.cleaned_data['what']
location = gig_search_form.cleaned_data['location']
gig_types_list = [ gig_type.id for gig_type in gig_types if str(gig_type.id) not in gig_types_string]
results = get_results(what, location, request.GET.get("page", 1), gig_types_list)
print 'all_gigs %s jobs ' % len(results)
#results = get_results(what, location, page, gig_types)
gigs = paginate(results, request.GET.get("page", 1),
settings.GIGS_PER_PAGE,
settings.MAX_PAGING_LINKS)
context = {
'gigs' : gigs,
'categories' : categories,
'gig_types' : gig_types,
'starting_price' : starting_price,
'gig_search_form' : gig_search_form,
}
return render(request, template_name, context)
def all_gigs_long(request, searchincludetag=None, template_name = 'gigs/index_long.html'):
"""
Returns gigs on the home page
"""
# gigs need to be filtred based on order processed
# based on site_id,etc by creating a models.Manager
if searchincludetag is None:
searchincludetag = settings.SITE_SEARCH_INCLUDE_TAG
settings.use_editable()
site_id = current_site_id()
related_sites = settings.RELATED_SITE[ site_id - 1]
# If site is not active
if not settings.SITE_IS_ACTIVE:
template_name = 'gigs/not_active_index.html'
context = {
'site_id' : current_site_id(),
}
return render(request, template_name, context)
# search form
gig_search_form = GigSearchForm()
categories = Category.objects.all().filter(on_site=site_id)
# for search and filtering
gig_types = GigType.objects.filter(on_site=site_id)
results = []
#starting_price = GigType.get_starting_price()
starting_price = GigType.objects.all().aggregate(Min('price'))['price__min']
if request.method == 'GET':
#print 'call Get Method'
#print [Q(on_site__id=related_site_id) for related_site_id in related_sites]
search_include_tag = settings.SITE_SEARCH_INCLUDE_TAG
if related_sites is not None:
Q_related_site_ids = [ Q(on_site__id=related_site_id) for related_site_id in related_sites]
Q_related_site_ids.append(Q(site_id=site_id))
results = Gig.objects.filter(reduce(OR, Q_related_site_ids))
results = results.distinct().filter(valid = True).order_by('-publish_date')
else:
results = Gig.objects.filter(site_id=site_id).filter(valid = True).order_by('-publish_date')
#results = results.filter(Q(location__icontains=search_include_tag)|
# Q(area_level2__iexact=search_include_tag)|
# Q(area_level3__iexact=search_include_tag))
#results = Gig.objects.filter(valid=True)
#if related_sites is not None:
# for related_site in related_sites:
# results.filter(site_id=related_site)
#results.filter
gigs = paginate(results, request.GET.get("page", 1),
settings.GIGS_PER_PAGE,
settings.MAX_PAGING_LINKS)
context = {
'gigs' : gigs,
'searchincludetag' : searchincludetag,
'categories' : categories,
'gig_types' : gig_types,
'starting_price' : starting_price,
'gig_search_form' : gig_search_form,
}
return render(request, template_name, context)
elif request.method == 'POST' and gig_search_form.is_valid():
print 'call POST Method'
what = gig_search_form.cleaned_data['what']
location = gig_search_form.cleaned_data['location']
gig_types_list = [ gig_type.id for gig_type in gig_types if str(gig_type.id) not in gig_types_string]
results = get_results(what, location, request.GET.get("page", 1), gig_types_list)
print 'all_gigs %s jobs ' % len(results)
#results = get_results(what, location, page, gig_types)
gigs = paginate(results, request.GET.get("page", 1),
settings.GIGS_PER_PAGE,
settings.MAX_PAGING_LINKS)
context = {
'gigs' : gigs,
'categories' : categories,
'gig_types' : gig_types,
'starting_price' : starting_price,
'gig_search_form' : gig_search_form,
}
return render(request, template_name, context)
def all_gigs_tag(request, tag=None, location=None, template_name='gigs/index.html'):
"""returns gigs with the related tag"""
if tag is not None:
tag = unslugify(tag)
site_id = current_site_id()
related_sites = settings.RELATED_SITE[ site_id - 1]
# search form
gig_search_form = GigSearchForm()
categories = Category.objects.all().filter(on_site=site_id)
# for search and filtering
gig_types = GigType.objects.filter(on_site=site_id)
results = []
#starting_price = GigType.get_starting_price()
starting_price = GigType.objects.all().aggregate(Min('price'))['price__min']
search_include_tag = settings.SITE_SEARCH_INCLUDE_TAG
if related_sites is not None:
Q_related_site_ids = [ Q(on_site__id=related_site_id) for related_site_id in related_sites]
Q_related_site_ids.append(Q(site_id=site_id))
results = Gig.objects.filter(reduce(OR, Q_related_site_ids))
results = results.distinct().filter(valid = True).order_by('-publish_date')
else:
results = Gig.objects.filter(site_id=site_id).filter(valid = True).order_by('-publish_date')
#results = results.filter(Q(location__icontains=search_include_tag)|
# Q(area_level2__iexact=search_include_tag)|
# Q(area_level3__iexact=search_include_tag))
#results = Gig.objects.filter(valid=True)
#if related_sites is not None:
# for related_site in related_sites:
# results.filter(site_id=related_site)
#results.filter
results = results.filter(Q(title__icontains=tag) | Q(hidden_tags__icontains=tag)
| Q(description__icontains=tag))
gigs = paginate(results, request.GET.get("page", 1),
settings.GIGS_PER_PAGE,
settings.MAX_PAGING_LINKS)
context = {
'gigs' : gigs,
'categories' : categories,
'gig_types' : gig_types,
'starting_price' : starting_price,
'gig_search_form' : gig_search_form,
'what':tag,
'SITE_META_TITLE' : _('%s Jobs') % (tag)
}
return render(request, template_name, context)
def get_gig(request, slug=None, template_name='gigs/get_gig.html'):
"""
Returns the Gig page
"""
try:
#print slug
site_id = current_site_id()
#related_site_id = settings.RELATED_SITE[site_id-1]
#related_site_id = 1
#print 'site_id :%s' %site_id
#print 'related_site_id :%s' % related_site_id
gigs = Gig.objects.filter(Q(site_id=site_id) | Q(on_site__id=site_id))
#print gigs
#print Gig.objects.filter(on_site__id=site_id)
#gig = Gig.objects.get(slug=slug, on_site=site_id)
gig = gigs.filter(slug=slug)[0]
#print gig
#print 'hello %s' % gig
#print gig.on_site.all()
#gig = get_object_or_404(Gig, slug=slug)
#print Gig.objects.filter(Q(site_id=site_id) | Q(on_site__id=site_id))
#gig = Gig.objects.filter(Q(site_id=site_id) | Q(on_site__id=site_id)).get(slug=slug)
#gig = Gig.objects.filter(on_site__id=site_id, site_id=site_id).get(slug=slug)
apply_form = ApplyForm()
signup_form = ProfileForm2()
if 'shop/product' in request.META['HTTP_REFERER']:
message = _('Your listing is published successfully. \
Please visit "%s" to track listing statistics, make edits, and more.') % gig.company.email
info(request, message)
# Send signal when gig is visited
gig_is_visited.send(sender = 'get_gig', obj=gig, referrer=request.META.get('HTTP_REFERER', ''),
user= request.user if request.user.is_authenticated() else None)
except Exception as e:
print e
context = {
'apply_form' : apply_form,
'gig' : gig,
'signup_form' : signup_form,
}
return render(request, template_name, context)
@receiver(gig_is_visited, sender='get_gig')
def save_gig_stats(sender, **kwargs):
""" Save gig stats """
save_metric_item(metric_name='num_views', **kwargs)
def edit_gig(request, slug = None, template_name = 'gigs/edit_gig.html'):
site_id = current_site_id()
gig = get_object_or_404(Gig, slug = slug)
post_job_form = PostJobForm(instance = gig)
company_form = CompanyForm(instance = gig.company)
gig_types = GigType.objects.filter(on_site=site_id)
categories = Category.objects.all().filter(site_id = site_id)
request.session['edit'] = True
if request.method == 'POST':
print 'request post'
company_form = CompanyForm(request.POST, request.FILES)
post_job_form = PostJobForm(request.POST)
if company_form.is_valid() and post_job_form.is_valid():
print 'company_form is valid'
company = company_form.get_company_object()
print company
company.slug = slugify(company.company_name)
company.ip_address = request.META['REMOTE_ADDR']
company.id = gig.company.id
company.site_id = site_id
company.user = gig.company.user
#print company_form.get_company_create_data()
#company, created = Company.objects.get_or_create(email = company.email)
#print company, company.id, created
#company.save()
company.save(force_update = True)
#if post_job_form.is_valid():
print 'post_job_form is valid'
print 'post_job_form %s' % post_job_form.get_gig_create_data()
#gig_variation = ProductVariation(product = gig, default = True,
# unit_price = gig.job_type.price.amount, sale_price = gig.job_type.price.amount)
#gig_variation.save()
#product_image = ProductImage(file = company.profile_picture, product = gig)
#product_image.save()
print gig.variations.all()
new_gig = post_job_form.get_gig_object()
new_gig.id = gig.id
new_gig.site_id = site_id
new_gig.company = company
new_gig.save()
print new_gig
#gig.save(post_job_form.get_gig_create_data())
#gig.save(**post_job_form.get_gig_create_data())
#new_gig = post_job_form.get_gig_object()
#new_gig.available = True
#new_gig.unit_price = 100
#print new_gig
#new_gig.company = company
#new_gig.image = company.profile_picture
#new_gig.id = gig.id
#new_gig.product = gig.product
#new_gig.save()
#return redirect('gigs/get_gig.html')
else:
print 'post_job_form is NOT valid'
context = {
'gig' : gig,
'post_job_form' : post_job_form,
'company_form' : company_form,
'gig_types' : gig_types,
'gig_categories' : categories,
}
return render(request, template_name, context)
if 'Preview your listing' == request.POST['submit']:
print 'preview'
return redirect("shop_product", slug = new_gig.slug)
context = {
'gig' : gig,
'post_job_form' : post_job_form,
'company_form' : company_form,
'gig_types' : gig_types,
'gig_categories' : categories,
}
return render(request, template_name, context)
def post_job(request, slug = None, template_name = 'gigs/post_job.html'):
"""
Post Job Form
"""
site_id = current_site_id()
#related_sites = settings.RELATED_SITE[ site_id - 1]
if request.method == 'POST':
post_job_form = PostJobForm(request.POST)
company_form = CompanyForm(request.POST, request.FILES)
#post_job_form_data = post_job_form.get_gig_create_data()
print company_form
if post_job_form.is_valid():
print 'forms are valid'
# save company first
if request.user.is_authenticated() and request.user.company:
company = request.user.company
else:
if company_form.is_valid():
print 'company form is valid'
company = company_form.get_company_object()
company.slug = slugify(company.company_name)
#print company.slug
company.ip_address = request.META['REMOTE_ADDR']
#company.profile_picture = company_form.cleaned_data['profile_picture']
#company.profile_picture = request.FILES.get('profile_picture', '')
#print 'profile picture: %s' % company.profile_picture
company_password = company.save()
# Add company to the group Company
company_group = Group.objects.get(name = 'Company')
company.user.groups.add(company_group)
# send a signal that a user is added to a group
user_added_to_group.send(sender = post_job.func_name,
user = company.user, group = 'Company', password = <PASSWORD>)
# authenticate company
#print company.user.username
#print company.user.password
user = authenticate(username=company.user.username, password=<PASSWORD>)
#print user
login(request, user)
# save gig
gig = post_job_form.get_gig_object()
gig.company = company
# categories
gig_categories = post_job_form.cleaned_data['gig_categories']
#print gig_categories
#print request.FILES['profile_picture']
if 'Previewing ...' == request.POST['submit']:
# GigType temp fix
#gig_type = request.POST['job_type']
#job_type = GigType.objects.get(id=gig_type)
#gig.job_type = job_type
# call view preview listing
#print 'preview'
request.session['company'] = company
request.session['gig'] = gig
request.session['gig_categories'] = gig_categories
#print request.session['gig_categories']
gig.available = True
gig.unit_price = 100
gig.image = company.profile_picture
# updating the status to draft (needs review)
#gig.status = 1
#print 'passed'
if gig.company.valid:
gig.valid = True
gig.save()
#print 'not passed'
#Add gig to related sites
#gig.on_site.add(Site.objects.get(id=site_id))
#for related_site_id in related_sites:
#print 'hey : %s' % related_site_id
# gig.on_site.add(Site.objects.get(id=related_site_id))
# send company_post_job signal to notify
company_posted_job.send(sender = 'post_job', gig = gig)
# adding categories
for category in gig_categories:
gig.gig_categories.add(category)
#sending the gig is validated signal
if gig.valid:
gig_is_validated.send(sender = 'post_job', gig = gig)
gig_variation = ProductVariation(product = gig, default = True,
unit_price = gig.job_type.price.amount, sale_price = gig.job_type.price.amount)
gig_variation.save()
#print 'product variation sku %s' % gig_variation.sku
product_image = ProductImage(file = company.profile_picture, product = gig)
product_image.save()
return redirect("shop_product", slug = gig.slug)
#template = 'gigs/gig_product.html'
#product_view(slug = gig.slug, template = template)
else:
if slug:
gig = get_object_or_404(Gig, slug = slug)
#print 'gig %s' % gig
post_job_form = PostJobForm(instance = gig)
company_form = CompanyForm(instance = gig.company)
else:
post_job_form = PostJobForm()
company_form = CompanyForm()
gig_types = GigType.objects.filter(on_site=site_id)
context = {
'gig_categories' : Category.objects.filter(on_site=site_id).order_by('order'),
'post_job_form': post_job_form, 'company_form': company_form,
'gig_types': gig_types,
'title': _('Create Your Job Listing'),
'company_information': _('Company Information'),
}
return render(request, template_name, context)
#from django.db.models.signals import post_save
from django.dispatch import receiver
#from mezzanine.utils.email import send_mail_template
from gigs.models import Company
#@receiver(post_save, sender = Company)
def welcome_company(sender, **kwargs):
print kwargs
subject = 'welcome'
addr_from = '<EMAIL>'
#addr_to = sender.email
addr_to = '<EMAIL>'
template = "email/comment_notification"
send_mail_template(subject, template, addr_from, addr_to, context=None,
attachments=None, fail_silently = settings.DEBUG)
def gig_product(request, slug, template_name = 'gigs/gig_product.html'):
product = request.session['product']
variations = product.variations.all()
initial = {}
add_product_form = AddProductForm(request.POST, product=product, to_cart = True)
if request.method == "POST":
if add_product_form.is_valid():
quantity = add_product_form.cleaned_data["quantity"]
request.cart.add_item(add_product_form.variation, quantity)
info(request, _("Item added to cart"))
return redirect("shop_cart")
context ={
'gig' : request.session['gig'],
'product' : product,
'variations' : variations,
'add_product_form' : add_product_form,
}
return render(request, template_name, context)
@login_required
def company_listings(request, template_name = 'gigs/company/company_listings.html'):
""" returns a list of gigs based on the logged in company """
context = {}
return render(request, template_name, context)
@login_required
def company_infos(request, template_name ='gigs/company/company_infos.html'):
""" handle the input of the company Information """
if request.method == 'POST':
company_form = CompanyForm(request.POST, request.FILES)
if company_form.is_valid():
company = company_form.get_company_object()
company.save()
else:
company_form = CompanyForm(instance = request.user.company)
context = {
'company_form' : company_form,
}
return render(request, template_name, context)
def company_profile(request, slug, template_name = 'gigs/company/company_profile.html'):
""" returns the public company profile """
company = get_object_or_404(Company, slug = slug)
#print slug
#company = Company.objects.get(slug=slug)
context = {'company' : company,
'hey' : True }
return render(request, template_name, context)
@login_required
def view_listing(request, slug, template_name = 'gigs/company/view_listing.html'):
gig = get_object_or_404(Gig, slug = slug)
context = {
'gig' : gig,
}
return render(request, template_name, context)
#Applier
@login_required
def applier_applications(request, template_name = 'gigs/applier/applier_applications.html'):
""" returns a list of applications related to an applier """
applications = Application.objects.filter(sender = request.user).filter(gig__isnull = False)
context = {
'applications' : applications,
}
return render(request, template_name, context)
def apply(request, gig_slug, template_name = 'gigs/apply.html'):
""" handle applying to an application """
gig = get_object_or_404(Gig, slug = gig_slug)
if request.method == 'POST':
signup_form = ProfileForm2(request.POST)
apply_form = ApplyForm(request.POST, request.FILES)
if request.user.is_authenticated():
#if apply_form.is_valid():
user = request.user
#apply_form.save()
application = Application()
application.subject = gig.title
application.sender = user
application.recipient = gig.company.user
application.gig = gig
try:
apply_form.fields['motivation'].clean(request.POST.get('motivation'))
except:
print 'error'
context = {
'signup_form' : signup_form,
'apply_form': apply_form,
'gig' : gig,
}
return render(request, template_name, context)
application.body = request.POST.get('motivation')
print 'select_resume: %s' % request.POST.get('select_resume')
print request.FILES.get('resume')
# upload file
if request.FILES.get('resume'):
print 'resume'
if not apply_form.fields['resume']:
apply_form.clean_resume()
return redirect(gig.get_absolute_url())
resume = Resume(file = request.FILES['resume'], user = user)
resume.save()
application.resume = resume
else:
resume_id = request.POST.get('select_resume')
resume = Resume.objects.get( pk = resume_id)
print resume
print 'here %s' % resume
application.resume = resume
application.save()
user_apply.send(sender = apply.func_name,
user = user, gig = application.gig,
application=application, label='applications_received')
#notification.send([application.sender], "notify_applicant", {'message': message,})
#print application
message = _('<strong>You applied successfully. View your <a href="%s">Application</a></strong>' % application.get_absolute_url() )
info(request, message, extra_tags='success')
user_apply.send(sender = apply.func_name,
user = application.recipient, gig = application.gig,
application=application, label='applications_received')
#if notification:
# notification.send([application.recipient], "applications_received", {'message': message,})
return redirect(gig.get_absolute_url())
else:
if signup_form.is_valid() and apply_form.is_valid():
print 'both forms are valid'
user, password = signup_form.save()
# save a user profile
job_seeker_profile = JobSeekerProfile(user=user, ip_address=request.META['REMOTE_ADDR'])
job_seeker_profile.save()
# send signal user_added_to_group
user_added_to_group.send(sender = apply.func_name,
user = user, group = 'JobSeeker', password = <PASSWORD>)
application = Application()
application.subject = gig.title
application.sender = user
application.recipient = gig.company.user
application.gig = gig
application.body = apply_form.cleaned_data['motivation']
# upload file
resume = Resume(file = request.FILES['resume'], user = user)
resume.save()
application.resume = resume
application.save()
# send signal user_apply, when user apply to a new gig
user_apply.send(sender = apply.func_name,
application=application, user = user, gig = application.gig, label='user_apply')
user = authenticate(username = user.username,
password = <PASSWORD>)
login(request, user)
message = _('<strong>You applied successfully. View your <a href="%s">Application</a></strong>' % application.get_absolute_url() )
# an email is sent to the user with his new password
info(request, message, extra_tags='success')
#if notification:
# notification.send([user], "applications_received", {'message': message,})
user_apply.send(sender = apply.func_name,
user = application.recipient, gig=application.gig,
application=application, label='applications_received')
return redirect(gig.get_absolute_url())
else:
signup_form = ProfileForm2()
apply_form = ApplyForm()
context = {
'signup_form' : signup_form,
'apply_form': apply_form,
'gig' : gig,
}
return render(request, template_name, context)
def reply_to_apply(request, application_id, template_name = 'gigs/applier/application_detail.html'):
""" handles reply to application """
print 'CALL TO : reply_to_apply - > %s' % application_id
app = get_object_or_404(Application, id = application_id)
if request.method == 'POST':
reply_form = ReplyForm(request.POST)
print reply_form
if reply_form.is_valid():
print 'reply form is valid'
application = Application()
#application.subject = gig.title
application.sender = request.user
application.recipient = app.sender
application.body = reply_form.cleaned_data['reply']
application.parent_msg = app
application.save()
print application.sender, application.recipient
else:
reply_form = ReplyForm()
context = {
'reply_form' : reply_form,
}
return render(request, template_name, context)
def application_detail(request, message_id, template_name = 'gigs/applier/application_detail.html'):
""" returns application details """
application = get_object_or_404(Application, id = message_id)
resume_form = ResumeForm()
application_status_form = ApplicationStatusForm()
#print application.body
if (application.sender != request.user) and (application.recipient != request.user):
raise Http404
if application.read_at is None and application.recipient == request.user:
application.read_at = now()
application.save()
company_read_application.send(sender = application_detail.func_name,
user=application.sender, gig=application.gig,
application=application, label='applications_read')
#if notification:
# notification.send([application.sender], "applications_read")
if application.read_at is not None and application.sender == request.user:
application.is_read_by_sender = True
application.save()
application_followup = application_messages(application, user = request.user, application_followup = [])
# Get Log Entries
log_entries = LogEntry.objects.filter(object_id=message_id)
context ={
'application' : application,
'application_status_form' : application_status_form,
'resume_form' : resume_form,
'application_followup' : application_followup,
#'application_status' : application.status.select_related().reverse()[0].name or None,
'log_entries' : log_entries,
}
return render(request, template_name, context)
@login_required
def set_application_status(request):
if request.is_ajax():
application_status = request.GET.get('application_status')
application_status_text = request.GET.get('application_status_text')
child_status = ChildStatus()
child_status.name = application_status
child_status.user = request.user
child_status.save()
application_id = request.GET.get('application_id')
application = get_object_or_404(Application, id = application_id)
application.status.add(child_status)
message = 'The application status is <strong>%s</strong>' % application_status_text
ACTIVE, HIRED, NOT_HIRED = 4, 5 , 6;
LogEntry.objects.log_action(
user_id=request.user.id,
content_type_id=ContentType.objects.get_for_model(application).pk,
object_id=application.id,
object_repr=unicode(application.subject),
action_flag=CHANGE,
change_message = application_status_text)
response = simplejson.dumps({
'message' : message,
'application_status_text':application_status_text,
})
return HttpResponse(response, content_type='application/javascript')
@login_required
def save_note(request):
if request.is_ajax():
note_content = request.POST.get('note_content')
application_id = request.POST.get('application_id')
application = Application.objects.get(id=int(application_id))
note = Note()
note.content = note_content
note.user = request.user
note.application = application
note.save()
message = 'Your note is saved successfully'
NOTE_SAVED = 7
LogEntry.objects.log_action(
user_id=request.user.id,
content_type_id=ContentType.objects.get_for_model(application).pk,
object_id=application.id,
object_repr=unicode(application.subject),
action_flag=NOTE_SAVED,
change_message = 'Note')
response = simplejson.dumps({
'message' : message,
})
return HttpResponse(response, content_type='application/javascript')
def application_follower(request, sign, id, template_name = 'gigs/applier/application_detail.html'):
""" Browse to the next/previous application"""
app = get_object_or_404(Application, id = id)
if sign == 'previous':
# and app has_next()
# application.next()
follower_id = app.id - 1
if sign == 'next':
follower_id = app.id + 1
application = Application.objects.filter(gig = app.gig, id = follower_id)
context ={
'application' : application,
}
return render(request, template_name, context)
def application_accept(request):
""" Flag the application as favorited or rejected"""
app = get_object_or_404(Application, id = int(request.GET['id']))
if request.is_ajax():
action = request.GET['action']
#if action == 'favorite' and not app.favorited_at:
if action == 'favorite':
app.favorited_at = now()
app.save()
message = 'Added to favorites'
LogEntry.objects.log_action(
user_id=request.user.id,
content_type_id=ContentType.objects.get_for_model(app).pk,
object_id=app.id,
object_repr=unicode(app.subject),
action_flag=ADDITION)
if action == 'reject':
app.rejected_at = now()
app.save()
message = _('Added to rejected')
response = simplejson.dumps({
'message' : message,
})
return HttpResponse(response, content_type='application/javascript')
#Account
def account(request, template_name = 'gigs/account.html'):
profile_picture_form = ProfilePictureForm()
context = {
'profile_picture_form':profile_picture_form,
}
return render(request, template_name, context)
@login_required
def set_notifications(request, template_name = 'gigs/company/account_notifications.html'):
"""
Handle settings the notifications per user
logic followed : We set the new notice_setting based on
the notice_setting's in the request post,if it is found or not
in the default notice_settings of the user
"""
# returning notice_settings except welcome_user
notice_settings = request.user.noticesetting_set.all().exclude(notice_type__label__exact = 'welcome_user')
if request.method == 'POST':
post_keys = request.POST.keys()
for notice_setting in notice_settings:
notice_setting_object = NoticeSetting.objects.filter(user = request.user)\
.filter(notice_type = notice_setting.notice_type)[0]
if notice_setting.notice_type.label in post_keys:
notice_setting_object.send = True
else:
notice_setting_object.send = False
notice_setting_object.save()
notice_settings = request.user.noticesetting_set.all().exclude(notice_type__label__exact = 'welcome_user')\
.exclude(notice_type__label__exact = 'notify_applicant')
message = _('Your changes are saved')
info(request, message, extra_tags='success')
context = {
'notice_settings' : notice_settings,
}
return render(request, template_name, context)
# Set DEFAULT USER SETTINGS
def set_user_settings(notification_settings, user):
print notification_settings
for notice_type in notification_settings:
print notice_type
notice_type_obj = notification.NoticeType.objects.get(label = notice_type)
print notice_type_obj
try:
notification.NoticeSetting(user = user,
notice_type = notice_type_obj, medium = '0', send = True).save()
except:
pass
# when user signup @receiver(post_save, sender = 'signup')
@receiver(user_added_to_group, sender = 'apply')
@receiver(user_added_to_group, sender = 'post_job')
def set_user_default_settings(sender, **kwargs):
user = kwargs['user']
group = kwargs['group']
print kwargs
# set General USER_NOTIFICATION_SETTINGS
set_user_settings(settings.USER_NOTIFICATION_SETTINGS, user)
print user
print user.groups.all()
print 'the group is %s' % group
# set specific USER_NOTIFICATION_SETTINGS
if group == 'JobSeeker':
#if not user.company:
set_user_settings(settings.JOB_SEEKER_NOTIFICATION_SETTINGS, user)
if group == 'Company':
print 'hello'
#else:
set_user_settings(settings.COMPANY_NOTIFICATION_SETTINGS, user)
@receiver(user_added_to_group, sender = 'apply')
@receiver(user_added_to_group, sender = 'post_job')
def welcome_user(sender, **kwargs):
user = kwargs['user']
group = kwargs['group']
password = kwargs['<PASSWORD>']
if notification:
label = "welcome_user"
extra_context = {'SITE_TITLE' : settings.SITE_TITLE,
'SITE_EMAIL' : settings.SITE_EMAIL,
'SITE_PHONE' : settings.SITE_PHONE,
'group' : group,
'password' : <PASSWORD>,
'SHOP_PAYMENT_STEP_ENABLED' : settings.SHOP_PAYMENT_STEP_ENABLED,
}
sender = settings.SITE_EMAIL
notification_send_now_task.delay(user, label, extra_context, sender)
# Send a welcome Message to Inbox
# refer to Company Post a Job -2
subject = ''
context = Context({
'full_name' : user.company.company_name.capitalize() \
if user.groups.get().name == 'Company' else \
'%s %s' % (user.first_name.capitalize(), user.last_name.capitalize()) ,
'company':user.groups.get().name == 'Company',
'job_title':'',
'site_name':settings.SITE_TITLE,
})
body = loader.render_to_string(template_name='django_messages/welcome_to_inbox.html',
context_instance=context)
sender = User.objects.filter(username = 'admin')[0]
message = Message(subject = subject, body = body,
sender = sender, recipient = user)
message.save()
@receiver(company_posted_job, sender = 'post_job')
def notify_company_posted_job(sender, **kwargs):
""" notify company about the newly posted gig """
gig = kwargs['gig']
user = gig.company.user
label = 'notify_company_about_job'
extra_context = {
'user' : gig.company.user.username,
'group' : 'Company',
'GIG_TITLE' : '( %s ) %s - %s - ' % (gig.job_type,
gig.title.capitalize(), gig.location),
'LISTINGS_LINK' : '%s%s' % (Site.objects.get_current().domain, reverse('company_listings')),
'SHOP_PAYMENT_STEP_ENABLED' : settings.SHOP_PAYMENT_STEP_ENABLED,
'SITE_TITLE' : settings.SITE_TITLE,
'SITE_EMAIL' : settings.SITE_EMAIL,
'SITE_PHONE' : settings.SITE_PHONE,
}
sender = settings.SITE_EMAIL
notification_send_now_task.delay(user, label, extra_context, sender)
@receiver(company_read_application, sender='application_detail')
@receiver(user_apply, sender = 'apply')
def notify_applicant(sender, **kwargs):
""" notify applicant to the job he just applied to """
user = kwargs['user']
gig = kwargs['gig']
application = kwargs['application']
label = kwargs['label']
extra_context = {
#'USER_NAME' : gig.company.company_name if user.company else user.get_full_name(),
'user' : user.username,
'GIG_TITLE' : '( %s ) %s - %s - ' % (gig.job_type.type,
gig.title.capitalize(), gig.location),
'APPLICATIONS_LINK' : '%s%s' % (Site.objects.get_current().domain, reverse('applier_applications')),
'GIG_URL' : '%s%s' % (Site.objects.get_current().domain, gig.get_absolute_url()),
'SITE_TITLE' : settings.SITE_TITLE,
'SITE_EMAIL' : settings.SITE_EMAIL,
'SITE_PHONE' : settings.SITE_PHONE,
'APPLICATION_RECIPIENT_NAME' : gig.company.company_name.capitalize(),
}
sender = settings.SITE_EMAIL
notification_send_now_task.delay(user, label,
extra_context, sender)
@receiver(user_apply, sender='apply')
def notify_company(sender, **kwargs):
""" notify company about job application"""
user = kwargs['user']
application = kwargs['application']
gig = kwargs['gig']
label = 'applications_received'
extra_context = {
'APPLICATION_SENDER' : application.sender.get_full_name().capitalize(),
'GIG_TITLE' : '( %s ) %s - %s - ' % (gig.job_type.type,
gig.title.capitalize(), gig.location),
'LISTING_LINK' : '%s%s' % (Site.objects.get_current().domain,
reverse(viewname='view_listing', kwargs={'slug':gig.slug})),
'GIG_URL' : '%s%s' % (Site.objects.get_current().domain,
gig.get_absolute_url()),
'SITE_TITLE' : settings.SITE_TITLE,
'SITE_EMAIL' : settings.SITE_EMAIL,
'SITE_PHONE' : settings.SITE_PHONE,
}
sender = settings.SITE_EMAIL
notification_send_now_task.delay(user, label,
extra_context, sender)
# when gig is validated
# its company is validated, admins are notified,
# twitter, linkedin, RSS, Google is pinged
@receiver(gig_is_validated, sender = 'response_change')
def validate_company(sender, **kwargs):
""" validate company if it is not when gig is validated
and also validate other gigs posted by the same company """
gig = kwargs['gig']
if not gig.company.valid:
gig.company.valid = True
gig.company.save(force_update = True)
print 'company validated'
for gig in gig.company.gigs():
gig.valid = True
gig.save()
@receiver(gig_is_validated, sender = 'post_job')
@receiver(gig_is_validated, sender = 'response_change')
def feed_twitter(sender, **kwargs):
""" When gig is validated, a tweet is sent
tweet_status include: [job_type] gig title capitalized at company_name
location(area_level1, area_level2) : gig link, gig categories as hash tags
"""
settings.use_editable()
print 'twitter work'
print settings.TWITTER_ACCOUNT
if settings.TWITTER_ACCOUNT:
print 'tweet'
gig = kwargs.get('gig', '')
print gig
t = twitter.Twitter(
auth=OAuth(settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACCESS_TOKEN_SECRET,
settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET)
)
print t
# building the tweet
#tweet_status = '[%s] %s at %s %s, %s : http://%s%s ' % (gig.job_type.type, gig.title.capitalize(),
# gig.company.company_name.capitalize(), gig.area_level1, gig.area_level2, gig.site.domain, gig.get_absolute_url())
domain = Site.objects.get(id = current_site_id())
tweet_status = '[%s] %s at %s %s, %s : http://%s%s ' % (gig.job_type.type, gig.title.capitalize(),
gig.company.company_name.capitalize(), gig.area_level1, gig.area_level2,
domain, gig.get_absolute_url())
hash_tags = ''.join([ '#%s ' % category.title for category in gig.gig_categories.all() if category ])
tweet_status += hash_tags
t.statuses.update(status = tweet_status, lat = gig.latitude,
long = gig.longitude, include_entities = True)
def save_profile_picture(request, template_name = 'gigs/account.html'):
if request.method=='POST':
profile_picture_form = ProfilePictureForm(request.POST, request.FILES)
if profile_picture_form.is_valid():
profile_picture_form.save(user=request.user)
else:
profile_picture_form = ProfilePictureForm()
referrer = request.META['HTTP_REFERER']
print referrer
context = {
'profile_picture_form':profile_picture_form,
}
#return render(request, template_name, context)
return redirect(referrer)
# Profiles
@login_required
def company_profile2(request, template_name='gigs/company/company_profile.html'):
""" returns the company profile """
site_id = current_site_id()
if request.method == 'POST':
company_profile_form = CompanyProfileForm(request.POST)
#print company_profile_form
social_links_form = SocialLinksForm(request.POST)
#print social_links_form
if company_profile_form.is_valid() and social_links_form.is_valid():
company = company_profile_form.get_company_object()
company.id = request.user.company.id
company.site_id = site_id
company.user = request.user
company.ip_address = request.META['REMOTE_ADDR']
company.save(force_update=True)
social_links = social_links_form.get_sociallinks_object()
social_links.user = request.user
print social_links
print social_links.user
try:
SocialLinks.objects.get(user=request.user)
print 'in'
except:
#social_links.id = company.user.sociallinks.id
social_links.user = request.user
social_links.save()
#social_links.save()
message = _('Your changes to your <strong>Company Profile</strong> are saved')
info(request, message)
else:
company_profile_form = CompanyProfileForm()
social_links_form = SocialLinksForm()
context = {
'company_profile_form':company_profile_form,
'social_links_form':social_links_form,
}
return render(request, template_name, context)
@login_required
def jobseeker_profile(request, template_name='gigs/applier/jobseeker_profile.html'):
""" returns the JobSeeker profile """
site_id = current_site_id()
if request.method == 'POST':
job_seeker_profile_form = JobseekerProfileForm(request.POST)
social_links_form = SocialLinksForm(request.POST)
if job_seeker_profile_form.is_valid() and social_links_form.is_valid():
print 'job seeker form and social are valid'
job_seeker_profile_object = job_seeker_profile_form.get_job_seeker_profile_object()
jobseeker_profile = JobSeekerProfile.objects.get_or_create(user=request.user)[0]
jobseeker_profile.title = job_seeker_profile_object.title
jobseeker_profile.about = job_seeker_profile_object.about
jobseeker_profile.location = job_seeker_profile_object.location
jobseeker_profile.latitude = job_seeker_profile_object.latitude
jobseeker_profile.longitude = job_seeker_profile_object.longitude
jobseeker_profile.area_level1 = job_seeker_profile_object.area_level1
jobseeker_profile.area_level2 = job_seeker_profile_object.area_level2
jobseeker_profile.area_level3 = job_seeker_profile_object.area_level3
jobseeker_profile.area_level4 = job_seeker_profile_object.area_level4
jobseeker_profile.phone_number = job_seeker_profile_object.phone_number
#print job_seeker_profile
jobseeker_profile.save()
print 'done with job seeker'
social_links = social_links_form.get_sociallinks_object()
social_links.user = request.user
saved_social_links=SocialLinks.objects.get_or_create(user=request.user)
print saved_social_links
social_links.id = saved_social_links[0].id
print social_links
social_links.save()
message = _('Changes to your <strong>Profile</strong> are saved')
info(request, message)
context = {
'job_seeker_profile_form':job_seeker_profile_form,
'social_links_form':social_links_form,
}
return render(request, template_name, context)
else:
job_seeker_profile_form = JobseekerProfileForm()
social_links_form = SocialLinksForm()
context = {
'job_seeker_profile_form':job_seeker_profile_form,
'social_links_form':social_links_form,
}
return render(request, template_name, context)
<file_sep>/feedb/templates/feedb/feedbacks_list.html
{% load i18n %}
{% if feedbacks %}
<h5 class="well well-small">
{{ obj.rated_feedbacks|length }} rated out of {{ feedbacks|length }} total {% trans 'Feedback(s)' %}
<span class="rateit" data-rateit-value="{{ obj.average_rating }}" data-rateit-ispreset="true" data-rateit-readonly="true">Average rating score = {{ obj.average_rating }} </span>
</h5>
{% for feedback in feedbacks %}
<div class="row-fluid">
<div class="span3">
<strong>{{ feedback.user }}</strong>
<br>{{ feedback.submit_date|date:"M d, Y" }}
<div class="rateit" data-rateit-value="{{ feedback.rating }}" data-rateit-ispreset="true" data-rateit-readonly="true"></div>
</div>
<div class="span8">{{ feedback.feedback|capfirst }}</div>
</div>
<hr>
{% endfor %}
{% else %}
<h4 class="well well-small">
{{ feedbacks|length }} {% trans 'Feedback(s)' %}
<span class="rateit" data-rateit-value="{{ obj.average_rating }}" data-rateit-ispreset="true" data-rateit-readonly="true"></span>
</h4>
{% endif %}<file_sep>/stats/utils.py
from django.contrib.contenttypes.models import ContentType
from stats.models import Metric, MetricItem
def save_metric_item(metric_name, **kwargs):
#print 'call to save_metric_item'
obj = kwargs['obj']
user = kwargs['user']
referrer = kwargs['referrer']
metric = Metric.objects.get(name=metric_name)
MetricItem(content_object=obj, metric=metric, user=user, referrer=referrer).save()
def get_metricitem_set(obj, metric_name, excluded_owner):
"""
returns metric items for an object regarding a metric
while excluding the owner of the object
"""
content_type = ContentType.objects.get_for_model(obj)
return content_type.metricitem_set.filter(metric__name=metric_name)\
.exclude(user=excluded_owner).filter(object_id=obj.id)
<file_sep>/linked_thief/views.py
import logging
from django.utils import simplejson
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from mezzanine.utils.views import render
logger = logging.getLogger(__name__)
@csrf_exempt
def linked_save_profile(request, template_name='linked_thief/test.html'):
#if request.method=='POST' a:qnd request.is_ajax():
for k,v in request.POST.iteritems():
print k, v
response = simplejson.dumps({
#'data' : request.POST.copy(),
'data' : 'success',
})
return HttpResponse(response, content_type='application/javascript')
<file_sep>/middlewares.py
import re
from django.utils import translation
from mezzanine.conf import settings
from mezzanine.utils.sites import current_site_id
class LocaleSelectorMiddleware(object):
"Set the language code for the request depending on what host we're requesting."
#these constants must match what the sites as they are defined in the django_site table
#LOCALHOST = 1
#FR = 3
#languages = { LOCALHOST: 'en', FR: 'fr', }
locales = {
#1 : 'nl_NL.UTF-8', # Dutch
3 : 'en_CA.utf8', # Canada
#4 : 'en_GB.UTF-8', # British
5 : 'sv_SE.UTF-8', # Swedish
10 : 'nl_NL.UTF-8', # Dutch
}
def process_request(self, req):
#change_lang(req)
if self.localize_request(req):
if req.session.get('LANGUAGE_CODE', ''):
language = req.session['LANGUAGE_CODE']
else:
language = self.get_language()
translation.activate(language)
req.LANGUAGE_CODE = translation.get_language()
# set SHOP_CURRENCY_LOCALE
settings.SHOP_CURRENCY_LOCALE =self.locales.get(current_site_id(),'')
req.SHOP_CURRENCY_LOCALE = self.locales.get(current_site_id(),'')
def get_language(self):
#sid = current_site_id()
#if self.languages.get(sid):
# return self.languages[sid]
#else:
# logger.error("Couldn't get language for site id: %s" % sid)
# return 'en'
return getattr(settings, 'SITE_LANGUAGE', 'en')
def localize_request(self, req):
for no_rewrite_path in ['^/admin/*']:
if re.match(no_rewrite_path, req.path):
return False
return True<file_sep>/contact/tasks.py
from celery import task
from django.core.mail import EmailMessage
from mezzanine.conf import settings
@task()
def notify_admins(subject, body, from_email, to):
email = EmailMessage(subject = subject, body = body,
from_email = from_email, to = to)
result = email.send()<file_sep>/planet/managers.py
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from mezzanine.utils.sites import current_site_id
class FeedManager(models.Manager):
"""
"""
def get_query_set(self):
qs = super(FeedManager, self).get_query_set()
return qs.filter(site=current_site_id(), is_active=True)
class FeedLinkManager(models.Manager):
"""
"""
def get_query_set(self):
qs = super(FeedLinkManager, self).get_query_set()
return qs.filter(feed__site=current_site_id())
class BlogManager(models.Manager):
"""
"""
def get_query_set(self):
qs = super(BlogManager, self).get_query_set()
return qs.filter(feed__site=current_site_id()).distinct()
class GeneratorManager(models.Manager):
"""
"""
def get_query_set(self):
qs = super(GeneratorManager, self).get_query_set()
return qs.filter(feed__site=current_site_id()).distinct()
class AuthorManager(models.Manager):
"""
"""
def get_query_set(self):
qs = super(AuthorManager, self).get_query_set()
return qs.filter(post__feed__site=current_site_id()).distinct()
class PostManager(models.Manager):
"""
"""
def get_query_set(self):
qs = super(PostManager, self).get_query_set()
return qs.filter(feed__site=current_site_id()).distinct()
class PostLinkManager(models.Manager):
"""
"""
def get_query_set(self):
qs = super(PostLinkManager, self).get_query_set()
return qs.filter(post__feed__site=current_site_id()).distinct()
class EnclosureManager(models.Manager):
"""
"""
def get_query_set(self):
qs = super(EnclosureManager, self).get_query_set()
return qs.filter(post__feed__site=current_site_id()).distinct()
<file_sep>/feedb/templatetags/feedback_tags.py
from django import template
register = template.Library()
@register.inclusion_tag('feedb/feedbacks_list.html')
def feedbacks_for(obj):
feedbacks = obj.feedbacks.all().order_by('-submit_date')
return {
'feedbacks' : feedbacks,
'obj' : obj,
}
<file_sep>/gigs/templatetags/gig_tags.py
from itertools import chain
from mezzanine import template
from django.contrib.sites.models import Site
from gigs.models import Application, Gig
register = template.Library()
@register.inclusion_tag('gigs/applier/related_jobs.html', takes_context=True)
def related_jobs(context):
logged_user = context['user']
current_site = Site.objects.get_current()
number_categories = current_site.category_set.count()
if number_categories == 1:
application = Application.objects.filter(sender = logged_user).filter(gig__isnull = False)[0]
targeted_location = application.gig.area_level2
related_jobs = Gig.objects.filter(area_level2=targeted_location).exclude(slug=application.gig.slug).order_by('publish_date')[:6]
print application, targeted_location, related_jobs
return { 'related_jobs':related_jobs}
<file_sep>/utils_app/models.py
from django.contrib.auth.models import User, Group
from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Ownable
from gigs.models import Application
class EmailContentBase(models.Model):
recipients = models.CharField(max_length = 1000)
subject = models.CharField(max_length=300, default = _('Resume Forwarded from {0}'.format('hello')))
body = models.TextField()
sender = models.ForeignKey(User)
def __unicode__(self):
return '{0} sent {1} to {2}'.format(self.sender,
self.subject, self.recipients)
class EmailedResume(EmailContentBase):
application = models.ForeignKey(Application)
def __unicode__(self):
return '{0} sent {1} to {2}'.format(self.sender,
self.application, self.recipients)
class Team(Ownable, Group):
#pass
def __unicode__(self):
return self.name
class GroupWithType(Group, Ownable):
"""
Group model with a type attribute
A company owns a group (Intwerviewer, Recruiter) and 1 or more
users belong to this group owned by the company
"""
TYPE_CHOICES = (
('INTERVIEWER', _('Interviewer')),
('RECRUITER', _('Recruiter')),
#('ADMIN', _('Administrator')),
)
group_type = models.CharField(max_length = 15, choices = TYPE_CHOICES,
default = TYPE_CHOICES[0][0])
def __unicode__(self):
return '%s(%s) owner by %s' % (self.name, self.group_type, self.user)
<file_sep>/marketing/urls.py
from django.conf.urls.defaults import patterns, url
from mezzanine.core.views import direct_to_template
from marketing.feeds import GigFeed
urlpatterns = patterns('',
url("^about/$", direct_to_template, {"template": "marketing/about.html"}, name = "about"),
url("^our-network/$", direct_to_template, {"template": "marketing/our_network.html"}, name="our_network"),
# generate feed (?P<slug>[-\w]+)/
url("^jobs/feed/$", GigFeed(), name = 'jobs_feed'),
url("^jobs/feed/(?P<what>[-\w]+)/$", GigFeed()),
url("^jobs/feed/(?P<what>[-\w]+)/(?P<location>[-\w ]+)/$", GigFeed()),
url("^jobs/feed/(?P<what>[-\w]+)/(?P<location>[-\w ]+)/(?P<gig_types>[-\w ]+)/(?P<remote>[-\w ]+)/$", GigFeed()),
)
urlpatterns += patterns('marketing.views',
# subscribe to email
url("^subscribe/email/$", 'subscribe_email', name = 'subscribe_email'),
# subscribe to prelaunch email
url("^subscribe/prelaunch-email/$", 'subscribe_prelaunch_email',
name = 'subscribe_prelaunch_email'),
)<file_sep>/gigs/signals.py
"""
Signals relating to adding a user to a group.
The purpose is to assign Notice settings to the user once
the user is added to a group (categorized)
"""
from django.dispatch import Signal
# Sent just after a user (Company/JobSeeker) is added to a group
user_added_to_group = Signal(providing_args=["user", "group", "password"])
# Sent after a registred JobSeeker apply for a job
company_posted_job = Signal(providing_args=["gig",])
# Sent after a registred JobSeeker apply for a job
user_apply = Signal(providing_args=["user", "gig", "application"])
# Sent after a gig is validated
gig_is_validated = Signal(providing_args=['gig',])
# Sent after a gig is visited
gig_is_visited = Signal(providing_args=['gig', 'user', 'referrer',])
# Sent after a Company reads an Application
company_read_application = Signal(providing_args=["user", "gig", "application", "label"])
<file_sep>/utils_app/urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url("^/email_resume/(?P<attach>[-\w]+)$", 'utils_app.views.email_resume', {'template_name' : 'gigs/company/application_detail.html'} , name = "email_resume"),
url("^/people/$", 'utils_app.views.people', {'template_name' : 'utils_app/people.html'} , name = "people"),
)
<file_sep>/gigs/tests.py
from moneyed import Money, USD
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone
from mezzanine.core.fields import FileField
from gigs.forms import PostJobForm
from gigs.models import Category
from gigs.models import Company
from gigs.models import Gig
from gigs.models import GigType
from gigs.models import GigStat
class CategoryModelTest(TestCase):
"""
Test for Category model (Slugged)
"""
def test_can_create_a_category_and_save_it(self):
#check we can create a category
category = Category()
category.title = 'UI Design (Visual Design, user experience, ...'
category.pub_date = timezone.now()
category.custom = True
#check that it can be saved
category.save()
#check it exists in db
categories = Category.objects.all()
category_in_db = categories[0]
self.assertEquals(len(categories), 1)
self.assertEquals(category_in_db, category)
#check it saved with attributes
self.assertEquals(category_in_db.title, category.title)
self.assertEquals(category_in_db.pub_date, category.pub_date)
class CompanyModelTest(TestCase):
"""
Test for Company model (Displayable, Ownable)
"""
def test_can_create_company_and_save_it(self):
#create user
#create company
company = Company()
company.type = 'Startup'
company.title = 'Alpha'
#title is confidential is not required
company.title_is_confidential = False
company.url = 'http://www.google.com'
company.elevator_pitch = 'elevator pitch'
company.profile_picture_choice = 'OWN_PICTURE'
company.profile_picture = 'company_logos/logo.png'
# TO DO : enable for ip_v6
company.ip_address = '127.0.0.1'
# a user is created along through the Company.save()
#check save
company.save()
#check it's in db and has the right attributes
companies = Company.objects.all()
company_in_db = companies[0]
self.assertEquals(len(companies), 1)
self.assertEquals(company_in_db.type, 'Startup')
self.assertEquals(company_in_db.title, 'Alpha')
self.assertEquals(company_in_db.title_is_confidential, False)
self.assertEquals(company_in_db.url, 'http://www.google.com')
self.assertEquals(company_in_db.elevator_pitch, 'elevator pitch')
self.assertEquals(company_in_db.profile_picture_choice, 'OWN_PICTURE')
self.assertEquals(company_in_db.profile_picture.path, 'company_logos/logo.png')
self.assertEquals(company_in_db.ip_address, '127.0.0.1')
self.assertEqual(company_in_db.user, company.user)
self.assertEqual(company_in_db.user.email, company.email)
class GigTypeTest(TestCase):
"""
Test for the Type of Gig
"""
def test_create_gigtype_and_save_it(self):
# check you can create a type and save it
gig_type = GigType()
gig_type.type = 'Full-time'
gig_type.description = 'Salaried position, ...'
gig_type.price = Money(249, USD)
# check it can be saved
gig_type.save()
# check it's saved with attributes
gig_types = GigType.objects.all()
gig_type_in_db = gig_types[0]
self.assertEquals(len(gig_types), 1)
self.assertEquals(gig_type_in_db.type, 'Full-time')
self.assertEquals(gig_type_in_db.description, 'Salaried position, ...')
self.assertEquals(gig_type_in_db.price, Money(249, USD))
class GigModelTest(TestCase):
"""
Test for Gig model
"""
def setUp(self):
self._category1 = self._create_category()
self._category2 = self._create_category()
self._company = self._create_company()
self._gig_type = self._create_gig_type()
def _create_category(self):
category = Category()
category.title = 'UI Design (Visual Design, user experience, ...'
category.pub_date = timezone.now()
category.custom = True
category.save()
return category
def _create_company(self):
company = Company()
company.title = 'Alpha'
company.type = 'Startup'
company.url = 'http://www.alpha.com'
company.elevator_pitch = 'Elevator pitch content'
company_profile_picture_field = FileField()
company_profile_picture = company_profile_picture_field.path = 'company_logo.png'
company.profile_picture = company_profile_picture
company.ip_address = '127.0.0.1'
company.save()
return company
def _create_gig_type(self):
gig_type = GigType()
gig_type.type = 'Full-time'
gig_type.description = 'Salaried position, ...'
gig_type.price = Money(249, USD)
gig_type.save()
return gig_type
def test_gig_type_in_db(self):
self.assertEqual(GigType.objects.count(), 1)
self.assertEqual(GigType.objects.all()[0].type, 'Full-time')
def test_can_create_a_gig_and_save_it(self):
#create a gig
gig = Gig()
gig.job_type = GigType.objects.all()[0]
gig.title = ' Python / Django developer'
gig.descr = ' This is the content'
gig.location = ' Chicago, California, usa'
gig.latitude = '41.87811360'
gig.longitude = '-87.62979820'
gig.is_relocation = True
gig.perks = 'Free food'
gig.how_to_apply = Gig.HOW_TO_APPLY_CHOICES[0][0]
if gig.how_to_apply == Gig.HOW_TO_APPLY_CHOICES[0][0]:
gig.via_email = '<EMAIL>'
elif gig.how_to_apply == Gig.HOW_TO_APPLY_CHOICES[0][1]:
gig.via_url = 'http://www.google.com'
gig.apply_instructions = 'Apply by email'
gig.is_onsite = True
gig.is_filled = False
#gig.category = self.category
gig.company = self._company
# check you can save it
gig.save()
# Associate the gig with the Categories
gig.categories.add(self._category1)
gig.categories.add(self._category2)
#check that gig is saved with the right attributes
gigs_in_db = Gig.objects.all()
gig_in_db = gigs_in_db[0]
self.assertEquals(len(gigs_in_db), 1)
self.assertEquals(gig_in_db.job_type, self._gig_type)
self.assertEquals(gig_in_db.title, ' Python / Django developer')
self.assertEqual(gig_in_db.descr, ' This is the content')
self.assertEqual(gig_in_db.location, ' Chicago, California, usa')
self.assertEqual(gig_in_db.latitude, '41.87811360')
self.assertEqual(gig_in_db.longitude, '-87.62979820')
self.assertEqual(gig_in_db.is_relocation, True)
self.assertEqual(gig_in_db.perks, 'Free food')
self.assertEqual(gig_in_db.how_to_apply, Gig.HOW_TO_APPLY_CHOICES[0][0])
self.assertEqual(gig_in_db.via_email, '<EMAIL>')
self.assertEqual(gig_in_db.apply_instructions, 'Apply by email')
self.assertEqual(gig_in_db.is_onsite, True)
self.assertEqual(len(gig_in_db.categories.all()), 2)
self.assertEqual(gig_in_db.company, self._company)
class GigStatTest(TestCase):
"""
GigStat TestCase
"""
def test_can_create_gig_stat_and_save_it(self):
gig_stat = GigStat()
gig_stat.views = 100
gig_stat.clicked_apply = 80
gig_stat.notified_users = 300
gig_stat.save()
# check it's saved with its attributes
gig_stats = GigStat.objects.all()
gig_stat_in_db = gig_stats[0]
self.assertEqual(len(gig_stats), 1)
self.assertEqual(gig_stat_in_db.views, 100)
self.assertEqual(gig_stat_in_db.clicked_apply, 80)
self.assertEqual(gig_stat_in_db.notified_users, 300)
class CompanyFormTest(TestCase):
pass
class PostJobFormTest(TestCase):
"""
PostJobForm TestCase
"""
def setUp(self):
self._GIG_TYPES = (
('Full Time $249', 'Salaried positions ...', Money(249, USD)),
('Contract $249', 'Temporary ...', Money(249, USD)),
)
self._CATEGORIES = (
('UI Design'),
('Front-end ...'),
('Information Architecture ...'),
)
def _set_up_gig_types(self):
for gig_type in self._GIG_TYPES:
gig_type_object = GigType(type = gig_type[0],
description = gig_type[1], price = gig_type[2])
gig_type_object.save()
def _set_up_categories(self):
for category in self._CATEGORIES:
category_object = Category(title = category.title)
category_object.save()
def test_post_job(self):
# setup Gig types
self._set_up_gig_types()
self.assertEqual(GigType.objects.count(), 2)
# setup Categories
self._set_up_categories()
self.assertEqual(Category.objects.count(), 3)
post_job_form = PostJobForm()
post_job_form.job_type = GigType.objects.all()[0]
post_job_form.category = Category.objects.filter(
title__icontains = 'UI')[0]
post_job_form.title = 'Python / Django developer'
post_job_form.location = 'Chicago IL, USA'
# latitude and longitude
# is_relocation is False by default
# is_onsite is False by default
post_job_form.descr = 'Python description'
# perks is optional
post_job_form.how_to_apply = 'VIA_EMAIL'
post_job_form.via_email = '<EMAIL>'
# apply_instructions is optional
# print post_job_form
# self.assertTrue(post_job_form.is_valid())
post_job_form.save()
class PostJobViewTest(TestCase):
"""
post_job view test case
"""
def test_post_job_view(self):
#response = self.client.get('/post_job')
#print response
#self.assertTemplateUsed(response, 'gigs/post_job.html')
#self.assertIn('hi', response.content)
pass
<file_sep>/gigs/templates/gigs/apply.html
{% load mezzanine_tags i18n %}
<div id="notMyModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="myModalLabel" class="modal-title">{% trans 'Warning' %}</h4>
</div>
<div class="modal-body">
<p><strong>{% trans 'Only Applicants can apply to Jobs' %}</strong></p>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="ehlo" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="myModalLabel" class="modal-title">{% trans 'Apply to' %} <strong>{{ gig.title|capfirst }}</strong></h4>
</div>
<div class="modal-body">
{% if not request.user.is_authenticated and not request.user.company%}
<p>
<strong>Have an account?</strong>
<a class="btn btn-u btn-sm" href="{% url login %}?next={{request.path}}">{% trans 'Sign in' %}</a>
Don't have one? No worries, you'll create one in a minute.
</p>
{% endif %}
<form id="application-form" class="form-horizontal" role="form" method="post" action="{% url apply gig_slug=gig.slug %}" enctype="multipart/form-data">{% csrf_token %}
{% if not request.user.is_authenticated %}
{% comment %}{% fields_for signup_form %}{% endcomment %}
<div class="form-group input_id_email">
<label for="id_email" class="col-sm-2 control-label">{% trans 'E-mail' %}</label>
<div class="col-sm-10">
<input id="id_email" class="form-control" type="email" name="email" maxlength="75" value="{% if signup_form.email.value %}{{ signup_form.email.value }}{% endif %}" placeholder="Email Address">
{% if signup_form.email.errors %}
<span class="help-block error">
{% for e in signup_form.email.errors %}
{{e}}
{% endfor %}
</span>
{% endif %}
</div>
</div>
<div class="form-group">
<label for="id_last_name" class="col-sm-2 control-label">{% trans 'Last name' %}</label>
<div class="col-sm-10">
<input id="id_last_name" type="text" class="form-control" name="last_name" maxlength="30" value="{% if signup_form.last_name.value %}{{ signup_form.last_name.value }}{% endif %}" placeholder="{% trans 'Last Name' %}">
{% if signup_form.last_name.errors %}
<span class="help-block error">
{% for e in signup_form.last_name.errors %}
{{e}}
{% endfor %}
</span>
{% endif %}
</div>
</div>
<div class="form-group">
<label for="id_first_name" class="col-sm-2 control-label">{% trans 'First name' %}</label>
<div class="col-sm-10">
<input id="id_first_name" type="text" class="form-control" name="first_name" maxlength="30" value="{% if signup_form.first_name.value %}{{ signup_form.first_name.value }}{% endif %}" placeholder="{% trans 'First Name' %}">
{% if signup_form.first_name.errors %}
<span class="help-block error">
{% for e in signup_form.first_name.errors %}
{{e}}
{% endfor %}
</span>
{% endif %}
<span class="help-inline"></span>
</div>
</div>
{% endif %}
{% comment %}{% fields_for apply_form %}{% endcomment %}
{{ apply_form.csrf}}
{% if request.user.is_authenticated %}
{% if request.user.resume_set %}
<div class="form-group row-fluid">
<label class="col-sm-4 control-label" for="id_select_resume">{% trans 'Use <strong>existing</strong> Resume' %}</label>
<div class="col-sm-8 row-fluid">
<select class="show-tick" name="select_resume" id="id_select_resume" title="Choose your resume" data-width="auto" data-style="btn-inverse">
{% for resume in request.user.resume_set.all reversed %}
<option value="{{ resume.id }}" data-subtext=" {% trans ' uploaded' %} {{ resume.created_at|date:'m-d-Y' }} ">{{ resume.get_filename }}</option>
{% endfor %}
</select>
</div>
</div>
{% endif %}
{% endif %}
<div class="form-group">
<label for="id_resume" class="{% if request.user.is_authenticated %}col-sm-4{% else %}col-sm-3{% endif %} control-label">{% if request.user.resume_set %}{% trans ' or Upload a <strong>new</strong> Resume' %}{% else %}{% trans 'Upload Resume' %}{% endif %}</label>
<div class="{% if request.user.is_authenticated %}col-sm-8{% else %}col-sm-9{% endif %}">
<a class="btn btn-u" id="browse_for_file">{% trans 'Browse for file' %}</a> <span id="filename"></span>
<input type="file" title="{% trans 'Browse for file' %}" name="resume" id="id_resume">
<p class="help-block">{% trans 'We only accept pdf format' %}</p>
{% if apply_form.resume.errors %}
<span class="help-block error">
{% for e in apply_form.resume.errors %}
{{e}}
{% endfor %}
</span>
{% endif %}
</div>
</div>
<div class="form-group input_id_motivation">
<label for="id_motivation" class="col-sm-2 control-label">{% trans 'Message' %}</label>
<div class="col-sm-10">
<textarea id="id_motivation" class="form-control" rows="5" cols="40" name="motivation">{% if apply_form.motivation.value %}{{ apply_form.motivation.value }}{% endif %}</textarea>
{% if apply_form.motivation.errors %}
<span class="help-block error">
{% for e in apply_form.motivation.errors %}
{{e}}
{% endfor %}
</span>
{% endif %}
</div>
</div>
</div>
<div class="modal-footer">
<!-- <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> -->
<button input="submit" id="send_application" class="btn btn-primary" data-loading-text="{% trans 'Sending Application' %} ...">{% trans 'Submit Application' %}</button>
</div>
</form>
</div>
</div>
</div>
<file_sep>/feedb/views.py
#from django.contrib.contenttypes.models
from django.contrib.messages import info
from django.contrib.sites.models import Site
from django.db.models import get_model
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from mezzanine.utils.sites import current_site_id
from mezzanine.utils.views import render
from feedb.models import Feedback
from feedb.forms import FeedbackForm
def submit_feedback(request, app_name = None, model_name = None, id = None, template_name = 'feedb/submit_feedback.html'):
"""
handles submitting feedback regardless of the object type
"""
if request.method == 'POST':
feedback_form = FeedbackForm(request.POST)
obj_id = request.POST['obj']
model_name = request.POST['model_name']
app_name = request.POST['app_name']
model = get_model(app_name, model_name)
obj = model.objects.get( id = obj_id )
if feedback_form.is_valid():
print 'form is valid'
post_data = feedback_form.cleaned_data
feedback = Feedback(content_object = obj, user = request.user)
feedback.feedback = post_data['feedback']
feedback.rating = post_data['rating']
feedback.site = Site.objects.get(id = current_site_id())
feedback.save()
message = _('Feedback on <strong>%s</strong> application is saved.' % obj.sender.get_full_name().capitalize())
info(request, message, extra_tags='success')
return redirect(obj.get_absolute_url())
else:
context = {
'feedback_form' : feedback_form,
'obj' : obj,
'model_name' : model_name,
'app_name' : app_name,
}
template_name = request.META['HTTP_REFERER']
#return render(request, template_name, context)
return redirect(obj.get_absolute_url(), context)
else:
model = get_model(app_name, model_name)
obj = model.objects.get( id = id )
feedback_form = FeedbackForm()
context = {
'feedback_form' : feedback_form,
'obj' : obj,
'model_name' : model_name,
'app_name' : app_name,
}
return render(request, template_name, context)
<file_sep>/marketing/forms.py
from django import forms
from marketing.models import PreLaunch
class SubscribeForm(forms.Form):
email = forms.EmailField()
class PreLaunchForm(forms.ModelForm):
class Meta:
model = PreLaunch
fields = ['email',]
<file_sep>/static/cartridge/js/shipping_fields.js
$(function() {
var sameShipping = $('#id_same_billing_shipping');
// prepopulate shipping fields with billing values if "same as" checkbox
// checked by iterating the billing fields, mapping each billing field name
// to the shipping field name and setting its value
$('#checkout-form').submit(function() {
if (sameShipping.attr('checked')) {
$('input[name^=billing_]').each(function() {
var shippingName = this.name.replace('billing_', 'shipping_');
$('input[name=' + shippingName + ']').attr('value', this.value);
});
$('select[name^=billing_]').each(function() {
var shippingSelected = $(this).children('option[selected]').val();
var shippingSelName = this.name.replace('billing_', 'shipping_');
$('select[name=' + shippingSelName + '] option[value=' + shippingSelected +']').attr('selected', 'selected');
});
}
});
// show/hide shipping fields on change of "same as" checkbox and call on load
sameShipping.change(function() {
$('#shipping_fields')[sameShipping.attr('checked') ? 'hide' : 'show']();
}).change();
});
<file_sep>/searchapp/forms.py
from django import forms
from searchapp.models import GigSearch
class GigSearchForm(forms.ModelForm):
class Meta:
model = GigSearch
fields = ('what', 'location', )
def __init__(self, *args, **kwargs):
super(GigSearchForm,self).__init__(*args, **kwargs)
what_default = 'Job title, Keywords, Company name, ...'
self.fields['what'].widget.attrs['placeholder'] = what_default
self.fields['what'].widget.attrs['class'] = 'span5'
location_default = 'City, State or Zip code'
self.fields['location'].widget.attrs['placeholder'] = location_default
self.fields['location'].widget.attrs['class'] = 'span5'
<file_sep>/faqs/models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Displayable, Orderable, RichText, Slugged
#from faqs.managers import FaqManager
#class FaqCategory(Orderable, Slugged):
# pass
class Faq(Orderable, Displayable, RichText):
"""
Frequently Asked Question
Note : i put Orderable first, then it works
"""
#categories = models.ManyToManyField(FaqCategory)
#objects = FaqManager()
pass
def __unicode__(self):
return u'Q : {0} - A : {1}'.format(self.title, self.content)
@models.permalink
def get_absolute_url(self):
url_name = 'faqs'
kwargs = {}
return (url_name, (), kwargs)
<file_sep>/contact/urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url("^/$", 'contact.views.contact', {"template_name": "contact/contact.html"}, name = "contact"),
)
<file_sep>/searchapp/search.py
from itertools import chain
from django.conf import settings
from django.contrib.humanize.templatetags.humanize import naturalday
from django.core import serializers
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.template.defaultfilters import date
from mezzanine.utils.sites import current_site_id
from mezzanine.utils.urls import slugify
from gigs.models import Gig, GigType
from searchapp.models import GigSearch
STRIP_WORDS = ['a', 'an', 'and', 'by', 'for', 'from', 'in', 'no', 'not',
'of', 'on', 'or', 'that', 'the', 'to', 'with']
def store(request, what, location, gig_types_string, remote):
gig_search = GigSearch()
if what is not None and len(what) > 2:
gig_search.what = what
gig_search.location = location
#gig_terms.longitude = longitude
#gig_terms.latitude = latitude
#gig_terms.area_level1 = area_level1
#gig_terms.area_level2 = area_level2
gig_search.ip_address = request.META.get('REMOTE_ADDR','')
if request.user.is_authenticated():
gig_search.user = request.user
#gig_terms.is_onsite = is_onsite
if remote == 'True':
gig_search.is_onsite = True
gig_search.save()
gig_types_list = gig_types_string.split()
for gig_type_id in gig_types_list:
gig_type = GigType.objects.get(id = gig_type_id)
gig_search.gig_type.add(gig_type)
# slugify gig_search
gig_search.slug = slugify('%s %s %s %s' % (gig_search.what,
gig_search.location, gig_search.user, gig_types_string))
gig_search.save()
return gig_search
def get_results(what, location, page, gig_types_list, remote = False):
site_id = current_site_id()
related_sites = settings.RELATED_SITE[ site_id - 1]
#gigs = Gig.objects.filter(site_id = current_site_id()).filter(valid = True)
search_include_tag = settings.SITE_SEARCH_INCLUDE_TAG
if related_sites is not None:
Q_related_site_ids = [ Q(on_site__id=related_site_id) for related_site_id in related_sites]
Q_related_site_ids.append(Q(site_id=site_id))
gigs = Gig.objects.filter(reduce(OR, Q_related_site_ids))
gigs = gigs.distinct().filter(valid = True).order_by('-publish_date')
else:
gigs = Gig.objects.filter(site_id=site_id).filter(valid = True).order_by('-publish_date')
gigs = gigs.filter(Q(location__icontains=search_include_tag)|
Q(area_level2__iexact=search_include_tag)|
Q(area_level3__iexact=search_include_tag))
try:
page = int(page)
if page == 1:
start = 0
end = settings.GIGS_PER_PAGE
else :
end = page * settings.GIGS_PER_PAGE
start = end - settings.GIGS_PER_PAGE
except:
pass
if what:
terms = _prepare_words(what)
#results = Gig.objects.all()
results = []
#| Q(tags__icontains = what )
if terms:
for term in terms:
gigs = gigs.filter(Q(title__icontains = term)|Q(description__icontains = term)| Q(company__company_name__icontains = term )
| Q(hidden_tags__icontains = term ))
if location:
gigs = gigs.filter(Q(location__icontains = location) | Q(area_level2__icontains = location))
# Any remote jobs
if remote == 'True':
#print 'remote'
gigs = gigs.filter(is_remote = True) # Remote gigs
# Exclude all unchecked gig types
for gig_type in gig_types_list:
gigs = gigs.exclude(job_type = GigType.objects.get(pk = gig_type))
#for gig in gigs.order_by('-publish_date')[start:end]:
# results.append({
# 'gig_id' : gig.id,
# 'gig_title' : gig.title,
# 'gig_link' : gig.get_absolute_url(),
# 'gig_job_type' : gig.job_type.type,
# 'gig_publish_date' : date(gig.publish_date),
# 'gig_company' : gig.company.company_name,
# 'gig_company_elevator_pitch' : gig.company.elevator_pitch,
# 'gig_company_logo' : gig.company.profile_picture.name\
# if gig.company.profile_picture.name else 'company_logos/employer_default.png',
# 'gig_company_profile' : reverse('company_profile', args = (gig.company.slug,)),
# 'gig_location' : gig.location,
# 'gig_is_new' : 'today' in naturalday(gig.publish_date),
# 'gig_tags' : gig.get_tags() if gig.hidden_tags else False,
# })
#print len(results)
# the results are either resumes or gigs or a company
#return results
return gigs.order_by('-publish_date')
def _prepare_words(what):
"""
Filter search query from common words like 'a, the, etc'
based on the site language
"""
# Should implement filter based on common words based on
# site language
if what:
query_terms = what.split()
search_terms = [ term for term in query_terms if term not in STRIP_WORDS]
return search_terms[0:5]
def gig_searches_similar_to_gig():
"""
return gig_searches similar to a gig
"""
pass
<file_sep>/gigs/migrations/0001_initial.py
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Category'
db.create_table('gigs_category', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('site', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['sites.Site'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=500)),
('slug', self.gf('django.db.models.fields.CharField')(max_length=2000, null=True, blank=True)),
('pub_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('is_custom', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal('gigs', ['Category'])
# Adding model 'Company'
db.create_table('gigs_company', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('keywords_string', self.gf('django.db.models.fields.CharField')(max_length=500, blank=True)),
('site', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['sites.Site'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=500)),
('slug', self.gf('django.db.models.fields.CharField')(max_length=2000, null=True, blank=True)),
('_meta_title', self.gf('django.db.models.fields.CharField')(max_length=500, null=True, blank=True)),
('description', self.gf('django.db.models.fields.TextField')(blank=True)),
('gen_description', self.gf('django.db.models.fields.BooleanField')(default=True)),
('status', self.gf('django.db.models.fields.IntegerField')(default=2)),
('publish_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('expiry_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('short_url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True)),
('in_sitemap', self.gf('django.db.models.fields.BooleanField')(default=True)),
('type', self.gf('django.db.models.fields.CharField')(max_length=200)),
('title_is_confidential', self.gf('django.db.models.fields.BooleanField')(default=False)),
('url', self.gf('django.db.models.fields.URLField')(max_length=200)),
('email', self.gf('django.db.models.fields.EmailField')(max_length=75)),
('elevator_pitch', self.gf('django.db.models.fields.CharField')(max_length=200)),
('profile_picture_choice', self.gf('django.db.models.fields.CharField')(default=u'No picture', max_length=60)),
('profile_picture', self.gf('mezzanine.core.fields.FileField')(max_length=255, null=True, blank=True)),
('ip_address', self.gf('django.db.models.fields.GenericIPAddressField')(max_length=39)),
('user', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['auth.User'], unique=True)),
('keywords', self.gf('mezzanine.generic.fields.KeywordsField')(object_id_field='object_pk', to=orm['generic.AssignedKeyword'], frozen_by_south=True)),
))
db.send_create_signal('gigs', ['Company'])
# Adding model 'GigType'
db.create_table('gigs_gigtype', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('type', self.gf('django.db.models.fields.CharField')(max_length=20)),
('description', self.gf('django.db.models.fields.CharField')(max_length=200)),
('price_currency', self.gf('djmoney.models.fields.CurrencyField')(default='USD')),
('price', self.gf('djmoney.models.fields.MoneyField')(frozen_by_south=True, max_digits=10, decimal_places=2, default_currency='USD')),
))
db.send_create_signal('gigs', ['GigType'])
# Adding model 'Gig'
db.create_table('gigs_gig', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('keywords_string', self.gf('django.db.models.fields.CharField')(max_length=500, blank=True)),
('site', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['sites.Site'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=500)),
('slug', self.gf('django.db.models.fields.CharField')(max_length=2000, null=True, blank=True)),
('_meta_title', self.gf('django.db.models.fields.CharField')(max_length=500, null=True, blank=True)),
('description', self.gf('django.db.models.fields.TextField')(blank=True)),
('gen_description', self.gf('django.db.models.fields.BooleanField')(default=True)),
('status', self.gf('django.db.models.fields.IntegerField')(default=2)),
('publish_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('expiry_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('short_url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True)),
('in_sitemap', self.gf('django.db.models.fields.BooleanField')(default=True)),
('job_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['gigs.GigType'])),
('location', self.gf('django.db.models.fields.CharField')(max_length=200)),
('latitude', self.gf('django.db.models.fields.CharField')(max_length=15)),
('longitude', self.gf('django.db.models.fields.CharField')(max_length=15)),
('is_relocation', self.gf('django.db.models.fields.BooleanField')(default=False)),
('is_onsite', self.gf('django.db.models.fields.BooleanField')(default=False)),
('descr', self.gf('mezzanine.core.fields.RichTextField')()),
('perks', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('how_to_apply', self.gf('django.db.models.fields.CharField')(default='VIA_EMAIL', max_length=15)),
('via_email', self.gf('django.db.models.fields.EmailField')(max_length=75, null=True, blank=True)),
('via_url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True)),
('apply_instructions', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('is_filled', self.gf('django.db.models.fields.BooleanField')(default=False)),
('company', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['gigs.Company'])),
('keywords', self.gf('mezzanine.generic.fields.KeywordsField')(object_id_field='object_pk', to=orm['generic.AssignedKeyword'], frozen_by_south=True)),
))
db.send_create_signal('gigs', ['Gig'])
# Adding M2M table for field categories on 'Gig'
db.create_table('gigs_gig_categories', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('gig', models.ForeignKey(orm['gigs.gig'], null=False)),
('category', models.ForeignKey(orm['gigs.category'], null=False))
))
db.create_unique('gigs_gig_categories', ['gig_id', 'category_id'])
# Adding model 'GigStat'
db.create_table('gigs_gigstat', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('views', self.gf('django.db.models.fields.IntegerField')()),
('clicked_apply', self.gf('django.db.models.fields.IntegerField')()),
('notified_users', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('gigs', ['GigStat'])
def backwards(self, orm):
# Deleting model 'Category'
db.delete_table('gigs_category')
# Deleting model 'Company'
db.delete_table('gigs_company')
# Deleting model 'GigType'
db.delete_table('gigs_gigtype')
# Deleting model 'Gig'
db.delete_table('gigs_gig')
# Removing M2M table for field categories on 'Gig'
db.delete_table('gigs_gig_categories')
# Deleting model 'GigStat'
db.delete_table('gigs_gigstat')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'generic.assignedkeyword': {
'Meta': {'ordering': "('_order',)", 'object_name': 'AssignedKeyword'},
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'keyword': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'assignments'", 'to': "orm['generic.Keyword']"}),
'object_pk': ('django.db.models.fields.IntegerField', [], {})
},
'generic.keyword': {
'Meta': {'object_name': 'Keyword'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
},
'gigs.category': {
'Meta': {'object_name': 'Category'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_custom': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
},
'gigs.company': {
'Meta': {'object_name': 'Company'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'elevator_pitch': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'ip_address': ('django.db.models.fields.GenericIPAddressField', [], {'max_length': '39'}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}),
'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'profile_picture': ('mezzanine.core.fields.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'profile_picture_choice': ('django.db.models.fields.CharField', [], {'default': "u'No picture'", 'max_length': '60'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'title_is_confidential': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'gigs.gig': {
'Meta': {'object_name': 'Gig'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'apply_instructions': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['gigs.Category']", 'symmetrical': 'False'}),
'company': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gigs.Company']"}),
'descr': ('mezzanine.core.fields.RichTextField', [], {}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'how_to_apply': ('django.db.models.fields.CharField', [], {'default': "'VIA_EMAIL'", 'max_length': '15'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_filled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_onsite': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_relocation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'job_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gigs.GigType']"}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}),
'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'latitude': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'location': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'longitude': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'perks': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'via_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'via_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
'gigs.gigstat': {
'Meta': {'object_name': 'GigStat'},
'clicked_apply': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notified_users': ('django.db.models.fields.IntegerField', [], {}),
'views': ('django.db.models.fields.IntegerField', [], {})
},
'gigs.gigtype': {
'Meta': {'object_name': 'GigType'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'price': ('djmoney.models.fields.MoneyField', [], {'frozen_by_south': 'True', 'max_digits': '10', 'decimal_places': '2', 'default_currency': "'USD'"}),
'price_currency': ('djmoney.models.fields.CurrencyField', [], {'default': "'USD'"}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '20'})
},
'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
}
}
complete_apps = ['gigs']<file_sep>/feedb/models.py
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.sites.models import Site
from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import settings
from mezzanine.core.models import Ownable
from mezzanine.utils import timezone
class FeedbackBase(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
site = models.ForeignKey(Site)
class Meta:
abstract = True
RATING_RANGE = [ i/2.0 for i in range(settings.RATINGS_MIN, ((settings.RATINGS_MAX + 1) * 2) - 1)]
class Feedback(Ownable, FeedbackBase):
feedback = models.TextField(_('Feedback'))
rating = models.FloatField(_("Rating"), blank = True, null = True)
# Metadata about the Feedback
submit_date = models.DateTimeField(_('date/time submitted'), default=None)
def __unicode__(self):
return '%s (%s) by %s to %s(%s)' % (self.feedback, self.rating, self.user,
self.content_object.__class__.__name__, self.content_object.id)
def save(self, *args, **kwargs):
if self.submit_date is None:
self.submit_date = timezone.now()
if self.rating not in RATING_RANGE:
raise ValueError("Invalid rating. %s is not within %s and %s" %
(self.rating, RATING_RANGE[0], RATING_RANGE[-1]))
super(FeedbackBase, self).save(*args, **kwargs)<file_sep>/feedb/urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url("^/$", 'feedb.views.submit_feedback', {"template_name": "feedb/submit_feedback.html"}, name = "submit_feedback"),
url("^/(?P<app_name>[-\w]+)/(?P<model_name>[-\w]+)/(?P<id>[-\w]+)$", 'feedb.views.submit_feedback',
{"template_name": "feedb/submit_feedback.html"}, name = "submit_feedback"),
)
<file_sep>/planet/templates/planet/posts/list.html
{% extends "base.html" %}
{% load i18n pagination_tags planet_tags %}
{% load url from future %}
{% block meta_title %}{{ settings.SITE_SEARCH_INCLUDE_TAG }} {% trans 'Community' %}{% endblock %}
{% block meta_description %}{{ settings.SITE_SEARCH_INCLUDE_TAG }} Community is a community page aggregating the best {{ settings.SITE_SEARCH_INCLUDE_TAG }} blogs and content available around the web{% endblock %}
{% block meta_keywords %}{{ settings.SITE_META_KEYWORDS }}{% endblock %}
{% block head_title %}
{% trans 'django-planet: django blog news aggregator' %}{{ block.super }}
{% endblock %}
{% block extra_head %}
<link rel="canonical" href="http://{{ settings.SITE_DOMAIN }}{% url 'planet.views.posts_list' %}"/>
{% endblock %}
{% block title_bread %}
<!--=== Breadcrumbs ===-->
<div class="breadcrumbs margin-bottom-10">
<div class="container">
<h1 class="pull-left">{{ settings.SITE_SEARCH_INCLUDE_TAG }} {% trans 'Community' %}</h1>
{% comment %}
<ul class="pull-right breadcrumb">
<li><a href="{% url 'home' %}">Home</a></li>
<li><a href="">Pages</a></li>
<li class="active">Invoice</li>
</ul>
{% endcomment %}
</div><!--/container-->
</div><!--/breadcrumbs-->
<!--=== End Breadcrumbs ===-->
{% endblock %}
{% block breadcrumb_section %}<li class="active">{% trans 'Posts' %}</li>{% endblock %}
{% block posts_class %}class="active"{% endblock %}
{% block main %}
<h1>What's new in {{ settings.SITE_TITLE }} community? </h1>
{% comment %} {% autopaginate posts 15 %}
{% for post in posts %}
<div class="post">
{% post_details post %}
<a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a> {{ post.feed.title}}
<p>{{ post.content|truncatewords:10 }}</p>
</div>
{% endfor %}
{% paginate %}
{% endcomment %}
{% comment %}
<div class="row well">
<form class="sky-form form-inline" role="form" method="get" action="{% url 'planet_index' %}">
{{ search_form }}
<button type="submit" class="btn btn-default">{% trans 'Find' %}</button>
</form>
</div>
{% endcomment %}
{% if not request.GET.w %}
<div class="row">
{% if settings.PLANET_JOBS_CATEGORY %}
<div class="col-md-6">
<h2 class="headline">{{ settings.SITE_SEARCH_INCLUDE_TAG }} Jobs
<a class="btn btn-inverse btn-sm" href="{{ settings.PLANET_JOBS_CATEGORY|slugify }}">View more</a>
</h2>
{% planet_post_list with category=settings.PLANET_JOBS_CATEGORY limit=5 %}
{% comment %}
<div class="post">
{% for post in posts %}
{% if loopfor.counter.1 < 10 %}
{% post_details post %}
<a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a> {{ post.feed.title}}
<p>{{ post.content|truncatewords:10 }}</p>
{% endif %}
{% endfor %}
</div>
{% endcomment %}
</div>
{% endif %}
{% if settings.PLANET_BLOGS_CATEGORY %}
<div class="col-md-6">
<h2 class="headline">{{ settings.SITE_SEARCH_INCLUDE_TAG }} Blogs
<a class="btn btn-inverse btn-sm" href="{{ settings.PLANET_BLOGS_CATEGORY|slugify }}">View more</a>
</h2>
<p>
{% planet_post_list with category=settings.PLANET_BLOGS_CATEGORY limit=5 %}
</p>
</div>
{% endif %}
</div>
<div class="row">
{% if settings.PLANET_FORUMS_CATEGORY %}
<div class="col-md-6">
<h2 class="headline">{{ settings.SITE_SEARCH_INCLUDE_TAG }} Forums
<a class="btn btn-inverse btn-sm" href="{{ settings.PLANET_FORUMS_CATEGORY|slugify }}">View more</a>
</h2>
{% planet_post_list with category=settings.PLANET_FORUMS_CATEGORY limit=5 %}
{% comment %}
<div class="post">
{% for post in posts %}
{% if loopfor.counter.1 < 10 %}
{% post_details post %}
<a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a> {{ post.feed.title}}
<p>{{ post.content|truncatewords:10 }}</p>
{% endif %}
{% endfor %}
</div>
{% endcomment %}
</div>
{% endif %}
{% if settings.PLANET_LINKS_CATEGORY %}
<div class="col-md-6">
<h2 class="headline">{{ settings.SITE_SEARCH_INCLUDE_TAG }} Links
<a class="btn btn-inverse btn-sm" href="{{ settings.PLANET_LINKS_CATEGORY|slugify }}">View more</a>
</h2>
<p>
{% planet_post_list with category=settings.PLANET_LINKS_CATEGORY limit=5 %}
</p>
</div>
{% endif %}
</div>
<div class="row">
{% if settings.PLANET_PACKAGES_CATEGORY %}
<div class="col-md-6">
<h2 class="headline">{{ settings.SITE_SEARCH_INCLUDE_TAG }} Packages
<a class="btn btn-inverse btn-sm" href="{{ settings.PLANET_PACKAGES_CATEGORY|slugify }}">View more</a>
</h2>
{% planet_post_list with category=settings.PLANET_PACKAGES_CATEGORY limit=5 %}
{% comment %}
<div class="post">
{% for post in posts %}
{% if loopfor.counter.1 < 10 %}
{% post_details post %}
<a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a> {{ post.feed.title}}
<p>{{ post.content|truncatewords:10 }}</p>
{% endif %}
{% endfor %}
</div>
{% endcomment %}
</div>
{% endif %}
{% comment %}
<div class="col-md-6">
<h2 class="headline">{{ settings.SITE_SEARCH_INCLUDE_TAG }} Links
<a class="btn btn-inverse btn-sm" href="{{ settings.PLANET_LINKS_CATEGORY|slugify }}">View more</a>
</h2>
<p>
{% planet_post_list with category=settings.PLANET_LINKS_CATEGORY limit=5 %}
</p>
</div>
{% endcomment %}
</div>
{% else %}
<div class="row">
<h2>Search Results for {{ request.GET.q }}</h2>
{% for post in posts_list %}
<a href="#">{{ post.title }}</a>
<p>{{ post.content|safe|truncatewords:25 }}</p>
{% endfor %}
{% for post in blogs_list %}
<a href="#">{{ blog.title }}</a>
{% endfor %}
</div>
{% endif %}
{% endblock %}
{% block right_panel %}
<aside class="margin-bottom-40">
{% include 'gigs/includes/social.html' %}
</aside>
<aside class="margin-bottom-40">
{% include 'gigs/includes/contact.html' %}
</aside>
{% endblock %}
<file_sep>/searchapp/urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns(
'searchapp.views',
#url("^/$", 'search_objects', {"template_name": "searchapp/results.html"}, name = "find_jobs"),
url("^/$", 'search_objects', {"template_name": "gigs/index.html"}, name = "find_jobs"),
#url("^/(?P<what>[-\w]+)/$", 'search_objects', {"template_name": "gigs/index.html"}, name = "find_jobs"),
#url("^/location/(?P<loc>[-\w]+)/$", 'search_objects', {"template_name": "gigs/index.html"}, name = "find_jobs_location"),
#url("^/$", 'gigs.views.all_gigs', {"template_name": "gigs/index.html"}, name = "find_jobs"),
)
<file_sep>/marketing/views.py
from django.contrib.messages import info
from django.contrib.sites.models import Site
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.http import HttpResponse
from django.utils import simplejson
from django.utils.translation import ugettext_lazy as _
from mezzanine.blog.models import BlogPost
from mezzanine.conf import settings
from mezzanine.utils.views import render
from mezzanine.utils.sites import current_site_id
from gigs.signals import gig_is_validated
from marketing.forms import SubscribeForm, PreLaunchForm
from marketing.models import PreLaunch
from searchapp.models import GigSearch
from searchapp.search import store, gig_searches_similar_to_gig
from utils_app.tasks import ping_search_engines
def subscribe_email(request, template_name = 'gigs/index.html'):
if request.method == 'POST' and request.is_ajax():
subscribe_form = SubscribeForm(request.POST)
print request.POST
if subscribe_form.is_valid():
post_data = subscribe_form.cleaned_data
what = request.POST.get('what','')
location = request.POST.get('location','')
gig_types_string = request.POST.get('gig_types_string','')
remote = request.POST.get('remote','')
gig_search = store(request, what, location, gig_types_string, remote)
gig_search.subscribed_user = post_data['email']
gig_search.save()
message = '<strong>Subscribed</strong>We will be sending you matching jobs as they come in. Good luck'
response = simplejson.dumps({
'full_name' : request.user.get_full_name(),
'message' : message.lower(),
})
return HttpResponse(response, content_type='application/javascript')
else:
subscribe_form = SubscribeForm()
context = {
'subscribe_form' : subscribe_form,
}
return render(request, template_name, context)
def subscribe_prelaunch_email(request, template_name = 'gigs/not_active_index.html'):
if request.method == 'POST':
prelaunch_form = PreLaunchForm(request.POST)
if prelaunch_form.is_valid():
email = prelaunch_form.cleaned_data['email']
site = Site.objects.get_current()
prelaunch_instance = PreLaunch(email=email, site = site)
prelaunch_instance.save()
message = _('Thank you for sign up')
info(request, message, extra_tags='success')
context = {}
else:
context = {'prelaunch_form':prelaunch_form}
return render(request, template_name, context)
@receiver(gig_is_validated, sender = 'post_job')
@receiver(gig_is_validated, sender = 'response_change')
def email_subscribed_users(sender, **kwargs):
"""
Subscribed users to gig search similar to the validated
gig are notified
"""
gig = kwargs['gig']
print 'send notification to subscribed_user'
#gig_searches = gig_searches_similar_to_gig(gig)
# send email/ notification to subscribed users
@receiver(gig_is_validated, sender = 'post_job')
@receiver(gig_is_validated, sender = 'response_change')
@receiver(post_save, sender = BlogPost)
def load_ping_search_engines_task(sender, **kwargs):
ping_search_engines.apply_async(countdown = 15)<file_sep>/stats/models.py
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Metric(models.Model):
name = models.CharField(_('Name'), max_length=100)
description = models.TextField()
def __unicode__(self):
return self.name
class MetricSet(models.Model):
name = models.CharField(max_length=75)
metrics = models.ManyToManyField(Metric)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return '%s [%s]' % (self.name, self.metrics)
class MetricItem(models.Model):
metric = models.ForeignKey(Metric)
referrer = models.URLField(blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
value = models.IntegerField(_('Value'), default=1)
publish_date = models.DateField(auto_now_add=True)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return ('%s %s %s') % (self.metric.name, self.value, self.publish_date)
<file_sep>/faqs/admin.py
from django.contrib import admin
from faqs.models import Faq
#class FaqCategoryAdmin(admin.ModelAdmin):
# list_display = ('title',)
class FaqAdmin(admin.ModelAdmin):
list_display = ('title', 'content',)
#admin.site.register(FaqCategory, FaqCategoryAdmin)
admin.site.register(Faq, FaqAdmin)
<file_sep>/feedb/forms.py
from django import forms
class FeedbackForm(forms.Form):
feedback = forms.CharField(max_length=1000, widget = forms.Textarea)
rating = forms.FloatField(required = False, widget = forms.HiddenInput)
app_name = forms.CharField(max_length = 100, widget = forms.HiddenInput)
model_name = forms.CharField(max_length = 100, widget = forms.HiddenInput)
obj = forms.IntegerField(widget = forms.HiddenInput)<file_sep>/wsgi.py
"""
WSGI config for hello project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
import sys
# Set up virtualenv
venv = '/webapps/hello_django/bin/activate_this.py'
execfile(venv, dict(__file__=venv))
_PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEZZANINE_PATH = '/webapps/hello_django/lib/python2.7/site-packages/mezzanine'
CARTRIDGE_PATH = '/webapps/hello_django/lib/python2.7/site-packages/cartridge'
sys.path.insert(0, MEZZANINE_PATH)
sys.path.insert(0, CARTRIDGE_PATH)
sys.path.insert(0, _PROJECT_DIR)
sys.path.insert(0, os.path.dirname(_PROJECT_DIR))
#_PROJECT_NAME = _PROJECT_DIR.split('/')[-1]
_PROJECT_NAME= 'jobconnector'
print _PROJECT_NAME
os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % _PROJECT_NAME
#os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rien2.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
<file_sep>/marketing/templates/marketing/about.html
{% extends 'base.html' %}
{% load mezzanine_tags i18n pages_tags %}
{% block meta_title %}{{ page.title }}{% endblock %}
{% block extra_css %}
<style type="text/css">
.red{
color:#811001;
}
hr{
margin:0;
padding:0;
}
</style>
{% endblock %}
{% block meta_description %}{% metablock %}
{{ page.description|truncatewords:"25" }}
{% endmetablock %}{% endblock %}
{% block meta_keywords %}{% metablock %}
{% for keyword in page.keywords.all %}
{% if not forloop.first %}, {% endif %}
{{ keyword }}
{% endfor %}
{% endmetablock %}{% endblock %}
{% block page_class %}about{% endblock %}
{% block title_bread %}
<!--=== Breadcrumbs ===-->
<div class="breadcrumbs margin-bottom-10">
<div class="container">
<h1 class="pull-left">{% trans 'About Us' %}</h1>
<ul class="pull-right breadcrumb">
<li><a href="index.html">Home</a></li>
<li><a href="">Pages</a></li>
<li class="active">Invoice</li>
</ul>
</div><!--/container-->
</div><!--/breadcrumbs-->
<!--=== End Breadcrumbs ===-->
{% endblock %}
{% block main_content %}
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="headline"><h3>{% trans 'Our Clients' %}</h3></div>
<p>hello there herelllo</p>
</div>
</div>
</div>
<div class="hero-unit">
<div class="container">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="{{ STATIC_URL }}images/satisfaction-guaranteed.png" alt="{{ settings.SITE_TITLE}} satisfaction guaranteed">
</a>
<div class="media-body">
<h3 class="media-heading">{% trans 'The perfect blend of talent & opportunity.' %}</h3>
<!-- Nested media object -->
<div class="media">
<p class="lead red">{{ settings.SITE_TITLE }} is where companies and creative professionals
meet to make a better web. In other words, you.</p>
</div>
</div>
</div>
</div><!-- end container -->
</div><!--end hero -->
<div class="container clearfix" id="main-content">
<hr>
<!--begin main content-->
<p class="big"></p>
<div class="row-fluid">
<div class="span4"> <img class="aligncenter" src="../demo/about-me.png" alt="<NAME>" />
<h5><NAME></h5>
<h6><em>Designer</em></h6>
<p>Crisp is the industry leader of open-source user communities. We will enlarge our ability to synergize without lessening our aptitude to do something else.</p>
<ul class="social">
<li><a class="socicon facebook" href="#" title="Facebook"></a></li>
<li><a class="socicon twitterbird" href="#" title="Twitter"></a></li>
<li><a class="socicon linkedin" href="#" title="LinkedIn"></a></li>
<li><a class="socicon dribbble" href="#" title="dribble"></a></li>
</ul>
</div>
<!--close span4-->
<div class="span4"> <img class="aligncenter" src="../demo/about-3.png" alt="" />
<h5><NAME></h5>
<h6><em>Writer</em></h6>
<p>Image by <a href="http://fotogrph.com">fotogrph.</a> Nulla facilisi. Curabitur quis ligula est. In a sem eget ipsum blandit condimentum. Vestibulum lacinia accumsan dolor, sagittis venenatis nunc hendrerit quis.</p>
<ul class="social">
<li><a class="socicon facebook" href="#" title="Facebook"></a></li>
<li><a class="socicon twitterbird" href="#" title="Twitter"></a></li>
<li><a class="socicon linkedin" href="#" title="LinkedIn"></a></li>
<li><a class="socicon dribbble" href="#" title="dribble"></a></li>
</ul>
</div>
<!--close span4-->
<div class="span4"> <img class="aligncenter" src="../demo/about-2.png" alt="<NAME>" />
<h5><NAME></h5>
<h6><em>Programmer</em></h6>
<p>Image by <a href="http://fotogrph.com">fotogrph.</a> Fusce nunc lacus, tempor et aliquet lacinia, volutpat ut justo. Aenean sodales lacinia dignissim. Sed vel lorem ut augue pretium luctus. Sed semper purus sed erat placerat dapibus.</p>
<ul class="social">
<li><a class="socicon facebook" href="#" title="Facebook"></a></li>
<li><a class="socicon twitterbird" href="#" title="Twitter"></a></li>
<li><a class="socicon linkedin" href="#" title="LinkedIn"></a></li>
<li><a class="socicon dribbble" href="#" title="dribble"></a></li>
</ul>
</div>
<!--close span4 -->
</div>
<!--close row-fluid -->
<div class="row-fluid">
<h5>{% trans 'Anything else I should know?' %}</h5>
<p class="big">{% blocktrans %}Looking for more detail? Try the {{ settings.SITE_NAME }} FAQ. If you have specific questions or comments, let us know. You can contact us directly at {{ settings.SITE_EMAIL }} or {{ settings.SITE_PHONE }}{% endblocktrans %}</p>
</div>
<div class=" well row-fluid clientlogos">
<h3 class="margin-top lead"><span>{% trans 'You will also find your listing on these fantastic sites' %}</span></h3>
<p>{% trans 'Post a listing with us, and it’ll be featured across our network of partners and advertisers.' %}</p>
<ul class="slides">
<li><a href="http://twitter.com/{{ settings.TWITTER_ACCOUNT }}"
><img src="http://images.authenticjobs.com/partners/twitter.v1405370271.png" alt="" /></a></li>
<li><a href="http://facebook.com.com/{{ settings.FACEBOOK_ACCOUNT }}">
<img src="http://images.authenticjobs.com/partners/facebook.v1405370271.gif" alt="" /></li>
<li><img src="../demo/fakelogo-3.png" alt="" /></li>
<li><img src="../demo/fakelogo-4.png" alt="" /></li>
<li><img src="../demo/fakelogo-5.png" alt="" /></li>
</ul>
</div>
<!--close row-fluid clientlogos-->
</div>
<!--close .container id="main-content" -->
{% endblock %}<file_sep>/contact/views.py
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from mezzanine.utils.views import render
from mezzanine.conf import settings
from contact.forms import ContactForm
from contact.tasks import notify_admins
def contact(request, template_name = 'contact/contact.html'):
if request.method == 'POST':
contact_form = ContactForm(request.POST)
if contact_form.is_valid():
if request.user.is_authenticated():
contact_form.save(request.user)
else:
contact_form.save()
messages.info(request, _("<strong>Message Sent Successfully</strong>. We will be in touch shortly."),
extra_tags='success')
notify_admins.delay(subject = contact_form.cleaned_data['subject'],
body = contact_form.cleaned_data['message'],
from_email = contact_form.cleaned_data['email'],
to = [ settings.SITE_EMAIL ])
else:
contact_form = ContactForm()
context = {
'contact_form' : contact_form,
}
return render(request, template_name, context)
<file_sep>/gigs/urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('gigs.views',
url("^$", 'all_gigs', {"template_name": "gigs/index.html"}, name = "home"),
url("^(?P<searchincludetag>[-\w]+)-jobs-developers/$", 'all_gigs_long', {"template_name": "gigs/index_long.html"}, name = "home_long"),
url("^(?P<tag>[-\w]+)-jobs/$", 'all_gigs_tag', {"template_name": "gigs/index.html"}, name = "home_tag"),
url("^(?P<location>[-\w]+)-jobs/$", 'all_gigs_tag', {"template_name": "gigs/index.html"}, name = "home_tag_location"),
#url("^(?P<tag>[-\w]+)-(?P<location>[-\w]+)/$", 'all_gigs_tag', {"template_name": "gigs/index.html"}, name = "home_tag"),
#url("^find_jobs/$", 'find_jobs', name = "find_jobs"),
url('post-job-listing/$','post_job',{'template_name':'gigs/post_job.html'}, name = 'post_job'),
url('post-job-listing/(?P<slug>[-\w]+)/$','post_job',{'template_name':'gigs/post_job.html'}, name = 'post_job'),
url("^job/(?P<slug>[-\w]+)/$", 'get_gig', {"template_name": "gigs/get_gig.html"}, name="get_gig"),
url("^job_edit/(?P<slug>[-\w]+)/$", 'edit_gig', {"template_name": "gigs/edit_gig.html"}, name="edit_gig"),
# Company urls
url('company/(?P<slug>[-\w]+)/$', 'company_profile', {'template_name':'gigs/company/company_profile.html'}, name = 'company_profile'),
url('profile/listings/$', 'company_listings', {'template_name':'gigs/company/company_listings.html'}, name = 'company_listings'),
url('profile/infos/$', 'company_infos', {'template_name':'gigs/company/company_infos.html'}, name = 'company_infos'),
url('company/listing/(?P<slug>[-\w]+)/$', 'view_listing', {'template_name':'gigs/company/view_listing.html'}, name = 'view_listing'),
url('application/(?P<message_id>[\d]+)/$','application_detail', {'template_name':'gigs/company/application_detail.html'}, name = 'application_detail'),
url('application/(?P<sign>[-\w]+)/(?P<id>[-\w]+)/$','application_follower', {'template_name':'gigs/company/application_detail.html'}, name = 'application_follower'),
url('application/accept/$', 'application_accept', name = 'application_accept'),
url('application/status/$', 'set_application_status', name = 'set_application_status'),
url('application/save-note/$', 'save_note', name = 'save_note'),
url('company-profile/$', 'company_profile2', name='company_profile2'),
# Apply
url('profile/applications/$', 'applier_applications', {'template_name':'gigs/applier/applier_applications.html'}, name = 'applier_applications'),
#url('apply/(?P<gig_slug>[-\w]+)/$','apply',{'template_name':'gigs/apply.html'}, name = 'apply'),
url('apply/(?P<gig_slug>[-\w]+)/$','apply',{'template_name':'gigs/get_gig.html'}, name = 'apply'),
url('application/reply/(?P<application_id>[-\w]+)$', 'reply_to_apply', {'template_name':'gigs/company/application_detail.html'}, name = 'reply_to_apply'),
# Profile
#url('profile/account/password_reset$', django.contrib.auth.views.password_reset, {'template_name':'gigs/account.html'}, name = 'password_reset'),
# JobSeeker urls
url('my-profile/$', 'jobseeker_profile', name='jobseeker_profile'),
)
urlpatterns += patterns('gigs.utils.views',
#returns gig info for cart.html page using ajax
url('get_gig_info/(?P<sku>[-\w]+)/$','get_gig_info', name = 'get_gig_info'),
)
urlpatterns += patterns('',
#Profile
url(r'^account/$', 'gigs.views.account', {'template_name':'gigs/account.html'} , name='account'),
# profile password change
url(r'^account/password_change/$', 'django.contrib.auth.views.password_change', {'template_name':'gigs/company/account_password_change.html'}, name='password_change'),
url(r'^account/password_change/done/$', 'django.contrib.auth.views.password_change_done', {'template_name':'gigs/company/account_password_change_done.html'}, name='password_change_done'),
# Update profile
url(r'^account/update-profile/$', 'mezzanine.accounts.views.profile_update', {'template':'gigs/company/account_personal.html'} ,name='profile_update'),
# Account notifications
url(r'^account/notifications$', 'gigs.views.set_notifications', {'template_name':'gigs/company/account_notifications.html'}, name='account_notifications'),
# Profile picture
url(r'^account/profile-picture/$', 'gigs.views.save_profile_picture', name='save_profile_picture'),
)<file_sep>/README.md
rien
====<file_sep>/searchapp/admin.py
from django.contrib import admin
from searchapp.models import GigSearch
class GigSearchAdmin(admin.ModelAdmin):
list_display = ('user', 'what', 'location', 'is_onsite',
'subscribed_user', 'publish_date', 'ip_address',)
admin.site.register(GigSearch, GigSearchAdmin)
<file_sep>/gigs/notify.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from mezzanine.utils.email import send_mail_template
from gigs.models import Company
@receiver(post_save, sender = Company)
def welcome_company(sender, **kwargs):
print kwargs
subject = 'welcome'
addr_from = '<EMAIL>'
#addr_to = sender.email
addr_to = '<EMAIL>'
template = "email/comment_notification"
send_mail_template(subject, template, addr_from, addr_to, context=None,
attachments=None, fail_silently = settings.DEBUG)<file_sep>/contact/forms.py
from django import forms
from contact.models import Contact
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
exclude = ['user',]
def save(self, user = None, commit = True):
instance = super(ContactForm, self).save(commit=False)
if user:
instance.user = user
if commit:
instance.save()
return instance<file_sep>/faqs/views.py
from django.http import Http404
from mezzanine.utils.views import render
from faqs.models import Faq
def faqs_list(request, template_name = 'faqs/faqs_list.html'):
"""
returns a list of published FAQs
"""
try:
faqs = Faq.objects.published()
except:
raise Http404
context = {
'faqs' : faqs,
}
return render(request, template_name, context)<file_sep>/templates/accounts/account_signup.html
{% extends "accounts/account_form.html" %}
{% load i18n mezzanine_tags %}
{% block main %}
{% if request.user.is_authenticated %}
<p>{% trans "You're already logged in. If you'd like to create a new account, you'll need to log out first." %}</p>
{% else %}
<div class="register-box clearfix">
<h2 class="short_headline"><span>{% trans 'Create your Resume' %}</span></h2>
<form class="form-horizontal" action="" method="post">
<fieldset>{% csrf_token %}
<div class="control-group input_id_first_name {% if form.first_name.errors %}error{% endif %}">
<label for="id_first_name" class="required control-label">{% trans 'First Name' %} <span class="required">*</span></label>
<div class="controls">
<input name="first_name" id="id_first_name" class="span12" type="text" autofocus value="{% if form.first_name.value %}{{ form.first_name.value }}{% endif %}" />
{% if form.first_name.errors %}
<span class="help-inline">
{% for error in form.first_name.errors %}
{{ error }}
{% endfor %}
</span>
{% endif %}
</div>
</div>
<div class="control-group input_id_last_name {% if form.last_name.errors %}error{% endif %}">
<label for="id_last_name" class="required control-label">{% trans 'Last Name' %} <span class="required">*</span></label>
<div class="controls">
<input name="last_name" id="id_last_name" class="span12" type="text" value="{% if form.last_name.value %}{{ form.last_name.value }}{% endif %}" />
{% if form.last_name.errors %}
<span class="help-inline">
{% for error in form.last_name.errors %}
{{ error }}
{% endfor %}
</span>
{% endif %}
</div>
</div>
<div class="control-group input_id_email {% if form.email.errors %}error{% endif %}">
<label for="id_email" class="required control-label">Email <span class="required">*</span></label>
<div class="controls">
<input name="email" id="id_email" class="span12" type="email" value="{% if form.email.value %}{{ form.email.value }}{% endif %}"/>
{% if form.email.errors %}
<span class="help-inline">
{% for error in form.email.errors %}
{{ error }}
{% endfor %}
</span>
{% endif %}
</div>
</div>
<div class="control-group input_id_username {% if form.username.errors %}error{% endif %}">
<label for="id_username" class="required control-label">Username <span class="required">*</span></label>
<div class="controls">
<input name="username" id="id_username" class="span12" type="text" value="{% if form.username.value %}{{ form.username.value }}{% endif %}"/>
{% if form.username.errors %}
<span class="help-inline">
{% for error in form.username.errors %}
{{ error }}
{% endfor %}
</span>
{% endif %}
</div>
</div>
<div class="control-group input_id_password1 {% if form.password1.errors %}error{% endif %}">
<label for="id_password1" class="required control-label">Password <span class="required">*</span></label>
<div class="controls">
<input name="password1" id="id_password1" class="span12" type="password" value="{% if form.password1.value %}{{ form.password1.value }}{% endif %}" />
{% if form.password1.errors %}
<span class="help-inline">
{% for error in form.password1.errors %}
{{ error }}
{% endfor %}
</span>
{% endif %}
</div>
</div>
<div class="control-group input_id_password2 {% if form.password2.errors %}error{% endif %}">
<label for="id_password2" class="required control-label">Password (again) <span class="required">*</span></label>
<div class="controls">
<input name="password2" id="id_password2" class="span12" type="password" value="{% if form.password2.value %}{{ form.password2.value }}{% endif %}" />
{% if form.password2.errors %}
<span class="help-inline">
{% for error in form.password2.errors %}
{{ error }}
{% endfor %}
</span>
{% endif %}
</div>
</div>
<div class="form-actions">
<input class="btn btn-primary btn-large" type="submit" name="register" value="{{ title }}" />
</div>
</fieldset>
</form>
<!-- end registration form-->
<p>Already have an account? <a href="{% url login %}">Login.</a></p>
</div>
<!--close .register-box-->
{% if settings.ACCOUNTS_VERIFICATION_REQUIRED %}
<p>{% trans "After signing up, you'll receive an email with a link you need to click, in order to activate your account." %}</p>
{% endif %}
{% endif %}
{% endblock %}
<file_sep>/utils_app/templatetags/messages_tags.py
from django import template
from django_messages.models import Message
from collections import deque
register = template.Library()
def get_parents(message, messages_list):
parent_message = getattr(message, 'parent_msg', False)
if isinstance(parent_message, Message):
messages_list.append(parent_message)
get_parents(parent_message, messages_list)
@register.inclusion_tag('utils_app/message_family.html')
def message_family(message):
messages_list = []
get_parents(message, messages_list)
return {'messages' : messages_list}
<file_sep>/gigs/migrations/0048_auto__del_field_company_type__add_field_company_company_name.py
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Company.type'
db.delete_column('gigs_company', 'type')
# Adding field 'Company.company_name'
db.add_column('gigs_company', 'company_name',
self.gf('django.db.models.fields.CharField')(default='', max_length=500),
keep_default=False)
def backwards(self, orm):
# Adding field 'Company.type'
db.add_column('gigs_company', 'type',
self.gf('django.db.models.fields.CharField')(default='', max_length=200),
keep_default=False)
# Deleting field 'Company.company_name'
db.delete_column('gigs_company', 'company_name')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'django_messages.message': {
'Meta': {'ordering': "['-sent_at']", 'object_name': 'Message'},
'body': ('django.db.models.fields.TextField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'parent_msg': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'next_messages'", 'null': 'True', 'to': "orm['django_messages.Message']"}),
'read_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'recipient': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'received_messages'", 'null': 'True', 'to': "orm['auth.User']"}),
'recipient_deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'replied_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'sender': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sent_messages'", 'to': "orm['auth.User']"}),
'sender_deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'sent_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '120'})
},
'feedb.feedback': {
'Meta': {'object_name': 'Feedback'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'feedback': ('django.db.models.fields.TextField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'rating': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'submit_date': ('django.db.models.fields.DateTimeField', [], {'default': 'None'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'feedbacks'", 'to': "orm['auth.User']"})
},
'generic.assignedkeyword': {
'Meta': {'ordering': "('_order',)", 'object_name': 'AssignedKeyword'},
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'keyword': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'assignments'", 'to': "orm['generic.Keyword']"}),
'object_pk': ('django.db.models.fields.IntegerField', [], {})
},
'generic.keyword': {
'Meta': {'object_name': 'Keyword'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
},
'generic.rating': {
'Meta': {'object_name': 'Rating'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_pk': ('django.db.models.fields.IntegerField', [], {}),
'rating_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'ratings'", 'null': 'True', 'to': "orm['auth.User']"}),
'value': ('django.db.models.fields.IntegerField', [], {})
},
'gigs.application': {
'Meta': {'ordering': "['-sent_at']", 'object_name': 'Application', '_ormbases': ['django_messages.Message']},
'favorited_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gig': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gigs.Gig']", 'null': 'True', 'blank': 'True'}),
'is_read_by_sender': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}),
'message_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['django_messages.Message']", 'unique': 'True', 'primary_key': 'True'}),
'printed_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'rejected_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'resume': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gigs.Resume']"}),
'status': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['gigs.ChildStatus']", 'symmetrical': 'False'})
},
'gigs.category': {
'Meta': {'object_name': 'Category'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_custom': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
},
'gigs.childstatus': {
'Meta': {'object_name': 'ChildStatus'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'default': "'NEW'", 'max_length': '15'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'gigs.company': {
'Meta': {'object_name': 'Company'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'company_name': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'ip_address': ('django.db.models.fields.GenericIPAddressField', [], {'max_length': '39'}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}),
'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'profile_picture': ('django.db.models.fields.files.ImageField', [], {'default': "'/static/media/company_logos/employer_default.png'", 'max_length': '255', 'null': 'True', 'blank': 'True'}),
'profile_picture_choice': ('django.db.models.fields.CharField', [], {'default': "u'No picture'", 'max_length': '60'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'title_is_confidential': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'twitter_username': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}),
'valid': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'gigs.gig': {
'Meta': {'object_name': 'Gig', '_ormbases': ['shop.Product']},
'apply_instructions': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'area_level1': ('django.db.models.fields.CharField', [], {'max_length': '25', 'null': 'True', 'blank': 'True'}),
'area_level2': ('django.db.models.fields.CharField', [], {'max_length': '25', 'null': 'True', 'blank': 'True'}),
'area_level3': ('django.db.models.fields.CharField', [], {'max_length': '25', 'null': 'True', 'blank': 'True'}),
'area_level4': ('django.db.models.fields.CharField', [], {'max_length': '25', 'null': 'True', 'blank': 'True'}),
'by_us': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'company': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gigs.Company']"}),
'gig_categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['gigs.Category']", 'symmetrical': 'False'}),
'hidden_tags': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'how_to_apply': ('django.db.models.fields.CharField', [], {'default': "'VIA_EMAIL'", 'max_length': '15'}),
'is_filled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_relocation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_remote': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'job_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gigs.GigType']"}),
'latitude': ('django.db.models.fields.CharField', [], {'max_length': '25'}),
'location': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'longitude': ('django.db.models.fields.CharField', [], {'max_length': '25'}),
'perks': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'processed': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}),
'product': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['shop.Product']", 'unique': 'True', 'primary_key': 'True'}),
'tags': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'valid': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'via_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'via_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
'gigs.gigstat': {
'Meta': {'object_name': 'GigStat'},
'clicked_apply': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notified_users': ('django.db.models.fields.IntegerField', [], {}),
'views': ('django.db.models.fields.IntegerField', [], {})
},
'gigs.gigtype': {
'Meta': {'object_name': 'GigType'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'on_site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'price': ('djmoney.models.fields.MoneyField', [], {'frozen_by_south': 'True', 'max_digits': '10', 'decimal_places': '2', 'default_currency': "'USD'"}),
'price_currency': ('djmoney.models.fields.CurrencyField', [], {'default': "'USD'"}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '20'})
},
'gigs.jobseekerprofile': {
'Meta': {'object_name': 'JobSeekerProfile'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'area_level1': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}),
'area_level2': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'ip_address': ('django.db.models.fields.GenericIPAddressField', [], {'max_length': '39'}),
'is_looking': ('django.db.models.fields.NullBooleanField', [], {'default': 'True', 'null': 'True', 'blank': 'True'}),
'is_relocation': ('django.db.models.fields.NullBooleanField', [], {'default': 'True', 'null': 'True', 'blank': 'True'}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}),
'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'latitude': ('django.db.models.fields.CharField', [], {'max_length': '25', 'null': 'True', 'blank': 'True'}),
'location': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'longitude': ('django.db.models.fields.CharField', [], {'max_length': '25', 'null': 'True', 'blank': 'True'}),
'profile_picture': ('django.db.models.fields.files.ImageField', [], {'default': "'job_seekers_pictures/.thumbnails/job_seeker_picture.png'", 'max_length': '255', 'null': 'True', 'blank': 'True'}),
'profile_picture_choice': ('django.db.models.fields.CharField', [], {'default': "u'No picture'", 'max_length': '60'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'twitter_username': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'gigs.note': {
'Meta': {'object_name': 'Note'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'application': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gigs.Application']"}),
'content': ('mezzanine.core.fields.RichTextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}),
'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'notes'", 'to': "orm['auth.User']"})
},
'gigs.resume': {
'Meta': {'object_name': 'Resume'},
'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'pages.page': {
'Meta': {'ordering': "('titles',)", 'object_name': 'Page'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'content_model': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_menus': ('mezzanine.pages.fields.MenusField', [], {'default': '(1, 2, 3)', 'max_length': '100', 'null': 'True', 'blank': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}),
'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['pages.Page']"}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'titles': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'})
},
'shop.category': {
'Meta': {'ordering': "('_order',)", 'object_name': 'Category', '_ormbases': ['pages.Page']},
'combined': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'content': ('mezzanine.core.fields.RichTextField', [], {}),
'featured_image': ('mezzanine.core.fields.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'options': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'product_options'", 'blank': 'True', 'to': "orm['shop.ProductOption']"}),
'page_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['pages.Page']", 'unique': 'True', 'primary_key': 'True'}),
'price_max': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'price_min': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Product']", 'symmetrical': 'False', 'blank': 'True'}),
'sale': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['shop.Sale']", 'null': 'True', 'blank': 'True'})
},
'shop.product': {
'Meta': {'object_name': 'Product'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'available': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Category']", 'symmetrical': 'False', 'blank': 'True'}),
'content': ('mezzanine.core.fields.RichTextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}),
'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'num_in_stock': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'rating': ('mezzanine.generic.fields.RatingField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.Rating']", 'frozen_by_south': 'True'}),
'rating_average': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'rating_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'rating_sum': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'related_products': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'related_products_rel_+'", 'blank': 'True', 'to': "orm['shop.Product']"}),
'sale_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'sale_id': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'sale_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'sale_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'unit_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'upsell_products': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'upsell_products_rel_+'", 'blank': 'True', 'to': "orm['shop.Product']"})
},
'shop.productoption': {
'Meta': {'object_name': 'ProductOption'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('cartridge.shop.fields.OptionField', [], {'max_length': '50', 'null': 'True'}),
'type': ('django.db.models.fields.IntegerField', [], {})
},
'shop.sale': {
'Meta': {'object_name': 'Sale'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'sale_related'", 'blank': 'True', 'to': "orm['shop.Category']"}),
'discount_deduct': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'discount_exact': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'discount_percent': ('cartridge.shop.fields.PercentageField', [], {'null': 'True', 'max_digits': '5', 'decimal_places': '2', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Product']", 'symmetrical': 'False', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'valid_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'valid_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
}
}
complete_apps = ['gigs']<file_sep>/planet/defaults.py
"""
Default settings for the ``mezzanine.core`` app. Each of these can be
overridden in your project's settings module, just like regular
Django settings. The ``editable`` argument for each controls whether
the setting is editable via Django's admin.
Thought should be given to how a setting is actually used before
making it editable, as it may be inappropriate - for example settings
that are only read during startup shouldn't be editable, since changing
them would require an application reload.
"""
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import register_setting
register_setting(
name="PLANET_JOBS_CATEGORY",
description=_("Planet Jobs category"),
editable=True,
default="",
)
register_setting(
name="PLANET_BLOGS_CATEGORY",
description=_("Planet blogs category"),
editable=True,
default="",
)
register_setting(
name="PLANET_FORUMS_CATEGORY",
description=_("Planet Forums/ Q&A category"),
editable=True,
default="",
)
register_setting(
name="PLANET_LINKS_CATEGORY",
description=_("Planet Links category"),
editable=True,
default="",
)
register_setting(
name="PLANET_PACKAGES_CATEGORY",
description=_("Planet Packages category"),
editable=True,
default="",
)
register_setting(
name="TEMPLATE_ACCESSIBLE_SETTINGS",
description=_("Sequence of setting names available within templates."),
editable=False,
default=(
"PLANET_JOBS_CATEGORY", "PLANET_BLOGS_CATEGORY",
"PLANET_FORUMS_CATEGORY", "PLANET_LINKS_CATEGORY",
"PLANET_PACKAGES_CATEGORY",
),
append=True,
)
<file_sep>/gigs/quickstart.py
#!/usr/bin/python
import httplib2
import pprint
import os,sys
#Settings are imported
#because environment variable DJANGO_SETTINGS_MODULE is not defined
path=os.path.dirname(os.path.abspath(__file__))
path=os.path.join(path,'..')
sys.path.insert(0,path)
os.environ['DJANGO_SETTINGS_MODULE']='settings'
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow
from mezzanine.conf import settings
# Copy your credentials from the APIs Console
CLIENT_ID = settings.GOOGLE_CLIENT_ID
CLIENT_SECRET = settings.GOOGLE_CLIENT_SECRET
# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
# Redirect URI for installed apps
#REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
REDIRECT_URI = 'http://localhost:8000'
# Path to the file to upload
FILENAME = '/Users/elmahdibouhram/job_connector/gigs/document.txt'
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)
# Insert a file
media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
body = {
'title': 'My document',
'description': 'admin',
'mimeType': 'text/plain'
}
file = drive_service.files().insert(body=body, media_body=media_body).execute()
pprint.pprint(file)<file_sep>/templates/notification/notify_company_about_job/full.html
{% load i18n %}
{% trans 'Hello,' %}<br />
{% if group == 'Company' %}
{% if SHOP_PAYMENT_STEP_ENABLED %}
{% blocktrans %}
<p>
Your Job Listing <strong>{{ GIG_TITLE }}</strong> has been added to <strong>{{ SITE_TITLE }}</strong>. <br />Upon receipt of payment, it will be <u>validated</u> by us and published. Thank you for your patience.</p>
{% endblocktrans %}
{% else %}
{% blocktrans %}
<p>
Your Job Listing <strong>{{ GIG_TITLE }}</strong> has been added to <strong>{{ SITE_TITLE }}</strong>. <br />It will be <u>validated</u> by us and published. Thank you for your patience.</p>
{% endblocktrans %}
{% endif %}
{% blocktrans %}
<p>You can make edits to your Job Listing and monitor job applications in the link below :<br />
<a target="_blank" href="http://{{ LISTINGS_LINK }}">http://{{ LISTINGS_LINK }}</a>
</p>
{% endblocktrans %}
{% endif %}
<file_sep>/planet/templates/planet/posts/blog_list_extension.html
{% load i18n pagination_tags planet_tags %}
{% load url from future %}
{% for post in posts %}
<div class="post">
{% comment %}{% post_details post %}{% endcomment %}
<h3 class="media-heading">
<a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a>
</h3>
{{ post.date_created|date:"d, M" }}
<p>{{ post.content|safe|truncatewords_html:100 }}</p></i></strong>
</div>
<hr>
{% endfor %}<file_sep>/linked_thief/urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
#url("^/save-profile/(?P<attach>[-\w]+)$", 'utils_app.views.email_resume', {'template_name' : 'gigs/company/application_detail.html'} , name = "email_resume"),
url("^/save-profile/$", 'linked_thief.views.linked_save_profile', name = "linked_save_profile"),
)
<file_sep>/searchapp/views.py
from django.conf import settings
from django.core import serializers
from django.http import HttpResponse
from django.utils import simplejson
from django.utils.translation import ugettext_lazy as _
from mezzanine.utils.sites import current_site_id
from mezzanine.utils.views import render, paginate
from gigs.models import GigType
from searchapp.forms import GigSearchForm
from searchapp.models import GigSearch
from searchapp.search import store, get_results
def get_gig_types_to_display(list1, list2):
delta = len (list1) - len(list2)
if delta == 2:
return _('(%s)' % ' & '.join([GigType.objects.get(id = item).type for item in list2]))
elif delta == 3:
return _('(except %s)' % GigType.objects.get(id = list2[0]).type)
elif delta == 4:
return ''
def search_objects(request, template_name = 'gigs/index.html'):
gig_search_form = GigSearchForm(request.POST)
#if request.method == 'POST' and request.is_ajax():
if request.method == 'POST':
if gig_search_form.is_valid():
what = gig_search_form.cleaned_data['what'].strip()
location = gig_search_form.cleaned_data['location'].strip()
remote = True if request.POST.get('remote') else False
#gig_types = gig_search_form.cleaned_data['gig_types']
#gig_types = request.POST['gig_types']
#print 'gig types : %s ' % gig_types
#page = request.POST['page']
gig_types_string = '%s %s %s %s' % (request.POST.get('Full-time',''),
request.POST.get('Internship',''),
request.POST.get('Contract',''),
request.POST.get('Freelance',''),
)
#elif request.method == 'GET' and request.is_ajax():
elif request.method == 'GET':
page = request.GET.get('page')
gig_types = request.GET.get('gig_types', None)
remote = True if request.GET.get('remote') else False
gig_types_string = request.GET.get('gig_types_string', '')
#response = simplejson.dumps({
# 'results' : get_results(what, location, page, gig_types),
# 'what' : what.capitalize(),
# 'location' : location.title(),
# })
#http_response = HttpResponse(response, content_type='application/javascript')
gig_types = GigType.objects.filter(on_site=current_site_id())
gig_types_list = [ gig_type.id for gig_type in gig_types if str(gig_type.id) not in gig_types_string]
# STORE search terms
store(request, what, location, gig_types_string, remote)
results = get_results(what, location, request.GET.get("page", 1), gig_types_list, remote)
print 'search objects : %s jobs ' % len(results)
gigs = paginate(results, request.GET.get("page", 1),
settings.GIGS_PER_PAGE,
settings.MAX_PAGING_LINKS)
context = {
'gigs' : gigs,
'what' : what.capitalize(),
#'location' : '' if location is None else location.capitalize(),
'location' : location.capitalize(),
'gig_search_form' : gig_search_form,
'gig_types' : gig_types,
'gig_types_string' : gig_types_string,
'gig_types_list' : gig_types_list,
'gig_types_to_display' : get_gig_types_to_display(gig_types, gig_types_list),
'remote' : remote,
}
return render(request, template_name, context)
<file_sep>/searchapp/models.py
from django.contrib.auth.models import User
from django.db import models
from mezzanine.core.models import Displayable
from gigs.models import GigType
class BaseSearch(Displayable):
"""
Base Model for Search
"""
what = models.CharField(max_length = 100, null = True, blank = True)
location = models.CharField(max_length = 50, null = True, blank = True)
longitude = models.CharField(max_length = 25, null = True, blank = True)
latitude = models.CharField(max_length = 25, null = True, blank = True)
area_level1 = models.CharField(max_length = 20, blank = True, null = True)
area_level2 = models.CharField(max_length = 20, blank = True, null = True)
ip_address = models.GenericIPAddressField()
user = models.ForeignKey(User, null = True, blank = True)
subscribed_user = models.EmailField(blank = True, null = True)
class Meta:
abstract = True
class ResumeSearch(BaseSearch):
pass
class GigSearch(BaseSearch):
is_onsite = models.NullBooleanField()
gig_type = models.ManyToManyField(GigType)
#full_time = models.NullBooleanField(default=True)
#contract = models.NullBooleanField(default=True)
#freelance = models.NullBooleanField(default=True)
#internship = models.NullBooleanField(default=True)
def __unicode__(self):
return ("{0} {1}").format(self.what, self.location)
@models.permalink
def get_absolute_url(self):
url_name = 'find_jobs'
kwargs = {}
return (url_name, (), kwargs)
<file_sep>/gigs/utils/views.py
from django.http import HttpResponse
from django.utils import simplejson
from cartridge.shop.models import ProductVariation
from mezzanine.utils.timezone import now
from gigs.models import Application
def application_messages(application, user = None, application_followup = []):
for message in application.next_messages.all().order_by('sent_at'):
if user == message.recipient and message.read_at is None:
message.read_at = now()
message.save()
application_followup.append(message)
application_messages(message, user , application_followup)
return application_followup
def get_gig_info(request, sku):
"""
Returns gig object from sku
"""
gig = ProductVariation.objects.filter(sku = sku)[0].product.gig
response = simplejson.dumps({
'gig_type' : gig.job_type.type,
'gig_picture' : gig.company.twitter_username or gig.company.profile_picture.name,
'gig_twitter_username' : gig.company.twitter_username,
})
return HttpResponse(response, content_type='application/javascript')
def application_count_for(user):
"""
returns the number of unread messages for the given user but does not
mark them seen
"""
return Application.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True).count()
def unread_applications(user):
"""
returns the number of unread messages for the given user but does not
mark them seen
"""
return Application.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True)
def read_applications(user):
"""
returns the read applications for the given sender but does not
mark them seen
"""
return Application.objects.filter(sender=user, read_at__isnull=False, is_read_by_sender=False, recipient_deleted_at__isnull=True)
<file_sep>/faqs/urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('faqs.views',
url("^/$", 'faqs_list', {"template_name": "faqs/faqs_list.html"}, name = "faqs"),
)
<file_sep>/marketing/feeds.py
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed
# find a use for reverse
#from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from mezzanine.utils.sites import current_site_id
from mezzanine.conf import settings
from gigs.models import Gig, GigType
from searchapp.search import get_results
class GigFeed(Feed):
"""
RSS Feed for gigs
"""
# need to add Description
def get_object(self, request, *args, **kwargs):
self.what = request.GET.get('what', None)
self.location = request.GET.get('location', None)
gig_types = GigType.objects.all()
if request.GET.get('gig_types_string'):
self.gig_types_list = [ gig_type.id for gig_type in gig_types
if str(gig_type.id) not in request.GET.get('gig_types_string')]
else:
self.gig_types_list = list()
self.remote = request.GET.get('remote', False)
def link(self):
# need to not hard code it
return '/jobs/feed/'
def title(self):
settings.use_editable()
return _('%s Job Listings' % settings.SITE_TITLE)
def items(self):
return get_results(what = self.what, location = self.location,
page = 1, gig_types_list = self.gig_types_list, remote = self.remote)
def item_title(self, item):
return '[%s] %s, %s' % (item.job_type.type, item.title.capitalize(), item.location)
def item_description(self, item):
# would i just want to return 25 words or the whole descr
return truncate_words(item.description.capitalize(), num = 25)
def item_pubdate(self, item):
return item.publish_date
def item_categories(self, item):
return [ category for category in item.gig_categories.all()]
<file_sep>/utils_app/tasks.py
from celery import task
from django.contrib.sitemaps import ping_google
from notification import models as notification
@task
def ping_search_engines():
print 'pinging search engines ...'
ping_google()
print 'done pinging'
@task
def notification_send_now_task(user, label, extra_context, sender):
notification.send_now(users=[user], label=label,
extra_context=extra_context, sender=sender)
<file_sep>/stats/admin.py
from django.contrib import admin
from stats.models import Metric, MetricItem, MetricSet
class MetricAdmin(admin.ModelAdmin):
list_display = ['name',]
class MetricItemAdmin(admin.ModelAdmin):
list_display = ['metric', 'content_object', 'user', 'referrer' ,'publish_date',]
class MetricSetAdmin(admin.ModelAdmin):
list_display = ['name', 'content_object',]
admin.site.register(Metric, MetricAdmin)
admin.site.register(MetricItem, MetricItemAdmin)
admin.site.register(MetricSet, MetricSetAdmin)<file_sep>/gigs/defaults.py
"""
Default settings for the ``mezzanine.blog`` app. Each of these can be
overridden in your project's settings module, just like regular
Django settings. The ``editable`` argument for each controls whether
the setting is editable via Django's admin.
Thought should be given to how a setting is actually used before
making it editable, as it may be inappropriate - for example settings
that are only read during startup shouldn't be editable, since changing
them would require an application reload.
"""
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import register_setting
register_setting(
name="RECRUITMENT_IS_ACTIVE",
label=_("RECRUITMENT IS ACTIVE"),
description=_("If the recruiting is active"),
editable=True,
default= False,
)
register_setting(
name="SITE_IS_ACTIVE",
label=_("SITE IS ACTIVE"),
description=_("If site is active"),
editable=True,
default= True,
)
register_setting(
name="SITE_MULTIPLE_LANG",
label=_("SITE IS MULTIPLE LANG"),
description=_("Does the site support multiple langs"),
editable=True,
default=False,
)
register_setting(
name="SITE_SECOND_LANG",
label=_("SITE SECOND LANG"),
description=_("Site second language"),
editable=True,
choices = (
('ENGLISH', 'ENGLISH'),
('DUTCH', 'DUTCH'),
('DEUTSCH', 'DEUTSCH'),
('FRANCAIS', 'FRANCAIS'),
),
default='ENGLISH',
)
register_setting(
name="SITE_SEARCH_INCLUDE_TAG",
label=_("Site search INCLUDE tag"),
# could be general mission / vision / description
description=_("Include search tag used in retrieving \
gigs from other websites"),
editable=True,
default= '',
)
register_setting(
name="SITE_THEME",
label=_("Site's theme"),
# could be general mission / vision / description
description=_("name of site's theme"),
editable=True,
default= 'default',
)
register_setting(
name="SITE_DOMAIN",
label=_("Site's domain name"),
# could be general mission / vision / description
description=_("Site's domain name"),
editable=True,
default= 'www.djangojobs.org',
)
register_setting(
name="SITE_ABOUT_US",
label=_("Site about us"),
# could be general mission / vision / description
description=_("Site about us"),
editable=True,
default= '',
)
register_setting(
name="BLOG_USE_FEATURED_IMAGE",
label=_("Blog use featured image "),
description=_("Enable featured images in blog posts"),
editable=True,
default= 'True',
)
register_setting(
name="BLOG_EXTENDED",
label=_("Blog extended"),
description=_("Blog Posts list extended"),
editable=True,
default=False,
)
register_setting(
name="SITE_ADDRESS",
label=_("Address *"),
description=_("Site address"),
editable=True,
default= '836 Sierra Vista Mountain View Ca',
)
register_setting(
name="SITE_LOCATION_LOOKUP",
label=_("Location lookup"),
description=_("Location lookup example : San Francisco, Seattle etc"),
editable=True,
default='San Francisco, CA; Seattle; Anywhere',
)
register_setting(
name="SITE_EMAIL",
label=_("A dedicated email address to the side"),
description=_("eg. <EMAIL>"),
editable=True,
default= '<EMAIL>',
)
register_setting(
name="SITE_CURRENCY",
label=_("Site Currency"),
description=_("The website currecy, needed for Paypal"),
editable=True,
default= 'USD',
)
register_setting(
name="SITE_HERO_UNIT",
label=_("Site Hero unit *"),
description=_("site hero unit"),
editable=True,
default= '',
)
register_setting(
name="SITE_META_TITLE",
label=_("Site Meta Title"),
# could be general mission / vision / description
description=_("First part of the site's title"),
editable=True,
default= '',
)
register_setting(
name="SITE_LANGUAGE",
label=_("Site Language *"),
description=_("The site language"),
editable=True,
default= 'en',
)
register_setting(
name="SITE_COUNTRY",
label=_("Site Country *"),
description=_("country matches a country name or a two letter ISO 3166-1 country code \
refer to : https://developers.google.com/maps/documentation/geocoding/ and http://en.wikipedia.org/wiki/CcTLD"),
editable=True,
default= 'us',
)
register_setting(
name="SITE_OPERATOR",
label=_("Site Operator"),
description=_("Responsible for customer service"),
editable=True,
default= 'Mike',
)
register_setting(
name="SITE_PHONE",
label=_("Phone *"),
description=_("Site phone"),
editable=True,
default= '',
)
register_setting(
name="SITE_STATE",
label=_("SITE STATE"),
description=_("eg. Florida / Eastern Time"),
editable=True,
default= '',
)
register_setting(
name="SITE_META_DESCRIPTION",
label=_("SITE META DESCRIPTION *"),
description=_("contains the site description meta tag"),
editable=True,
default= '',
)
register_setting(
name="SITE_META_KEYWORDS",
label=_("SITE META KEYWORDS *"),
description=_("contains the site keywords meta tag"),
editable=True,
default= '',
)
register_setting(
name="SITE_INDEX_EXTENDED",
label=_("Site index page extended"),
description=_("The site index page has an extension to help for seo"),
editable=True,
default=False,
)
register_setting(
name="SITE_INDEX_EXTENDED_VISIBLE",
label=_("Site index page extended Visibility"),
description=_("Visibility of site index page extension"),
editable=True,
default=False,
)
register_setting(
name="PAYPAL_USER",
label=_("Paypal User *"),
description=_("Paypal user"),
editable=True,
default= 'contact_api1.djangojobs.org',
)
register_setting(
name="PAYPAL_PASSWORD",
label=_("Paypal password *"),
description=_("Paypal password"),
editable=True,
default= '<PASSWORD>',
)
register_setting(
name="PAYPAL_SIGNATURE",
label=_("Paypal signature *"),
description=_("Paypal signature"),
editable=True,
default= 'AR6gDcq86QpriE9SFyYUOIjn4mByANdDCi9Tmu.OemEkbdE6g-dDyWVO',
)
register_setting(
name="TWITTER_ACCOUNT",
label=_("Site twitter account *"),
description=_("Twitter account link"),
editable=True,
default= '',
)
register_setting(
name="TWITTER_CONSUMER_KEY",
label=_("Site twitter consumer key *"),
description=_("Twitter consumer key"),
editable=True,
default= '',
)
register_setting(
name="TWITTER_CONSUMER_SECRET",
label=_("Site twitter consumer secret *"),
description=_("Twitter consumer secret"),
editable=True,
default= '',
)
register_setting(
name="TWITTER_ACCESS_TOKEN",
label=_("Site twitter access token *"),
description=_("Twitter access token"),
editable=True,
default= '',
)
register_setting(
name="TWITTER_ACCESS_TOKEN_SECRET",
label=_("Site twitter access token secret *"),
description=_("Twitter access token secret"),
editable=True,
default= '',
)
register_setting(
name="SITE_FACEBOOK_ACCOUNT",
label=_("Site facebook account *"),
description=_("Facebook account link"),
editable=True,
default= 'http://facebook.com',
)
register_setting(
name="SITE_LINKEDIN_ACCOUNT",
label=_("Site linkedin account *"),
description=_("Linkedin account link"),
editable=True,
default= 'http://linkedin.com',
)
register_setting(
name="SITE_GOOGLE_PLUS",
label=_("Google plus account *"),
description=_("Google plus account link"),
editable=True,
default= '',
)
register_setting(
name="TEMPLATE_ACCESSIBLE_SETTINGS",
description=_("Sequence of setting names available within templates."),
editable=False,
default=("RECRUITMENT_IS_ACTIVE", "SITE_ABOUT_US", "BLOG_USE_FEATURED_IMAGE", "SITE_ADDRESS", "SITE_COUNTRY",
"SITE_CURRENCY", "SITE_EMAIL", "SITE_HERO_UNIT", "SITE_LANGUAGE",
"SITE_LOCATION_LOOKUP", "SITE_OPERATOR", "SITE_META_TITLE", "SITE_SEARCH_INCLUDE_TAG",
"SITE_PHONE", "SITE_STATE", "SITE_META_DESCRIPTION", "SITE_META_KEYWORDS",
"SHOP_PAYMENT_STEP_ENABLED","PAYPAL_USER", "PAYPAL_PASSWORD", "PAYPAL_SIGNATURE",
"TWITTER_ACCOUNT", "SITE_FACEBOOK_ACCOUNT", "SITE_LINKEDIN_ACCOUNT",
"SITE_GOOGLE_PLUS", "SITE_ACTIVE", "SITE_THEME", "SITE_DOMAIN", "SITE_MULTIPLE_LANG",
"SITE_SECOND_LANG", "SITE_INDEX_EXTENDED", "SITE_INDEX_EXTENDED_VISIBLE",
"BLOG_EXTENDED",),
append=True,
)
<file_sep>/templates/notification/notify_applicant/full.html
{% load i18n %}
{% trans 'Hello,' %}<br />
{% blocktrans %}
<p>
You applied successfully to <strong>{{ GIG_TITLE }}</strong>.</p>
<p>You can the monitor the <u>status</u> change of your application in the following link : <br />
<a target="_blank" href="http://{{ APPLICATIONS_LINK }}">http://{{ APPLICATIONS_LINK }}</a>
</p>
{% endblocktrans %}
<file_sep>/marketing/admin.py
from django.contrib import admin
from marketing.models import PreLaunch
class PreLaunchAdmin(admin.ModelAdmin):
list_display = ['email', 'publish_date', 'site',]
admin.site.register(PreLaunch, PreLaunchAdmin)
<file_sep>/gigs/forms.py
import logging
from django import forms
from django.conf import settings
from django.contrib.auth.models import User, Group
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from mezzanine.accounts.forms import ProfileForm
from mezzanine.core.forms import TinyMceWidget
from mezzanine.utils.sites import current_site_id
from gigs.models import (Category, ChildStatus, Company, Gig,
GigType, SocialLinks, JobSeekerProfile)
logger = logging.getLogger(__name__)
class PostJobForm(forms.ModelForm):
"""
Model form for Gig model
"""
title = forms.CharField(label = _('Job Title'), max_length = 255)
class Meta:
model = Gig
fields = [
'job_type', 'gig_categories', 'title', 'location', 'latitude',
'longitude', 'is_relocation', 'area_level1', 'area_level2',
'area_level3', 'area_level4', 'is_remote', 'content', 'tags', 'hidden_tags',
'perks', 'via_email', 'via_url', 'apply_instructions',
#'how_to_apply'
#'gig_categories',
]
#def __init__(self, *args, **kwargs):
# site_id = current_site_id()
# self.fields['job_type'].queryset = GigType.objects.\
# filter(on_site=site_id)
def clean_job_type(self):
job_type = self.cleaned_data.get('job_type')
#print 'jobtype from form : %s' % job_type.type
#print type(job_type)
site_id = current_site_id()
#print [ gj.type for gj in GigType.objects.filter(on_site=site_id)]
if job_type.type not in [ gj.type for gj in GigType.objects.filter(on_site=site_id)]:
#print 'hello'
raise forms.ValidationError(
_("Select a valid Job Type. That choice is not one of the available choices."))
return job_type
def get_gig_object(self):
"""
Return a new (unsaved) Gig object based on the info in this form.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``
"""
GigModel = self.get_gig_model()
gig = GigModel(**self.get_gig_create_data())
return gig
def get_gig_model(self):
"""
Get the Gig model to create with this form.
"""
return Gig
def get_gig_create_data(self):
"""
Returns the dict of data to be used to create a Gig
"""
return dict(
#job_type = self.cleaned_data['job_type'],
job_type = self.cleaned_data['job_type'],
title = self.cleaned_data['title'],
location = self.cleaned_data['location'],
latitude = self.cleaned_data['latitude'],
longitude = self.cleaned_data['longitude'],
area_level1 = self.cleaned_data['area_level1'],
area_level2 = self.cleaned_data['area_level2'],
area_level3 = self.cleaned_data['area_level3'],
area_level4 = self.cleaned_data['area_level4'],
is_relocation = self.cleaned_data['is_relocation'],
is_remote = self.cleaned_data.get('is_remote', True),
content = self.cleaned_data['content'],
hidden_tags = self.cleaned_data['hidden_tags'],
perks = self.cleaned_data.get('perks',''),
#how_to_apply = self.cleaned_data['how_to_apply'],
via_email = self.cleaned_data.get('via_email', ''),
via_url = self.cleaned_data.get('via_url', ''),
apply_instructions = self.cleaned_data.get('apply_instructions', ''),
#gig_categories = self.cleaned_data['gig_categories'],
)
def _add_categories_to_gig(self, gig):
for posted_category in self.cleaned_data['categories']:
gig.categories.add(category)
class CompanyForm(forms.ModelForm):
"""
Model form for Company model
"""
profile_picture = forms.ImageField(required = False, label = _('Profile Picture'))
class Meta:
model = Company
fields = (
#'type',
'company_name', 'title_is_confidential', 'url', 'email',
'profile_picture_choice', 'profile_picture',
'twitter_username',
)
def get_company_model(self):
"""
Get the Company model to create with this form
"""
return Company
def get_company_create_data(self):
return dict(
#type = self.cleaned_data['type'],
company_name = self.cleaned_data['company_name'],
title_is_confidential = self.cleaned_data['title_is_confidential'],
url = self.cleaned_data['url'],
email = self.cleaned_data['email'],
#elevator_pitch = self.cleaned_data['elevator_pitch'],
profile_picture_choice = self.cleaned_data['profile_picture_choice'],
profile_picture = self.cleaned_data['profile_picture'],
twitter_username = self.cleaned_data['twitter_username'],
)
def get_company_object(self):
"""
"""
CompanyModel = self.get_company_model()
print 'company create data :%s' % self.get_company_create_data()
new = CompanyModel(**self.get_company_create_data())
print new
return new
class ApplyForm(forms.Form):
resume = forms.FileField()
motivation = forms.CharField(widget= forms.Textarea)
def clean_resume(self):
file = self.cleaned_data['resume']
if file:
file_type = file.content_type.split('/')[1]
print file_type
if len(file.name.split('.')) == 1:
raise forms.ValidationError(_('File type is not supported'))
if file_type in settings.TASK_UPLOAD_FILE_TYPES:
if file._size > settings.TASK_UPLOAD_FILE_MAX_SIZE:
raise forms.ValidationError(('Please keep file size under %s. Current file size %s') % (filesizeformat(settings.TASK_UPLOAD_FILE_MAX_SIZE), filesizeformat(file._size)))
else:
raise forms.ValidationError(_('File type is not supported'))
return file
class ProfileForm2(forms.ModelForm):
class Meta:
model = User
fields = ('last_name', 'first_name', 'email',)
#exclude = ('username', '<PASSWORD>', )
def __init__(self, *args, **kwargs):
super(ProfileForm2, self).__init__(*args, **kwargs)
user_fields = User._meta.get_all_field_names()
#self.fields['username'] = self.fields['email']
for field in self.fields:
# Make user fields required.
if field in user_fields:
self.fields[field].required = True
# Add user to the JobSeeker group
def _add_to_job_seeker_group(self, user):
job_seeker_group = Group.objects.get(name = 'JobSeeker')
user.groups.add(job_seeker_group)
def clean_email(self):
"""
Ensure the email address is not already registered.
"""
email = self.cleaned_data.get("email")
try:
User.objects.exclude(id=self.instance.id).get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError(_("This email is already registered"))
def save(self, *args, **kwargs):
"""
Create the new user using their email address as their username.
"""
password = User.objects.make_random_password()
print password
user = User(username = self.cleaned_data['email'],
email = self.cleaned_data['email'],
last_name = self.cleaned_data['last_name'], first_name = self.cleaned_data['first_name'])
user.set_password(<PASSWORD>)
user.save()
self._add_to_job_seeker_group(user)
return user, password
class ReplyForm(forms.Form):
reply = forms.CharField()
class ApplicationStatusForm(forms.ModelForm):
class Meta:
model = ChildStatus
fields = ['name',]
class ProfilePictureForm(forms.Form):
twitter_username = forms.CharField(label= _('Use Twitter profile picture'),
max_length=255, required=False)
profile_picture = forms.ImageField(required=False)
def save(self, *args, **kwargs):
"""Based on If the user is a JobSeeker or a Company,
we save the twitter_username and the profile_picture
"""
user = kwargs['user']
twitter_username = self.cleaned_data.get('twitter_username', '')
profile_picture = self.cleaned_data.get('profile_picture','')
if user.groups.get().name == 'Company':
user.company.twitter_username = twitter_username
user.company.profile_picture = profile_picture
user.company.save(force_update = True)
else:
user.jobseekerprofile.twitter_username = twitter_username
user.jobseekerprofile.profile_picture = profile_picture
user.jobseekerprofile.save()
class CompanyProfileForm(forms.ModelForm):
""" Company Profile Form """
class Meta:
model = Company
exclude = ['title', 'email', 'valid', 'ip_address', 'user',
'profile_picture_choice', 'profile_picture', 'twitter_username',
'status',
]
def get_company_object(self):
"""
Return a new (unsaved) Company object based on the info in this form.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``
"""
CompanyModel = self.get_gig_model()
company = CompanyModel(**self.get_company_create_data())
return company
def get_gig_model(self):
"""
Get the Company model to create with this form.
"""
return Company
def get_company_create_data(self):
"""
Returns the dict of data to be used to create a Gig
"""
return dict(
#job_type = self.cleaned_data['job_type'],
company_name = self.cleaned_data['company_name'],
elevator_pitch = self.cleaned_data['elevator_pitch'],
about_the_company = self.cleaned_data['about_the_company'],
#location = self.cleaned_data['location'],
#latitude = self.cleaned_data['latitude'],
#longitude = self.cleaned_data['longitude'],
#area_level1 = self.cleaned_data['area_level1'],
#area_level2 = self.cleaned_data['area_level2'],
#area_level3 = self.cleaned_data['area_level3'],
#area_level4 = self.cleaned_data['area_level4'],
url = self.cleaned_data['url'],
#founded = self.cleaned_data['founded'],
size = self.cleaned_data['size'],
)
def clean_founded(self):
""" Ensure that the Founded year is between 1970
and the current year
"""
from datetime import datetime
current_year = datetime.now().year
founded = self.cleaned_data.get("founded")
if int(founded) < 1970 or int(founded) > current_year:
raise forms.ValidationError(_("The year should be betwen 1970 and %s" % current_year))
else:
return int(founded)
class JobseekerProfileForm(forms.ModelForm):
""" JobSeeker Profile Form """
title = forms.CharField(max_length=300, required=False)
phone_number = forms.RegexField(regex=r'^\+?1?\d{9,15}$',
required=False,
error_message = _("Phone number must be entered in \
the format: '+999999999'. Up to 15 digits allowed."),
help_text=_("Add your Phone Number, so Companies can reach out to you"))
class Meta:
model = JobSeekerProfile
exclude = ['email', 'valid', 'ip_address', 'user',
'profile_picture_choice', 'profile_picture', 'twitter_username',
'status',
]
def get_job_seeker_profile_object(self):
"""
Return a new (unsaved) Company object based on the info in this form.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``
"""
JobSeekerProfileModel = self.get_job_seeker_profile_model()
job_seeker_profile = JobSeekerProfileModel(**self.get_job_seeker_profile_create_data())
return job_seeker_profile
def get_job_seeker_profile_model(self):
"""
Get the Company model to create with this form.
"""
return JobSeekerProfile
def get_job_seeker_profile_create_data(self):
"""
Returns the dict of data to be used to create a Gig
"""
return dict(
title = self.cleaned_data['title'],
about = self.cleaned_data['about'],
location = self.cleaned_data['location'],
latitude = self.cleaned_data['latitude'],
longitude = self.cleaned_data['longitude'],
area_level1 = self.cleaned_data['area_level1'],
area_level2 = self.cleaned_data['area_level2'],
area_level3 = self.cleaned_data['area_level3'],
area_level4 = self.cleaned_data['area_level4'],
phone_number = self.cleaned_data['phone_number'],
)
class SocialLinksForm(forms.ModelForm):
class Meta:
model = SocialLinks
exclude = ['user',]
def get_sociallinks_object(self):
"""
Return a new (unsaved) Company object based on the info in this form.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``
"""
SocialLinkModel = self.get_sociallinks_model()
#print self.get_sociallinks_create_data()
social_link = SocialLinkModel(**self.get_sociallinks_create_data())
#print 'hello %s' % social_link
return social_link
def get_sociallinks_model(self):
"""
Get the Company model to create with this form.
"""
return SocialLinks
def get_sociallinks_create_data(self):
"""
Returns the dict of data to be used to create a Gig
"""
return dict(
twitter_link = self.cleaned_data['twitter_link'],
linkedin_link = self.cleaned_data['linkedin_link'],
facebook_link = self.cleaned_data['facebook_link'],
github_link = self.cleaned_data['github_link'],
)
|
71f9b8b3cfc780d08ffb7bb22da3229e0b1c2200
|
[
"JavaScript",
"Python",
"HTML",
"Markdown"
] | 71
|
Python
|
webpioneer/rien3
|
23fbd6c117feb4e203574488fdc57d4e3c949252
|
154c10156033e17888863adf425ffbab5e70a5eb
|
refs/heads/master
|
<repo_name>SanketGupte/mobile_app_ws<file_sep>/mobile_app_ws/target/classes/application.properties
spring.datasource.username=Sanket
spring.datasource.password=<PASSWORD>
spring.datasource.url=jdbc:mysql://localhost:3306/app_db
spring.jpa.hibernate.ddl-auto=update
<file_sep>/mobile_app_ws/src/main/java/com/sanket/app/ws/service/UserService.java
package com.sanket.app.ws.service;
import com.sanket.app.ws.shared.dto.UserDto;
public interface UserService {
UserDto createUser(UserDto user);
}
|
7ca658a198063df2da6c60e4098b2227112adfb1
|
[
"Java",
"INI"
] | 2
|
INI
|
SanketGupte/mobile_app_ws
|
e7b40bebabf844f107145dc35bd60b25c83549bf
|
448f2521872b9482125340114a1527ad403646e1
|
refs/heads/master
|
<repo_name>jdromero88/woof-woof-js-practice-dc-web-102819<file_sep>/src/index.js
var totalPages;
document.addEventListener('DOMContentLoaded', webIsReady)
function webIsReady() {
getPups()
getDogBar().addEventListener('click', showPupsInfo)
btnDog()
}
function getPups() {
fetch('http://localhost:3000/pups')
.then(response => response.json())
.then(pupsData => pupsData.forEach(puppy => renderPup(puppy)))
.catch(error => console.log(error.message))
}
function renderPup(puppy) {
let divDogBarTag = document.querySelector('#dog-bar')
let spanName = document.createElement('span')
spanName.dataset.id = puppy.id
spanName.dataset.behavior = puppy.isGoodDog
// spanName.setAttribute('id', puppy.id)
spanName.innerHTML = puppy.name
divDogBarTag.appendChild(spanName)
}
function getDogBar() {
return document.querySelector('#dog-bar')
}
function getDogInfoSpan(){
return document.getElementsByTagName('span')
}
function showPupsInfo(e, puppyId) {
const spanDogId = e.target.dataset.id
console.log(spanDogId);
fetch(`http://localhost:3000/pups/${spanDogId}`)
.then(res => res.json())
// .then(data => console.log(data))
.then(puppyInfo => showPuppyInfo(puppyInfo))
.catch(error => console.log(error.message))
}
function showPuppyInfo(puppyInfo) {
getDivDogInfo().innerHTML = ''
// console.log(puppyInfo);
let img = document.createElement('img')
img.src = puppyInfo.image
let h2 = document.createElement('h2')
h2.innerText = puppyInfo.name
let btnInfo = document.createElement('button')
btnValue = puppyInfo.isGoodDog
let behavior;
if (btnValue === true) {
btnInfo.innerText = 'Good Dog!'
behavior = false
// updatePuppy(puppyInfo.id, behavior)
} else {
btnInfo.innerText = 'Bad Dog!'
behavior = true
// updatePuppy(puppyInfo.id, behavior)
}
getDivDogInfo().append(img, h2, btnInfo)
// debugger
// btnInfo.addEventListener('click', {updatePuppy(puppyInfo.id, behavior)})
btnInfo.addEventListener('click', () => {updatePuppy(puppyInfo.id, behavior)})
// doge
}
function updatePuppy(puppyId, behavior) {
dataToUpdate = {isGoodDog: behavior}
console.log(dataToUpdate);
// debugger
confObj = {
method: 'PATCH',
headers:{
'Content-Type': 'application/json',
'Accept': 'applications/json'
},
body: JSON.stringify(dataToUpdate)
}
fetch(`http://localhost:3000/pups/${puppyId}`, confObj)
.then(res => res.json())
.then(puppy => showPuppyInfo(puppy))
// .then(puppy => console.log('puppy should be updated ' + puppy.isGoodDog))
.catch(error => console.log(error.message))
}
function getDivDogInfo() {
return document.querySelector('#dog-info')
}
function btnDog() {
let btnFilter = document.querySelector('#good-dog-filter')
btnFilter.addEventListener('click', (e) => {
let dogSpans = getDogBar().querySelectorAll('span')
// console.log(span.dataset.behavior)
if (btnFilter.innerText === 'Filter good dogs: OFF') {
dogSpans.forEach( span => {
if (span.dataset.behavior === 'false') {
span.style.display = 'none'
}
})
btnFilter.innerHTML = 'Filter good dogs: ON'
} else {
dogSpans.forEach( span => {
// debugger
console.log(span.dataset.behavior)
if (span.dataset.behavior === 'false') {
span.style.display = 'inline-flex'
}
})
btnFilter.innerHTML = 'Filter good dogs: OFF'
}
})
}
|
6e6a09b61e1f98902bb63273e0e288109d1f6632
|
[
"JavaScript"
] | 1
|
JavaScript
|
jdromero88/woof-woof-js-practice-dc-web-102819
|
8edfdb954139dedca04e6070af75f855447e52c0
|
68e01a10326fab40d4f5cd6bde482cfb155b8fb4
|
refs/heads/master
|
<repo_name>swipswaps/scrcpy-launcher<file_sep>/README.md
# Remote Android via ADB Wireless using scrcpy
Wireless remote your Android Phone or Tablet without Internet and any 3rd party software installed on your Android device (Android 5+). Older version of Android can still use this tool by installing *WiFi ADB - Debug Over Air* app available [here](https://play.google.com/store/apps/details?id=com.ttxapps.wifiadb).

## How to use?
First of all you must connect your Android and PC to same network.
### (Android) Enable ADB over Network
Setting > Developer Options > Enable ADB over network
Remember your IP address

If you are using an older device under Android 5.0 (Lolipop) must install *WiFi ADB - Debug Over Air* app available [here](https://play.google.com/store/apps/details?id=com.ttxapps.wifiadb) this app need root access to work with scrcpy-launcher.
### (PC) Download and Install Scrcpy Launcher
Install Depedency
```shell
sudo apt install git adb scrcpy -y
git clone https://github.com/dianariyanto/scrcpy-launcher.git
cd scrcpy-launcher
chmod +x install
```
Install Scrcpy Launcher
```shell
./install <DeviceName> <IPADDRESS>
```

Remove Scrcpy Launcher
```shell
./remove <DeviceName>
```
# Log
```shell
dianariyanto@pop-os:~/$ git clone <EMAIL>:dianariyanto/scrcpy-launcher.git
Cloning into 'scrcpy-launcher'...
remote: Enumerating objects: 16, done.
remote: Counting objects: 100% (16/16), done.
remote: Compressing objects: 100% (11/11), done.
remote: Total 16 (delta 2), reused 16 (delta 2), pack-reused 0
Receiving objects: 100% (16/16), done.
Resolving deltas: 100% (2/2), done.
dianariyanto@pop-os:~/$ cd scrcpy-launcher/
dianariyanto@pop-os:~/scrcpy-launcher$ chmod +x install
dianariyanto@pop-os:~/scrcpy-launcher$ ./install "Redmi Note 6 Pro" 192.168.xx.xx
Install Scrcpy Launcher : Add Redmi Note 6 Pro
Install Scrcpy Launcher : Processing..
Install Scrcpy Launcher : Copying Redmi Note 6 Pro to Launcher
Install Scrcpy Launcher : Processing..
Install Scrcpy Launcher : Fix Redmi Note 6 Pro Permission
Install Scrcpy Launcher : Processing..
Install Scrcpy Launcher : Done.
dianariyanto@pop-os:~/scrcpy-launcher$ ./remove "Redmi Note 6 Pro"
Remove Scrcpy Launcher : Delete Redmi Note 6 Pro
Remove Scrcpy Launcher : Processing..
Remove Scrcpy Launcher : Done.
```
<file_sep>/remove
#!/bin/bash
echo "Remove Scrcpy Launcher : Delete $1"
rm $PWD/shortcut/"$1".desktop
echo "Remove Scrcpy Launcher : Processing.."
rm $HOME/.local/share/applications/"$1".desktop
echo "Remove Scrcpy Launcher : Done."<file_sep>/runner
#!/bin/bash
# Screen Resolution
DEFAULT_RESOLUTION="720"
# Refered to your Local network Bandwith
DEFAULT_BITRATE="1M"
# FPS
DEFAULT_FPS="15"
# ADB Port
DEFAULT_PORT="5555"
DEVICE_S=$1":"$DEFAULT_PORT
# connect devices
adb connect $DEVICE_S
# cek devices
adb devices
#start
scrcpy --serial $DEVICE_S --bit-rate $DEFAULT_BITRATE --max-size $DEFAULT_RESOLUTION --max-fps $DEFAULT_FPS<file_sep>/install
#!/bin/bash
echo "Install Scrcpy Launcher : Add $1"
echo "Install Scrcpy Launcher : Processing.."
echo "#!/bin/bash
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Exec=bash $PWD/runner $2
Name=$1
Comment=$1
Icon=$PWD/icon/phone.png
" > shortcut/"$1".desktop
echo "Install Scrcpy Launcher : Copying $1 to Launcher"
echo "Install Scrcpy Launcher : Processing.."
cp $PWD/shortcut/"$1".desktop $HOME/.local/share/applications/"$1".desktop
#cp $PWD/shortcut/"$1".desktop $HOME/Desktop/"$1".desktop
echo "Install Scrcpy Launcher : Fix $1 Permission"
echo "Install Scrcpy Launcher : Processing.."
chmod +x runner
chmod +x remove
chmod +x $HOME/.local/share/applications/"$1".desktop
#chmod +x $HOME/Desktop/"$1".desktop
echo "Install Scrcpy Launcher : Done."
|
e6ca3ae3a26789fd0ec66881eef01ba62eac345d
|
[
"Markdown",
"Shell"
] | 4
|
Markdown
|
swipswaps/scrcpy-launcher
|
84b7ae8f2bcbbe6439ba8841b2304674adcf5c8b
|
bd1cd6aa5dd65722325eb545e35a93fd06a064eb
|
refs/heads/master
|
<file_sep># Node class for pathfinding method
__author__ = '<NAME>'
class Node:
x = 0
y = 0
position = []
closed = False
obstacle_bool = False
obstacle = 0
# Calculate Heuristic using the Manhattan Method
H_value = 0 # Heuristic - Distance from node to target node
# Movements costs will be 10 for any horizontal or vertical movement and a cost of 14 for any diagonal movement
G_value = 0 # Movement Cost
F_value = 0 # G + H
Parent = 5 # A node to reach this node
def setH(self, value):
self.H_value = value
def getH(self):
return self.H_value
def setG(self, value):
self.G_value = value
def getG(self):
return self.G_value
def getF(self):
return self.F_value
def calcF(self):
self.F_value = self.G_value + self.H_value
def setParent(self, parent):
self.Parent = parent
def getParent(self):
return self.Parent
def setObstacle(self, state):
self.obstacle = state
self.checkState()
def checkState(self):
if (self.obstacle == 0):
self.obstacle_bool = False
else:
self.obstacle_bool = True
def getObstacle(self):
return self.obstacle_bool
def close(self):
self.closed = True
def isclosed(self):
return self.closed
def getPosition(self):
return self.position
def __init__(self, state, x_ord, y_ord):
self.setObstacle(state)
self.x = x_ord
self.y = y_ord
self.position = [x_ord, y_ord]
<file_sep># HonoursProject
# https://github.com/Ruenzic/HonoursProject
<file_sep># RobotModule.py Library
__author__ = '<NAME>'
import RPi.GPIO as GPIO
import time
from Node import *
class _Singleton(type):
""" A metaclass that creates a Singleton base class when called. """
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Singleton(_Singleton('SingletonMeta', (object,), {})): pass
class Movement(Singleton):
pass
__RIGHT_PWM_PIN = 19
__RIGHT_1_PIN = 19
__RIGHT_2_PIN = 22
__LEFT_PWM_PIN = 11
__LEFT_1_PIN = 11
__LEFT_2_PIN = 7
__LED1_PIN = 24
__LED2_PIN = 26
__left_pwm = 0
__right_pwm = 0
__pwm_scale = 0
__old_left_dir = -1
__old_right_dir = -1
__move_delay = 0.4 #See what happens when you change delay
__voltage = 5
__left_voltage_scale_reverse = 0.66
__right_voltage_scale_reverse = 0.7
__left_voltage_scale_forward = 0.65
__right_voltage_scale_forward = 0.735
# Make a forwards and reverse sleep timers, different
# For forward 1.0
# 1.3 for reverse
# will need to make a new reverse diagonal
__left_turn_voltage = 0.8
__right_turn_voltage = 0.8
__step_time = 1.15
__step_time_diagonal = 1.6
__turn_time = 0.335
start_pos = [2,3]
start_rot = 0
current_pos = [2,3]
current_rot = 0
__x_lim = 5 # Bounds for the grid/enclosure. X[0,10]
__y_lim = 7 # Bounds for the grid/enclosure. Y[0,10]
grid_map = [[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0]]
grid_map_clear = [[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0]]
def __init__(self):
self.__pwm_scale = 1
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(self.__LEFT_PWM_PIN, GPIO.OUT)
self.__left_pwm = GPIO.PWM(self.__LEFT_PWM_PIN, 500)
self.__left_pwm.start(0)
GPIO.setup(self.__LEFT_1_PIN, GPIO.OUT)
GPIO.setup(self.__LEFT_2_PIN, GPIO.OUT)
GPIO.setup(self.__RIGHT_PWM_PIN, GPIO.OUT)
self.__right_pwm = GPIO.PWM(self.__RIGHT_PWM_PIN, 500)
self.__right_pwm.start(0)
GPIO.setup(self.__RIGHT_1_PIN, GPIO.OUT)
GPIO.setup(self.__RIGHT_2_PIN, GPIO.OUT)
GPIO.setup(self.__LED1_PIN, GPIO.OUT)
GPIO.setup(self.__LED2_PIN, GPIO.OUT)
def __set_motors(self, __left_pwm, left_dir, __right_pwm, right_dir):
self.__set_driver_pins(__left_pwm, left_dir, __right_pwm, right_dir)
self.__old_left_dir = left_dir
self.__old_right_dir = right_dir
def __set_driver_pins(self, __left_pwm, left_dir, __right_pwm, right_dir):
self.__left_pwm.ChangeDutyCycle(__left_pwm * 100 * self.__pwm_scale)
GPIO.output(self.__LEFT_1_PIN, left_dir)
GPIO.output(self.__LEFT_2_PIN, not left_dir)
self.__right_pwm.ChangeDutyCycle(__right_pwm * 100 * self.__pwm_scale)
GPIO.output(self.__RIGHT_1_PIN, right_dir)
GPIO.output(self.__RIGHT_2_PIN, not right_dir)
def __update_txt(self):
with open("/tmp/robotPos.txt", "w") as f:
pos = self.get_pos()
rot = self.get_rot()
f.write("%d,%d,%d\n" % (pos[0], pos[1], rot))
def forward(self, steps = 1): # 1 step by default
self.stop() # Stop motors before moving them again
if (self.__check_pos(self.current_pos[0], self.current_pos[1], steps)):
print("Requested move will either go out of bounds or hit an obstacle and therefore can't be performed")
else:
print("Moving Robot Forward %d Steps" % steps) # Debugging statement
# When moving a step forward while at 45 degrees, so rotations 1,5,7,3. You must move root(2) steps forward for every step.
# Use step_time_diagonal instead of normal step_time
for num in range(0,steps):
self.__set_motors(self.__left_voltage_scale_forward, 1, self.__right_voltage_scale_forward, 1)
if (self.current_rot == 1 or self.current_rot == 5 or self.current_rot == 7 or self.current_rot == 3):
time.sleep(self.__step_time_diagonal)
else:
time.sleep(self.__step_time)
self.stop() # Delay between each movement
time.sleep(self.__move_delay)
self.__manage_pos(steps)
print("Rotation:",self.current_rot) # Debugging
print("X:",self.current_pos[0])
print("Y:",self.current_pos[1])
def stop(self):
self.__set_motors(0, 0, 0, 0)
def reverse(self, steps = 1): # 1 step by default
self.stop() # Stop motors before moving them again
if (self.__check_pos(self.current_pos[0], self.current_pos[1], steps * -1)):
print("Requested move will either go out of bounds or hit an obstacle and therefore can't be performed")
else:
print("Moving Robot Backward %d Steps" % steps) # Debugging statement
for num in range(0,steps):
self.__set_motors(self.__left_voltage_scale_reverse, 0, self.__right_voltage_scale_reverse, 0)
if (self.current_rot == 1 or self.current_rot == 5 or self.current_rot == 7 or self.current_rot == 3):
time.sleep(self.__step_time_diagonal)
else:
time.sleep(self.__step_time)
self.stop() # Delay between each movement
time.sleep(self.__move_delay)
self.__manage_pos(steps * -1) # Make the steps negative so that the manage_pos func will move robot in correct dir based on its rot
print("Rotation:",self.current_rot) # Debugging
print("X:",self.current_pos[0])
print("Y:",self.current_pos[1])
def left(self, steps=1): # 45 degrees by default
self.stop() # Stop motors before moving them again
print("Turning Robot Left %d Steps" % steps) # Debugging statement
if (steps >= 8):
steps -= 8 # Remove 360 degree turns
for num in range(0,steps):
self.__set_motors(self.__left_turn_voltage, 0, self.__right_turn_voltage, 1)
time.sleep(self.__turn_time)
self.stop() # Delay between each movement
time.sleep(self.__move_delay)
self.current_rot -= steps
self.__manage_rot()
print("Rotation:",self.current_rot) # Debugging
print("X:",self.current_pos[0])
print("Y:",self.current_pos[1])
def right(self, steps=1): # 45 degrees by default
self.stop() # Stop motors before moving them again
print("Turning Robot Right %d Steps" % steps) # Debugging statement
if (steps >= 8):
steps -= 8 # Remove 360 degree turns
for num in range(0,steps):
self.__set_motors(self.__left_turn_voltage, 1, self.__right_turn_voltage, 0)
time.sleep(self.__turn_time)
self.stop() # Delay between each movement
time.sleep(self.__move_delay)
self.current_rot += steps
self.__manage_rot()
print("Rotation:",self.current_rot) # Debugging
print("X:",self.current_pos[0])
print("Y:",self.current_pos[1])
def set_led_red(self, state): # 0/1 for state
GPIO.output(self.__LED1_PIN, state)
def set_led_green(self, state): # 0/1 for state
GPIO.output(self.__LED2_PIN, state)
def cleanup(self):
GPIO.cleanup()
def __manage_rot(self): # Manage the current rotation by removing 360 degrees when needed.
if (self.current_rot >= 8):
self.current_rot -= 8
elif (self.current_rot < 0):
self.current_rot += 8
def __manage_pos(self, steps): # Method to manage the position of the robot in the grid world (keep track)
self.__manage_rot() # Make sure rotation is in positive form for ease
if (self.current_rot == 0): # Increase the y value by the number of steps
self.current_pos[1] += steps
elif (self.current_rot == 1): # Increase x and y
self.current_pos[0] += steps
self.current_pos[1] += steps
elif (self.current_rot == 2): # Increase x
self.current_pos[0] += steps
elif (self.current_rot == 3): # Increase x, Decrease y
self.current_pos[0] += steps
self.current_pos[1] -= steps
elif (self.current_rot == 4): # Decrease y
self.current_pos[1] -= steps
elif (self.current_rot == 5): # Decrease x and y
self.current_pos[0] -= steps
self.current_pos[1] -= steps
elif (self.current_rot == 6): # Decrease x
self.current_pos[0] -= steps
elif (self.current_rot == 7): # Decrease x, Increase y
self.current_pos[0] -= steps
self.current_pos[1] += steps
self.__update_txt()
def __check_pos(self, x, y, steps): # Method to check if moving the robot will move it out of bounds.
self.__manage_rot() # Make sure rotation is in positive form for ease
if (self.current_rot == 0): # Increase the y value by the number of steps
y += steps
elif (self.current_rot == 1): # Increase x and y
x += steps
y += steps
elif (self.current_rot == 2): # Increase x
x += steps
elif (self.current_rot == 3): # Increase x, Decrease y
x += steps
y -= steps
elif (self.current_rot == 4): # Decrease y
y -= steps
elif (self.current_rot == 5): # Decrease x and y
x -= steps
y -= steps
elif (self.current_rot == 6): # Decrease x
x -= steps
elif (self.current_rot == 7): # Decrease x, Increase y
x -= steps
y += steps
if (x > self.__x_lim or x < 0 or y > self.__y_lim or y < 0 or self.grid_map[y][x] == 1):
return True # The next move violates the boundaries
else:
return False # The next move won't violate the boundaries
def reset_position(self):
print("Resetting Position of Robot")
# Reverse if the robot has the correct opposite rotation that it needs to be in
# Move the robot back to the start position
# Move on the y axis
# Check to see if there are obstacles present, if not, use this method, else call pathfinding and follow the path.
if (self.grid_map == self.grid_map_clear): # No obstacles
startx = self.get_start_pos()[0]
starty = self.get_start_pos()[1]
startrot = self.get_start_rot()
if (self.current_pos[1] > starty):
if (self.current_rot != 4 and self.current_rot != 0):
# rotate towards the start
if (self.current_rot >= 0 and self.current_rot < 4):
self.right(4 - self.current_rot)
elif (self.current_rot > 4):
self.left(self.current_rot - 4)
if (self.current_rot == 4):
self.forward(self.current_pos[1] - starty)
elif (self.current_rot == 0):
self.reverse(self.current_pos[1] - starty)
elif (self.current_pos[1] < starty):
if (self.current_rot != 0 and self.current_rot != 4):
# rotate towards the start
if (self.current_rot >= 0 and self.current_rot < 4):
self.left(self.current_rot)
elif (self.current_rot > 4):
self.right(8 - self.current_rot)
if (self.current_rot == 0):
self.forward(starty - self.current_pos[1]) # Change negative to positive
elif (self.current_rot == 4):
self.reverse(starty - self.current_pos[1])
# Move on the x axis
if (self.current_pos[0] > startx):
if (self.current_rot != 6 and self.current_rot != 2):
# rotate towards the start
if (self.current_rot >= 2 and self.current_rot < 6):
self.right(6 - self.current_rot)
elif (self.current_rot < 2):
self.left(2 + self.current_rot)
elif (self.current_rot > 6):
self.left(7 - self.current_rot)
if (self.current_rot == 6):
self.forward(self.current_pos[0] - startx)
elif (self.current_rot == 2):
self.reverse(self.current_pos[0] - startx)
elif (self.current_pos[0] < startx):
if (self.current_rot != 2 and self.current_rot != 6):
# rotate towards the start
if (self.current_rot >= 2 and self.current_rot < 6):
self.left(self.current_rot - 2)
elif (self.current_rot < 2):
self.right(2 - self.current_rot)
elif (self.current_rot > 6):
self.right(8 - self.current_rot + 1)
if (self.current_rot == 2):
self.forward(startx - self.current_pos[0]) # Change the negative to positive
elif (self.current_rot == 6):
self.reverse(startx - self.currrent_pos[0])
# Set the rotation of the robot back to the original direction
# Check to see if rotation is bigger or smaller than 4, then rotate the shorter direction
if (self.current_rot != startrot):
# rotate towards the start
self.change_rot(self.current_rot, startrot)
else:
self.follow_path(self.pathfind(self.get_pos(),self.get_start_pos()))
if (self.get_rot() != self.get_start_rot()):
self.change_rot(self.get_rot(),self.get_start_rot())
self.current_pos[0] = self.start_pos[0]
self.current_pos[1] = self.start_pos[1]
self.current_rot = self.start_rot
def cont_forward(self): # Move the robot forward continuously with no sleep or delay
self.stop() # Stop motors before moving them again
print("Moving Robot Forward Indefinitely")
self.__set_motors(self.__left_voltage_scale_forward, 1, self.__right_voltage_scale_forward, 1)
def cont_reverse(self): # Move the robot backwards continuously with no sleep or delay
self.stop() # Stop motors before moving them again
print("Moving Robot Backward Indefinitely")
self.__set_motors(self.__left_voltage_scale_reverse, 0, self.__right_voltage_scale_reverse, 0)
def cont_left(self): # Turn the robot left continuously with no sleep or delay
self.stop() # Stop motors before moving them again
print("Turing Robot Left Continuously")
self.__set_motors(self.__left_turn_voltage, 0, self.__right_turn_voltage, 1)
def cont_right(self): # Turn the robot left continuously with no sleep or delay
self.stop() # Stop motors before moving them again
print("Turing Robot Right Continuously")
self.__set_motors(self.__left_turn_voltage, 1, self.__right_turn_voltage, 0)
def follow_path(self, nodes_path): # Method that will have the robot follow a path returned by pathfinding
if (nodes_path == "No Path"):
print("No Path can be found with current obstacle setup")
else:
print ("Robot Following A* Path:")
# Loop through nodes_path backwards, as it is from goal - > start
# At each node, check where the parent is, if above, below, left, right or any diagonal
# After check what the current rotation of the robot is
# Change rotation, move robot
#print("length of nodes path is " + str(len(nodes_path))) # Note, prints out 4
for i in range (len(nodes_path)-1, 0, -1): # Added -1 at end
if (i != 0):
current_node = nodes_path[i]
next_node = nodes_path[i - 1]
current_pos = current_node.getPosition()
next_pos = next_node.getPosition()
current_rot = self.get_rot()
#print("node " + str(i)) # Note, follow_path doesnt even get to here
rot1 = 0
rot2 = 0
if (next_pos[0] > current_pos[0] and next_pos[1] == current_pos[1]): # Right
rot1 = 2
rot2 = 6
elif (next_pos[0] < current_pos[0] and next_pos[1] == current_pos[1]): # Left
rot1 = 6
rot2 = 2
elif (next_pos[0] == current_pos[0] and next_pos[1] > current_pos[1]): # Above
rot1 = 0
rot2 = 4
elif (next_pos[0] == current_pos[0] and next_pos[1] < current_pos[1]): # Below
rot1 = 4
rot2 = 0
elif (next_pos[0] > current_pos[0] and next_pos[1] > current_pos[1]): # Top right
rot1 = 1
rot2 = 5
elif (next_pos[0] < current_pos[0] and next_pos[1] < current_pos[1]): # Bottom left
rot1 = 5
rot2 = 1
elif (next_pos[0] > current_pos[0] and next_pos[1] < current_pos[1]): # Bottom right
rot1 = 3
rot2 = 7
elif (next_pos[0] < current_pos[0] and next_pos[1] > current_pos[1]): # Top left
rot1 = 7
rot2 = 3
# Now that we know the position of the next spot, change rotation and move there
if (current_rot != rot1 and current_rot != rot2):
print("changing rot, from " + str(current_rot) + " to " + str(rot1))
self.change_rot(current_rot, rot1)
if (self.get_rot() == rot1):
self.forward(1)
elif (current_rot == rot2):
self.reverse(1)
def change_rot(self, current_rot, goal_rot): # Method to change rotation from current to destination rotation
# Check to see if its quicker to rotate left or right to destination rotation
# Turn left or right the required steps
leftTurn = 0
rightTurn = 0
if (goal_rot > current_rot):
rightTurn = abs(goal_rot - current_rot)
leftTurn = abs(8 - goal_rot + current_rot)
elif (goal_rot < current_rot):
rightTurn = abs(8 - current_rot + goal_rot)
leftTurn = abs(current_rot - goal_rot)
if (leftTurn < rightTurn):
self.left(leftTurn)
else:
self.right(rightTurn)
def get_pos(self): # Return [x,y] position of robot to the user
return self.current_pos
def get_rot(self): # Return rotation variable to user
return self.current_rot
def add_obstacles(self, obstacles):
num = len(obstacles)
for i in range (0,num):
x = obstacles[i][0]
y = obstacles[i][1]
self.grid_map[y][x] = 1
def reset_obstacles(self):
for i in range (0,self.__y_lim + 1):
for j in range (0, self.__x_lim + 1):
self.grid_map[i][j] = 0
def pathfind(self, start_pos, goal_pos):
print("Running Pathfinding Algorithm")
grid_nodes = []
# Create the grid of nodes
for i in range (0,self.__y_lim + 1):
temp = []
for j in range (0, self.__x_lim + 1):
state = self.grid_map[i][j]
tempNode = Node(state, j, i)
#tempNode.setObstacle(state)
temp.append(tempNode)
grid_nodes.append(temp)
start_node = grid_nodes[start_pos[1]][start_pos[0]] # Changed from grid_map to grid_nodes
goal_node = grid_nodes[goal_pos[1]][goal_pos[0]]
closed_set = [] # Set of nodes that have been checked
open_set = [start_node] # Set of nodes that need to be checked
#Calculate the G values of all nodes in grid_nodes
for i in range (0,self.__y_lim + 1):
for j in range (0, self.__x_lim + 1):
node = grid_nodes[i][j]
G_value = abs(goal_pos[0] - j) + abs(goal_pos[1] - i)
node.setG(abs(G_value))
#print(j,i," ", grid_nodes[i][j].getG()) # Debugging
# While open set is not empty
# Take next element out of openset with lowest F score
# Check if this node is the goal node
# Remove it from the set
# Add it to closed set
# For each of the nodes neighbours
# if not closed, if not in open, add to open.
# if current g score + distance between the 2 is greater, ignore
# Note: G cost = Parent G cost + movement cost (10/14)
while (len(open_set) > 0 ):
# Use smallest F value node next in our list
current_node = self.__find_smallest(open_set)
# Add to closed set 'mark closed'
current_node.close()
# Remove from open set
open_set.remove(current_node)
# Add neighbours if they aren't added already
self.__add_neighbours(grid_nodes, open_set, current_node)
# Once the open list is empty, create path
nodes_path = []
current = goal_node
while (current != start_node):
try:
nodes_path.append(current)
#print(current)
temp = current.getParent()
current = temp
except TypeError and AttributeError: # If goal node has no parent as it cant find a path
return "No Path"
nodes_path.append(start_node)
# Print path to user
print ("Path for robot found:")
for i in range (self.__y_lim,-1,-1):
line = ""
for j in range (0, self.__x_lim+1):
if (grid_nodes[i][j] == start_node):
line += " S "
elif (grid_nodes[i][j] == goal_node):
line += " E "
elif (grid_nodes[i][j] in nodes_path):
line += " 0 "
elif (grid_nodes[i][j].getObstacle() == True):
line += " X "
else:
line += " - "
print(line)
#print(len(nodes_path))
return nodes_path
def __add_neighbours(self, grid_nodes, open_set, current_node): # Add the current nodes neighbours to the open_set
current_pos = current_node.getPosition()
if (current_pos[0] + 1 <= self.__x_lim):
node = grid_nodes[current_pos[1]][current_pos[0] + 1] # Right
self.__test_node(node, open_set, current_node, 10)
if (current_pos[0] - 1 >= 0):
node = grid_nodes[current_pos[1]][current_pos[0] - 1] # Left
self.__test_node(node, open_set, current_node, 10)
if (current_pos[1] + 1 <= self.__y_lim):
node = grid_nodes[current_pos[1] + 1][current_pos[0]] # Above
self.__test_node(node, open_set, current_node, 10)
if (current_pos[1] - 1 >= 0):
node = grid_nodes[current_pos[1] - 1][current_pos[0]] # Below
self.__test_node(node, open_set, current_node, 10)
if (current_pos[0] + 1 <= self.__x_lim and current_pos[1] + 1 < self.__y_lim):
node = grid_nodes[current_pos[1] + 1][current_pos[0] + 1] # Top Right
self.__test_node(node, open_set, current_node, 14)
if (current_pos[0] - 1 >= 0 and current_pos[1] + 1 < self.__y_lim):
node = grid_nodes[current_pos[1] + 1][current_pos[0] - 1] # Top Left
self.__test_node(node, open_set, current_node, 14)
if (current_pos[0] + 1 <= self.__x_lim and current_pos[1] - 1 > 0):
node = grid_nodes[current_pos[1] - 1][current_pos[0] + 1] # Bottom Right
self.__test_node(node, open_set, current_node, 14)
if (current_pos[0] - 1 >= 0 and current_pos[1] - 1 > 0):
node = grid_nodes[current_pos[1] - 1][current_pos[0] - 1] # Bottom Left
self.__test_node(node, open_set, current_node, 14)
def __test_node(self, node, open_set, current_node, cost):
if (node.isclosed() == False and node.getObstacle() == False):
if (node not in open_set):
open_set.append(node) # Right
node.setG(current_node.getG() + cost)
node.calcF()
node.setParent(current_node)
elif (current_node.getG() + cost < node.getG()):
node.setParent(current_node)
def __find_smallest(self, open_set):
if (len(open_set) == 1):
return open_set[0]
smallest = 0
for i in range (0,len(open_set)):
if (i == 0):
smallest = open_set[i]
else:
if (open_set[i].getF() < smallest.getF()):
smallest = open_set[i]
return smallest
def set_start_pos(self, x, y): # Method to set the x and y start position of the robot
self.start_pos[0] = x
self.start_pos[1] = y
def set_start_rot(self, rotation): # Method to set the start rotation of the robot
self.start_rot = rotation
def get_start_pos(self): # Method to return the start position
return self.start_pos
def get_start_rot(self): # Method to return the start rotation
return self.start_rot
def print_grid(self): # Print out the grid, with 0 meaning no obstacle and 1 an obstacle
for i in range (self.__y_lim,-1,-1):
print(self.grid_map[i])
def __del__(self):
self.reset_position() # Reset robot to start position
self.set_led_green(0) # Set green led off
self.set_led_red(0) # Set red led off
self.cleanup() # Cleanup gpio pins
<file_sep>#Used the below code to get the IP address from the raspberry pi and updated it to a gist on github,
#So that everytime i connect to different wifi hot spots, i didn't need to plug the robot into a monitor to check the address.
from datetime import datetime
from simplegist import Simplegist
from urllib2 import urlopen
import os
f = os.popen('ifconfig wlan0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1')
addr = str(f.read().strip())
#print(addr)
gg = Simplegist(username='Ruenzic', api_token='<PASSWORD>')
current_time = str(datetime.now())
ip = urlopen('http://ipinfo.io/ip').read().strip()
content = current_time + " " + addr
gg.profile().edit(id='1a9229e4de7ebaa8cc617163a52ced2f', content=content)
#print(content)
<file_sep>Items todo:
<file_sep># Script to form as a wrapper class for the Robot
# Contains all functions for movement and the features
__author__ = '<NAME>'
from Movement import *
from Camera import *
from Infrared import *
from LED import *
from Ultrasonic import *
import time
class Robot(Singleton):
def __init__(self):
self.__movement = Movement()
self.camera = Camera()
self.us = Ultrasonic()
self.led = LED()
self.ir = Infrared()
print("Created Robot")
#Movement Functions
def forward(self, steps = 1):
self.__movement.forward(steps)
def reverse(self, steps = 1):
self.__movement.reverse(steps)
def left(self, steps = 1):
self.__movement.left(steps)
def right(self, steps = 1):
self.__movement.right(steps)
def stop(self):
self.__movement.stop()
def cleanup(self):
self.__movement.cleanup()
def reset_position(self):
self.__movement.reset_position()
def follow_path(self, nodes_path):
self.__movement.follow_path(nodes_path)
def change_rotation(self, goal_rot):
self.__movement.change_rot(self.get_rotation(), goal_rot)
def get_position(self):
return self.__movement.get_pos()
def get_rotation(self):
return self.__movement.get_rot()
def add_obstacles(self, obstacles):
self.__movement.add_obstacles(obstacles)
def reset_obstacles(self):
self.__movement.reset_obstacles()
def find_path(self, start_pos, goal_pos):
return self.__movement.pathfind(start_pos, goal_pos)
def pathfind(self, goal_pos):
self.follow_path(self.find_path(self.get_position(), goal_pos))
def __set_start_pos(self, x, y):
self.__movement.set_start_pos(x, y)
def __set_start_rot(self, rotation):
self.__movement.set_start_rot(rotation)
def get_start_pos(self):
return self.__movement.get_start_pos()
def get_start_rot(self):
return self.__movement.get_start_rot()
def print_grid(self):
self.__movement.print_grid()
def reset(self):
self.led.blue_off()
self.led.red_off()
self.led.yellow_off()
self.led.blue_on()
self.led.red_on()
self.led.yellow_on()
time.sleep(1)
self.led.blue_off()
self.led.red_off()
self.led.yellow_off()
time.sleep(2)
self.__movement.reset_position()
self.__movement.set_led_green(0)
self.__movement.set_led_red(0)
self.__movement.cleanup()
<file_sep>#Method that will get current position written to robotPos.txt
#and return it to the start position.
#This is used when the robot has to be force stopped and needs to recover.
#Only to be used in emergencies.
from Movement import *
from Robot import *
try:
f = open("/tmp/robotPos.txt", "r")
data = f.read().split(",")
data = [int(i) for i in data]
m = Movement()
m.current_pos = data[0:2]
m.current_rot = data[2]
m.reset_position()
r = Robot()
r.reset()
except:
print "Error"
|
8d794e93c1498a3d8dbcbeb673fcad22cf1f0b22
|
[
"Markdown",
"Python",
"Text"
] | 7
|
Python
|
Ruenzic/HonoursProject
|
fe31b789fce025e87cda1c0afa02f3625b8ed21d
|
67923bed551eda81cb2da58f60882f01055eaf03
|
refs/heads/master
|
<file_sep>package com.example.flutter_rolling_dice
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
|
78fb67e2fb214bce1cf20633a7e8fc8e7287cef6
|
[
"Kotlin"
] | 1
|
Kotlin
|
Mufaddal5253110/Flutter_Roll_The_Dice
|
68b05e5a93809b4661cae4134f36fc9e56e9fabf
|
dd9b2e7f04db76027b57325c667fb61113f1992e
|
refs/heads/master
|
<repo_name>AlxHnr/minigame<file_sep>/main.c
#include <SDL.h>
#include "SDL_image.h"
void set_frame(SDL_Rect *char_source, SDL_Rect *char_dest, short x, short y, short w, short h)
{
char_source->x = x;
char_source->y = y;
char_source->w = w;
char_source->h = h;
char_dest->w = char_source->w;
char_dest->h = char_source->h;
}
#ifdef __WIN32__
int WinMain(int argc, char *argv[])
#else
int main(int argc, char *argv[])
#endif
{
//var declaration start
SDL_Surface *screen, *background, *character;
SDL_Event keyboard_input;
SDL_Rect character_source, character_dest;
char programm_running = 1;
//var declaration end
//init start
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
exit(-1);
}
if((screen = SDL_SetVideoMode(640, 400, 16, SDL_SWSURFACE)) == NULL)
{
exit(-1);
}
SDL_WM_SetCaption("Minigame", NULL);
atexit(SDL_Quit);
if((character = IMG_Load("character.png")) == NULL)
{
exit(-1);
}
if((background = IMG_Load("background.png")) == NULL)
{
exit(-1);
}
SDL_BlitSurface(background, NULL, screen, NULL);
SDL_Flip(screen);
set_frame(&character_source, &character_dest, 0, 0, 31, 35);
character_dest.x = screen->w/2 - character_source.w/2;
character_dest.y = screen->h/2 - character_source.h/2;
SDL_EnableKeyRepeat(1, 0);
SDL_ShowCursor(SDL_DISABLE);
//init end
//main programm start
while(programm_running)
{
while(SDL_PollEvent(&keyboard_input))
{
//erase old character
SDL_BlitSurface(background, &character_dest, screen, &character_dest);
SDL_UpdateRects(screen, 1, &character_dest);
switch(keyboard_input.type)
{
case SDL_QUIT:
programm_running = 0;
break;
case SDL_KEYDOWN:
switch(keyboard_input.key.keysym.sym)
{
case SDLK_LEFT:
set_frame(&character_source, &character_dest, 0, 35, 42, 35);
character_dest.x -= 1;
break;
case SDLK_RIGHT:
set_frame(&character_source, &character_dest, 0, 70, 43, 35);
character_dest.x += 1;
break;
case SDLK_UP:
set_frame(&character_source, &character_dest, 0, 106, 23, 36);
character_dest.y -= 1;
break;
case SDLK_DOWN:
set_frame(&character_source, &character_dest, 0, 0, 31, 35);
character_dest.y += 1;
break;
case SDLK_ESCAPE:
programm_running = 0;
break;
default:
break;
}
break;
default:
break;
}
}
//correct x, y
if(character_dest.x < 0) character_dest.x = 0;
else if(character_dest.x > screen->w-character_source.w) character_dest.x = screen->w-character_source.w;
else if(character_dest.y < 0) character_dest.y = 0;
else if(character_dest.y > 330-character_source.h) character_dest.y = 330-character_source.h;
//update screen
SDL_BlitSurface(character, &character_source, screen, &character_dest);
SDL_UpdateRects(screen, 1, &character_dest);
SDL_Delay(5);
}
//main programm end
//programm end
SDL_FreeSurface(character);
SDL_FreeSurface(background);
SDL_FreeSurface(screen);
return 0;
}
<file_sep>/README.md

Use the arrow keys to move around.
## Building
This program requires the development files of the following libraries:
* SDL (_not_ SDL2)
* SDL\_image
Build and run the game using `make run`.
|
05a284ce25dc35305d21892b362e03c8f3d748a9
|
[
"Markdown",
"C"
] | 2
|
C
|
AlxHnr/minigame
|
90321264e0d8d1bb3bce900fcfaa5c2ab6e66bc7
|
0384418854ccedb5129562d58c03b2fd6e38708f
|
refs/heads/master
|
<repo_name>daniel-j/fallout-term<file_sep>/README.md
# Fallout terminal hacking simulator
#### Demo on Youtube:
[](https://www.youtube.com/watch?v=8lvdZyhnTm4)
Requires python2 and urwid
```
$ python2 fallout.py
```
<file_sep>/fallout.py
import urwid
from random import randrange
content = [
[
["out", "SECURITY RESET..."],
["wait", 0.08]
],
[
["wait", 0.1],
["out", "WELCOME TO ROBCO INDUSTRIES (TM) TERMLINK\n"],
["in", "SET TERMINAL/INQUIRE"],
["wait", 0.2],
["out", "RIT-V300\n"],
["in", "SET FILE/PROTECTION-OWNER:RWED ACCOUNTS.F"],
["in", "SET HALT RESTART/MAINT"],
["wait", 0.4],
["out", "Initializing Robco Industries(TM) MF Boot Agent v2.3.0\n"
"RETROS BIOS\n"
"RBIOS-4.02.08.00 52EE5.E7.E8\n"
"Copyright 2201-2203 Rob<NAME>.\n"
"Uppermem: 64 KB\n"
"Root (5AB)\n"
"Maintenance Mode\n"],
["in", "RUN DEBUG/ACCOUNTS.F"],
["wait", 0.8]
],
[
["out", "ROBCO INDUSTRIES (TM) TERMLINK PROTOCOL\nENTER PASSWORD NOW"]
]
]
palette = [
('inverted', 'black', 'light gray')
]
screen = 0
line = 0
pos = 0
delay = 0
state = 0
startAddress = randrange(0xF000, 0xFE7F)
#for screen in copy:
# for item in screen:
# s = item[1]
# if item[0] == 'in':
# s = ">"+s
addresses = [[], []]
addrPile = [urwid.Pile([]), urwid.Pile([])]
for i in range(16):
for j in range(2):
s = "0x" + (hex(startAddress+16*12*j+i*12).upper()[2:])+" ............"
#txt = urwid.Text(s)
addresses[j].append(s)
bootpile = urwid.Pile([])
attemptstxt = urwid.Text("")
columns = urwid.Columns([('fixed', 20, addrPile[0]), ('fixed', 20, addrPile[1]), urwid.Divider(" ")])
toppile = urwid.Pile([bootpile, attemptstxt, columns])
TYPE_SPEED = 0.055
OUTPUT_SPEED = 0.018
def typeText(loop):
global content, screen, line, pos, bootpile, delay, state
if state == 0:
type = content[screen][line][0]
value = content[screen][line][1]
else:
type = "out"
value = addresses[screen][line]
if line == 0 and pos == 0 and state == 0: # clear screen
del bootpile.contents[:]
if type == 'wait':
delay = value
bootpile.contents.append((urwid.Text(""), bootpile.options()))
line += 1
else:
if type == 'out':
delay = OUTPUT_SPEED
else:
delay = TYPE_SPEED
s = value+" "
if type == 'in':
s = ">"+s
if pos == 1:
delay = 0.5
if pos == 0:
txt = urwid.Text("")
if state == 0:
bootpile.contents.append((txt, bootpile.options()))
else:
addrPile[screen].contents.append((txt, addrPile[screen].options()))
else:
if state == 0:
txt = bootpile.contents[line][0]
else:
txt = addrPile[screen].contents[line][0]
if pos == len(s) or (type == 'in' and pos == 0):
txt.set_text(s[:pos])
else:
txt.set_text([s[:pos], ('inverted', " ")])
pos += 1
if pos == len(s)+1: # after a line
pos = 0
line += 1
if type == 'in':
delay = 0
if (state == 0 and line == len(content[screen])) or (state == 1 and line == len(addresses[screen])): # after a screen
line = 0
screen += 1
if state == 0:
return screen < len(content)
else:
return screen < len(addresses)
def unhandled_input(key):
if key in ('q', 'Q'):
raise urwid.ExitMainLoop()
#txt.set_text(repr(key))
def animate(loop, user_data=None):
global delay, state, screen, line, pos
if state == 0:
cont = typeText(loop)
if not cont:
state = 1
screen = 0
line = 0
pos = 0
delay = 0
elif state == 1:
cont = typeText(loop)
cont = typeText(loop)
if not cont:
state = 2
if state < 2:
animate_alarm = loop.set_alarm_in(delay, animate)
padding = urwid.Padding(toppile, left=0, right=0)
top = urwid.Filler(padding, 'top', top=0, bottom=0)
loop = urwid.MainLoop(top, palette, unhandled_input=unhandled_input)
animate(loop)
loop.run()
|
8a72c34a9f6e798d679278327bf52bfaa0fbbce2
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
daniel-j/fallout-term
|
ebdab75bb823552f10f0532998498fe3b2af79c4
|
0541de771130d0f9290ff901609b534f1e0f2d58
|
refs/heads/master
|
<repo_name>aleksey-zhidkov/restler<file_sep>/test-api/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>restler</artifactId>
<groupId>org.restler</groupId>
<version>0.5.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<spring.version>4.1.6.RELEASE</spring.version>
<jackson.version>2.6.0</jackson.version>
</properties>
<artifactId>restler-test-api</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<source>${project.basedir}/src/main/kotlin</source>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
</project><file_sep>/restler-integration-tests/src/main/resources/import.sql
CREATE TABLE persons(id INT PRIMARY KEY, name VARCHAR(255));
CREATE TABLE pets(id INT PRIMARY KEY, name VARCHAR(255), owner_id INT, FOREIGN KEY(owner_id) REFERENCES persons(id));
CREATE TABLE addresses(id INT PRIMARY KEY, name VARCHAR(255), owner_id INT, FOREIGN KEY(owner_id) REFERENCES persons(id));
CREATE TABLE posts(id INT PRIMARY KEY, message VARCHAR(255), author_id INT, FOREIGN KEY(author_id) REFERENCES persons(id));
INSERT INTO persons (id, name) VALUES ('0', 'person0');
INSERT INTO persons (id, name) VALUES ('1', 'person1');
INSERT INTO persons (id, name) VALUES ('2', 'person2');
INSERT INTO pets (id, name, owner_id) VALUES ('0', 'bobik', '0');
INSERT INTO pets (id, name, owner_id) VALUES ('1', 'sharik', '0');
INSERT INTO pets (id, name, owner_id) VALUES ('2', 'pet2', '1');
INSERT INTO pets (id, name, owner_id) VALUES ('3', 'pet3', '1');
INSERT INTO addresses (id, name, owner_id) VALUES ('0', 'Earth', '0');
INSERT INTO addresses (id, name, owner_id) VALUES ('1', 'Mars', '0');
INSERT INTO posts (id, message, author_id) VALUES ('0', 'Hello', '0');
INSERT INTO posts (id, message, author_id) VALUES ('1', 'World', '1');
INSERT INTO posts (id, message, author_id) VALUES ('2', 'Hello, again!', '2');<file_sep>/restler-spring-data-rest/src/main/java/org/restler/spring/data/methods/SaveRepositoryMethod.java
package org.restler.spring.data.methods;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMultimap;
import org.restler.client.Call;
import org.restler.client.RestlerException;
import org.restler.http.HttpCall;
import org.restler.http.HttpMethod;
import org.restler.spring.data.calls.ChainCall;
import org.restler.spring.data.proxy.ResourceProxy;
import org.restler.spring.data.util.CloneMaker;
import org.restler.util.Pair;
import org.restler.spring.data.util.Repositories;
import org.restler.spring.data.util.RepositoryUtils;
import org.restler.util.UriBuilder;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.Repository;
import javax.persistence.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;
/**
* CrudRepository save method implementation.
*/
public class SaveRepositoryMethod extends DefaultRepositoryMethod {
private static final Method saveMethod;
static {
try {
saveMethod = CrudRepository.class.getMethod("save", Object.class);
} catch (NoSuchMethodException e) {
throw new RestlerException("Can't find CrudRepository.save method.", e);
}
}
private final String baseUri;
private final String repositoryUri;
private final Repositories repositories;
private static final ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public SaveRepositoryMethod(String baseUri, String repositoryUri, Repositories repositories) {
this.baseUri = baseUri;
this.repositoryUri = repositoryUri;
this.repositories = repositories;
}
@Override
public boolean isRepositoryMethod(Method method) {
return saveMethod.equals(method);
}
@Override
public Call getCall(URI uri, Class<?> declaringClass, Object[] args) {
ResourceTree resourceTree = makeTree(args[0], new HashSet<>());
Object currentObject = resourceTree.getTopResource();
resourceTree.forEach(resource-> {
if(resource != currentObject) {
saveResource(resource);
}
});
List<Call> calls = new ArrayList<>();
Type returnType;
if(args[0] instanceof ResourceProxy) {
ResourceProxy resourceProxy = (ResourceProxy) args[0];
returnType = resourceProxy.getObject().getClass();
calls.add(update(resourceProxy, currentObject));
} else {
Object object = args[0];
returnType = object.getClass();
calls.add(add(currentObject));
}
calls.add(makeAssociations(args[0], getChildren(args[0])));
return new ChainCall(this::filterNullResults, calls, returnType);
}
@Override
public String getPathPart(Object[] args) {
Object arg = args[0];
if(arg instanceof ResourceProxy) {
ResourceProxy resourceProxy = (ResourceProxy)arg;
return resourceProxy.getResourceId().toString();
}
return getId(arg).toString();
}
//need for filtering results are returned by associate call
private Object filterNullResults(Object prevResult, Object object) {
if(object != null) {
return object;
} else {
return null;
}
}
private Object getRequestBody(Object arg) {
if(arg instanceof ResourceProxy) {
ResourceProxy resourceProxy = (ResourceProxy)arg;
arg = resourceProxy.getObject();
}
String json;
try {
json = objectMapper.writeValueAsString(arg);
} catch (JsonProcessingException e) {
throw new RestlerException("Can't create json from object", e);
}
return json;
}
private List<Pair<Field, Object>> getChildren(Object object) {
List<Pair<Field, Object>> result = new ArrayList<>();
if(object instanceof ResourceProxy) {
object = ((ResourceProxy) object).getObject();
}
Class<?> argClass = object.getClass();
Field[] fields = argClass.getDeclaredFields();
for(Field field : fields) {
try {
field.setAccessible(true);
Object fieldValue = field.get(object);
if(fieldValue != null) {
result.add(new Pair<>(field, fieldValue));
}
field.setAccessible(false);
} catch (IllegalAccessException e) {
throw new RestlerException("Can't get value from field", e);
}
}
return result;
}
/**
* Builds resource tree for some object.
* It is recursive method that passes each resource and add it to ResourceTree.
* Also the method removes all references between resources, as result
* ResourceTree will contain resources without references to other resources.
* @param object that used for building resource tree.
* @param set it is set of references that had visited already.
*/
private ResourceTree makeTree(Object object, Set<Object> set) {
set.add(object);
if(object instanceof ResourceProxy) {
object = ((ResourceProxy) object).getObject();
}
object = CloneMaker.shallowClone(object);
List<Pair<Field, Object>> children = getChildren(object).
stream().
filter(this::isResourceOrCollection).
collect(Collectors.toList());
List<ResourceTree> resourceChildren = new ArrayList<>();
try {
for(Pair<Field, Object> child : children) {
child.getFirstValue().setAccessible(true);
if(!set.contains(child.getSecondValue())) {
if (child.getSecondValue() instanceof Collection) {
for (Object item : (Collection) child.getSecondValue()) {
resourceChildren.add(makeTree(item, set));
}
} else {
resourceChildren.add(makeTree(child.getSecondValue(), set));
}
}
child.getFirstValue().set(object, null);
child.getFirstValue().setAccessible(false);
}
} catch (IllegalAccessException e) {
throw new RestlerException("Can't set value to field.", e);
}
return new ResourceTree(resourceChildren, object);
}
private boolean isResourceOrCollection(Pair<Field, Object> item) {
Object value = item.getSecondValue();
if(value instanceof ResourceProxy) {
value = ((ResourceProxy)item.getSecondValue()).getObject();
}
return value.getClass().isAnnotationPresent(Entity.class) &&
getId(value) != null ||
value instanceof Collection;
}
private Object saveResource(Object resource) {
if(resource instanceof ResourceProxy) {
resource = ((ResourceProxy)resource).getObject();
}
Repository repository = repositories.getByResourceClass(resource.getClass()).orElse(null);
if(repository == null) {
return null;
}
if(repository instanceof CrudRepository) {
return ((CrudRepository)repository).save(resource);
}
return null;
}
/**
* Make calls that associated parent and children using OneToMany and ManyToOne associations.
* It uses OneToMany and ManyToOne annotations for building associations.
*/
private ChainCall makeAssociations(Object parent, List<Pair<Field, Object>> children) {
List<Call> calls = new ArrayList<>();
String fieldName;
for(Pair<Field, Object> child : children) {
if(child.getFirstValue().isAnnotationPresent(OneToMany.class)) {
OneToMany annotation = child.getFirstValue().getAnnotation(OneToMany.class);
fieldName = annotation.mappedBy();
if(!fieldName.isEmpty()) {
if (child.getSecondValue() instanceof Collection) {
for (Object item : (Collection) child.getSecondValue()) {
calls.add(associate(parent, item, fieldName));
}
} else {
calls.add(associate(parent, child.getSecondValue(), fieldName));
}
}
} else if(child.getFirstValue().isAnnotationPresent(ManyToOne.class)) {
calls.add(associate(child.getSecondValue(), parent, child.getFirstValue().getName()));
}
}
return new ChainCall(calls, String.class);
}
private String getUri(Object object) {
String result;
if(object instanceof ResourceProxy) {
result = ((ResourceProxy) object).getSelfUri();
} else {
Repository repository = repositories.getByResourceClass(object.getClass()).orElse(null);
if(repository == null) {
throw new RestlerException("Can't find repository " + object.getClass() + ".");
}
Object id = getId(object);
if(id == null) {
return null;
}
result = baseUri + "/" + RepositoryUtils.getRepositoryPath(repository.getClass().getInterfaces()[0]) + "/" + id;
}
return result;
}
private Call associate(Object parent, Object child, String fieldName) {
String parentUri;
String childUri;
parentUri = getUri(parent);
childUri = getUri(child);
if(parentUri == null || childUri == null) {
return null;
}
ImmutableMultimap<String, String> header = ImmutableMultimap.of("Content-Type", "text/uri-list");
/**
* The call creates request for associating parent and child.
* PUT uses for adding new associations between resources
* {@link http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_put_2}
* */
return new HttpCall(new UriBuilder(childUri + "/" + fieldName).build(), HttpMethod.PUT, parentUri, header, String.class);
}
private Call add(Object object) {
if(getId(object) == null) {
return null;
}
Object body = getRequestBody(object);
ImmutableMultimap<String, String> header = ImmutableMultimap.of("Content-Type", "application/json");
//POST uses for creating new entity
return new HttpCall(new UriBuilder(repositoryUri).build(), HttpMethod.POST, body, header, object.getClass());
}
private Call update(ResourceProxy resource, Object objectWithoutCycle) {
Object body = getRequestBody(objectWithoutCycle);
ImmutableMultimap<String, String> header = ImmutableMultimap.of("Content-Type", "application/json");
//PUT uses for replacing values
return new HttpCall(new UriBuilder(resource.getSelfUri()).build(), HttpMethod.PUT, body, header, resource.getObject().getClass());
}
private Object getId(Object object) {
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getDeclaredAnnotation(Id.class) != null || field.getDeclaredAnnotation(EmbeddedId.class) != null) {
field.setAccessible(true);
try {
Object id = field.get(object);
field.setAccessible(false);
return id;
} catch (IllegalAccessException e) {
throw new RestlerException("Can't get value from id field.", e);
}
}
}
throw new RestlerException("Can't get id.");
}
private class ResourceTree implements Iterable<Object> {
private final Object resource;
private final List<ResourceTree> children;
ResourceTree(List<ResourceTree> children, Object resource) {
this.resource = resource;
this.children = children;
}
Object getTopResource() {
return resource;
}
@Override
public Iterator<Object> iterator() {
return new TreeIterator(this);
}
private class TreeIterator implements Iterator<Object> {
private final Stack<Pair<ResourceTree, Iterator<ResourceTree>>> greyNodes = new Stack<>();
TreeIterator(ResourceTree firstNode) {
Iterator<ResourceTree> childrenIterator = firstNode.children.iterator();
greyNodes.push(new Pair<>(firstNode, childrenIterator));
}
@Override
public boolean hasNext() {
return !greyNodes.empty();
}
@Override
public Object next() {
Pair<ResourceTree, Iterator<ResourceTree>> pair = goToBottom(greyNodes.peek());
Object resource = pair.getFirstValue().resource;
greyNodes.pop();
return resource;
}
private Pair<ResourceTree, Iterator<ResourceTree>> goToBottom(Pair<ResourceTree, Iterator<ResourceTree>> node) {
Iterator<ResourceTree> childrenIterator = node.getSecondValue();
while(childrenIterator.hasNext()) {
ResourceTree newNode = childrenIterator.next();
childrenIterator = newNode.children.iterator();
greyNodes.add(new Pair<>(newNode, childrenIterator));
}
return greyNodes.peek();
}
}
}
}
<file_sep>/restler-integration-tests/src/main/kotlin/org/restler/integration/springdata/Person.java
package org.restler.integration.springdata;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Entity(name = "persons")
public class Person implements Serializable {
@Id private Long id;
@Column private String name;
@OneToMany(mappedBy = "person"/*, cascade = CascadeType.ALL*/)
private List<Pet> pets = new ArrayList<>();
@OneToMany(mappedBy = "person"/*, cascade = CascadeType.ALL*/)
private List<Address> addresses;
public Person(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public List<Pet> getPets() {return pets;}
public List<Address> getAddresses() {return addresses;}
// for JPA
Person() {
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
|
f5bdc45fa5a5ae27a3c485b9bf2331ddc1afb767
|
[
"Java",
"SQL",
"Maven POM"
] | 4
|
Maven POM
|
aleksey-zhidkov/restler
|
bc3152523cf48e69201c357f7d61df6f0d8cf5e4
|
a80da359b93a489dff9790ce6d41e4bd46bd0d3f
|
refs/heads/master
|
<file_sep>import React, { useState } from "react";
const Url = ({ url, hashid }) => {
let textArea;
const [clicked, setClicked] = useState(false);
let fixedUrl = url.split("");
if(fixedUrl.length > 30) {
let newArr = fixedUrl.slice(0,30);
newArr.push("...");
fixedUrl = newArr;
}
const copyText = () => {
const el = textArea
el.select()
document.execCommand("copy")
window.getSelection().removeAllRanges();
setClicked(true);
console.log("show");
setTimeout(() => {
setClicked(false);
console.log("hide");
}, 2000);
}
const copiedText = {
"display" : "block"
}
const done = {
"display" : "none"
}
return(
<div className="url">
<p className="oldUrl">{fixedUrl}</p>
<textarea wrap="off" spellCheck="false" cols="auto" ref={(textarea) => textArea = textarea} value={"https://www.rel.ink/" + hashid} onClick={copyText} className="newUrl" />
<div style={clicked ? copiedText : done} className="balloon">
Url copied!
<div className="arrow"></div>
</div>
</div>
)
}
export default Url;<file_sep>import React, { useState, useEffect } from "react";
import Axios from "axios";
// Components
import Url from "../components/Url";
const Main = () => {
const [list, setList] = useState([]);
const [currentUrl, setCurrentUrl] = useState("");
const [copy, setCopy] = useState(false);
useEffect(() => {
let linkList = JSON.parse(localStorage.getItem("links"));
if(linkList != null){
if(linkList.length > -1) {
setList(linkList);
}
}
}, [])
useEffect(() => {
localStorage.setItem("links", JSON.stringify(list));
}, [list])
async function getUrl(e) {
Axios.post("https://rel.ink/api/links/", {
"url":currentUrl
})
.then((response) => {
if(list.length >= 3) {
let newArr = list.splice(0,3);
setList([response.data, ...newArr]);
} else {
setList([response.data, ...list]);
}
setCurrentUrl("https://www.rel.ink/" + response.data.hashid);
setCopy(true);
})
.catch((err) => {
console.log(err);
})
console.log(list);
e.preventDefault();
}
const copying = (e) => {
e.preventDefault();
let link = document.querySelector('#bar');
link.select();
link.setSelectionRange(0, 99999);
document.execCommand("copy");
}
const setUrl = (e) => {
setCurrentUrl(e.target.value);
}
const reset = (e) => {
setCopy(false);
setCurrentUrl(e.target.value);
}
return(
<div className="urlBar">
<p id="logo">URL Shortener</p>
<form id="form" onSubmit={copy ? copying : getUrl} autoComplete="off">
<input value={currentUrl} id="bar" type="search" onChange={copy ? reset : setUrl} placeholder="enter url" />
<input id="btn" type="submit" value={copy ? "Copy" : "Shorten"} />
</form>
<div className="prevUrls">
{
list ?
list.map(item => {
return <Url url={item.url} hashid={item.hashid} key={item.created_at} />
}) : console.log("no")
}
</div>
</div>
)
}
export default Main;<file_sep>import React from "react";
// components
import Url from "../components/Url";
const UrlList = () => {
return(
<div className="urlList">
</div>
)
}
export default UrlList;
|
a128b5d5ee2626aa09951ed1ab2e7a22c2e63f0a
|
[
"JavaScript"
] | 3
|
JavaScript
|
dacqcastro/urlshorty
|
467878bd2d4682a2b6ee65145f15df5508b3ba83
|
53a062aaad3a9830bfa7e9de06d2b4ecebf20783
|
refs/heads/main
|
<repo_name>jessejonass/worldtrip<file_sep>/src/components/Header/types.ts
export type HeaderProps = {
hasBackButton: boolean;
};<file_sep>/src/components/Pages/Continent/components/Card/types.ts
export type CityCardProps = {
image: string;
capital: string;
country: string;
flag: string;
};
<file_sep>/src/components/Pages/Continent/index.ts
import Continent from './Continent';
export default Continent;
<file_sep>/src/components/Pages/Continent/components/Banner/types.ts
export type BannerProps = {
backgroundImage: string;
title: string;
};
<file_sep>/src/components/Pages/Home/components/Carousel/components/Background/types.ts
export type BackgroundProps = {
backgroundImage: string;
children: React.ReactNode;
};<file_sep>/README.md
<h1 align="center">
WorldTrip
</h1>
## Sobre o projeto
Projeto desenvolvido durante o capítulo 04 do Bootcamp [Ignite - Rocketseat](https://rocketseat.com.br/) utilizando as seguintes tecnologias:
- [ReactJS](https://reactjs.org/)
- [NextJS](https://nextjs.org/)
- [TypeScript](https://www.typescriptlang.org/)
- [Chakra-ui](https://chakra-ui.com/)
- [Swiperjs](https://swiperjs.com/)
## Download e instalação
### **Clone do projeto**
```bash
# Clonar repositório
$ git clone https://github.com/jessejonass/worldtrip.git
# Entrar na pasta clonada
$ cd worldtrip
```
### **Executando o projeto**
```bash
# Executar o comando para instalalação de dependências
$ yarn
# Executar o comando para iniciar a aplicação
$ yarn dev
```
## Screenshots
##### **Home**

##### **Detalhes**

<file_sep>/_/types.ts
export type Type = {
type: string;
}<file_sep>/src/styles/theme.ts
import { extendTheme, Theme } from "@chakra-ui/react";
export const theme = extendTheme<Theme>({
colors: {
text: {
"900": "#47585B",
"500": "#DADADA",
"100": "#F5F8FA",
},
highlight: {
"900": "#FFBA08",
"50": "rgba(255, 186, 8, 0.5)",
},
info: {
"900": "#999999",
"50": "rgba(153, 153, 153, 0.5)",
}
},
fonts: {
heading: 'Poppins',
body: 'Poppins',
},
styles: {
global: {
body: {
bg: 'text.100',
color: 'text.900',
}
}
}
});<file_sep>/src/components/Pages/Home/components/Carousel/components/Slide/types.ts
export type SlideProps = {
backgroundImage: string;
href: string;
title: string;
subtitle: string;
};
|
f08122204746b7342372f3c2e55c52c2d499177e
|
[
"Markdown",
"TypeScript"
] | 9
|
TypeScript
|
jessejonass/worldtrip
|
7a6d685180ef37835328b4580de1730db88bcd84
|
60ca75245a63989d8def64828470e9cfdb73d960
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "da.h"
#include "integer.h"
//#include "real.h"
//#include "string.h"
extern long random(void);
extern void srandom(unsigned int seed);
int
main(void)
{
printf("DA tester: 0,5\n");
printf("you can retrieve this test with:\n");
printf("wget beastie.cs.ua.edu/cs201/testing/0/da-test-0-5.c\n");
printf("\noutput:\n\n");
DA *d = newDA(displayINTEGER);
insertDA(d,newINTEGER(985));
insertDA(d,newINTEGER(112));
insertDA(d,newINTEGER(665));
insertDA(d,newINTEGER(308));
insertDA(d,newINTEGER(285));
insertDA(d,newINTEGER(286));
insertDA(d,newINTEGER(43));
insertDA(d,newINTEGER(2));
insertDA(d,newINTEGER(778));
insertDA(d,newINTEGER(935));
insertDA(d,newINTEGER(323));
insertDA(d,newINTEGER(605));
insertDA(d,newINTEGER(93));
insertDA(d,newINTEGER(842));
insertDA(d,newINTEGER(616));
insertDA(d,newINTEGER(400));
insertDA(d,newINTEGER(92));
insertDA(d,newINTEGER(23));
insertDA(d,newINTEGER(944));
insertDA(d,newINTEGER(951));
insertDA(d,newINTEGER(270));
printf("array d:");
visualizeDA(stdout,d);
printf("\n");
void *x = 0;
x = getDA(d,sizeDA(d)-1);
printf("last element is ");
displayINTEGER(stdout,x);
printf("\n");
void *y = 0;
y = getDA(d,0);
printf("first element is ");
displayINTEGER(stdout,y);
printf("\n");
printf("swapping first and last elements\n");
x = setDA(d,0,x);
y = setDA(d,sizeDA(d)-1,y);
printf("array d:");
visualizeDA(stdout,d);
printf("\n");
printf("setting the first available slot\n");
y = setDA(d,sizeDA(d),newINTEGER(540));
printf("array d:");
visualizeDA(stdout,d);
printf("\n");
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "da.h"
#include "../integerClass/integer.h"
int main(void) {
DA *items = newDA(displayINTEGER);
int i;
for (i = 0; i < 50; i++) {
insertDA(items, newINTEGER(i));
}
for (i = 0; i < 50; i++) {
int x = getINTEGER((INTEGER *) getDA(items,i));
printf("element at index %d is %d\n", i, x);
}
displayDA(stdout, items);
printf("\n");
return 0;
}
<file_sep>#!/bin/bash
echo "Running stack test from aloung..."
make
gcc test-stack.c da.o stack.o ../integerClass/integer.o
./a.out
<file_sep>!#/bin/bash
echo "Running Jake's da test..."
make
gcc personalDAtest.c da.o ../integerClass/integer.o
./a.out
<file_sep>/*Author: <NAME> (Credit: Dr. <NAME>)
*Date: 08/26/17
*University of Alabama
*
*This file serves as the header for the stack.c file
*/
#ifndef __STACK_INCLUDED__
#define __STACK_INCLUDED__
#include <stdio.h>
#include "da.h"
typedef struct stack STACK;
extern STACK *newSTACK(void (*d)(FILE *,void *));
extern void push(STACK *items,void *value);
extern void *pop(STACK *items);
extern void *peekSTACK(STACK *items);
extern int sizeSTACK(STACK *items);
extern void displaySTACK(FILE *,STACK *items);
extern void visualizeSTACK(FILE *,STACK *items);
#endif
<file_sep>/* Writen by <NAME>
* Test STACK class */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "stack.h"
#include "integer.h"
static void displayItems(STACK *);
static void visualizeItems(STACK *);
static void testPushPopPeek(STACK *);
int main(void) {
printf("\n********************** Running test-stack *************************\n");
STACK *items = newSTACK(displayINTEGER);
testPushPopPeek(items);
return 0;
}
static void testPushPopPeek(STACK *items) {
int i;
// Display empty STACK
displayItems(items);
visualizeItems(items);
printf("The size is %d.\n", sizeSTACK(items));
printf("\n");
// Add 100 values in
for (i = 0; i < 100; i++)
push(items, newINTEGER(i));
displayItems(items);
visualizeItems(items);
printf("\n");
// Show the last value
int x = getINTEGER((INTEGER *) peekSTACK(items));
printf("The last item is %d.\n", x);
printf("The size is %d.\n", sizeSTACK(items));
// Remove the last value
printf("The value ");
displayINTEGER(stdout, pop(items));
printf(" was removed.\n");
printf("The size is %d.\n", sizeSTACK(items));
// Remove the rest
for (i = 0; i < 99; i++)
pop(items);
displayItems(items);
visualizeItems(items);
printf("\n");
// Add 10 values back in
for (i = 0; i < 10; i++)
push(items, newINTEGER(i));
displayItems(items);
visualizeItems(items);
printf("\n");
}
static void displayItems(STACK *items) {
printf("displaySTACK: ");
displaySTACK(stdout,items);
printf("\n");
}
static void visualizeItems(STACK *items) {
printf("visualizeSTACK: ");
visualizeSTACK(stdout,items);
printf("\n");
}
<file_sep>/* Writen by <NAME>
* Test DA class */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "da.h"
#include "integer.h"
static void displayItems(DA *);
static void visualizeItems(DA *);
static void testInsertAndRemove(DA *);
static void testSetAndGet(DA *);
static void testUnion(DA *, DA *);
static void testExtract(DA *);
int main(void) {
printf("\n*********************** Running test-da ***************************\n");
int i;
DA *items = newDA(displayINTEGER);
testInsertAndRemove(items);
// Currently, items = [][1]
testSetAndGet(items);
// Set up recipient and donor
DA *recipient = newDA(displayINTEGER);
for (i = 0; i < 4; i++)
insertDA(recipient, newINTEGER(i));
DA *donor = newDA(displayINTEGER);
for (i = 0; i < 5; i++)
insertDA(donor, newINTEGER(i));
// Test union
testUnion(recipient, donor);
testExtract(recipient);
return 0;
}
static void testInsertAndRemove(DA *items) {
int i;
// Display an empty DA
displayItems(items);
printf("\n");
// Put 100 values in the array
for (i = 0; i < 100; i++)
insertDA(items, newINTEGER(i));
displayItems(items);
visualizeItems(items);
printf("\n");
// Remove the last value
printf("The value ");
displayINTEGER(stdout, removeDA(items));
printf(" was removed.\n");
printf("\n");
// Remove the rest
for (i = 0; i < 99; i++)
removeDA(items);
displayItems(items);
visualizeItems(items);
printf("\n");
}
static void testSetAndGet(DA *items) {
insertDA(items, newINTEGER(1));
visualizeItems(items);
int x = getINTEGER((INTEGER *) getDA(items,0));
printf("The first item is %d.\n", x);
setDA(items, 0, newINTEGER(2));
printf("After set:\n");
visualizeItems(items);
printf("\n");
printf("doing some more set testing...\n");
setDA(items, 1, newINTEGER(10));
visualizeItems(items);
printf("\n");
printf("doing some more set testing...\n");
setDA(items, 1, newINTEGER(11));
visualizeItems(items);
printf("\n");
printf("doing some more set testing...\n");
setDA(items, 2, newINTEGER(50));
visualizeItems(items);
printf("\n");
}
static void testUnion(DA *recipient, DA *donor) {
// Union
unionDA(recipient, donor);
// Show donor
printf("Donor:\n");
displayItems(donor);
visualizeItems(donor);
printf("\n");
// Show recipient
printf("Recipient:\n");
displayItems(recipient);
visualizeItems(recipient);
printf("\n");
}
static void testExtract(DA *items) {
// Extract
int size = sizeDA(items);
void **array = extractDA(items);
printf("Recipient after extracting:\n");
visualizeItems(items);
printf("\n");
printf("The last item in the extracted array is %d\n", getINTEGER((INTEGER *)array[size-1]));
}
static void displayItems(DA *items) {
printf("displayItems: ");
displayDA(stdout,items);
printf("\n");
}
static void visualizeItems(DA *items) {
printf("visualizeItems: ");
visualizeDA(stdout,items);
printf("\n");
}
<file_sep>/*Author: <NAME>
*Date: 08/26/17
*University of Alabama
*This file serves as method implementations for the
*dynamic array object
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "da.h"
struct da {
void (*display)(FILE *, void*);
int size;
int filledIndices;
void **array;
};
DA *newDA(void (*d)(FILE *, void *)) {
assert( sizeof(DA) != 0 );
DA *arr = malloc( sizeof(DA) );
arr->array = malloc( 1 * sizeof(void*) );
arr->display = d;
arr->size = 1;
arr->filledIndices = 0;
return arr;
}
void insertDA(DA *items, void *value) {
assert(sizeof(void*) * items->size * 2 != 0);
//If there is room in the array for the insert
if ( items->filledIndices < items->size ) {
items->array[items->filledIndices] = value;
items->filledIndices += 1;
}
else {
items->array = realloc( items->array, 2 * items->size * sizeof(void*) );
items->array[items->filledIndices] = value;
items->size *= 2;
items->filledIndices += 1;
}
return;
}
void *removeDA(DA *items) {
assert(items->filledIndices > 0);
void *tmp = items->array[items->filledIndices-1];
items->array[items->filledIndices-1] = NULL;
items->filledIndices -= 1;
if (items->filledIndices < items->size * .25) {
items->array = realloc( items->array, (items->size/2) * sizeof(void*) );
items->size /= 2;
}
return tmp;
}
void unionDA(DA *recipient, DA *donor) {
int i;
for (i = 0; i < donor->filledIndices; i++) {
insertDA(recipient, donor->array[i]);
}
donor->array = realloc( donor->array, sizeof(void*) );
donor->size = 1;
donor->filledIndices = 0;
}
void *getDA(DA *items, int index) {
assert(index >= 0 && index < items->filledIndices);
return items->array[index];
}
void *setDA(DA *items, int index, void *value) {
assert(index >= 0 && index <= items->filledIndices);
void *replacedVal;
if (index == items->filledIndices) {
insertDA(items, value);
replacedVal = NULL;
}
else {
replacedVal = items->array[index];
items->array[index] = value;
}
return replacedVal;
}
void **extractDA(DA *items) {
if (items->filledIndices == 0) {
return 0;
}
assert( items->filledIndices * sizeof(void*) != 0 );
void **newArr = malloc( items->size * sizeof(void *));
int i;
for (i = 0; i < items->size; i++) {
newArr[i] = items->array[i];
}
items->array = realloc( items->array, items->filledIndices * sizeof(void*) );
items->array = realloc( items->array, sizeof(void*) );
items->size = 1;
items->filledIndices = 0;
return newArr;
}
int sizeDA(DA *items) {
return items->filledIndices;
}
void visualizeDA(FILE *fp, DA *items) {
int remaining = items->size - items->filledIndices;
fprintf(fp, "[");
if (items->filledIndices != 0) {
int i;
for (i = 0; i < items->filledIndices; i++) {
items->display(fp, items->array[i]);
if (i != items->filledIndices - 1) { fprintf(fp, ","); }
}
}
fprintf(fp, "]");
fprintf(fp, "[%d]", remaining);
}
void displayDA(FILE *fp, DA *items) {
fprintf(fp, "[");
if (items->filledIndices != 0) {
int i;
for (i = 0; i < items->filledIndices; i++) {
items->display(fp, items->array[i]);
if (i != items->filledIndices - 1) { fprintf(fp, ","); }
}
}
fprintf(fp, "]");
}
<file_sep>#Author: <NAME>
#Date: 08/26/17
#University of Alabama
#This is the generic makefile for the data structures created
OPTS = -Wall -Wextra -std=c99
OBJS = da.o cda.o stack.o queue.o integer.o real.o
TESTOBJS = test-da.o test-cda.o test-stack.o test-queue.o failed-test.o failed-test2.o failed-test3.o resub_failed_test.o
TESTEXES = runDATest runCDATest runStackTest runQueueTest runFailedTest1 runFailedTest2 runFailedTest3 runResubTest
all: $(OBJS)
test: $(OBJS) $(TESTOBJS)
#./runFailedTest1
#./runFailedTest2
#./runFailedTest3
#./runDATest
#./runCDATest
#./runStackTest
#./runQueueTest
./runResubTest
real.o: real.c real.h
gcc $(OPTS) -c real.c
integer.o: integer.c integer.h
gcc $(OPTS) -c integer.c
da.o: da.c da.h
gcc $(OPTS) -c da.c
cda.o: cda.c cda.h
gcc $(OPTS) -c cda.c
stack.o: stack.c stack.h
gcc $(OPTS) -c stack.c
queue.o: queue.c queue.h
gcc $(OPTS) -c queue.c
clean:
rm -rf *.o $(TESTEXES) ./a.out
#******************************************************************************#
resub_failed_test.o: resub_failed_test.c da.o integer.o real.o
gcc $(OPTS) resub_failed_test.c da.o integer.o real.o -o runResubTest
failed-test.o: da-test-0-5.c da.o integer.o
gcc $(OPTS) da-test-0-5.c da.o integer.o -o runFailedTest1
failed-test2.o: cda-test-0-4.c cda.o integer.o
gcc $(OPTS) cda-test-0-4.c cda.o integer.o -o runFailedTest2
failed-test3.o: cda-test-0-5.c cda.o integer.o
gcc $(OPTS) cda-test-0-5.c cda.o integer.o -o runFailedTest3
test-da.o: test-da.c da.o integer.o
gcc $(OPTS) test-da.c da.o integer.o -o runDATest
test-cda.o: test-cda.c cda.o integer.o
gcc $(OPTS) test-cda.c cda.o integer.o -o runCDATest
test-stack.o: test-stack.c stack.o da.o integer.o
gcc $(OPTS) test-stack.c stack.o da.o integer.o -o runStackTest
test-queue.o: test-queue.c queue.o cda.o integer.o
gcc $(OPTS) test-queue.c queue.o cda.o integer.o -o runQueueTest
<file_sep>/* Writen by <NAME>
* Test CDA class */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "cda.h"
#include "integer.h"
static void displayItems(CDA *);
static void visualizeItems(CDA *);
static void testInsertAndRemove(CDA *);
static void testSetAndGet(CDA *);
static void testUnion(CDA *, CDA *);
static void testExtract(CDA *);
int main(void) {
CDA *donor = newCDA(displayINTEGER);
CDA *recipient = newCDA(displayINTEGER);
int i;
for (i = 0; i < 10; i++) {
insertCDAback(recipient, newINTEGER(i));
}
for (i = 10; i < 20; i++) {
insertCDAback(donor, newINTEGER(i));
}
printf("recipient: \n");
displayCDA(stdout, recipient);
printf("\n");
visualizeCDA(stdout, recipient);
printf("\n");
printf("donor: \n");
displayCDA(stdout, donor);
printf("\n");
visualizeCDA(stdout, donor);
printf("\n");
printf("Executing union...\n");
unionCDA(recipient, donor);
printf("\n");
printf("union done, here is donor: \n");
displayCDA(stdout, donor);
printf("\n");
visualizeCDA(stdout, donor);
printf("\n");
printf("here is recipient: \n");
displayCDA(stdout, recipient);
printf("\n");
visualizeCDA(stdout, recipient);
printf("\n");
printf("extracting recipient...\n");
void **arr = extractCDA(recipient);
printf("extracted array is: \n");
for (i = 0; i < 20; i++) {
printf("%d\t", getINTEGER(arr[i]));
}
printf("\n");
printf("recipient is now: \n");
visualizeCDA(stdout, recipient);
printf("\n");
printf("now adding more stuff to recipient...\n");
printf("adding some values at front...\n");
for (i = 0; i < 50; i++) {
insertCDAfront(recipient, newINTEGER(i));
}
printf("recipient now is: \n");
visualizeCDA(stdout, recipient);
printf("\n");
printf("now adding values at back...\n");
for (i = 0; i < 73; i++) {
insertCDAback(recipient, newINTEGER(i));
}
printf("recipient is now: \n");
visualizeCDA(stdout, recipient);
printf("\n");
printf("extracting recipient again...\n");
extractCDA(recipient);
printf("recipient now is: \n");
visualizeCDA(stdout, recipient);
printf("now adding at both front and back...\n");
for (i = 0; i < 50; i++) {
insertCDAfront(recipient, newINTEGER(i));
insertCDAback(recipient, newINTEGER(0-i));
}
printf("finally, recipient is: \n");
visualizeCDA(stdout, recipient);
printf("\n");
CDA *items = newCDA(displayINTEGER);
testInsertAndRemove(items);
// Currently, items = [][1]
testSetAndGet(items);
// Set up recipient and donor
CDA *recip = newCDA(displayINTEGER);
for (i = 0; i < 4; i++)
insertCDAback(recip, newINTEGER(i));
CDA *don = newCDA(displayINTEGER);
for (i = 0; i < 5; i++)
insertCDAback(don, newINTEGER(i));
// Test union
testUnion(recip, don);
testExtract(recip);
return 0;
}
static void testInsertAndRemove(CDA *items) {
int i;
// Display an empty DA
displayItems(items);
printf("\n");
// Put 100 values in the array
for (i = 0; i < 50; i++)
insertCDAback(items, newINTEGER(i));
for (i = 50; i < 100; i++)
insertCDAfront(items, newINTEGER(i));
displayItems(items);
visualizeItems(items);
printf("\n");
// Remove the last value
printf("The value ");
displayINTEGER(stdout, removeCDAback(items));
printf(" was removed.\n");
printf("\n");
// Remove the first value
printf("The value ");
displayINTEGER(stdout, removeCDAfront(items));
printf(" was removed.\n");
printf("\n");
// Remove the rest
for (i = 0; i < 49; i++)
removeCDAback(items);
for (i = 0; i < 49; i++)
removeCDAfront(items);
displayItems(items);
visualizeItems(items);
printf("\n");
}
static void testSetAndGet(CDA *items) {
insertCDAback(items, newINTEGER(1));
visualizeItems(items);
int x = getINTEGER((INTEGER *) getCDA(items,0));
printf("The first item is %d.\n", x);
setCDA(items, 0, newINTEGER(2));
printf("After set:\n");
visualizeItems(items);
printf("\n");
}
static void testUnion(CDA *recipient, CDA *donor) {
// Union
unionCDA(recipient, donor);
// Show donor
printf("Donor:\n");
displayItems(donor);
visualizeItems(donor);
printf("\n");
// Show recipient
printf("Recipient:\n");
displayItems(recipient);
visualizeItems(recipient);
printf("\n");
}
static void testExtract(CDA *items) {
// Extract
int size = sizeCDA(items);
void **array = extractCDA(items);
printf("Recipient after extracting:\n");
visualizeItems(items);
printf("\n");
printf("The last item in the extracted array is %d\n", getINTEGER((INTEGER *)array[size-1]));
}
static void displayItems(CDA *items) {
printf("displayItems: ");
displayCDA(stdout,items);
printf("\n");
}
static void visualizeItems(CDA *items) {
printf("visualizeItems: ");
visualizeCDA(stdout,items);
printf("\n");
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "cda.h"
#include "../integerClass/integer.h"
void testSmall(CDA *items);
void testLarge(CDA *items);
int main(void) {
CDA *items = newCDA(displayINTEGER);
testSmall(items);
return 0;
}
void testSmall(CDA *items) {
printf("Adding a few values...\n");
int i;
for (i = 1; i < 6; i++) {
insertCDAfront(items, newINTEGER(i));
}
show(items);
printf("Removing front...\n");
printf("removing front index, which is: %d\n", getINTEGER(removeCDAfront(items)));
show(items);
printf("removing front index, which is: %d\n", getINTEGER(removeCDAfront(items)));
show(items);
printf("removing front index, which is: %d\n", getINTEGER(removeCDAfront(items)));
show(items);
printf("removing front index, which is: %d\n", getINTEGER(removeCDAfront(items)));
show(items);
printf("Now adding more...\n");
for (i = 0; i < 100; i++) {
insertCDAfront(items, newINTEGER(i));
}
show(items);
}
void testLarge(CDA *items) {
show(items);
/******************************************************************************/
printf("Inserting a bunch of values at front...\n");
int i;
for (i = 0; i < 100; i++) {
insertCDAfront(items, newINTEGER(i));
}
show(items);
/******************************************************************************/
printf("Inserting a bunch of values at back...\n");
CDA *items2 = newCDA(displayINTEGER);
for (i = 0; i < 100; i++) {
insertCDAback(items2, newINTEGER(i));
}
show(items2);
/******************************************************************************/
printf("Removing a bunch of values from the front of items...\n");
for (i = 0; i < 99; i++) {
removeCDAfront(items);
}
show(items);
/******************************************************************************/
printf("Removing a bunch of values from the back of items2...\n");
for (i = 0; i < 99; i++) {
removeCDAfront(items2);
}
show(items2);
}
void show(CDA *items) {
printf("displayCDA: "); displayCDA(stdout, items); printf("\n");
printf("=============================================================\n");
printf("visualizeCDA: "); visualizeCDA(stdout, items); printf("\n");
printf("\n");
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "../integerClass/integer.h"
#include "da.h"
static void showItemsDA(DA *items) {
printf("The items are ");
displayDA(stdout,items);
printf("\n");
}
int main(void) {
DA *array = newDA(displayINTEGER);
return 0;
}
<file_sep># Dynamic-Structures
C implementation of Dynamic Array (vector), Circular Dynamic Array, Stack (based on top of Dynamic Array), and Queue (based on top of Circular Dynamic Array).
Utilized void pointers to essentially create "objects" within C.
To use makefile (after cloning repo):</br>
~$ make</br>
(compiles C files to executables)</br>
~$ make clean</br>
(cleans directory of executables)</br>
~$ make test</br>
(compiles C files to executables and runs line of tests to ensure correct output)
<file_sep>#!/bin/bash
echo "Running test..."
make
gcc personalCDAtest.c cda.o ../integerClass/integer.o
./a.out
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "stack.h"
#include "../integerClass/integer.h"
int main() {
STACK *items = newSTACK(displayINTEGER);
int i;
for (i = 0; i < 500; i++) {
push(items, newINTEGER(i));
}
int x = getINTEGER( (INTEGER*)pop(items) );
printf("x is %d\n", x);
displaySTACK(stdout, items);
return 0;
}
<file_sep>/* Writen by <NAME>
* Test QUEUE class */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "queue.h"
#include "integer.h"
static void displayItems(QUEUE *);
static void visualizeItems(QUEUE *);
static void testEnqueueDequeuePeek(QUEUE *);
int main(void) {
printf("\n********************** Running test-queue *************************\n");
QUEUE *items = newQUEUE(displayINTEGER);
testEnqueueDequeuePeek(items);
return 0;
}
static void testEnqueueDequeuePeek(QUEUE *items) {
int i;
// Display empty QUEUE
displayItems(items);
visualizeItems(items);
printf("The size is %d.\n", sizeQUEUE(items));
printf("\n");
// Add 100 values in
for (i = 0; i < 100; i++)
enqueue(items, newINTEGER(i));
displayItems(items);
visualizeItems(items);
printf("\n");
// Show the last value
int x = getINTEGER((INTEGER *) peekQUEUE(items));
printf("The last item is %d.\n", x);
printf("The size is %d.\n", sizeQUEUE(items));
// Remove the last value
printf("The value ");
displayINTEGER(stdout, dequeue(items));
printf(" was removed.\n");
printf("The size is %d.\n", sizeQUEUE(items));
// Remove the rest
for (i = 0; i < 99; i++)
dequeue(items);
displayItems(items);
visualizeItems(items);
printf("\n");
// Add 10 values back in
for (i = 0; i < 10; i++)
enqueue(items, newINTEGER(i));
displayItems(items);
visualizeItems(items);
printf("\n");
}
static void displayItems(QUEUE *items) {
printf("displayQUEUE: ");
displayQUEUE(stdout,items);
printf("\n");
}
static void visualizeItems(QUEUE *items) {
printf("visualizeQUEUE: ");
visualizeQUEUE(stdout,items);
printf("\n");
}
<file_sep>/*
*Author: <NAME>
*
*Question: Should set return 0 or NULL if it is added to the to the end of the array?
*
*This test will run every case and edge case I
*can conceive right now on CDA
*
*Some of the methods have assertion testing commented out. Scroll down and
*uncomment to test assertions.
*
*If you want the program to print to the console, change fp to
*fopen(stdout, "w+").
*/
#include <stdio.h>
#include <stdlib.h>
#include "cda.h"
#include "integer.h"
void showResults(FILE *, CDA *);
void testInsertFront(FILE *, CDA *);
void testInsertBack(FILE*, CDA *);
void testRemoveCDAfront(FILE *, CDA *);
void testRemoveCDAback(FILE *,CDA *);
void testUnion(FILE *, CDA *, CDA *);
void testUnionExtra(FILE *, CDA *, CDA *);
void testGet(FILE *, CDA *);
void testSet(FILE *, CDA *);
void testExtract(FILE *, CDA *);
void testSizeCDA(FILE *, CDA *);
int main(void) {
FILE *fp = fopen("/home/jake/CS201/megaTest.txt", "w+");
fprintf(fp, "\n");
/*** Initializing CDA's ***/
CDA *items = newCDA(displayINTEGER);
CDA *items2 = newCDA(displayINTEGER);
CDA *recipient = newCDA(displayINTEGER);
CDA *donor = newCDA(displayINTEGER);
CDA *testArr = newCDA(displayINTEGER);
CDA *testArr2 = newCDA(displayINTEGER);
CDA *testArr3 = newCDA(displayINTEGER);
CDA *recip = newCDA(displayINTEGER);
CDA *don = newCDA(displayINTEGER);
/*** Adding 100 elements to items and items2 ***/
testInsertFront(fp, items);
testInsertBack(fp, items2);
/*** Removing all 100 items from items (front) ***/
testRemoveCDAfront(fp, items);
/*** Removing all 100 items from items2 (back) ***/
testRemoveCDAback(fp, items2);
/*** Testing unionCDA (lot of edge cases, look at function definition) ***/
testUnion(fp, recipient, donor);
/*** Testing get() function on recipient array ***/
testGet(fp, recipient);
/*** Testing set() function on new array ***/
testSet(fp, testArr);
/*** Testing extract() function on both full and empty arrays ***/
testExtract(fp, testArr2);
/*** Testing sizeCDA() function on both full and empty arrays ***/
testSizeCDA(fp, testArr3);
/*** Testing some additional edge cases for union ***/
testUnionExtra(fp, recip, don);
return 0;
}
void showResults(FILE *fp, CDA *items) {
fprintf(fp, "!!!\n\n");
fprintf(fp, "Displaying CDA: \n");
displayCDA(fp, items);
fprintf(fp, "\n\n");
fprintf(fp, "Visualizing CDA: \n");
visualizeCDA(fp, items);
fprintf(fp, "\n\n!!!\n\n");
}
void testInsertFront(FILE *fp, CDA *items) {
fprintf(fp, "Testing generic insert FRONT (x100)\n");
fprintf(fp, "*********************************************************************\n");
int i;
for (i = 0; i < 100; i++) {
insertCDAfront(items, newINTEGER(i));
}
showResults(fp, items);
fprintf(fp, "*********************************************************************\n");
}
void testInsertBack(FILE *fp, CDA *items) {
fprintf(fp, "Testing generic insert BACK (x100)\n");
fprintf(fp, "*********************************************************************\n");
int i;
for (i = 0; i < 100; i++) {
insertCDAback(items, newINTEGER(i));
}
showResults(fp, items);
fprintf(fp, "*********************************************************************\n");
}
void testRemoveCDAfront(FILE *fp, CDA *items) {
fprintf(fp, "Testing generic remove FRONT (x100)\n");
fprintf(fp, "*********************************************************************\n");
fprintf(fp, "Array should be empty...\n");
int i;
for (i = 0; i < 100; i++) {
removeCDAfront(items);
}
showResults(fp, items);
/* NOTE: Use the below code to be sure your assertion is correctly triggered
fprintf(fp, "Attempting to removeCDAfront from empty array (assertion should trigger)...\n");
removeCDAfront(items);
showResults(fp, items);
*/
fprintf(fp, "*********************************************************************\n");
}
void testRemoveCDAback(FILE *fp, CDA *items) {
fprintf(fp, "Testing generic remove BACK (x100)\n");
fprintf(fp, "*********************************************************************\n");
fprintf(fp, "Array should be empty...\n");
int i;
for (i = 0; i < 100; i++) {
removeCDAback(items);
}
showResults(fp, items);
/* NOTE: Use the below code to be sure your assertion is correctly triggered
fprintf(fp, "Attempting to removeCDAfront from empty array (assertion should trigger)...\n");
removeCDAback(items);
showResults(fp, items);
*/
fprintf(fp, "*********************************************************************\n");
}
void testUnion(FILE *fp, CDA *recipient, CDA *donor) {
fprintf(fp, "Testing union after inserting 20 values\n");
fprintf(fp, "*********************************************************************\n");
int i;
for (i = 0; i < 10; i++) {
insertCDAback(recipient, newINTEGER(i));
}
for (i = 10; i < 20; i++) {
insertCDAback(donor, newINTEGER(i));
}
fprintf(fp, "Inserted 10 values in recipient and donor...\n");
fprintf(fp, "unionizing...\n");
unionCDA(recipient, donor);
fprintf(fp, "Results for donor: \n");
showResults(fp, donor);
fprintf(fp, "Results for recipient: \n");
showResults(fp, recipient);
fprintf(fp, "Now inserting a bunch of values to recipient...\n");
for (i = 0; i < 25; i++) {
insertCDAfront(recipient, newINTEGER(i));
insertCDAback(recipient, newINTEGER(i));
}
showResults(fp, recipient);
fprintf(fp, "Attempting to union empty donor array into recipient...\n");
unionCDA(recipient, donor);
fprintf(fp, "Recipient is: \n");
showResults(fp, recipient);
fprintf(fp, "Donor is: \n");
showResults(fp, donor);
fprintf(fp, "Now trying to union recipient array into empty donor...\n");
unionCDA(donor, recipient);
fprintf(fp, "Recipient is: \n");
showResults(fp, recipient);
fprintf(fp, "Donor is: \n");
showResults(fp, donor);
fprintf(fp, "Now recipient should be empty and donor should be full, trying to pass all back to recipient...\n");
unionCDA(recipient, donor);
fprintf(fp, "Recipient is: \n");
showResults(fp, recipient);
fprintf(fp, "Donor is: \n");
showResults(fp, donor);
fprintf(fp, "*********************************************************************\n");
}
void testGet(FILE *fp, CDA *items) {
fprintf(fp, "Testing get\n");
fprintf(fp, "*********************************************************************\n");
fprintf(fp, "Getting front of array...\n");
int num = getINTEGER( (INTEGER *)getCDA(items, 0) );
fprintf(fp, "Value at recipient->array[0] is: %d\n", num);
fprintf(fp, "Getting back of array...\n");
num = getINTEGER( (INTEGER *)getCDA(items, sizeCDA(items) - 1) );
fprintf(fp, "Value at back of the array is: %d\n\n", num);
/*NOTE: Use the below code to determine if your assertion is correctly triggered
fprintf(fp, "Attempting to access out of bounds array index...\n");
num = getINTEGER( (INTEGER *)getCDA(items, sizeCDA(items)) );
fprintf(fp, "The program should not get to this point, but somehow it did\n");
*/
fprintf(fp, "*********************************************************************\n");
}
void testSet(FILE *fp, CDA *items) {
fprintf(fp, "Testing set\n");
fprintf(fp, "*********************************************************************\n");
int i;
for (i = 0; i < 50; i++) {
insertCDAback(items, newINTEGER(i));
}
fprintf(fp, "Array before set is: \n");
showResults(fp, items);
fprintf(fp, "Setting first element of the array with 5...\n");
int num = getINTEGER( (INTEGER *)setCDA(items, 0, newINTEGER(5)) );
fprintf(fp, "Value replaced is: %d\n", num);
fprintf(fp, "Array is now: \n");
showResults(fp, items);
fprintf(fp, "Setting last element of the array with 10...\n");
num = getINTEGER( (INTEGER *)setCDA(items, 49, newINTEGER(10)) );
fprintf(fp, "Replaced value is: %d\n", num);
fprintf(fp, "Array is now: \n");
showResults(fp, items);
fprintf(fp, "Setting empty element after last element in the array with 69...\n");
num = getINTEGER( (INTEGER *)setCDA(items, 49, newINTEGER(69)) );
fprintf(fp, "Replaced value is: %d\n", num);
fprintf(fp, "Array is now: \n");
showResults(fp, items);
fprintf(fp, "Setting the [-1] element to 32...\n");
setCDA(items, -1, newINTEGER(32));
fprintf(fp, "Array is now: \n");
showResults(fp, items);
/*NOTE: Use the following code to determine if your assertion is correctly triggered
fprintf(fp, "Attempting to set out of bounds index\n");
num = getINTEGER( (INTEGER *)setCDA(items, 55, newINTEGER(98)) );
fprintf(fp, "Replaced value is: %d\n", num);
fprintf(fp, "Array is now: \n");
showResults(fp, items);
*/
fprintf(fp, "*********************************************************************\n");
}
void testExtract(FILE *fp, CDA *items) {
fprintf(fp, "Testing extract\n");
fprintf(fp, "*********************************************************************\n");
fprintf(fp, "Inserting a bunch of values into array...\n");
int i;
for (i = 0; i < 20; i++) {
insertCDAback(items, newINTEGER(i));
insertCDAfront(items, newINTEGER(i*-1));
}
fprintf(fp, "Array is: \n");
showResults(fp, items);
fprintf(fp, "Now extracting array...\n");
int **array = extractCDA(items);
fprintf(fp, "Array is now: \n");
showResults(fp, items);
fprintf(fp, "And the extracted array is: \n");
for (i = 0; i < 40; i++) { fprintf(fp, "%d\t", getINTEGER( (INTEGER *)array[i]) ); }
fprintf(fp, "\n");
fprintf(fp, "Attempting to extract from empty array...\n");
extractCDA(items);
showResults(fp, items);
fprintf(fp, "*********************************************************************\n");
}
void testSizeCDA(FILE *fp, CDA *items) {
fprintf(fp, "Testing sizeCDA...\n");
fprintf(fp, "*********************************************************************\n");
fprintf(fp, "Size of array is: %d (it should be 0)\n", sizeCDA(items));
fprintf(fp, "Adding some values to the array...\n");
int i;
for (i = 0; i < 4; i++) {
insertCDAback(items, newINTEGER(i));
}
fprintf(fp, "Size of array is: %d (it should be 4)\n", sizeCDA(items));
fprintf(fp, "*********************************************************************\n");
}
void testUnionExtra(FILE *fp, CDA* recip, CDA *don) {
fprintf(fp, "Running extra union test...\n");
fprintf(fp, "*********************************************************************\n");
fprintf(fp, "Filling array to size 4 so that there are 0 leftover spaces\n");
int i;
for (i = 0; i < 4; i++) {
insertCDAback(recip, newINTEGER(i));
}
fprintf(fp, "Adding 2 values to donor array...\n");
for (i = 0; i < 2; i++) {
insertCDAback(don, newINTEGER(i));
}
fprintf(fp, "Unionizing...\n");
unionCDA(recip, don);
fprintf(fp, "Recip is now: \n");
showResults(fp, recip);
fprintf(fp, "Don is now: \n");
showResults(fp, don);
fprintf(fp, "Now unionizing into donor...\n");
unionCDA(don, recip);
fprintf(fp, "Recip is now: \n");
showResults(fp, recip);
fprintf(fp, "Don is now: \n");
showResults(fp, don);
fprintf(fp, "*********************************************************************\n");
}
<file_sep>!#/bin/bash
echo "Running other kid's queue test..."
make
gcc test-queue.c cda.o queue.o ../integerClass/integer.o
./a.out
<file_sep>/* Test cda prog wrtten by <NAME> */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "cda.h"
#include "integer.h"
void test1(CDA *, CDA *);
void test2(CDA *);
void test3(CDA *, CDA *);
int main(void) {
printf("\n*********************** Running test-cda **************************\n");
CDA *donor = newCDA(displayINTEGER);
CDA *recipient = newCDA(displayINTEGER);
CDA *items = newCDA(displayINTEGER);
test1(donor, recipient);
test2(items);
CDA *donor2 = newCDA(displayINTEGER);
CDA *recipient2 = newCDA(displayINTEGER);
test3(recipient2, donor2);
return 0;
}
void test1(CDA *recipient, CDA *donor) {
int i;
for (i = 0; i < 10; i++) {
insertCDAback(recipient, newINTEGER(i));
}
for (i = 10; i < 20; i++) {
insertCDAback(donor, newINTEGER(i));
}
printf("recipient: \n");
displayCDA(stdout, recipient);
printf("\n");
visualizeCDA(stdout, recipient);
printf("\n");
printf("donor: \n");
displayCDA(stdout, donor);
printf("\n");
visualizeCDA(stdout, donor);
printf("\n");
printf("Executing union...\n");
unionCDA(recipient, donor);
printf("\n");
printf("union done, here is donor: \n");
displayCDA(stdout, donor);
printf("\n");
visualizeCDA(stdout, donor);
printf("\n");
printf("here is recipient: \n");
displayCDA(stdout, recipient);
printf("\n");
visualizeCDA(stdout, recipient);
printf("\n");
printf("extracting recipient...\n");
void **arr = extractCDA(recipient);
printf("extracted array is: \n");
for (i = 0; i < 20; i++) {
printf("%d\t", getINTEGER(arr[i]));
}
printf("\n");
printf("recipient is now: \n");
visualizeCDA(stdout, recipient);
printf("\n");
printf("now adding more stuff to recipient...\n");
printf("adding some values at front...\n");
for (i = 0; i < 50; i++) {
insertCDAfront(recipient, newINTEGER(i));
}
printf("recipient now is: \n");
visualizeCDA(stdout, recipient);
printf("\n");
printf("now adding values at back...\n");
for (i = 0; i < 73; i++) {
insertCDAback(recipient, newINTEGER(i));
}
printf("recipient is now: \n");
visualizeCDA(stdout, recipient);
printf("\n");
printf("extracting recipient again...\n");
extractCDA(recipient);
printf("recipient now is: \n");
visualizeCDA(stdout, recipient);
printf("now adding at both front and back...\n");
for (i = 0; i < 50; i++) {
insertCDAfront(recipient, newINTEGER(i));
insertCDAback(recipient, newINTEGER(0-i));
}
printf("finally, recipient is: \n");
visualizeCDA(stdout, recipient);
printf("\n");
}
void test2(CDA *items) {
printf("=================================================================\n");
int i;
for (i = 0; i < 35; i++) {
insertCDAback(items, newINTEGER(i));
}
printf("removing all but one element from the array...\n");
for (i = 0; i < 34; i++) {
removeCDAback(items);
}
visualizeCDA(stdout, items);
printf("\n=================================================================\n");
printf("removing last element...\n");
removeCDAback(items);
visualizeCDA(stdout, items);
printf("\n");
printf("adding one element back in...\n");
insertCDAfront(items, newINTEGER(1));
visualizeCDA(stdout, items);
printf("\n");
printf("removing that element...\n");
int val = getINTEGER(removeCDAfront(items));
visualizeCDA(stdout, items);
printf("\nand the value removed was %d\n", val);
printf("=================================================================\n\n");
}
void test3(CDA *recip, CDA *don) {
int i;
for (i = 0; i < 63; i++) {
insertCDAback(don, newINTEGER(i));
}
printf("before union, recip is: \n");
visualizeCDA(stdout, recip);
printf("\n");
printf("and don is: \n");
visualizeCDA(stdout, don);
printf("\n");
printf("performing union...\n");
unionCDA(recip, don);
printf("after union, recip is: \n");
visualizeCDA(stdout, recip);
printf("\n");
printf("and don is: \n");
visualizeCDA(stdout, don);
printf("\n");
}
<file_sep>#!/bin/bash
echo "Running other kid's test..."
make
gcc test-cda.c cda.o ../integerClass/integer.o
./a.out
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "da.h"
#include "integer.h"
#include "real.h"
#include "string.h"
extern long random(void);
extern void srandom(unsigned int seed);
int
main(void)
{
printf("DA tester: 1,6\n");
printf("you can retrieve this test with:\n");
printf("wget beastie.cs.ua.edu/cs201/testing/0/da-test-1-6.c\n");
printf("\noutput:\n\n");
DA *d = newDA(displayINTEGER);
insertDA(d,newINTEGER(189));
insertDA(d,newINTEGER(468));
insertDA(d,newINTEGER(583));
insertDA(d,newINTEGER(868));
insertDA(d,newINTEGER(885));
insertDA(d,newINTEGER(35));
insertDA(d,newINTEGER(592));
insertDA(d,newINTEGER(686));
insertDA(d,newINTEGER(32));
insertDA(d,newINTEGER(874));
insertDA(d,newINTEGER(222));
insertDA(d,newINTEGER(631));
insertDA(d,newINTEGER(281));
insertDA(d,newINTEGER(719));
insertDA(d,newINTEGER(909));
insertDA(d,newINTEGER(828));
insertDA(d,newINTEGER(395));
insertDA(d,newINTEGER(481));
insertDA(d,newINTEGER(674));
insertDA(d,newINTEGER(442));
insertDA(d,newINTEGER(346));
printf("array d:");
visualizeDA(stdout,d);
printf("\n");
int size = sizeDA(d);
printf("extracting the underlying array\n");
void **a = extractDA(d);
void *p = a[0];
printf("the first element of the extracted array: ");
displayINTEGER(stdout,p);
printf("\n");
p = a[size-1];
printf("the last element of the extracted array: ");
displayINTEGER(stdout,p);
printf("\n");
printf("array d:");
visualizeDA(stdout,d);
printf("\n");
return 0;
}
<file_sep>/*Author: <NAME>
*Date: 08/26/17
*University of Alabama
*This file serves as method implementations for the
*dynamic array object
*/
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include "stack.h"
//#include "integerClass/integer.h"
struct stack {
DA *vector;
void (*display)(FILE *, void*);
};
STACK *newSTACK(void (*d)(FILE *, void *)) {
assert( sizeof(STACK) != 0 );
STACK *myStack = malloc( sizeof(STACK) );
myStack->vector = newDA(d);
myStack->display = d;
return myStack;
}
void push(STACK *items, void *value) {
insertDA(items->vector, value);
}
void *pop(STACK *items) {
assert( sizeDA(items->vector) > 0 );
void *popVal = removeDA(items->vector);
return popVal;
}
void *peekSTACK(STACK *items) {
assert( sizeDA(items->vector) > 0 );
int index = sizeDA(items->vector);
return getDA(items->vector, index - 1);
}
int sizeSTACK(STACK *items) {
return sizeDA(items->vector);
}
void displaySTACK(FILE *fp, STACK *items) {
// getDA(items->vector, 0);
/******************************************************************************/
fprintf(fp, "|");
if (sizeDA(items->vector) != 0) {
int vectorSize = sizeDA(items->vector);
int i;
for (i = 0; i < vectorSize; i++ ) {
void *element = getDA(items->vector, (vectorSize - 1) - i);
items->display(fp, element);
if (i != sizeSTACK(items) - 1) { fprintf(fp, ","); }
}
}
fprintf(fp, "|");
/******************************************************************************/
}
void visualizeSTACK(FILE *fp, STACK *items) {
displayDA(fp, items->vector);
}
<file_sep>!#/bin/bash
echo "Running Jake stack test..."
make
gcc personalStackTest.c da.o stack.o ../integerClass/integer.o
./a.out
<file_sep>/*Author: <NAME>
*The University of Alabama
*Date: 9/7/2017
*
*This test program mimics what is on Dr. John Lusth's test0 submit utility
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "cda.h"
#include "integer.h"
int main(void) {
printf("Making a new array, inserting numbers 0 through 4 inclusive...\n");
CDA *items = newCDA(displayINTEGER);
int i;
for (i = 0; i < 5; ++i) {
insertCDAback(items, newINTEGER(i));
}
displayCDA(stdout, items);
printf("\nremoving the head item in the array...\n");
removeCDAfront(items);
printf("displaying the array...\n");
displayCDA(stdout, items);
printf("\n");
printf("making a new array, inserting numbers 5 through 9, inclusive...\n");
CDA *items2 = newCDA(displayINTEGER);
for (i = 5; i <= 9; ++i) {
insertCDAfront(items2, newINTEGER(i));
}
printf("displaying the array...\n");
displayCDA(stdout, items2);
printf("\n");
printf("merging the two arrays...\n");
unionCDA(items, items2);
printf("dipslaying the two arrays...\n");
displayCDA(stdout, items);
displayCDA(stdout, items2);
printf("\n");
printf("removing the tail item in the array...\n");
removeCDAback(items);
printf("displaying the array...\n");
displayCDA(stdout, items);
printf("\n");
return 0;
}
<file_sep>/*Author: <NAME> (Credit: Dr. J. Lusth)
*Date: 08/26/17
*University of Alabama
*
*This file serves as the header for the da.c file
*/
#ifndef __DA_INCLUDED__
#define __DA_INCLUDED__
#include <stdio.h>
typedef struct da DA;
extern DA *newDA(void (*d)(FILE *,void *));
extern void insertDA(DA *items,void *value);
extern void *removeDA(DA *items);
extern void unionDA(DA *recipient,DA *donor);
extern void *getDA(DA *items,int index);
extern void *setDA(DA *items,int index,void *value);
extern void **extractDA(DA *items);
extern int sizeDA(DA *items);
extern void visualizeDA(FILE *fp,DA *items);
extern void displayDA(FILE *fp,DA *items);
#endif
<file_sep>!#/bin/bash
echo "Running other kid's da test..."
make
gcc test-da.c da.o ../integerClass/integer.o
./a.out
|
70ebe98087fbb1eb1438375e34496c58289e9ee6
|
[
"Markdown",
"C",
"Makefile",
"Shell"
] | 26
|
C
|
jaw653/Dynamic-Structures
|
f775f05618a883cb0bd532c2fcf12b635184ff51
|
7cbbfedd15dace42755b81a4b150187efd8d3252
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RapidCMS.Core.Abstractions.Data;
using RapidCMS.Core.Abstractions.Resolvers;
using RapidCMS.Core.Abstractions.Setup;
using RapidCMS.Core.Extensions;
namespace RapidCMS.Core.Resolvers.Data
{
internal class FormDataViewResolver : IDataViewResolver
{
private readonly IServiceProvider _serviceProvider;
private readonly ISetupResolver<ICollectionSetup> _collectionResolver;
public FormDataViewResolver(
IServiceProvider serviceProvider,
ISetupResolver<ICollectionSetup> collectionResolver)
{
_serviceProvider = serviceProvider;
_collectionResolver = collectionResolver;
}
public async Task ApplyDataViewToQueryAsync(IQuery query)
{
if (string.IsNullOrEmpty(query.CollectionAlias))
{
throw new ArgumentNullException($"{nameof(query)}.{nameof(query.CollectionAlias)}");
}
var collection = await _collectionResolver.ResolveSetupAsync(query.CollectionAlias);
if (collection.DataViewBuilder != null || collection.DataViews?.Count > 0)
{
var dataViews = await GetDataViewsAsync(collection);
var dataView = dataViews.FirstOrDefault(x => x.Id == query.ActiveTab)
?? dataViews.FirstOrDefault();
if (dataView != null)
{
query.SetDataView(dataView);
}
}
}
public async Task<IEnumerable<IDataView>> GetDataViewsAsync(string collectionAlias)
{
var collection = await _collectionResolver.ResolveSetupAsync(collectionAlias);
return await GetDataViewsAsync(collection);
}
private Task<IEnumerable<IDataView>> GetDataViewsAsync(ICollectionSetup collection)
{
if (collection.DataViewBuilder == null)
{
return Task.FromResult(collection.DataViews ?? Enumerable.Empty<IDataView>());
}
else
{
var builder = _serviceProvider.GetService<IDataViewBuilder>(collection.DataViewBuilder);
return builder.GetDataViewsAsync();
}
}
}
}
<file_sep>using RapidCMS.Core.Enums;
namespace RapidCMS.Core.Abstractions.Setup
{
public interface IButton
{
DefaultButtonType DefaultButtonType { get; }
string Label { get; }
string Icon { get; }
IEntityVariantSetup? EntityVariant { get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using RapidCMS.Core.Abstractions.Config;
using RapidCMS.Core.Abstractions.Data;
using RapidCMS.Core.Abstractions.Resolvers;
using RapidCMS.Core.Extensions;
namespace RapidCMS.Core.Resolvers.Data
{
internal class ApiDataViewResolver : IDataViewResolver
{
private readonly IReadOnlyDictionary<string, Type> _dataViewTypes;
private readonly IServiceProvider _serviceProvider;
public ApiDataViewResolver(
IApiConfig apiConfig,
IServiceProvider serviceProvider)
{
_dataViewTypes = apiConfig.DataViews.ToDictionary(dataView => dataView.Alias, dataView => dataView.DataViewBuilder);
_serviceProvider = serviceProvider;
}
public async Task ApplyDataViewToQueryAsync(IQuery query)
{
if (string.IsNullOrEmpty(query.CollectionAlias))
{
throw new ArgumentNullException($"{nameof(query)}.{nameof(query.CollectionAlias)}");
}
var dataViews = await GetDataViewsAsync(query.CollectionAlias);
var dataView = dataViews.FirstOrDefault(x => x.Id == query.ActiveTab)
?? dataViews.FirstOrDefault();
if (dataView != null)
{
query.SetDataView(dataView);
}
}
public Task<IEnumerable<IDataView>> GetDataViewsAsync(string collectionAlias)
{
if (!_dataViewTypes.TryGetValue(collectionAlias, out var dataView))
{
return Task.FromResult(Enumerable.Empty<IDataView>());
}
var builder = _serviceProvider.GetService<IDataViewBuilder>(dataView);
return builder.GetDataViewsAsync();
}
}
}
|
99918d799f0f7b916f65ada195a4880f93ba2634
|
[
"C#"
] | 3
|
C#
|
Eurobric/RapidCMS
|
95f406d7e1e0d9015917947307b1be14a030982c
|
ff498513994181c23b69be8a5f216293e1e6cec2
|
refs/heads/master
|
<repo_name>shedbuilt/libdrm<file_sep>/build.sh
#!/bin/bash
mkdir build &&
cd build &&
meson --prefix=/usr \
-Dudev=true &&
NINJAJOBS=$SHED_NUM_JOBS ninja &&
DESTDIR="$SHED_FAKE_ROOT" ninja install
|
47bfc5a3e5f5736a482b8d663c9fa7d2291c567c
|
[
"Shell"
] | 1
|
Shell
|
shedbuilt/libdrm
|
c1936da2d46850f94666017d113a3aa93b1b2585
|
fe55ccaf1fa3efa56edb72b5aeb2a0a4449bb0f8
|
refs/heads/master
|
<file_sep>package onceler.internal;
import java.lang.invoke.*;
public class Factory {
private Factory() {}
public static CallSite bootstrap(
MethodHandles.Lookup lookup
, String invokedName
, MethodType invokedType
, MethodHandle factory
) throws Throwable {
return new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), factory.invoke()));
}
}
|
4509d3ee81b096f9f6b1adff0c678db6d3cbd033
|
[
"Java"
] | 1
|
Java
|
hrhino/onceler
|
407c209f24489d42e17302eedbd0e9b1f0887a5b
|
776da68525adf2f760f55a5ac894bacc4cf87dd0
|
refs/heads/master
|
<file_sep>Rails.application.routes.draw do
root 'buildings#index'
resources :buildings
resources :apartments
end
<file_sep>class Apartment < ApplicationRecord
belongs_to :building
validate :numeros_sin_duplicar
validates :numero, presence:true
validates :building_id, presence:true
private
def numeros_sin_duplicar
encontrados = self.building.apartments.select {|depto|
depto.numero == self.numero
}
if encontrados.count != 0
self.errors.add(:error_duplicado, "El departamento ingresado ya existe")
end
end
end
<file_sep>class Building < ApplicationRecord
has_many :apartments
before_validation(:cambiar_a_mayusculas)
validates :nombre, presence:true
validates :direccion, uniqueness:true
validates :direccion, presence:true
validates :ciudad, presence:
private
def cambiar_a_mayusculas
puts self.nombre = self.nombre.upcase
puts self.direccion = self.direccion.upcase
puts self.ciudad = self.ciudad.upcase
end
end
<file_sep>module BuildingsHelper
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Building.create([
{
nombre: 'Gran Torre Santiago',
direccion: 'Av. Andrés Bello 2425, Sector Nueva Tobalaba, Providencia',
ciudad: 'Santiago',
},
{
nombre: 'Titanium La Portada',
direccion: 'Av. Del Condor 844, Las Condes',
ciudad: 'Santiago',
},
{
nombre: 'Hotel Marriott Santiago de Chile',
direccion: 'Avenida Kennedy 5741, Las Condes',
ciudad: 'Santiago',
},
{
nombre: 'Territoria 3000',
direccion: 'Isidora Goyenechea 3000, Las Condes',
ciudad: 'Santiago',
},
{
nombre: '<NAME>',
direccion: 'Alvarez 58',
ciudad: 'Viña del Mar',
},
{
nombre: '<NAME> ',
direccion: 'Las Torpederas 40',
ciudad: 'Valparaíso',
}
])
|
0f5ac3e6d3f0c617fbb3150d2e8c9c77a970486d
|
[
"Ruby"
] | 5
|
Ruby
|
carpenaloza/edificios
|
4cc8459075c35143d011a7163e90e434fbbc3d43
|
d39f8d1832b0a143ad87311e447920449ccb870f
|
refs/heads/main
|
<file_sep>import { Server } from "socket.io";
// Because NextJS doesn't officially support websockets, need to deploy using heroku
// This solution is by rogeriojlle on StackOverflow:
// https://stackoverflow.com/questions/57512366/how-to-use-socket-io-with-next-js-api-routes/62547135#62547135
const ioHandler = (req, res) => {
if (!res.socket.server.io) {
console.log("first use, starting socket.io");
//create a websocket server
const io = new Server(res.socket.server);
// when a message is submitted, broadcast it
io.on("connection", (socket) => {
// echo msg to user
socket.on("message-submitted", (msg) => {
socket.emit("message", msg);
// broadcast to everyone else
socket.broadcast.emit("message", msg);
});
});
// make the socket available externally
res.socket.server.io = io;
} else {
// if already started sever, dont do anything
console.log("Server already started");
}
//send back an empty 200
res.end();
};
export default ioHandler;
|
a4ddf2e31106351dc9e87e885c9222a4a26d2e22
|
[
"JavaScript"
] | 1
|
JavaScript
|
elim04/chatapp
|
95b1edd75fc4d4ca7a4593b0f762ab0925eba45f
|
e6d3cd9c6a70f25b77058f7337ce852446e206b0
|
refs/heads/master
|
<repo_name>hs-webdev/starter-store<file_sep>/config/initializers/session_store.rb
# Be sure to restart your server when you modify this file.
StarterStore::Application.config.session_store :cookie_store, key: '_starter_store_session'
|
8e6eb1ebefc6d3a02daec4a0f13f0851b1172aa7
|
[
"Ruby"
] | 1
|
Ruby
|
hs-webdev/starter-store
|
9be9e8067a1ab09327341c8802105d2e67676b22
|
3821944dbca640d39623a88dfd899d81cdf72bc7
|
refs/heads/master
|
<file_sep>package com.jlapp.startdeeplink
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
val uri = Uri.parse("myapp://product?productId=123")
val myApp = Intent(Intent.ACTION_VIEW, uri)
startActivity(myApp)
}
}
}
<file_sep>include ':app'
rootProject.name='StartDeeplink'
|
189ec4ba5c96f396a64875b633977123a4dbe79b
|
[
"Kotlin",
"Gradle"
] | 2
|
Kotlin
|
jjaviles2010/StartDeeplink
|
0b4df36b26298ed2bdb862f572352695dc19b3f5
|
a6098592db9e0896708f4a216457b1667cf86ddc
|
refs/heads/master
|
<repo_name>Kahefsay/wip<file_sep>/api/routes/index.js
/* eslint new-cap: [0] */
let express = require('express');
let router = express.Router();
let jwt = require('express-jwt');
let auth = jwt({
secret: 'secret',
userProperty: 'payload',
});
let ctrlAccueil = require('../controllers/accueil');
let ctrlAuth = require('../controllers/authentication');
// profile
router.get('/accueil', auth, ctrlAccueil.accueil);
// authentication
router.post('/register', ctrlAuth.register);
router.post('/login', ctrlAuth.login);
module.exports = router;
<file_sep>/api/models/user.js
/* eslint new-cap: [0] */
let crypto = require('crypto');
let jwt = require('jsonwebtoken');
module.exports = function(sequelize, Sequelize) {
let userSchema = sequelize.define('User', {
id: {
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
firstname: {
type: Sequelize.STRING,
notEmpty: true,
},
lastname: {
type: Sequelize.STRING,
notEmpty: true,
},
username: {
type: Sequelize.TEXT,
notEmpty: true,
},
hash: {
type: Sequelize.STRING,
},
salt: {
type: Sequelize.STRING,
},
last_login: {
type: Sequelize.DATE,
},
status: {
type: Sequelize.ENUM('active', 'inactive'),
defaultValue: 'active',
},
});
userSchema.setPassword = function(password) {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512')
.toString('hex');
};
userSchema.validPassword = function(password) {
let hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512')
.toString('hex');
return this.hash === hash;
};
userSchema.generateJwt = function() {
let expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
return jwt.sign({
_id: this.id,
username: this.username,
name: this.lastname,
exp: parseInt(expiry.getTime() / 1000),
}, 'secret');
};
return userSchema;
};
|
bf71126bbda3cd8aa65df02e7a32e4c0000bdea6
|
[
"JavaScript"
] | 2
|
JavaScript
|
Kahefsay/wip
|
b5bb2d046c7d57bbc09d5ae6e5cd7aa3bb5550cf
|
ef8c5009a50e27d1be6f805940e0a5440c06ecae
|
refs/heads/master
|
<repo_name>ZeeshanAhmedoff1997/AwesomeImages<file_sep>/README.md
# AwesomeImages
An App that contains the Awesome Images
<file_sep>/src/components/Listitem/ListItem.js
/* eslint-disable space-infix-ops */
/* eslint-disable eol-last */
/* eslint-disable react/self-closing-comp */
/* eslint-disable import/newline-after-import */
/* eslint-disable no-unused-vars */
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
const ListItem = (props) => (
<TouchableOpacity onPress={props.onItemPressed}>
<View style={styles.ListItem} >
<Text style={styles.ListItemText}>{props.placeName}</Text>
</View>
</TouchableOpacity>
);
const styles=StyleSheet.create({
ListItem: {
margin: 5,
// padding: 10,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#eee',
width: '100%',
},
ListItemText: {
// borderWidth: 1,
// borderColor: 'black',
fontFamily: 'GreatVibes-Regular',
fontSize: 30,
}
});
export default ListItem;<file_sep>/index.js
/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
/* eslint-disable arrow-body-style */
/* eslint-disable space-infix-ops */
/* eslint-disable no-unused-labels */
/* eslint-disable import/newline-after-import */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-labels */
import React, { Component } from 'react';
// eslint-disable-next-line no-unused-vars
// eslint-disable-next-line import/newline-after-import
// eslint-disable-next-line no-unused-vars
import { View, AppRegistry, TextInput, StyleSheet, Button, Text } from 'react-native';
import ListItem from './src/components/Listitem/ListItem';
import PlacesList from './src/components/PlacesList/PlacesList';
export default class MyApp extends Component {
state = {
placeName: '',
places: [],
}
ChangePlaceName= val => {
this.setState({
placeName: val,
});
};
PlaceSubmitHandler= () => {
if (this.state.placeName === '') {
return;
}
this.setState(preState => {
return {
places: preState.places.concat({value:preState.placeName,
key:Math.random()}),
placeName: ''
};
});
// eslint-disable-next-line no-undef
//alert(this.state.placeName);
}
ItemDeletedHandler= key => {
this.setState(prevState=>{
return {
places: prevState.places.filter(place => {
return place.key !== key;
})
};
});
}
// eslint-disable-next-line padded-blocks
render() {
return (
<View style={styles.Container}>
<View style={styles.InputContainer}>
<TextInput
placeholder="Enter the place"
style={styles.inputPlace}
value={this.state.placeName}
onChangeText={this.ChangePlaceName}
/>
<Button
title="Add"
style={styles.inputButton}
onPress={this.PlaceSubmitHandler}
/>
</View>
<PlacesList places={this.state.places} OnItemDeleted={this.ItemDeletedHandler}/>
</View>
);
}
}
const styles = StyleSheet.create({
Container: {
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
textDecorationLine: 'underline',
},
InputContainer: {
width: '100%',
padding: 20,
//flex:1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
inputPlace: {
width: '70%',
fontSize: 20,
},
inputButton: {
width: '30%',
},
ListView: {
width: '100%',
marginLeft: 40,
marginRight: 40,
}
});
AppRegistry.registerComponent('AwesomePlaces2', () => MyApp);
<file_sep>/src/components/PlaceInput/PlaceInput.js
/* eslint-disable space-infix-ops */
/* eslint-disable eol-last */
/* eslint-disable react/self-closing-comp */
/* eslint-disable import/newline-after-import */
/* eslint-disable no-unused-vars */
import React from 'react';
import { View, StyleSheet, TextInput, Button } from 'react-native';
const PlaceInput = (props) => (
<View style={styles.InputContainer}>
<TextInput
placeholder="Enter the place"
style={styles.inputPlace}
value={this.state.placeName}
onChangeText={this.ChangePlaceName}
/>
<Button
title="Add"
style={styles.inputButton}
onPress={props.placeadded}
/>
</View>
);
const styles = StyleSheet.create({
Container: {
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
textDecorationLine: 'underline',
},
InputContainer: {
width: '100%',
padding: 20,
//flex:1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
inputPlace: {
width: '70%',
fontSize: 20,
},
inputButton: {
width: '30%',
},
ListView: {
width: '100%',
marginLeft: 40,
marginRight: 40,
}
});
export default PlaceInput;<file_sep>/android/settings.gradle
rootProject.name = 'AwesomePlaces2'
include ':app'
|
7beeb51b460c4100589ffc64a35a68f2c4869a40
|
[
"Markdown",
"JavaScript",
"Gradle"
] | 5
|
Markdown
|
ZeeshanAhmedoff1997/AwesomeImages
|
54fd68b1ff503e8fb29dc8de26fa8e35b8f5ed85
|
f4d9d3f9b9cc322babd61d1979092c0efade230d
|
refs/heads/master
|
<file_sep>package com.olecco.android.companyprofile.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class CompanyData {
@SerializedName("symbol")
@Expose
var symbol: String? = null
@SerializedName("divisionData")
@Expose
var divisions: Map<String, Division>? = null
@SerializedName("treeData")
@Expose
var treeData: TreeData? = null
}<file_sep>package com.olecco.android.companyprofile.api
import com.olecco.android.companyprofile.model.CompanyData
import com.olecco.android.companyprofile.model.CompanyList
import kotlinx.coroutines.experimental.Deferred
import retrofit2.http.GET
import retrofit2.http.Path
const val BASE_URL = "https://www.trefis.com/api/ameritrade/"
interface ApiClient {
@GET("price/list")
fun getCompanyList(): Deferred<CompanyList>
@GET("modeldata/{symbol}")
fun getCompanyData(@Path("symbol") symbol: String): Deferred<CompanyData>
}<file_sep>package com.olecco.android.companyprofile.ui
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import com.olecco.android.companyprofile.CompanyProfileApplication
import com.olecco.android.companyprofile.R
import com.olecco.android.companyprofile.api.ApiResponse
import com.olecco.android.companyprofile.api.ApiResponseState
import com.olecco.android.companyprofile.api.ProfilesRepository
import com.olecco.android.companyprofile.model.Company
import com.olecco.android.companyprofile.model.CompanyList
import com.olecco.android.companyprofile.model.DivisionData
import com.olecco.android.companyprofile.ui.piechart.PieChartAdapter
import com.olecco.android.companyprofile.ui.piechart.PieChartClickListener
import com.olecco.android.companyprofile.ui.piechart.PieChartLegendAdaper
import com.olecco.android.companyprofile.ui.piechart.PieChartView
import com.olecco.android.companyprofile.ui.viewmodel.ProfilesViewModel
import com.olecco.android.companyprofile.ui.viewmodel.ProfilesViewModelFactory
class MainActivity : AppCompatActivity() {
val profileApplication: CompanyProfileApplication
get() = application as CompanyProfileApplication
val profilesRepository: ProfilesRepository
get() = profileApplication.profilesRepository
private lateinit var profilesViewModel: ProfilesViewModel
private lateinit var companyListAdapter: CompanyListAdapter
private lateinit var legendAdapter: PieChartLegendAdaper
private lateinit var companySpinnerView: Spinner
private lateinit var pieChartView: PieChartView
private lateinit var progressView: View
private lateinit var legendView: RecyclerView
private lateinit var pieChartAdapter: DivisionListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bindViews()
pieChartAdapter = DivisionListAdapter(resources.getIntArray(R.array.profile_colors))
profilesViewModel = ViewModelProviders.of(this,
ProfilesViewModelFactory(profilesRepository)).get(ProfilesViewModel::class.java)
profilesViewModel.companyList.observe(this, Observer {
handleCompanyListResponse(it)
})
profilesViewModel.divisionsData.observe(this, Observer {
handleDivisionListResponse(it)
})
}
private fun bindViews() {
companyListAdapter = CompanyListAdapter(this)
companyListAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
companySpinnerView = findViewById(R.id.company_list)
companySpinnerView.adapter = companyListAdapter
companySpinnerView.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) { }
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) {
val company = companyListAdapter.getCompany(position)
profilesViewModel.selectCompany(company.ticker ?: "")
}
}
pieChartView = findViewById(R.id.pie_chart)
progressView = findViewById(R.id.progress)
pieChartView.pieChartClickListener = object : PieChartClickListener {
override fun onSegmentClick(segmentIndex: Int) {
Log.d("111", "index=" + segmentIndex)
}
}
legendAdapter = PieChartLegendAdaper()
legendView = findViewById(R.id.legend)
legendView.layoutManager = LinearLayoutManager(this)
legendView.adapter = legendAdapter
}
private fun handleCompanyListResponse(companyListResponse: ApiResponse<CompanyList>?) {
when(companyListResponse?.state) {
ApiResponseState.LOADING -> {
companySpinnerView.hide()
//pieChartView.hide()
progressView.show()
}
ApiResponseState.SUCCESS -> {
val companies = companyListResponse.data?.companies
if (companies != null) {
companyListAdapter.data = companies
}
companySpinnerView.show()
progressView.hide()
}
ApiResponseState.ERROR -> {
// todo show error
}
else -> {
// do nothing
}
}
}
private fun handleDivisionListResponse(divisionListResponse: ApiResponse<List<DivisionData>>?) {
when(divisionListResponse?.state) {
ApiResponseState.LOADING -> {
pieChartView.cleanPie()
legendView.hide()
progressView.show()
}
ApiResponseState.SUCCESS -> {
pieChartAdapter.chartNameString = profilesViewModel.selectedCompany
pieChartAdapter.divisions = divisionListResponse.data ?: listOf()
pieChartView.adapter = pieChartAdapter
legendAdapter.pieChartAdapter = pieChartAdapter
pieChartView.fillPie()
legendView.show()
progressView.hide()
}
ApiResponseState.ERROR -> {
// todo show error
}
else -> {
// do nothing
}
}
}
private class CompanyListAdapter(context: Context): ArrayAdapter<String>(context,
R.layout.company_list_spinner_item) {
var data: List<Company> = ArrayList()
set(value) {
field = value
notifyDataSetChanged()
}
override fun getItem(position: Int): String {
return data[position].name?:""
}
override fun getCount(): Int {
return data.size
}
fun getCompany(position: Int): Company {
return data[position]
}
}
private class DivisionListAdapter(val colors: IntArray) : PieChartAdapter {
var divisions: List<DivisionData> = listOf()
var chartNameString: String = ""
override fun getChartName(): String {
return chartNameString
}
override fun getSegmentCount(): Int {
return divisions.size
}
override fun getSegmentValue(index: Int): Double {
return divisions[index].value ?: 0.0
}
override fun getSegmentColor(index: Int): Int {
if (index in 0 until colors.size) {
return colors[index]
}
return Color.BLACK
}
override fun getSegmentName(index: Int): String {
return divisions[index].name ?: ""
}
}
}
<file_sep>package com.olecco.android.companyprofile.ui.viewmodel
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Transformations
import android.arch.lifecycle.ViewModel
import com.olecco.android.companyprofile.api.ApiResponse
import com.olecco.android.companyprofile.api.ProfilesRepository
import com.olecco.android.companyprofile.model.CompanyData
import com.olecco.android.companyprofile.model.CompanyList
import com.olecco.android.companyprofile.model.DivisionData
class ProfilesViewModel(private val repository: ProfilesRepository) : ViewModel() {
private var _companyList: LiveData<ApiResponse<CompanyList>>? = null
val companyList: LiveData<ApiResponse<CompanyList>>
get() {
if (_companyList == null) {
_companyList = repository.getCompanyList()
}
return _companyList ?: MutableLiveData()
}
private val selectedCompanyData: MutableLiveData<String> = MutableLiveData()
val selectedCompany: String
get() = selectedCompanyData.value ?: ""
val divisionsData: LiveData<ApiResponse<List<DivisionData>>> =
Transformations.switchMap(selectedCompanyData) {
Transformations.map(repository.getCompanyData(it)) {
getDivisionDataList(it)
}
}
fun selectCompany(companySymbol: String) {
selectedCompanyData.value = companySymbol
}
private fun getDivisionDataList(companyDataResponse: ApiResponse<CompanyData>): ApiResponse<List<DivisionData>> {
val divisionDataResponse: ApiResponse<List<DivisionData>> = ApiResponse()
divisionDataResponse.state = companyDataResponse.state
divisionDataResponse.errorMessage = companyDataResponse.errorMessage
val companyData: CompanyData? = companyDataResponse.data
divisionDataResponse.data =
companyData?.treeData?.companyRoot?.divisionDataList ?: listOf()
return divisionDataResponse
}
}<file_sep>package com.olecco.android.companyprofile
import android.app.Application
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.experimental.CoroutineCallAdapterFactory
import com.olecco.android.companyprofile.api.ApiClient
import com.olecco.android.companyprofile.api.BASE_URL
import com.olecco.android.companyprofile.api.ProfilesRepository
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class CompanyProfileApplication : Application() {
lateinit var profilesRepository: ProfilesRepository
override fun onCreate() {
super.onCreate()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
profilesRepository = ProfilesRepository(retrofit.create(ApiClient::class.java))
}
}<file_sep>package com.olecco.android.companyprofile.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class DivisionData {
@SerializedName("text")
@Expose
var name: String? = null
@SerializedName("identifier")
@Expose
var identifier: String? = null
@SerializedName("value")
@Expose
var value: Double? = null
@SerializedName("percent")
@Expose
var percent: Double? = null
}
<file_sep>package com.olecco.android.companyprofile.ui.viewmodel
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import com.olecco.android.companyprofile.api.ProfilesRepository
@Suppress("UNCHECKED_CAST")
class ProfilesViewModelFactory(private val profilesRepository: ProfilesRepository):
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return ProfilesViewModel(profilesRepository) as T
}
}<file_sep>package com.olecco.android.companyprofile.ui
import android.content.res.Resources
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.TypedValue
import android.view.View
fun Int.toPx(resources: Resources): Float {
val displaymetrics = resources.displayMetrics
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), displaymetrics)
}
fun Canvas.drawTextCentered(text: String, centerX: Float, centerY: Float, textPaint: Paint) {
val textRect: Rect = Rect()
textPaint.getTextBounds(text, 0, text.length, textRect)
this.drawText(text, centerX - textRect.width() / 2,centerY + textRect.height() / 2, textPaint)
}
fun Paint.getTextHeight(text: String): Int {
val textRect: Rect = Rect()
this.getTextBounds(text, 0, text.length, textRect)
return textRect.height()
}
fun View.show() {
this.visibility = View.VISIBLE
}
fun View.hide() {
this.visibility = View.INVISIBLE
}<file_sep>package com.olecco.android.companyprofile.ui.piechart
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.support.v4.view.GestureDetectorCompat
import android.support.v4.view.animation.FastOutSlowInInterpolator
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import com.olecco.android.companyprofile.ui.drawTextCentered
import com.olecco.android.companyprofile.ui.toPx
import java.lang.Math.PI
private const val TRANS_LINE_WIDTH_DP = 4
private const val OVERLAY_RADIUS_PART = 0.55f
private const val INNER_RADIUS_PART = 0.5f
private const val TEXT_RADIUS_PART = 0.75f
private const val NAME_TEXT_SIZE = 24
private const val SEGMENT_TEXT_SIZE = 16
interface PieChartAdapter {
fun getChartName(): String
fun getSegmentCount(): Int
fun getSegmentValue(index: Int): Double
fun getSegmentColor(index: Int): Int
fun getSegmentName(index: Int): String
}
interface PieChartClickListener {
fun onSegmentClick(segmentIndex: Int)
}
class PieChartView : View {
var adapter: PieChartAdapter? = null
set(value) {
field = value
valueSum = if (value == null) 0.0 else calculateValueSum()
invalidate()
}
private var newAdapter: PieChartAdapter? = null
var pieChartClickListener: PieChartClickListener? = null
private var valueSum: Double = 0.0
private var radius: Float = 0.0f
private var minInnerRadius: Float = 0.0f
private var cleanEndAnglePart: Float = 0.0f
private var cleaned: Boolean = false
private var animationInProgress: Boolean = false
private var needStartAnimation: Boolean = false
private val segmentPaint: Paint = Paint()
private val overlayPaint: Paint = Paint()
private val transparentLinePaint: Paint = Paint()
private val transparentFillPaint: Paint
private val nameTextPaint: Paint = Paint()
private val segmentTextPaint: Paint
private val segmentCleanPaint: Paint
private val segmentPath: Path = Path()
private val segmentOverlayPath: Path = Path()
private val segmentRect: RectF = RectF()
private val segmentOverlayRect: RectF = RectF()
private val segmentRegions: MutableList<Region> = mutableListOf()
private val pathRotationMatrix: Matrix = Matrix()
private val pathRotationRegion: Region = Region()
private val gestureDetector: GestureDetectorCompat
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
with(segmentPaint) {
style = Paint.Style.FILL
isAntiAlias = true
}
segmentCleanPaint = Paint(segmentPaint)
segmentCleanPaint.color = Color.parseColor("#FF7B7B7B")
with(overlayPaint) {
color = Color.parseColor("#40000000")
style = Paint.Style.FILL
isAntiAlias = true
}
with(transparentLinePaint) {
color = Color.TRANSPARENT
style = Paint.Style.STROKE
isAntiAlias = true
strokeWidth = TRANS_LINE_WIDTH_DP.toPx(resources)
xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
}
transparentFillPaint = Paint(transparentLinePaint)
transparentFillPaint.style = Paint.Style.FILL
with(nameTextPaint) {
color = Color.parseColor("#E0FFFFFF") // todo set in attrs
textSize = NAME_TEXT_SIZE.toPx(resources)
isAntiAlias = true
}
segmentTextPaint = Paint(nameTextPaint)
segmentTextPaint.textSize = SEGMENT_TEXT_SIZE.toPx(resources)
setLayerType(LAYER_TYPE_SOFTWARE, null)
gestureDetector = GestureDetectorCompat(getContext(), object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
return true
}
override fun onSingleTapUp(e: MotionEvent): Boolean {
val segmentIndex = getClickedRegionIndex(e.x.toInt(), e.y.toInt())
if (segmentIndex != -1) {
notifySegmentClick(segmentIndex)
return true
}
return false
}
})
}
override fun onDraw(canvas: Canvas) {
val itemsAdapter = adapter
if (itemsAdapter != null) {
val overlayRadius = radius * OVERLAY_RADIUS_PART
val centerX: Float = (paddingStart + (measuredWidth - paddingStart - paddingEnd) / 2.0f)
val centerY: Float = (paddingTop + radius)
segmentRect.set(centerX - radius, centerY - radius, centerX + radius, centerY + radius)
segmentOverlayRect.set(centerX - overlayRadius, centerY - overlayRadius,
centerX + overlayRadius, centerY + overlayRadius)
val itemCount: Int = itemsAdapter.getSegmentCount()
segmentRect.set(centerX - radius, centerY - radius, centerX + radius, centerY + radius)
var regionRotationAngle = 0.0f
for (i in 0 until itemCount) {
val itemValuePart = calculateValuePart(i)
segmentPaint.color = itemsAdapter.getSegmentColor(i)
segmentPath.reset()
segmentPath.moveTo(centerX, centerY)
segmentPath.lineTo(centerX, (centerY - radius))
segmentPath.arcTo(segmentRect, 270.0f, 360 * itemValuePart)
segmentPath.close()
segmentOverlayPath.reset()
segmentOverlayPath.moveTo(centerX, centerY)
segmentOverlayPath.lineTo(centerX, (centerY - overlayRadius))
segmentOverlayPath.arcTo(segmentOverlayRect, 270.0f, 360 * itemValuePart)
segmentOverlayPath.close()
pathRotationMatrix.reset()
pathRotationMatrix.postRotate(regionRotationAngle, centerX, centerY)
segmentPath.transform(pathRotationMatrix)
segmentOverlayPath.transform(pathRotationMatrix)
regionRotationAngle += 360 * itemValuePart
pathRotationRegion.set(segmentRect.left.toInt(),
segmentRect.top.toInt(), segmentRect.right.toInt(), segmentRect.bottom.toInt())
segmentRegions[i].setPath(segmentPath, pathRotationRegion)
canvas.drawPath(segmentPath, segmentPaint)
canvas.drawPath(segmentOverlayPath, overlayPaint)
canvas.drawPath(segmentPath, transparentLinePaint)
}
drawSegmentLabels(canvas, radius, centerX, centerY)
// clean
if (cleaned) {
segmentPath.reset()
segmentPath.moveTo(centerX, centerY)
segmentPath.lineTo(centerX, (centerY - radius))
segmentPath.arcTo(segmentRect, 270.0f, cleanEndAnglePart * 360)
segmentPath.close()
segmentOverlayPath.reset()
segmentOverlayPath.moveTo(centerX, centerY)
segmentOverlayPath.lineTo(centerX, (centerY - overlayRadius))
segmentOverlayPath.arcTo(segmentOverlayRect, 270.0f, cleanEndAnglePart * 360)
segmentOverlayPath.close()
canvas.drawPath(segmentPath, segmentCleanPaint)
canvas.drawPath(segmentOverlayPath, overlayPaint)
canvas.drawPath(segmentPath, transparentLinePaint)
}
canvas.drawCircle(centerX, centerY, minInnerRadius, transparentFillPaint)
canvas.drawTextCentered(itemsAdapter.getChartName(), centerX, centerY, nameTextPaint)
}
}
private fun drawSegmentLabels(canvas: Canvas, radius: Float, centerX: Float, centerY: Float) {
val itemsAdapter = adapter
if (itemsAdapter != null) {
val itemCount: Int = itemsAdapter.getSegmentCount()
var regionRotationAngle = 0.0f
var textAngle: Float
for (i in 0 until itemCount) {
val itemValuePart = calculateValuePart(i)
textAngle = regionRotationAngle + 360 * itemValuePart / 2
regionRotationAngle += 360 * itemValuePart
val gap = TEXT_RADIUS_PART * radius
val textAngleRad = Math.toRadians(textAngle.toDouble())
val dx: Float = (gap * Math.sin(textAngleRad)).toFloat()
val dy: Float = (gap * Math.cos(textAngleRad + PI)).toFloat()
canvas.drawTextCentered("${Math.round(itemValuePart * 1000.0f) / 10.0f}%",
centerX + dx, centerY + dy, segmentTextPaint)
}
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
val radiusX = (measuredWidth - paddingStart - paddingEnd) / 2
val radiusY = (measuredHeight - paddingTop - paddingBottom) / 2
radius = Math.min(radiusX, radiusY).toFloat()
minInnerRadius = INNER_RADIUS_PART * radius
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
if (gestureDetector.onTouchEvent(event)) {
return true
}
return super.onTouchEvent(event)
}
private fun getClickedRegionIndex(x: Int, y: Int): Int {
for (i in 0 until segmentRegions.size) {
if (segmentRegions[i].contains(x, y)) {
return i
}
}
return -1
}
private fun calculateValuePart(index: Int) : Float {
val itemAdapter = adapter
if (itemAdapter != null) {
val itemValue = itemAdapter.getSegmentValue(index)
return (itemValue / valueSum).toFloat()
}
return 0.0f
}
private fun calculateValueSum(): Double {
segmentRegions.clear()
val itemsAdapter = adapter
if (itemsAdapter != null) {
val itemCount: Int = itemsAdapter.getSegmentCount()
var sum = 0.0
for (i in 0 until itemCount) {
sum += itemsAdapter.getSegmentValue(i)
segmentRegions.add(Region())
}
return sum
}
return 0.0
}
private fun notifySegmentClick(segmentIndex: Int) {
pieChartClickListener?.onSegmentClick(segmentIndex)
}
fun cleanPie() {
cleaned = true
if (!animationInProgress) {
animationInProgress = true
val animator: ValueAnimator = ValueAnimator.ofFloat(0.0f, 0.999f)
animator.duration = 600
animator.interpolator = FastOutSlowInInterpolator()
animator.addUpdateListener {
cleanEndAnglePart = it.animatedValue as Float
invalidate()
}
animator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
animationInProgress = false
if (needStartAnimation) {
needStartAnimation = false
fillPie()
}
}
})
animator.start()
} else {
needStartAnimation = true
}
}
fun fillPie() {
cleaned = true
if (!animationInProgress) {
animationInProgress = true
cleanEndAnglePart = 0.999f
val animator: ValueAnimator = ValueAnimator.ofFloat(-0.999f, 0.0f)
animator.duration = 600
animator.interpolator = FastOutSlowInInterpolator()
animator.addUpdateListener {
cleanEndAnglePart = it.animatedValue as Float
invalidate()
}
animator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
animationInProgress = false
cleaned = false
invalidate()
if (needStartAnimation) {
needStartAnimation = false
cleanPie()
}
}
})
animator.start()
} else {
needStartAnimation = true
}
}
}<file_sep>package com.olecco.android.companyprofile.api
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import com.olecco.android.companyprofile.model.Company
import com.olecco.android.companyprofile.model.CompanyData
import com.olecco.android.companyprofile.model.CompanyList
import kotlinx.coroutines.experimental.launch
class ProfilesRepository(private val apiClient: ApiClient) {
fun getCompanyList(): LiveData<ApiResponse<CompanyList>> {
val result = MutableLiveData<ApiResponse<CompanyList>>()
val apiResponse: ApiResponse<CompanyList> = ApiResponse()
apiResponse.state = ApiResponseState.LOADING
result.postValue(apiResponse)
launch {
try {
val request = apiClient.getCompanyList()
val data = request.await()
data.companies = data.companies?.sortedBy {it.name}
apiResponse.data = data
apiResponse.state = ApiResponseState.SUCCESS
}
catch (e: Exception) {
handleError(apiResponse, e)
}
result.postValue(apiResponse)
}
return result
}
fun getCompanyData(symbol: String): LiveData<ApiResponse<CompanyData>> {
val result = MutableLiveData<ApiResponse<CompanyData>>()
val apiResponse: ApiResponse<CompanyData> = ApiResponse()
apiResponse.state = ApiResponseState.LOADING
result.postValue(apiResponse)
launch {
try {
val request = apiClient.getCompanyData(symbol)
apiResponse.data = request.await()
apiResponse.state = ApiResponseState.SUCCESS
}
catch (e: Exception) {
handleError(apiResponse, e)
}
result.postValue(apiResponse)
}
return result
}
private fun handleError(apiResponse: ApiResponse<out Any>, e: Exception) {
apiResponse.state = ApiResponseState.ERROR
apiResponse.errorMessage = e.message ?: ""
}
}<file_sep>package com.olecco.android.companyprofile.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class CompanyList {
@SerializedName("companies")
@Expose
var companies: List<Company>? = null
}<file_sep>package com.olecco.android.companyprofile.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class TreeData {
@SerializedName("root")
@Expose
var companyRoot: CompanyRoot? = null
}
class CompanyRoot {
@SerializedName("text")
@Expose
var text: String? = null
@SerializedName("value")
@Expose
var value: Double? = null
@SerializedName("child")
@Expose
var divisionDataList: List<DivisionData>? = null
}<file_sep>package com.olecco.android.companyprofile.ui.piechart
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.olecco.android.companyprofile.R
class PieChartLegendAdaper : RecyclerView.Adapter<PieChartLegendAdaper.ItemViewHolder>() {
var pieChartAdapter: PieChartAdapter? = null
set(value) {
field = value
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, p1: Int): ItemViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(
R.layout.pie_chart_legend_item, parent, false)
return ItemViewHolder(itemView)
}
override fun getItemCount(): Int {
return pieChartAdapter?.getSegmentCount() ?: 0
}
override fun onBindViewHolder(viewHolder: ItemViewHolder, position: Int) {
viewHolder.nameView.text = pieChartAdapter?.getSegmentName(position) ?: ""
viewHolder.setColor(pieChartAdapter?.getSegmentColor(position) ?: Color.BLACK)
}
class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val nameView: TextView
val colorView: ImageView
init {
nameView = itemView.findViewById(R.id.text)
colorView = itemView.findViewById(R.id.color)
}
fun setColor(color: Int) {
colorView.setColorFilter(color)
}
}
}<file_sep>package com.olecco.android.companyprofile.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class Company {
@SerializedName("name")
@Expose
var name: String? = null
@SerializedName("ticker")
@Expose
var ticker: String? = null
@SerializedName("private")
@Expose
var private: Boolean? = null
@SerializedName("marketPrice")
@Expose
var marketPrice: String? = null
@SerializedName("updated")
@Expose
var updated: String? = null
@SerializedName("price")
@Expose
var price: String? = null
}
<file_sep>package com.olecco.android.companyprofile.api
enum class ApiResponseState { NONE, LOADING, SUCCESS, ERROR }
class ApiResponse<T> {
var data: T? = null
var state: ApiResponseState = ApiResponseState.NONE
var errorMessage: String = ""
}
|
032748947f8cd74913b8dc225c7232e9de146c36
|
[
"Kotlin"
] | 15
|
Kotlin
|
olecco/CompanyProfile
|
118936cff8c9de3c96780db17560e99bd9cfa320
|
5b558decd10144f4ee1e501b7e547796d10fe746
|
refs/heads/master
|
<repo_name>rfrancotechnologies/egrafana<file_sep>/README.md
# Grafana exporter
This is an small program that allows you to export Grafana dashboards and datasources and import them to other grafana or just store them as backup.
## Usage
You will require an API token. You can get it on Grafana UI, under `Configuration/API keys`.
With that token, you can list your data:
```
./egrafana.py http://localhost:3000/ list -b <TOKEN>
```
Export your data to the "data" directory:
```
./egrafana.py http://localhost:3000/ export -b <TOKEN>
```
And import it back:
```
./egrafana.py http://localhost:3000/ import -b <TOKEN>
```
## Known issues
- Folders are not generated and Dashboards are moved to main folder.
- Datasources passwords are lost. They must be inserted by hand after importing them or editing the json files.
- Overwriting dashboards or datasources doesn't work yet.
<file_sep>/egrafana.py
#!/usr/bin/env python
import os
import json
import argparse
import logging
import requests
logger = logging.getLogger(__name__)
def configure_logging(verbosity):
msg_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
VERBOSITIES = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
level = VERBOSITIES[min(int(verbosity), len(VERBOSITIES) - 1)]
formatter = logging.Formatter(msg_format)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(level)
def parse_args():
parser = argparse.ArgumentParser(description="Importer/Exporter for Grafana data")
parser.add_argument(
"server", help="Server url"
)
parser.add_argument(
"action", nargs='?', choices=('list', 'export', 'import'), default='list', help="Action to be performed"
)
parser.add_argument(
"-b", "--bearer", help="Bearer header"
)
parser.add_argument(
"-p", "--path", default="data", help="Path to import/export"
)
parser.add_argument(
"--override", default=False, action="store_true", help="Override if already exists (only for import)"
)
parser.add_argument(
"-v", "--verbose", action="count", default=0, help="Increase verbosity"
)
return parser.parse_args()
class Grafana:
def __init__(self, url, bearer):
self.url = url
self.bearer = bearer
self.session = requests.Session()
def _get(self, path):
headers = {}
if self.bearer:
headers["Authorization"] = f"Bearer {self.bearer}"
r = self.session.get(f"{self.url}{path}", headers=headers)
r.raise_for_status()
return r
def _post(self, path, content, override):
headers = {
'Content-Type': 'application/json',
'Accept': "application/json",
}
if self.bearer:
headers["Authorization"] = f"Bearer {self.bearer}"
r = self.session.post(f"{self.url}{path}", headers=headers, json=content)
if override and r.status_code == override:
#logger.debug("Already exists, but will be overriden")
#r = self._put(path, content)
logger.warning("Overriding is not implemented yet")
return
print(r.content)
r.raise_for_status()
return r
def _put(self, path, content):
headers = {
'Content-Type': 'application/json',
'Accept': "application/json",
}
if self.bearer:
headers["Authorization"] = f"Bearer {self.bearer}"
r = self.session.post(f"{self.url}{path}", headers=headers, json=content)
print(r.content)
r.raise_for_status()
return r
def _dashboard_list(self):
r = self._get("/api/search?query=&")
return r.json()
def _datasources_list(self):
r = self._get("/api/datasources")
return r.json()
def _alert_list(self):
r = self._get("/api/alert-notifications")
return r.json()
def list(self):
for item in self._dashboard_list():
print(f"dashboard: {item['type']} - {item['title']}")
for item in self._datasources_list():
print(f"datasource: {item['type']} - {item['name']}")
for item in self._alert_list():
print(f"alert: {item['type']} - {item['name']}")
def _create_directories(self, base):
for d in ("dashboards", "datasources"):
directory = os.path.join(base, d)
if (os.path.exists(directory)):
logger.info(f"Reusing directory {directory}")
else:
os.makedirs(directory)
logger.info(f"Created directory {directory}")
def _save(self, filename, data):
logger.debug(f"Saving {filename}")
with open(filename, 'w+') as fd:
json.dump(data, fd, indent=2)
def export(self, directory):
self._create_directories(directory)
for item in self._dashboard_list():
data = self._get(f"/api/dashboards/{item['uri']}")
filename = os.path.join(directory, "dashboards", f"{item['uri'].replace('/', '_')}.json")
self._save(filename, data.json())
for item in self._datasources_list():
filename = os.path.join(directory, "datasources", f"{item['name'].replace('/', '_')}.json")
data = dict(
meta=dict(
type="datasource"
),
datasource=item
)
self._save(filename, data)
def insert_file(self, path, override):
logger.info(f"Processing file {path}")
with open(path) as fd:
data = json.load(fd)
try:
meta = data['meta']
logger.info(f'file {path} has a type {meta["type"]}')
if meta['type'] == 'datasource':
return
self._post('/api/datasources', data['datasource'], 409 if override else None)
elif meta['type'] == 'db':
data['dashboard']['id'] = None
data['dashboard']['uid'] = None
del data['meta']
self._post('/api/dashboards/db', data, 412 if override else None)
else:
raise Exception(f"Unsupported type: {meta['type']}")
except Exception as e:
logger.error(f'file {path} could not be imported: {e}')
def insert(self, directory, override):
for root, dirs, files in os.walk(directory):
for f in files:
if not f.endswith('.json'):
continue
fullpath = os.path.join(root, f)
self.insert_file(fullpath, override)
def main():
args = parse_args()
configure_logging(args.verbose)
grafana = Grafana(args.server, args.bearer)
actions = {
'list': {'f': grafana.list},
'export': {'f': grafana.export, 'kwargs': {'directory': args.path}},
'import': {'f': grafana.insert, 'kwargs': {'directory': args.path, 'override': args.override}},
}
action = actions[args.action]
logger.debug(f"Running action {args.action}")
action['f'](**action.get('kwargs', {}))
if __name__ == "__main__":
main()
|
0d1aa63eacfac1664f7c5999e87310fabfa32b00
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
rfrancotechnologies/egrafana
|
dba6c0a7aeb236bd86dd766b3f2bbe37b6c9bea6
|
c0b430831e194bf6ce82ffd1c1c15b9ed04bbc09
|
refs/heads/master
|
<file_sep>require './rlox/error'
Token = Struct.new(:type, :lexeme, :literal, :line)
KEYWORDS = [
"and",
"class",
"else",
"false",
"for",
"fn",
"if",
"nil",
"or",
"return",
"super",
"self",
"true",
"let",
"while",
]
class Scanner
def initialize()
@start = 0
@current = 0
@line = 1
end
def is_at_end()
@current >= @source.length
end
def advance()
@current += 1
@source[@current-1]
end
def add_token(type, literal=nil)
Token.new(type, @source[@start, @current-@start], literal, @line)
end
def match(expected)
if is_at_end or @source[@current] != expected
return false
end
@current += 1
true
end
def peek()
if is_at_end
"\0"
else
@source[@current]
end
end
def peek_next()
if @current + 1 >= @source.length
"\0"
else
@source[@current+1]
end
end
def string()
while peek != '"' and not is_at_end
if peek == "\n"
@line += 1
end
advance
end
if is_at_end
raise ParseError.new(@line, "Unterminated string.")
end
advance
val = @source[@start+1, (@current-1)-(@start+1)]
add_token(:string, val)
end
def is_digit(c)
c >= '0' and c <= '9'
end
def number()
while is_digit(peek)
advance
end
if peek == '.' and is_digit(peek_next)
advance
while is_digit(peek)
advance
end
end
add_token(:number, Float(@source[@start, @current-@start]))
end
def is_alpha(c)
(c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or c == '_'
end
def is_alnum(c)
is_alpha(c) or is_digit(c)
end
def identifier()
while is_alnum peek
advance
end
text = @source[@start, @current-@start]
type = :id
if KEYWORDS.include?(text)
type = text.to_sym
end
add_token(type)
end
def token()
c = advance
case c
when '(' then add_token(:left_paren)
when ')' then add_token(:right_paren)
when '{' then add_token(:left_brace)
when '}' then add_token(:right_brace)
when ',' then add_token(:comma)
when '.' then add_token(:dot)
when '-' then add_token(:minus)
when '+' then add_token(:plus)
when ';' then add_token(:semicolon)
when '*' then add_token(:star)
when '!' then add_token(match('=') ? :bang_eq : :bang)
when '=' then add_token(match('=') ? :eq_eq : :eq)
when '<' then add_token(match('=') ? :leq : :lt)
when '>' then add_token(match('=') ? :geq : :gt)
when '/' then
if match('/')
while peek != "\n" and not is_at_end
advance
end
elsif match('*')
while peek != '*' and peek_next != '/' and not is_at_end
advance
end
if is_at_end
raise ParseError.new(@line, "Unterminated block comment.")
end
advance
advance
advance
nil
else
add_token(:slash)
end
when ' ', "\r", "\t" then nil
when "\n" then
@line += 1
nil
when '"' then string
else
if is_digit(c)
number
elsif is_alpha(c)
identifier
else
raise ParseError.new(
@line,
"Unexpected character: #{c} (char code: #{c.ord}).")
end
end
end
def scan()
had_error = false
tokens = []
while !is_at_end
@start = @current
begin
t = token
if t
tokens.push(t)
end
rescue ParseError => e
STDERR.puts e
had_error = true
end
end
if had_error
raise ParseError.new(0, "Too many errors, aborting.")
end
tokens.push(Token.new(:eof, "", nil, @line))
tokens
end
def scan_on(source)
@start = 0
@current = 0
@source = source
scan
end
def inc_line()
@line += 1
end
end
<file_sep>require './rlox/environment'
require './rlox/parse'
require './rlox/scan'
Env = Struct.new(:map, :scopes, :vars, :fn, :cls, :parent) do
def child()
Env.new(map, scopes, Environment.new(vars), fn, cls, self)
end
def lookup(expr, name)
distance = map[expr]
if distance
vars.get_at(name, distance)
else
vars.get_global(name)
end
end
end
class Executor
def initialize()
@env = Env.new({}, [], Environment.global, nil, nil, nil)
@scanner = Scanner.new
@parser = Parser.new
end
def run(source)
errord = false
tokens = @scanner.scan_on(source)
ast = @parser.parse_on(tokens)
ast.each { | stmt |
begin
stmt.resolve(@env)
rescue VarError => e
STDERR.puts e
errord = true
end
}
if errord
return
end
ast.map { | stmt |
stmt.eval(@env)
}
end
def inc_line()
@scanner.inc_line
end
end
<file_sep>#!/usr/bin/env ruby
require './rlox/prompt'
require './rlox/file'
case ARGV.length
when 0 then prompt
when 1 then
begin
file ARGV[0]
#rescue StandardError => e
# STDERR.puts e
end
else
puts "Usage: rlox [script]"
exit 64
end
<file_sep>require './rlox/executor'
def file(path)
exec = Executor.new
read = File.read(path)
exec.run read
end
<file_sep>class Callable
def initialize(name, params, body, env, &block)
@env = env
@name = name
@params = params
@body = body
@call = block
end
def to_s()
"#{@name}:#{arity}"
end
def name()
@name
end
def arity()
@params.length
end
def call(args)
begin
@call.call(args)
rescue ReturnError => e
e.value
end
end
def bind(instance)
env = @env.child
env.vars.define("self", instance)
Callable.new(@name, @params, @env, @body) { | args |
nenv = env.child
for i in 0..@params.length-1
nenv.vars.define(@params[i].lexeme, args[i])
end
@body.eval(env)
}
end
end
<file_sep>class LoxInstance
def initialize(klass)
@klass = klass
@fields = {}
end
def fieldnames()
"(#{@fields.keys.join(", ")})"
end
def get(name)
if @fields.has_key? name.lexeme
return @fields[name.lexeme]
end
method = @klass.find_method(self, name)
if method
return method
end
raise ExecError.new(
name.line,
"Undefined property '#{name.lexeme}' on #{self}, has #{fieldnames}."
)
end
def set(name, val)
@fields[name.lexeme] = val
end
def to_s()
"<instance of '#{@klass}'>"
end
end
class LoxClass
def initialize(name, methods, superclass)
@name = name
@methods = methods
@super = superclass
end
def to_s()
if @name
@name.to_s
else
"<anonymous class>"
end
end
def arity()
init = @methods["init"]
if init
init.arity
else
0
end
end
def name()
@name
end
def call(args)
ins = LoxInstance.new(self)
init = @methods["init"]
if init
init.bind(ins).call(args)
end
ins
end
def find_method(instance, name)
if name.lexeme == "init"
raise ExecError.new(name.line, "Cannot re-initialize class.")
end
if @methods.has_key? name.lexeme
return @methods[name.lexeme].bind(instance)
end
if @super
return @super.find_method(instance, name)
end
end
end
<file_sep>require './rlox/classes'
def truthy?(obj)
if [nil, false, "", 0].include? obj
false
else
true
end
end
def begin_scope(scopes)
scopes.push({})
end
def end_scope(scopes)
last_scope = scopes.pop()
last_scope.each { | key, val |
if val[:used] == 0
raise VarError.new(val[:line], "Variable #{key} declared but never used.")
end
}
end
def declare(scopes, name)
if scopes.length == 0
return
end
scope = scopes[-1]
if scope.has_key? name.lexeme
raise VarError.new(
name.line,
"Variable with the name '#{name.lexeme}' already declared in this scope."
)
end
scope[name.lexeme] = {:assigned => false, :used => 0, :line => name.line}
end
def define(scopes, name)
if scopes.length == 0
return
end
scope = scopes[-1]
if not scope.has_key? name.lexeme
raise VarError.new(
name.line,
"Variable '#{name.lexeme}' was assigned, but not declared."
)
end
scope[name.lexeme][:assigned] = true
scope[name.lexeme][:used] += 1
end
def resolve_local(env, expr, name)
if env.scopes.length == 0
return
end
(env.scopes.length-1).downto(0) { | i |
if env.scopes[i].has_key? name.lexeme
env.map[expr] = env.scopes.length - 2 - i
env.scopes[i][name.lexeme][:used] += 1
return
end
}
end
def check_number_op(operator, *operands)
operands.each{ | operand |
if not operand.is_a? Numeric
raise ExecError.new(operator.line,
"Operand to '#{operator.lexeme}' must be a number.")
end
}
end
def check_same_type_op(operator, *operands)
fst = operands[0]
operands.each{ | operand |
if not operand.is_a? fst.class
raise ExecError.new(operator.line,
"Operand to '#{operator.lexeme}' must be a #{fst.class}.")
end
}
end
Call = Struct.new(:callee, :paren, :arguments) do
def resolve(env)
callee.resolve(env)
arguments.each{ | arg |
arg.resolve(env)
}
end
def eval(env)
to_call = callee.eval(env)
al = arguments.length
if not to_call.class.method_defined? :call
raise ExecError.new(paren.line, "Can only call functions and classes.")
end
if al != to_call.arity
raise ExecError.new(
paren.line,
"#{to_call.name} expected #{to_call.arity} arguments but got #{al}."
)
end
args = []
arguments.each{ | arg |
args << arg.eval(env)
}
to_call.call(args)
end
end
Assign = Struct.new(:name, :value) do
def resolve(env)
value.resolve(env)
resolve_local(env, self, name)
end
def eval(env)
val = value.eval(env)
distance = env.map[self]
if distance
env.vars.assign_at(name, val, distance)
else
env.vars.assign_global(name, val)
end
val
end
end
Binary = Struct.new(:left, :operator, :right) do
def resolve(env)
left.resolve(env)
right.resolve(env)
end
def eval(env)
l = left.eval(env)
r = right.eval(env)
case operator.type
when :minus then
check_number_op(operator, l, r)
l - r
when :plus then
check_same_type_op(operator, l, r)
l + r
when :slash then
check_number_op(operator, l, r)
l / r
when :star then
check_number_op(operator, l, r)
l * r
when :gt then
check_number_op(operator, l, r)
l > r
when :geq then
check_number_op(operator, l, r)
l >= r
when :lt then
check_number_op(operator, l, r)
l < r
when :leq then
check_number_op(operator, l, r)
l <= r
when :bang_eq then l != r
when :eq_eq then l == r
when :comma then r
else nil
end
end
end
Grouping = Struct.new(:expression) do
def resolve(env)
expression.resolve(env)
end
def eval(env)
expression.eval(env)
end
end
Literal = Struct.new(:value) do
def resolve(env)
end
def eval(env)
value
end
end
Unary = Struct.new(:operator, :right) do
def resolve(env)
right.resolve(env)
end
def eval(env)
r = right.eval(env)
case operator.type
when :bang then truthy?(r)
when :minus then
check_number_op(operator, r)
-r
else nil
end
end
end
Var = Struct.new(:name) do
def resolve(env)
if (env.scopes.length > 0 and env.scopes[-1][name.lexeme] and
env.scopes[-1][name.lexeme][:assigned] == false)
raise VarError.new(
name.line,
"Cannot read local variable #{name.lexeme} in its own initializer."
)
end
resolve_local(env, self, name)
end
def eval(env)
env.lookup(self, name)
end
end
Logical = Struct.new(:left, :operator, :right) do
def resolve(env)
left.resolve(env)
right.resolve(env)
end
def eval(env)
l = left.eval(env)
case operator.type
when :or then
if truthy?(l)
return l
end
when :and then
if not truthy?(l)
return l
end
end
right.eval(env)
end
end
Fn = Struct.new(:params, :body) do
def resolve(env)
begin_scope(env.scopes)
params.each{ | param |
declare(env.scopes, param)
define(env.scopes, param)
}
body.resolve(env)
end_scope(env.scopes)
end
def eval(env)
Callable.new("fn", params, body, env) { | args |
nenv = env.child
for i in 0..params.length-1
nenv.vars.define(params[i].lexeme, args[i])
end
body.eval(nenv)
}
end
end
Get = Struct.new(:object, :name) do
def resolve(env)
object.resolve(env)
end
def eval(env)
obj = object.eval(env)
if obj.is_a? LoxInstance
return obj.get(name)
end
raise ExecError.new(
expr.name.line,
"Only instances have properties, #{object.lexeme} is a #{obj.class}."
)
end
end
Set = Struct.new(:object, :name, :value) do
def resolve(env)
value.resolve(env)
object.resolve(env)
end
def eval(env)
obj = object.eval(env)
if not obj.is_a? LoxInstance
raise ExecError.new(
name.line,
"Only instances have fields, #{obj} is a #{obj.class}."
)
end
val = value.eval(env)
obj.set(name, val)
val
end
end
Klass = Struct.new(:name, :methods, :superclass) do
def resolve(env)
enclosing = env.cls
env.cls = :class
declare(env.scopes, name)
if superclass != nil
env.cls = :subclass
superclass.resolve(env)
end
define(env.scopes, name)
if superclass
begin_scope(env.scopes)
dummy = Token.new(:id, "super", nil, 0)
declare(env.scopes, dummy)
define(env.scopes, dummy)
end
begin_scope(env.scopes)
dummy = Token.new(:id, "self", nil, 0)
declare(env.scopes, dummy)
define(env.scopes, dummy)
methods.each { | method |
method.resolve(env, method.name.lexeme == "init" ? :init : :method)
}
end_scope(env.scopes)
if superclass
end_scope(env.scopes)
end
env.cls = enclosing
end
def eval(env)
supcls = nil
if superclass
supcls = superclass.eval(env)
if not supcls.is_a? LoxClass
raise ExecError.new(name.line, "Superclass must be a class.")
end
end
if name
env.vars.define(name.lexeme, nil)
end
if superclass
env = env.child
env.vars.define("super", supcls)
end
methods_dict = {}
methods.each { | method |
fn = Callable.new(method.name.lexeme, method.params, method.body, env) {
| args |
nenv = env.child
for i in 0..method.params.length-1
nenv.vars.define(method.params[i].lexeme, args[i])
end
method.body.eval(nenv)
}
methods_dict[method.name.lexeme] = fn
}
klass = LoxClass.new(name ? name.lexeme : nil, methods_dict, supcls)
if superclass
env = env.parent
end
if name
env.vars.assign(name, klass)
end
klass
end
end
Self = Struct.new(:keyword) do
def resolve(env)
if env.cls != :class
raise VarError.new(keyword.line, "Cannot use 'self' outside of a class.")
end
resolve_local(env, self, keyword)
end
def eval(env)
env.lookup(self, keyword)
end
end
Super = Struct.new(:keyword, :method) do
def resolve(env)
if not env.cls
raise VarError.new(keyword.line, "Cannot use 'super' outside of a class.")
elsif env.cls != :subclass
raise VarError.new(
keyword.line,
"Cannot use 'super' in a class without superclass."
)
end
resolve_local(env, self, keyword)
end
def eval(env)
distance = env.map[self]
superclass = env.vars.get_at(keyword, distance)
dummy = Token.new(:id, "self", nil, 0)
obj = env.vars.get_at(dummy, distance-1)
m = superclass.find_method(obj, method)
if not m
raise ExecError.new(
method.line,
"Undefined 'super' property '#{method.lexeme}'."
)
end
m
end
end
Expression = Struct.new(:expression) do
def resolve(env)
expression.resolve(env)
end
def eval(env)
expression.eval(env)
end
end
Variable = Struct.new(:name, :initializer) do
def resolve(env)
declare(env.scopes, name)
if initializer
initializer.resolve(env)
end
define(env.scopes, name)
end
def eval(env)
value = nil
if initializer != nil
value = initializer.eval(env)
end
env.vars.define(name.lexeme, value)
end
end
Block = Struct.new(:stmts) do
def resolve(env)
begin_scope(env.scopes)
stmts.each{ | stmt |
stmt.resolve(env)
}
end_scope(env.scopes)
end
def eval(env)
child = env.child
ret = nil
stmts.each{ | stmt |
ret = stmt.eval(child)
}
ret
end
end
If = Struct.new(:cond, :thn, :els) do
def resolve(env)
cond.resolve(env)
thn.resolve(env)
if els
els.resolve(env)
end
end
def eval(env)
if truthy? cond.eval(env)
thn.eval(env)
elsif els != nil
els.eval(env)
end
end
end
While = Struct.new(:cond, :body) do
def resolve(env)
cond.resolve(env)
body.resolve(env)
end
def eval(env)
ret = nil
while truthy? cond.eval(env)
ret = body.eval(env)
end
ret
end
end
FnDef = Struct.new(:name, :params, :body) do
def resolve(env, fn=:fn)
declare(env.scopes, name)
define(env.scopes, name)
enclosing = env.fn
env.fn = fn
begin_scope(env.scopes)
params.each{ | param |
declare(env.scopes, param)
define(env.scopes, param)
}
body.resolve(env)
end_scope(env.scopes)
env.fn = enclosing
end
def eval(env)
env.vars.define(name.lexeme, Callable.new(name.lexeme, params, body, env) {
| args |
nenv = env.child
for i in 0..params.length-1
nenv.vars.define(params[i].lexeme, args[i])
end
body.eval(nenv)
})
end
end
Return = Struct.new(:keyword, :value) do
def resolve(env)
if not env.fn
raise VarError.new(keyword.line, "Cannot return from top-level code.")
end
if value
if env.fn == :init
raise VarError.new(keyword.line, "Cannot return a value from 'init()'.")
end
value.resolve(env)
end
end
def eval(env)
raise ReturnError.new(value == nil ? nil : value.eval(env))
end
end
<file_sep>require "readline"
require './rlox/executor'
def prompt()
exec = Executor.new
f = File.new("#{Dir.home}/.rlox", "a+")
File.readlines("#{Dir.home}/.rlox").each { | line |
Readline::HISTORY.push line.rstrip
}
begin
while buf = Readline.readline("> ", true)
Readline::HISTORY.pop if /^\s*$/ =~ buf
if buf[-1] != ';'
buf << ';'
end
begin
res = exec.run(buf)
if res
res.each { | res |
puts res.to_s
}
end
rescue LoxError => err
STDERR.puts err
ensure
f.write("#{buf}\n")
end
exec.inc_line
end
rescue Interrupt
ensure
f.close
end
end
<file_sep># rlox
`rlox` is an unpronouncable variant of the tree-walk interpreter laid out in
[Crafting Interpreters](http://craftinginterpreters.com/), written in Ruby,
because I want to learn it.
It deviates a little from the “canonical” version of Lox. I don’t use code
generation for the expressions, and I don’t use the visitor pattern. `var` and
`fun` are `let` and `fn`, respectively. And we don’t need parentheses around
branching conditions, instead we require the bodies to be blocks. We also have
closures and anonymous functions (and literals for them), and implicit returns.
If you wonder what that looks like, you can look at the [examples](/examples).
<file_sep>class LoxError < StandardError
def line_s()
@line > 0 ? "[line #{@line}] " : ""
end
def to_s()
"#{line_s}Error#{@where}: #{@msg}"
end
def initialize(line, msg, where="")
@line = line
@where = where
@msg = msg
super(msg)
end
end
class ParseError < LoxError
end
class VarError < LoxError
end
class ExecError < LoxError
end
class ReturnError < StandardError
def initialize(value)
@value = value
end
def value()
@value
end
end
<file_sep>require './rlox/expression'
class Parser
def initialize()
@current = 0
end
def match(*types)
types.each{ | type |
if check type
advance
return true
end
}
false
end
def check(type)
if is_at_end
false
else
peek.type == type
end
end
def check_next(type)
if is_at_end or peek_next.type == :eof
false
else
peek_next.type == type
end
end
def advance()
if !is_at_end
@current += 1
end
return previous
end
def is_at_end()
peek.type == :eof
end
def peek()
@tokens[@current]
end
def peek_next()
@tokens[@current+1]
end
def previous()
@tokens[@current-1]
end
def and_expr()
expr = equality
if match(:and)
operator = previous
right = equality
expr = Logical.new(expr, operator, right)
end
expr
end
def or_expr()
expr = and_expr
if match(:or)
operator = previous
right = and_expr
expr = Logical.new(expr, operator, right)
end
expr
end
def assignment()
expr = or_expr
if match(:eq)
equals = previous
value = assignment
if expr.is_a? Var
name = expr.name
return Assign.new(name, value)
elsif expr.is_a? Get
return Set.new(expr.object, expr.name, value)
end
error(equals, "Invalid assignment target: '#{expr.dbg}'.")
end
expr
end
def equality()
expr = comparison
while match(:bang_eq, :eq_eq)
operator = previous
right = comparison
expr = Binary.new(expr, operator, right)
end
expr
end
def addition()
expr = multiplication
while match(:minus, :plus)
operator = previous
right = multiplication
expr = Binary.new(expr, operator, right)
end
expr
end
def multiplication()
expr = unary
while match(:slash, :star)
operator = previous
right = unary
expr = Binary.new(expr, operator, right)
end
expr
end
def comparison()
expr = addition
while match(:gt, :geq, :lt, :leq)
operator = previous
right = addition
expr = Binary.new(expr, operator, right)
end
expr
end
def unary()
if match(:bang, :minus)
operator = previous
right = unary
return Unary.new(operator, right)
end
call
end
def call()
expr = primary
while true
if match(:left_paren)
expr = finish_call(expr)
elsif match(:dot)
name = consume(:id, "Expect property name after '.'.")
expr = Get.new(expr, name)
else
break
end
end
expr
end
def finish_call(callee)
args = []
if not check(:right_paren)
begin
args << expression
end while match(:comma)
end
paren = consume(:right_paren, "Expect ')' after arguments.")
return Call.new(callee, paren, args)
end
def anon_fn()
consume(:left_paren, "Expect '(' after 'fn' keyword'.")
params = []
if not check(:right_paren)
begin
params << consume(:id, "Expect parameter name")
end while match(:comma)
end
consume(:right_paren, "Expect ')' after parameters.")
consume(:left_brace, "Expect '{' before fn body.")
body = Block.new(block)
Fn.new(params, body)
end
def anon_class()
consume(:left_brace, "Expect '{' before body of anonymous class.")
methods = []
while not check(:right_brace) and not is_at_end
methods << function("method")
end
consume(:right_brace, "Expect '}' after class body.")
Klass.new(nil, methods)
end
def primary()
if match(:false)
Literal.new(false)
elsif match(:true)
Literal.new(true)
elsif match(:nil)
Literal.new(nil)
elsif match(:self)
Self.new(previous)
elsif match(:super)
kw = previous
consume(:dot, "Expect '.' after 'super'.")
method = consume(:id, "Expect superclass method name.")
Super.new(kw, method)
elsif match(:number, :string)
Literal.new(previous.literal)
elsif match(:left_paren)
expr = expression
consume(:right_paren, "Expect ')' after expression.")
Grouping.new(expr)
elsif match(:id)
Var.new(previous)
elsif match(:fn)
anon_fn
elsif match(:class)
anon_class
else
error(peek, "Expect expression.")
end
end
def consume(type, msg)
if check(type)
advance
else
error(peek, msg)
end
end
def error(token, msg)
if token.type == :eof
raise ParseError.new(token.line, msg, " at end")
else
raise ParseError.new(token.line, msg, " at '#{token.lexeme}'")
end
end
def expression()
assignment
end
def synchronize()
advance
while not is_at_end
if previous.type == :semicolon
return
end
case peek.type
when :class, :fun, :let, :for, :if, :while, :return then
return
end
advance
end
end
def expression_statement()
expr = expression
consume(:semicolon, "Expect ';' after expression.")
Expression.new(expr)
end
def block()
stmts = []
while not check(:right_brace) and not is_at_end
stmts << declaration
end
consume(:right_brace, "Expect '}' after block.")
return stmts
end
def if_statement()
cond = expression
consume(:left_brace, "Expect '{' after 'if' condition.")
thn = Block.new(block)
els = nil
if match(:else)
consume(:left_brace, "Expect '{' after 'else'.")
els = Block.new(block)
end
If.new(cond, thn, els)
end
def while_statement()
cond = expression
consume(:left_brace, "Expect '{' after 'if' condition.")
body = Block.new(block)
While.new(cond, body)
end
def for_statement()
init = if match(:semicolon)
nil
elsif match(:let)
var_declaration
else
expression_statement
end
cond = nil
if !check(:semicolon)
cond = expression
end
consume(:semicolon, "Expect ';' after loop condition.")
inc = nil
if !check(:semicolon)
inc = expression
end
consume(:left_brace, "Expect '{' after 'if' condition.")
body = Block.new(block)
if inc != nil
body = Block.new([body, Expression.new(inc)])
end
if cond == nil
cond = Literal.new(true)
end
body = While.new(cond, body)
if init != nil
body = Block.new([init, body])
end
body
end
def return_statement()
keyword = previous
value = nil
if !check(:semicolon)
value = expression
end
consume(:semicolon, "Expect ';' after return value.")
Return.new(keyword, value)
end
def statement()
if match(:if)
if_statement
elsif match(:for)
for_statement
elsif match(:return)
return_statement
elsif match(:while)
while_statement
elsif match(:left_brace)
Block.new(block)
else
expression_statement
end
end
def var_declaration()
name = consume(:id, "Expect variable name.")
initializer = nil
if match(:eq)
initializer = expression
end
consume(:semicolon, "Expect ';' after variable declaration.")
Variable.new(name, initializer)
end
def function(kind)
consume(:fn, "Expect 'fn' keyword.")
name = consume(:id, "Expect #{kind} name.")
consume(:left_paren, "Expect '(' after #{kind} name.")
params = []
if not check(:right_paren)
begin
params << consume(:id, "Expect paramenter name")
end while match(:comma)
end
consume(:right_paren, "Expect ')' after parameters.")
consume(:left_brace, "Expect '{' before #{kind} body.")
body = Block.new(block)
FnDef.new(name, params, body)
end
def class_declaration()
consume(:class, "Expect 'class' keyword.")
name = consume(:id, "Expect class name.")
superclass = nil
if match(:lt)
consume(:id, "Expect superclass name.")
superclass = Var.new(previous)
end
consume(:left_brace, "Expect '{' before body of class '#{name.lexeme}.'")
methods = []
while not check(:right_brace) and not is_at_end
methods << function("method")
end
consume(:right_brace, "Expect '}' after class body.")
Klass.new(name, methods, superclass)
end
def declaration()
begin
if check(:class) and check_next(:id)
class_declaration
elsif check(:fn) and check_next(:id)
function("fn")
elsif match(:let)
var_declaration
else
statement
end
rescue ParseError => e
synchronize
raise e
end
end
def parse()
statements = []
while not is_at_end
statements << declaration
match(:semicolon)
end
statements
end
def parse_on(tokens)
@current = 0
@tokens = tokens
parse
end
end
<file_sep>require './rlox/call'
class Environment
def self.global()
env = self.new()
env.define("print", Callable.new("print", ["obj"], nil, env) {
| args |
puts args[0]
})
env.define("clock", Callable.new("clock", [], nil, env) {
| args |
Time.now.to_i
})
env
end
def initialize(parent=nil)
@values = {}
@parent = parent
end
def to_s()
@values.to_s
end
def define(name, value)
@values[name] = value
end
def parent()
@parent
end
def get(name)
if @values.has_key? name.lexeme
return @values[name.lexeme]
end
if @parent != nil
return @parent.get(name)
end
raise ExecError.new(name.line, "Undefined variable '#{name.lexeme}'.")
end
def get_at(name, distance)
env = self
distance.times {
env = env.parent
}
env.get(name)
end
def get_global(name)
env = self
while env.parent
env = env.parent
end
env.get(name)
end
def assign(name, value)
if @values.has_key? name.lexeme
@values[name.lexeme] = value
return
end
if @parent != nil
return @parent.assign(name, value)
end
raise ExecError.new(name.line,
"Can’t assign undefined variable '#{name.lexeme}'.")
end
def assign_at(name, value, distance)
env = self
distance.times {
env = env.parent
}
env.assign(name, value)
end
def assign_global(name, value)
env = self
while env.parent
env = env.parent
end
env.assign(name, value)
end
end
|
3e20b6fbf054387750ddb1fe018f1ff63b51bc71
|
[
"Markdown",
"Ruby"
] | 12
|
Ruby
|
hellerve/rlox
|
668248bd840d1af104215f5ce8cca8abf989a7bd
|
7238ef04cdb25fcb4d7cfd81254c36d7d9f00689
|
refs/heads/master
|
<repo_name>swissarmykirpan/dockerfiles<file_sep>/squid/README.md
# about minimum2scp/squid image
* based on minimum2scp/baseimage (see https://github.com/minimum2scp/dockerfiles/tree/master/baseimage)
* squid3 package installed
## start container
```
docker run -d -p 3128:3128 minimum2scp/squid
```
and then use from localhost:
```
export http_proxy=htpt://127.0.0.1:3128
curl http://example.com/
```
## ssh login to container
ssh login to container:
```
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no debian@<container IP address>
```
or use published port:
```
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -p <published ssh port> debian@localhost
```
* user "debian" is available
* password is "<PASSWORD>"
* user "debian" can use sudo command without password
* `id debian`: `uid=2000(debian) gid=2000(debian) groups=2000(debian),4(adm),27(sudo)`
## processes
```
UID PID PPID C STIME TTY STAT TIME CMD
root 1 0 0 02:51 ? Ss 0:00 init [2]
root 37 1 0 02:51 ? Ssl 0:00 /usr/sbin/rsyslogd
root 62 1 0 02:51 ? Ss 0:00 /usr/sbin/cron
root 70 1 0 02:51 ? Ss 0:00 /usr/sbin/squid3 -YC -f /etc/squid3/squid.conf
proxy 72 70 0 02:51 ? S 0:00 \_ (squid-1) -YC -f /etc/squid3/squid.conf
proxy 77 72 0 02:51 ? S 0:00 \_ (logfile-daemon) /var/log/squid3/access.log
proxy 91 72 0 02:51 ? S 0:00 \_ (pinger)
root 84 1 0 02:51 ? Ss 0:00 /usr/sbin/sshd
root 92 84 1 02:52 ? Ss 0:00 \_ sshd: debian [priv]
debian 94 92 0 02:52 ? S 0:00 \_ sshd: debian@pts/0
debian 95 94 0 02:52 pts/0 Ss 0:00 \_ -bash
debian 100 95 0 02:53 pts/0 R+ 0:00 \_ ps -ef fww
```
## ports
* TCP/22: sshd
* TCP/3128: squid3
* TCP/3129: squid3 (transparent)
<file_sep>/squid/build/scripts/01-setup
#! /bin/sh
set -e
set -x
export DEBIAN_FRONTEND=noninteractive
##
## install squid3
##
apt-get install --no-install-recommends -y squid3
##
## configure squid3
##
cp -a /etc/squid3/squid.conf /etc/squid3/squid.conf.orig
( echo "include /etc/squid3/squid.acl.conf";
cat /etc/squid3/squid.conf;
echo "";
echo "include /etc/squid3/squid.local.conf";
) > /etc/squid3/squid.conf.new
mv /etc/squid3/squid.conf.new /etc/squid3/squid.conf
install -m 644 -o root -g root -p /build/etc/squid3/squid.acl.conf /etc/squid3/squid.acl.conf
install -m 644 -o root -g root -p /build/etc/squid3/squid.local.conf /etc/squid3/squid.local.conf
etckeeper commit "squid: allow from localnet, shorten shutdown_lifetime"
##
## workaround for squid3 init script: "/etc/init.d/squid3 stop" fails
##
cp -a /etc/init.d/squid3 /etc/init.d/squid3.orig
install -m 755 -o root -g root -p /build/etc/init.d/squid3 /etc/init.d/squid3
etckeeper commit "squid: workaround for init script"
##
## add user to proxy group
##
adduser debian proxy
etckeeper commit "add debian user to proxy group"
<file_sep>/spec/ruby-full/00base_spec.rb
require 'spec_helper'
describe 'minimum2scp/ruby-full' do
before(:all) do
start_container({
'Image' => ENV['DOCKER_IMAGE'] || "minimum2scp/#{File.basename(__dir__)}:latest",
'Env' => [ 'APT_LINE=keep' ]
})
end
after(:all) do
stop_container
end
#Dir["#{__dir__}/../ruby/*_spec.rb"].sort.each do |spec|
# load spec
#end
[
[ '2.2.2', 'ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux]' ],
[ '2.1.6', 'ruby 2.1.6p336 (2015-04-13 revision 50298) [x86_64-linux]' ],
[ '2.0.0-p645', 'ruby 2.0.0p645 (2015-04-13 revision 50299) [x86_64-linux]' ]
].each do |dir, version|
describe file("/opt/rbenv/versions/#{dir}") do
it { should be_directory }
end
describe command("/opt/rbenv/versions/#{dir}/bin/ruby -v") do
its(:stdout) { should include version }
end
describe command("/opt/rbenv/versions/#{dir}/bin/gem list") do
its(:stdout) { should match /^bundler / }
its(:stdout) { should match /^pry / }
end
end
%w[ruby2.2 ruby2.2-dev].each do |pkg|
describe package(pkg) do
it { should be_installed }
end
end
describe command('ruby2.2 -v') do
its(:stdout) { should include 'ruby 2.2.2p95 (2015-04-13) [x86_64-linux-gnu]'}
end
end
|
24b07664bd72337b0a770bc50d9cc2887700c6ad
|
[
"Markdown",
"Ruby",
"Shell"
] | 3
|
Markdown
|
swissarmykirpan/dockerfiles
|
7df54ad204e9771f468011ab9a85cbb075736be3
|
f76186a196b5d7e826f8522124e770a6a2afca4e
|
refs/heads/main
|
<file_sep><?php
include_once 'database.php';
$sql = "DELETE FROM infopdf WHERE fileid='" . $_GET["fileid"] . "'";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
header("location:table.php");
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?><file_sep><?php
if(isset($_POST['name'])){
$name=$_POST['name'];
$email=$_POST['email'];
$userid=$_POST['userid'];
$complaint=$_POST['complaint'];
date_default_timezone_set('Asia/Kolkata');
$date = date("Y-m-d");
include 'database.php';
$query = mysqli_query($conn,"insert into complaints (userid , name , email , complaint,date) values ('$userid' , '$name' , '$email' , '$complaint','$date')" );
if(!$query)
{
echo '<script>alert("ERROR OCCURED TRY AGAIN")</script>';
echo '<script>window.location="main.php"</script>';
}
else{
echo '<script>alert("COMPLAINT REGISTERED")</script>';
echo '<script>window.location="main.php"</script>';
}
}
else{
header("Location: http://localhost/smartsociety/main.php");
}
?>
<file_sep><?php
include_once 'database.php';
if(isset($_POST['save']))
{
$name = $_POST['name'];
$userid = $_POST['userid'];
$phone = $_POST['phone'];
$resident = $_POST['resident'];
$no = $_POST['no'];
$sql = "INSERT INTO tenants(userid,name,phone,no,resident) VALUES ('$userid','$name','$phone','$no','$resident')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully !";
header("Location:tenants.php");
}
else {
echo "Error: " . $sql . "
" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
<file_sep><?php
//$host = gethostbyaddr($_SERVER["REMOTE_ADDR"]);
$machineName = gethostname(); //for get current system name
$ip = gethostbyname($machineName); //For get ipaddress
include 'database.php';
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$sql="select * from login where username='$username' && password='$<PASSWORD>'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
if ($row['username'] == $username && $row['password'] == $password)
{
echo'<script type="text/javascript">alert("Login successful!! Welcome");</script>';
echo '<script> location.href = "admin1.php"; </script> ';
}
else{
echo'<script type="text/javascript">alert("check your login credentials");</script>';
echo '<script> location.href = "index.php"; </script> ';
}
date_default_timezone_set('Asia/Kolkata');
$login_date = date("Y-m-d");
$login_time = date("H:i:s");
$kyurie = "insert into login_details ( username , login_date , login_time, ip ) VALUES ('$username' , '$login_date' , '$login_time' , '$ip')";
$store=mysqli_query($conn , $kyurie);
}
?>
<file_sep># smartsociety
An online platform for smart and efficient management of society.
Run the main.php file
For admin side : Username : admin
password : <PASSWORD>
<file_sep><?php
include_once 'database.php';
if(isset($_POST['save']))
{
$name = $_POST['name'];
$userid = $_POST['userid'];
$phone = $_POST['phone'];
$resident = $_POST['resident'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$no = $_POST['no'];
$parking = $_POST['parking'];
$sql = "INSERT INTO members (userid,name,phone,email,dob,resident,no,parking)
VALUES ('$userid','$name','$phone','$email','$dob','$resident','$no','$parking')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully !";
header("Location:update.php");
}
else {
echo "Error: " . $sql . "
" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
<file_sep><?php
include 'database.php';
$sql = "SELECT * FROM infopdf order by fileid desc ";
$result = mysqli_query($conn, $sql);
$query="select *from output_images";
$result1 = mysqli_query($conn, $query);
?>
<!DOCTYPE html>
<title>SMART SOCIETY</title>
<!--M E T A T A G S-->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- LINKS-->
<link href="./Themesfinity's CSS Button_files/buttons.css" rel="stylesheet">
<link rel="stylesheet" href="main.css">
<link rel="icon" href="images/logo.png" type="image/icon type">
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
<link href='https://fonts.googleapis.com/css?family=Bevan' rel='stylesheet'>
<link href='https://fonts.googleapis.com/css?family=Aladin' rel='stylesheet'>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="http://fonts.googleapis.com/css?family=Cookie" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=initMap&libraries=&v=weekly"
defer></script>
<script src="index.js"></script>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</head>
<body>
<!--Nav Bar-->
<div id="mynav">
<div class="topnav" id="myTopnav">
<img onclick="window.location.reload()" src="images/logo.png" alt="logo" width="100" height="80" style="cursor: pointer;">
<a href="payments.html">PAYMENTS</a>
<a href="complaints.html" id="myBtn">COMPLAINTS</a>
<a href="memdetails1.php" id="mem">MEMBER DETAILS</a>
<a href="facilities.html">FACILITIES</a></li>
<a href="index.php">ABOUT</a>
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
</div>
<!--TOP BOX -->
<div class="top-container" style="margin-top: 180px;">
<div class="row">
<div class="column left" >
<div id="notice-box" class="notice-box">
<div style="border: 3px solid green; background-color: lightgoldenrodyellow;">
<h2 style=" color: green; font-family: Georgia, 'Times New Roman', Times, serif; " class="glow"><i
class="fa fa-bullhorn "></i>Notice </h2>
</div>
<marquee behavior="scroll" direction="down" scrollamount="3" style="text-align: center; font-size:20px;">
<?php
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<label><a href="'.$row['directory1'].'" target="_blank">'.$row['filename'].'</a><br></label>';
}
}
?>
</marquee>
</div>
</div>
<div class="column middle">
<!--slideshow-->
<div class="slideshow-container">
<div class="slideshow_wrapper">
<div class="slideshow">
<?php
while($row = mysqli_fetch_array($result1)) {
?>
<div class="slide_one slide">
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>"/>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="column right">
<div class="form-popup" id="myForm">
<form action="login.php" class="form-container" method="POST">
<h1
style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;">
ADMIN LOGIN</h1>
<label for=" email"><b><i class="fas fa-user"></i>USERNAME: </b></label>
<input type="text" placeholder="Enter Username.." name="username" required>
<br> <label for="psw"><b><i class="fas fa-lock"></i>PASSWORD: </b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<button type="submit" value="submit" class="btn btn-success btn-xs btn-radius">Login</button>
</form>
</div>
</div>
</div>
</div>
<!--main page contents-->
<div class="welcome">
<h1>WELCOME TO GOKULDHAM SOCIETY</h1>
</div>
<!--image gallery-->
<div class="row1">
<div class="column1">
<img src="images/ss1.jpg" style="width:100%">
<img src="images/pool.jpg" style="width:100%; height: 270px;">
</div>
<div class="column1">
<img src="images/ss3.jpg" style="width:100%">
<img src="images/ss4.jpg" style="width:100%">
</div>
<div class="column1">
<img src="images/ss2.jpg" style="width:100%; height: 230px;">
<img src="images/play.jpg" style="width:100%">
</div>
</div>
<!--text text-->
<div class="text">
<img src="images/society.jpg"
style="float: right; height: 300px; width:350px; border: 3px solid black; margin: 3px;">
<h1 style="margin-left:15px; color: green;">About</h1>
<p>
<br> A society is a group of individuals involved in persistent social interaction, or a large social group
sharing
the same spatial or social territory, typically subject to the same political authority and dominant
cultural
expectations. Societies are characterized by patterns of relationships (social relations) between
individuals
who share a distinctive culture and institutions; a given society may be described as the sum total of
such
relationships among its constituent of members. In the social sciences, a larger society often exhibits
stratification or dominance patterns in subgroups.
More broadly, and especially within structuralist thought, a society may be illustrated as an economic,
social,
industrial or cultural infrastructure, made up of, yet distinct from, a varied collection of
individuals. In
this regard society can mean the objective relationships people have with the material world and with
other
people, rather than "other people" beyond the individual and their familiar social environment.
A society is a group of individuals involved in persistent social interaction, or a large social group
sharing
the same spatial or social territory, typically subject to the same political authority and dominant
cultural
expectations. Societies are characterized by patterns of relationships (social relations) between
individuals
who share a distinctive culture and institutions; a given society may be described as the sum total of
such
relationships among its constituent of members. In the social sciences, a larger society often exhibits
stratification or dominance patterns in subgroups.
More broadly, and especially within structuralist thought, a society may be illustrated as an economic,
social,
industrial or cultural infrastructure, made up of, yet distinct from, a varied collection of
individuals. In
this regard society can mean the objective relationships people have with the material world and with
other
people, rather than "other people" beyond the individual and their familiar social environment.
</p>
</div>
<div class="text1">
<div class="pic">
<img src="images/plan.jpg" style="float: right; height: 400px; width:350px;border: 3px solid black; margin: 3px;"></div>
<h2 style="margin-left:15px; color: green ;">FLOOR PLAN</h2>
<p>
<br> A society is a group of individuals involved in persistent social interaction, or a large social group
sharing
the same spatial or social territory, typically subject to the same political authority and dominant
cultural
expectations. Societies are characterized by patterns of relationships (social relations) between
individuals
who share a distinctive culture and institutions; a given society may be described as the sum total of
such
relationships among its constituent of members. In the social sciences, a larger society often exhibits
stratification or dominance patterns in subgroups.
More broadly, and especially within structuralist thought, a society may be illustrated as an economic,
social,
industrial or cultural infrastructure, made up of, yet distinct from, a varied collection of
individuals. In
this regard society can mean the objective relationships people have with the material world and with
other
people, rather than "other people" beyond the individual and their familiar social environment.
A society is a group of individuals involved in persistent social interaction, or a large social group
sharing
the same spatial or social territory, typically subject to the same political authority and dominant
cultural
expectations. Societies are characterized by patterns of relationships (social relations) between
individuals
who share a distinctive culture and institutions; a given society may be described as the sum total of
such
relationships among its constituent of members. In the social sciences, a larger society often exhibits
stratification or dominance patterns in subgroups.
More broadly, and especially within structuralist thought, a society may be illustrated as an economic,
social,
industrial or cultural infrastructure, made up of, yet distinct from, a varied collection of
individuals. In
this regard society can mean the objective relationships people have with the material world and with
other
people, rather than "other people" beyond the individual and their familiar social environment.
</p>
</div>
<!--FOOTER-->
<footer class="footer-distributed">
<div class="footer-left" >
<h3>Gokuldham <span>Society</span></h3>
<p class="footer-links">
<a href="index.php" class="link-1">About</a>
<a href="facilities.html">Facilities</a>
<a href="memdetails1.php">Members</a>
<a href="complaints.html">Complaints</a>
<a href="payments.html">Payments</a>
</p>
<p class="footer-company-name">Gokuldham scoiety © 2020</p>
</div>
<div class="footer-center">
<div>
<i class="fa fa-map-marker"></i>
<a href="https://www.google.com/maps/place/Gokuldham+Society,+Satya+Nagar,+Sathi+D+Souza+Nagar,+Saki+Naka,+Mumbai,+Maharashtra+400072/@19.0998496,72.8850761,17z/data=!4m5!3m4!1s0x3be7c8702918b84f:0x2677f9d7454c6342!8m2!3d19.0998915!4d72.8873084"> <p>Film City Complex, Aarey Colony,<span>Goregaon, Mumbai, Maharashtra 400065</span></p></a>
</div>
<div>
<i class="fa fa-phone"></i>
<p> 022 2345678</p>
</div>
<div>
<i class="fa fa-envelope"></i>
<p><a href="mailto:<EMAIL>">info.gokuldhamsociety.com</a></p>
</div>
</div>
<div class="footer-right">
<div id="map" class="map">
</div>
</div>
</footer>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<style>
table {
width: 80%;
border-collapse: collapse;
margin: 20px;
}
table, td, th {
border: 3px solid green;
padding: 5px;
text-align: Center;}
</style>
</head>
<body>
<?php
$s = $_GET['s'];
$con = mysqli_connect('localhost','id15549943_aks','Aks#372936aks','id15549943_smartsociety');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"id15549943_smartsociety");
$sql="SELECT * FROM tenants WHERE userid = '".$s."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Name</th>
<th>Phone</th>
<th>People</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "<td>" . $row['no'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html><file_sep><?php
if(!isset($_SERVER['HTTP_REFERER'])){
// redirect them to your desired location
header('location:main.php');
exit;
}
?>
<!DOCTYPE html>
<head>
<title>ADMIN PAGE</title>
<!--M E T A T A G S-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="keywords" content="footer, address, phone, icons" />
<!-- LINKS-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="Astyle.css">
<link href="/css/ladda-themeless.min.css" rel="stylesheet">
<link rel="icon" href="images/logo.png" type="image/icon type">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
<link href="http://fonts.googleapis.com/css?family=Cookie" rel="stylesheet" type="text/css">
<link href="./Themesfinity's CSS Button_files/bootstrap.min.css" rel="stylesheet">
<link href="./Themesfinity's CSS Button_files/buttons.css" rel="stylesheet">
<link href="./Themesfinity's CSS Button_files/style..css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
function date_time(id) {
date = new Date;
year = date.getFullYear();
month = date.getMonth();
months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'Jully', 'August', 'September', 'October', 'November', 'December');
d = date.getDate();
day = date.getDay();
days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
h = date.getHours();
if (h < 10) {
h = "0" + h;
}
m = date.getMinutes();
if (m < 10) {
m = "0" + m;
}
s = date.getSeconds();
if (s < 10) {
s = "0" + s;
}
result = '' + days[day] + ' ' + months[month] + ' ' + d + ' ' + year + ' ' + h + ':' + m + ':' + s;
document.getElementById(id).innerHTML = result;
setTimeout('date_time("' + id + '");', '1000');
return true;
}
function openNav() {
document.getElementById("myNav").style.width = "20%";
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
}
$(document).ready(
function(){
$('input:file').change(
function(){
if ($(this).val()) {
$('input:submit').attr('disabled',false);
document.getElementById("sub1").style="cursor:pointer;"
document.getElementById("sub2").style="cursor:pointer;"
// or, as has been pointed out elsewhere:
// $('input:submit').removeAttr('disabled');
}
}
);
});
</script>
</head>
<body style="background-color: lightsalmon;">
<!--header-->
<div class="header">
<a href="admin1.php" class="logo"> <img src="images/logo.png"> </a>
<span>
<b><p style="font-size:30px;color:yellow; font: outline; font-family: Georgia, 'Times New Roman', Times, serif; margin-left: 30px;" >GOKULDHAM COOPERATIVE HOUSING SOCIETY</p></b>
</span>
<button id="button1" class="btn btn-primary btn-xs"
style="cursor:context-menu; font-size:15px;color: white;background-color:teal;float: right; margin-left: 150px;margin-top: 5px; font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;"><i
class="fa fa-user"></i> Hello <NAME>!</button>
<a href="logout.php" class="btn btn-danger btn-xs"
style="background-color:#f14e4e; font-size:15px; float: right;margin-right: -315px; margin-top: 65px;color: white;"
class="btn btn-primary btn-xs specialbuttonlabel"> <i class="fa fa-sign-out">Logout</i></a>
</div>
<div class="notice">
<b>
<marquee id="marq">
Welcome Admin! <span id="date_time"></span>
<script type="text/javascript">window.onload = date_time('date_time');</script>
</marquee></b>
</div>
<!--main body-->
<div class="row">
<div class="leftcolumn">
<div class="card" style="border: 3px outset black">
<div>
<mark style="border: 3px outset black">Upload Notice Here :</mark>
<br><br><br></div>
<div class="box1" style= "text-align: center;border: 3px solid brown;">
<form action="notice.php" name="myForm" method="POST" enctype="multipart/form-data">
<input class="input100" type="file" name="fileupload" accept=".pdf">
<br><br>
<input type="submit" name="submit" id="sub1" style="margin-top: -20px; cursor: not-allowed;" class="btn btn-light btn-sm btn-radius" disabled >
</form>
<a href="table.php" id="button" style="margin-bottom: 10px; margin-top: 10px;"
class="btn btn-light btn-sm btn-radius"> View </a>
</div>
</div>
<div class="card" style="border: 3px outset black">
<div>
<mark style="border: 3px outset black">Add/Delete Member Details: </mark>
<br><br><br></div>
<div class="butt" style="margin-left: 70px;margin-right: 70px; text-align: center;border: 3px solid brown;">
<a href="update.php" id="button" class="btn btn-light btn-sm btn-radius"
class="btn btn-primary btn-xs specialbuttonlabel"> Update </a>
<a href="tenants.php" id="button" class="btn btn-light btn-sm btn-radius"
class="btn btn-primary btn-xs specialbuttonlabel"> Tenants </a>
</div>
</div>
</div>
<div class="rightcolumn">
<div class="card" style="border: 3px outset black">
<div>
<mark style="border: 3px outset black">Upload Photos Here :</mark>
<br><br><br></div>
<div class="box1" style= "text-align: center;border: 3px solid brown;">
<form name="frmImage" enctype="multipart/form-data" action="index1.php" method="post">
<input class="input100" type="file" name="userImage" accept=".jpeg,.jpg,.png">
<br><br>
<input type="submit" id="sub2" style="margin-top: -20px;cursor: not-allowed;" class="btn btn-light btn-sm btn-radius" class="frmImageUpload" disabled >
</form>
<a href="listImages.php" id="button" style="margin-bottom: 10px; margin-top: 10px;"
class="btn btn-light btn-sm btn-radius"> View </a>
</div>
</div>
<div class="card" style="border: 3px outset black">
<div>
<mark style="border: 3px outset black">View Collection of Funds : </mark>
<br><br><br></div>
<div class="butt" style="margin-left: 70px; margin-right: 70px; text-align: center;border: 3px solid brown;">
<a href="https://dashboard.razorpay.com/#/access/signin" id="button" class="btn btn-light btn-sm btn-radius"
class="btn btn-primary btn-xs specialbuttonlabel">Payment </a>
<a href="complaint.php" id="button" class="btn btn-light btn-sm btn-radius"
class="btn btn-primary btn-xs specialbuttonlabel">Complaints </a>
</div>
</div>
</div>
</div>
</body>
</html><file_sep><?php
include 'login.php';
include 'database.php';
date_default_timezone_set('Asia/Kolkata');
$logout_date = date("Y-m-d");
$logout_time = date("H:i:s");
$kyurie = "update login_details set logout_time= '$logout_time' and logout_date = '$logout_date'";
$store=mysqli_query($conn , $kyurie);
header('location:index.php');
?><file_sep><!DOCTYPE html>
<html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<!--M E T A T A G S-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="keywords" content="footer, address, phone, icons" />
<!-- LINKS-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="Astyle.css">
<link href="/css/ladda-themeless.min.css" rel="stylesheet">
<link rel="icon" href="logo.png" type="image/icon type">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
<link href="http://fonts.googleapis.com/css?family=Cookie" rel="stylesheet" type="text/css">
<link href="./Themesfinity's CSS Button_files/bootstrap.min.css" rel="stylesheet">
<link href="./Themesfinity's CSS Button_files/buttons.css" rel="stylesheet">
<link href="./Themesfinity's CSS Button_files/style..css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<title> View Notice</title>
</head>
<body>
<!--header-->
<div class="header">
<a href="admin1.php" class="logo"> <img src="images/logo.png"> </a>
<span>
<b><p style="font-size:30px;color:yellow; font: outline; font-family: Georgia, 'Times New Roman', Times, serif; margin-left: 30px;" >GOKULDHAM COOPERATIVE HOUSING SOCIETY</p></b>
</span>
<button id="button1" class="btn btn-primary btn-xs"
style="cursor:context-menu; font-size:15px;color: white;background-color:teal;float: right; margin-left: 150px;margin-top: 5px; font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;"><i
class="fa fa-user"></i> Hello <NAME>!</button>
<a href="logout.php" class="btn btn-danger btn-xs"
style="background-color:#f14e4e; font-size:15px; float: right;margin-right: -315px; margin-top: 65px;color: white;"
class="btn btn-primary btn-xs specialbuttonlabel"> <i class="fa fa-sign-out">Logout</i></a>
</div>
<a href="table.php" class="btn btn-danger btn-sm btn-radius" style="background-color:white; margin-bottom:5px; margin-top:30px;align:left;"><i class="fa fa-reply"> Go Back</i></a>
<?php
// Database Connection
include 'database.php';
//Check for connection error
$fileid=@$_GET['fileid'];
$select = "SELECT * FROM `infopdf` where fileid ='$fileid'";
$result = $conn->query($select);
while($row = $result->fetch_object()){
$pdf = $row->filename;
$path = $row->directory;
}
?>
<br/><br/>
<div style="height: 591px;">
<iframe src="<?php echo $path.$pdf; ?>" width="100%" height="100%">
</iframe>
</div>
</body>
</html><file_sep><?php
if(!isset($_SERVER['HTTP_REFERER'])){
// redirect them to your desired location
header('location:main.php');
exit;
}
?>
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '<EMAIL>'; // SMTP username
$mail->Password = '<PASSWORD>'; // SMTP password
$mail->SMTPSecure = "tls"; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('<EMAIL>', '<EMAIL>');
// $mail->addAddress('<EMAIL>', '<NAME>');
$connection = mysqli_connect("localhost", "id15549943_aks", "Aks#372936aks") or die("Error".mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "id15549943_smartsociety") or die("Error".mysqli_error());
$sql = mysqli_query($connection, "SELECT email from members");
while ($row=mysqli_fetch_array($sql)) {
$to[] = $row['email'];
}
foreach($to as $email) {
$mail->addAddress($email);
}
// Add a recipient
// $mail->addAddress('<EMAIL>'); // Name is optional
// $mail->addReplyTo('<EMAIL>', 'Information');
// $mail->addCC('<EMAIL>');
// $mail->addBCC('<EMAIL>');
// Attachments
//$mail->addAttachment('notice.pdf'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$date = date("d-m-Y");
$month=date("F",$date);
$year=date("Y",$date);
$link="localhost/smartsociety/complaints.html";
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'MAINTAINANCE PAYMENT REMINDER';
$mail->Body = 'Hello Member, This is a gentle reminder to pay your maintainance outstanding amount for the month of '.$month.'. Kindly ignore if payed.
For any queries and griviences <a href="$link">click here</a>
This is an auto generated email. Please do not reply.';
//$mail->AltBody = 'Hello,Please find the below attached latest notice.Meeting on saturday, please attend.';
$mail->send();
echo '<script>alert("MAIL SENT!")</script>';
echo '<script>window.location="admin1.php"</script>';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
echo '<script>alert("ERROR OCCURED WHILE SENDING MAIL!")</script>';
echo '<script>window.location="admin1.php"</script>';
}
?><file_sep><?php
include_once 'database.php';
if(count($_POST)>0) {
mysqli_query($conn,"UPDATE members set userid='" . $_POST['userid'] . "', name='" . $_POST['name'] . "', phone='" . $_POST['phone'] . "', email='" . $_POST['email'] . "' ,dob='" . $_POST['dob'] . "' ,resident='" . $_POST['resident'] . "', no='" . $_POST['no'] . "',parking='" . $_POST['parking'] . "' WHERE userid='" . $_POST['userid'] . "'");
$message = "Record Modified Successfully";
}
$result = mysqli_query($conn,"SELECT * FROM members WHERE userid='" . $_GET['userid'] . "'ORDER BY userid ASC");
$row= mysqli_fetch_array($result);
?>
<html>
<head>
<title>Update Data</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="Astyle.css">
<link href="./Themesfinity's CSS Button_files/bootstrap.min.css" rel="stylesheet">
<link href="./Themesfinity's CSS Button_files/buttons.css" rel="stylesheet">
<link href="./Themesfinity's CSS Button_files/style..css" rel="stylesheet">
<script type = "text/javascript">
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
</script>
</head>
<body>
<!--header-->
<div class="header">
<a href="admin1.php" class="logo"> <img src="logo.jpg"> </a>
<span>
<b><p style="font-size:30px;color:yellow; font: outline; font-family: Georgia, 'Times New Roman', Times, serif; margin-left: 30px;" >GOKULDHAM COOPERATIVE HOUSING SOCIETY</p></b>
</span>
<button id="button1" class="btn btn-primary btn-xs"
style="cursor:context-menu; font-size:15px;color: white;background-color:teal;float: right; margin-left: 150px;margin-top: 5px; font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;"><i
class="fa fa-user"></i> Hello <NAME>!</button>
<a href="logout.php" class="btn btn-danger btn-xs"
style="background-color:#f14e4e; font-size:15px; float: right;margin-right: -315px; margin-top: 65px;color: white;"
class="btn btn-primary btn-xs specialbuttonlabel"> <i class="fa fa-sign-out">Logout</i></a>
</div>
<div style="margin-top: 10%;text-align: center;border: 2px outset black;margin-left:250px;margin-bottom: 2%;margin-right:250px;">
<a href="update.php" class="btn btn-danger btn-sm btn-radius" style="background-color:white;margin-bottom:5px;margin-top:2px;align:left;float: left;"><i class="fa fa-reply"> Go Back</i></a><br><br>
<form name="frmUser" method="post" action="">
<div><?php if(isset($message)) { echo $message; } ?> </div>
<div style="padding-bottom:5px;">
<a href="update.php">Member List</a>
</div>
Room NO : <br>
<input type="hidden" name="userid" class="txtField" value="<?php echo $row['userid']; ?>">
<input type="text" name="userid" value="<?php echo $row['userid']; ?>">
<br>
Name: <br>
<input type="text" name="name" class="txtField" value="<?php echo $row['name']; ?>">
<br>
Phone No :<br>
<input type="text" name="phone" class="txtField" value="<?php echo $row['phone']; ?>">
<br>
Email ID :<br>
<input type="text" name="email" class="txtField" value="<?php echo $row['email']; ?>">
<br>
Date Of Birth :<br>
<input type="date" name="dob" class="txtField" value="<?php echo $row['dob']; ?>">
<br>
Residing Year :<br>
<input type="text" name="resident" class="txtField" value="<?php echo $row['resident']; ?>">
<br>
No of Residence :<br>
<input type="number" name="no" class="txtField" value="<?php echo $row['no']; ?>">
<br>
Parking Lot :<br>
<input type="text" name="parking" class="txtField" value="<?php echo $row['parking']; ?>">
<br>
<input type="submit" name="submit" value="Submit" class="btn btn-outline-danger" style="margin-left: 1%;margin-bottom: 2%;">
</form>
</div>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<title>SMART SOCIETY</title>
<!--M E T A T A G S-->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- LINKS-->
<link rel="stylesheet" href="main.css">
<link rel="icon" href="images/logo.png" type="image/icon type">
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
<link href='https://fonts.googleapis.com/css?family=Bevan' rel='stylesheet'>
<link href='https://fonts.googleapis.com/css?family=Aladin' rel='stylesheet'>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="http://fonts.googleapis.com/css?family=Cookie" rel="stylesheet" type="text/css">
<script src="nav.js"></script>
</head>
<body style="background-color: white;">
<nav>
<div class="logo">
<img src="images/logo.png" alt="Logo Image">
</div>
<div class="hamburger" id="hamburger">
<div class="line1"></div>
<div class="line2"></div>
<div class="line3"></div>
</div>
<ul class="nav-links">
<li><a href="main.php">ABOUT</a></li>
<li><a href="facilities.html">FACILITIES</a></li>
<li><a href="complaints.html">COMPLAINTS</a></li>
<li><a href="memdetails.php">MEMBER DETAILS</a></li>
<li><a href="pay.php">PAYMENTS</a></li>
</ul>
</nav>
<!--TOP BOX -->
<div class="top-container">
<div class="form-popup" id="myForm">
<form action="login.php" class="form-container" method="POST">
<h1
style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;">
ADMIN LOGIN</h1>
<label for=" email"><b><i class="fas fa-user"></i>Email </b></label>
<input type="text" placeholder="Enter Email" name="username" required>
<br> <label for="psw"><b><i class="fas fa-lock"></i>Password </b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<button type="submit" value="submit" class="btn">Login</button>
</form>
</div>
<div class="slideshow-container">
<div class="slideshow_wrapper">
<div class="slideshow">
<div class="slide_one slide">
<img src="images/society.jpg" />
</div>
<div class="slide_two slide">
<img src="images/ss2.jpg" />
</div>
<div class="slide_three slide">
<img class="slide_img" src="images/ss3.jpg" />
</div>
</div>
</div>
</div>
<div id="notice-box" class="notice-box">
<div style="border: 3px solid green; background-color: lightgoldenrodyellow;">
<h2 style=" color: green; font-family: Georgia, 'Times New Roman', Times, serif; " class="glow"><i
class="fa fa-bullhorn "></i>Notice </h2>
</div>
<marquee direction="up" scrollamount="3">
<a href="notice.pdf"> NOTICE1</a> <br> <br>
<a href="notice.pdf"> NOTICE2</a> <br> <br>
<a href="notice.pdf"> NOTICE3</a>
</marquee>
</div>
</div>
</div>
<!--main page contents-->
<div class="welcome">
<h1>WELCOME TO <NAME></h1>
</div>
<!--image gallery-->
<div id="container">
<div class="gallery">
<a href="" target="_blank"><img src="images/ss1.jpg"></a>
</div>
<div class="gallery">
<a href="" target="_blank"><img src="images/ss2.jpg"></a>
</div>
<div class="gallery">
<a href="" target="_blank"><img src="images/ss3.jpg"></a>
</div>
<div class="gallery">
<a href="" target="_blank"><img src="images/ss4.jpg"></a>
</div>
<div class="gallery">
<a href="" target="_blank"><img src="images/pool.jpg"></a>
</div>
<div class="gallery">
<a href="" target="_blank"><img src="images/play.jpg"></a>
</div>
</div>
<!--text text-->
<div class="text">
<img src="images/society.jpg"
style="float: right; height: 300px; width:350px; border: 3px solid black; margin: 3px;">
<h1 style="margin-left:15px; color: green;">About</h1>
<p>
<br> A society is a group of individuals involved in persistent social interaction, or a large social group
sharing
the same spatial or social territory, typically subject to the same political authority and dominant
cultural
expectations. Societies are characterized by patterns of relationships (social relations) between
individuals
who share a distinctive culture and institutions; a given society may be described as the sum total of
such
relationships among its constituent of members. In the social sciences, a larger society often exhibits
stratification or dominance patterns in subgroups.
More broadly, and especially within structuralist thought, a society may be illustrated as an economic,
social,
industrial or cultural infrastructure, made up of, yet distinct from, a varied collection of
individuals. In
this regard society can mean the objective relationships people have with the material world and with
other
people, rather than "other people" beyond the individual and their familiar social environment.
A society is a group of individuals involved in persistent social interaction, or a large social group
sharing
the same spatial or social territory, typically subject to the same political authority and dominant
cultural
expectations. Societies are characterized by patterns of relationships (social relations) between
individuals
who share a distinctive culture and institutions; a given society may be described as the sum total of
such
relationships among its constituent of members. In the social sciences, a larger society often exhibits
stratification or dominance patterns in subgroups.
More broadly, and especially within structuralist thought, a society may be illustrated as an economic,
social,
industrial or cultural infrastructure, made up of, yet distinct from, a varied collection of
individuals. In
this regard society can mean the objective relationships people have with the material world and with
other
people, rather than "other people" beyond the individual and their familiar social environment.
</p>
</div>
<div class="text1">
<img src="images/plan.jpg" style="float: right; height: 400px; width:350px;border: 3px solid black; margin: 3px;">
<h2 style="margin-left:15px; color: green ;">FLOOR PLAN</h2>
<p>
<br> A society is a group of individuals involved in persistent social interaction, or a large social group
sharing
the same spatial or social territory, typically subject to the same political authority and dominant
cultural
expectations. Societies are characterized by patterns of relationships (social relations) between
individuals
who share a distinctive culture and institutions; a given society may be described as the sum total of
such
relationships among its constituent of members. In the social sciences, a larger society often exhibits
stratification or dominance patterns in subgroups.
More broadly, and especially within structuralist thought, a society may be illustrated as an economic,
social,
industrial or cultural infrastructure, made up of, yet distinct from, a varied collection of
individuals. In
this regard society can mean the objective relationships people have with the material world and with
other
people, rather than "other people" beyond the individual and their familiar social environment.
A society is a group of individuals involved in persistent social interaction, or a large social group
sharing
the same spatial or social territory, typically subject to the same political authority and dominant
cultural
expectations. Societies are characterized by patterns of relationships (social relations) between
individuals
who share a distinctive culture and institutions; a given society may be described as the sum total of
such
relationships among its constituent of members. In the social sciences, a larger society often exhibits
stratification or dominance patterns in subgroups.
More broadly, and especially within structuralist thought, a society may be illustrated as an economic,
social,
industrial or cultural infrastructure, made up of, yet distinct from, a varied collection of
individuals. In
this regard society can mean the objective relationships people have with the material world and with
other
people, rather than "other people" beyond the individual and their familiar social environment.
</p>
</div>
<!--FOOTER-->
<footer class="footer-distributed">
<div class="footer-left">
<h3>GOKULDHAM<span>Society</span></h3>
<p class="footer-links">
<a href="main.html" class="link-1">About</a>
<a href="facilities.html">Facilities</a>
<a href="memdetails.php">Members</a>
<a href="complaints.html">Complaints</a>
<a href="payment.php">Pay Maintaiance</a>
</p>
<p class="footer-company-name">Gokuldham scoiety © 2020</p>
</div>
<div class="footer-center">
<div>
<i class="fa fa-map-marker"></i>
<p>Film City Complex, Aarey Colony,<span>Goregaon, Mumbai, Maharashtra 400065</span></p>
</div>
<div>
<i class="fa fa-phone"></i>
<p> 022 2345678</p>
</div>
<div>
<i class="fa fa-envelope"></i>
<p><a href="mailto:<EMAIL>"><EMAIL></a></p>
</div>
</div>
<div class="footer-right">
</div>
</footer>
</body>
</html><file_sep>
<?php
session_start();
if(isset($_POST['name'])){
$name=$_POST['name'] ;
$email=$_POST['email'] ;
$userid=$_POST['userid'] ;
$number=$_POST['number'] ;
$type=$_POST['type'] ;
$date=$_POST['date'];
$amount=$_POST['amount'] ;
$connect=mysqli_connect("localhost" , "root" , "" , "smartsociety");
$query = mysqli_query($connect,"insert into payment (userid,name,email,number,type,date,amount)
values ('$userid','$name','$email','$number','$type','$date','$amount')");
if(!$query)
{
echo '<script>alert("ERROR OCCURED TRY AGAIN")</script>';
echo '<script>window.location="payment.php"</script>';
}
else{
echo '<script>alert("PAYMENT SUCCESSFULL")</script>';
echo '<script>window.location="Confirm.html"</script>';
header("location: https://rzp.io/l/2vH4Sdoyw");
}
}
else{
header("Location: http://localhost/smartsociety/index.php");
}
/*
<div class="razorpay-embed-btn" data-url="https://pages.razorpay.com/pl_G2FWCReR1V6tAI/view"
data-text="Pay Now" data-color="#528FF0" data-size="large">
<script>
(function(){
var d=document; var x=!d.getElementById('razorpay-embed-btn-js')
if(x){ var s=d.createElement('script'); s.defer=!0;s.id='razorpay-embed-btn-js';
s.src='https://cdn.razorpay.com/static/embed_btn/bundle.js';d.body.appendChild(s);} else{var rzp=window['__rzp__'];
rzp && rzp.init && rzp.init()}})();
</script>
</div> */
|
bc7508cf0fe088ef0cd9c8c9d0435b1ce2602a24
|
[
"Markdown",
"HTML",
"PHP"
] | 15
|
PHP
|
ateefradio/smartsociety.github.io
|
5b533f0895ac9a1e3690bf600ab0c839d29fa948
|
eee7604f1053925faf7de79fb19a6872f5014b53
|
refs/heads/master
|
<file_sep>//nav
const navIcon = document.getElementById('navIcon')
const nav = document.getElementById('navsub')
nav.style.display = 'none'
navIcon.addEventListener('click', () => {
if(nav.style.display == 'none') {
navIcon.classList.add('cross')
nav.style.display = 'block'
} else {
navIcon.classList.remove('cross')
nav.style.display = 'none'
}
})
////////////////////////////////
//section
const sectionCalc = document.querySelector('.calc')
const subSection = document.querySelector('.subSection')
const firstMoveSection = document.querySelector('.firstMove')
subSection.style.display = 'none'
sectionCalc.addEventListener('click', () => {
if(subSection.style.display == 'none') {
subSection.style.display = 'block'
subSection.style.top = '194px'
firstMoveSection.style.marginTop = '110px'
} else {
subSection.style.display = 'none'
subSection.style.top = '50px'
firstMoveSection.style.marginTop = '0'
}
})
|
1be4adeb28f1aafbac9b7246745458065d9c9629
|
[
"JavaScript"
] | 1
|
JavaScript
|
azemlyankin1/DTP
|
19cd61a5ce46b4baa303039f69db0ffbb1463dcb
|
5a1b0f018e47866d7c4783e53f27156d1dcd0ef9
|
refs/heads/master
|
<file_sep>import React, {Component} from 'react'
import {View} from '@tarojs/components'
export default class List extends Component {
constructor() {
super(...arguments)
this.state = {
current: 0
}
}
handleClick(value) {
this.setState({
current: value
})
}
render() {
return (
<View className='index'>
电影
</View>
)
}
}
<file_sep>import React, {Component} from 'react'
import {View} from '@tarojs/components'
import Taro from '@tarojs/taro'
import {AtButton} from "taro-ui";
export default class Index extends Component {
constructor() {
super(...arguments)
this.state = {
current: 0
}
}
naviTo() {
Taro.navigateTo({
url: '/pages/home/movie/list'
})
}
render() {
return (
<View className='index'>
首页
<AtButton type='primary' size='small' onClick={this.naviTo}>电影</AtButton>
</View>
)
}
}
<file_sep>export default {
navigationBarTitleText: '电影'
}
|
46a42a83d88520d010b874ea7ab2725bdb1e9b66
|
[
"JavaScript"
] | 3
|
JavaScript
|
yueyue10/taro_demo
|
359571cfb9c55242565b93fa59ab9f20da9365b6
|
80bdcfc10d1f6ec51e448581190d1fa6a8969dcb
|
refs/heads/master
|
<repo_name>dentriger/game<file_sep>/src/Security/UserProvider.php
<?php
/**
* Created by PhpStorm.
* User: andre
* Date: 09.09.2018
* Time: 17:15
*/
namespace App\Security;
use App\Controller\UserController;
use App\Entity\User;
use App\Repository\UserRepository;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUserProvider;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
class UserProvider implements OAuthAwareUserProviderInterface, UserProviderInterface
{
protected $userRepository;
public function __construct(UserRepository $userRepository){
$this->userRepository = $userRepository;
}
public function getUsernameForApiKey($apiKey)
{
// Look up the username based on the token in the database, via
// an API call, or do something entirely different
$username = 'ad';
return $username;
}
public function loadUserByUsername($username)
{
return $this->userRepository->findOneBy(['email'=>$username]);
}
public function refreshUser(UserInterface $user)
{
$user = $this->loadUserByUsername($user->getEmail());
return $user;
}
public function supportsClass($class)
{
return User::class === $class;
}
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$user = $this->userRepository->findOneBy(['uid' => $response->getUsername()]);
if(is_null($user)) {
$user = $this->userRepository->createUserFromResponse($response);
}
return $user;
}
}<file_sep>/src/Controller/UserController.php
<?php
namespace App\Controller;
use App\Entity\User;
use App\Entity\Wallet;
use App\Security\UserAuthenticationListener;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
class UserController extends Controller
{
}
<file_sep>/src/Entity/Bet.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\BetRepository")
*/
class Bet
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $user_id;
/**
* @ORM\Column(type="string", length=255)
*/
private $game_type;
/**
* @ORM\Column(type="integer")
*/
private $game_id;
/**
* @ORM\Column(type="integer")
*/
private $stake;
/**
* @ORM\Column(type="string")
*/
private $anticipated_event;
/**
* @ORM\Column(type="string", length=255)
*/
private $status;
public function getId(): ?int
{
return $this->id;
}
public function getUserId(): ?int
{
return $this->user_id;
}
public function setUserId(int $user_id): self
{
$this->user_id = $user_id;
return $this;
}
public function getGameType(): ?string
{
return $this->game_type;
}
public function setGameType(string $game_type): self
{
$this->game_type = $game_type;
return $this;
}
public function getStake(): ?int
{
return $this->stake;
}
public function setStake(int $stake): self
{
$this->stake = $stake;
return $this;
}
/**
* @return mixed
*/
public function getGameId()
{
return $this->game_id;
}
/**
* @param mixed $game_id
*/
public function setGameId($game_id): void
{
$this->game_id = $game_id;
}
/**
* @return mixed
*/
public function getAnticipatedEvent()
{
return $this->anticipated_event;
}
/**
* @param mixed $anticipated_event
*/
public function setAnticipatedEvent($anticipated_event): void
{
$this->anticipated_event = $anticipated_event;
}
public function getStatus(): ?string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
}
<file_sep>/src/Controller/DoubleGameController.php
<?php
/**
* Created by PhpStorm.
* User: andre
* Date: 10.09.2018
* Time: 12:27
*/
namespace App\Controller;
use App\Entity\Bet;
use App\Entity\Wallet;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class DoubleGameController extends Controller
{
/**
* @var \App\Repository\BetRepository
*/
private $bet_repository;
/**
* @var \App\Repository\WalletRepository
*/
private $wallet_repository;
public function __construct()
{
$this->bet_repository = $this->getDoctrine()->getRepository(Bet::class);
$this->wallet_repository = $this->getDoctrine()->getRepository(Wallet::class);
}
public function setBet(Request $request)
{
try {
$user = $this->getUser();
if (is_null($user)) {
throw new \Exception('Please login');
}
if ($this->wallet_repository->getUserWallet($user->getUid())->getBalance() < $request->query->get('bet_amount')) {
throw new \Exception('Not enough money');
}
$bet = $this->bet_repository->createBetFromRequest($request);
} catch (\Exception $exception) {
return Response::create($exception->getMessage(), 500);
}
return Response::create('Bet settled', 200);
}
}<file_sep>/src/Repository/UserRepository.php
<?php
namespace App\Repository;
use App\Entity\User;
use App\Entity\Wallet;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* @method User|null find($id, $lockMode = null, $lockVersion = null)
* @method User|null findOneBy(array $criteria, array $orderBy = null)
* @method User[] findAll()
* @method User[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class UserRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, User::class);
}
public function createUserFromResponse(UserResponseInterface $response) {
$user = new User();
$user->setUid($response->getUsername());
$user->setFirstName($response->getFirstName());
$user->setLastName($response->getLastName());
$user->setPhoto($response->getProfilePicture());
$user->setPhotoRec($response->getProfilePicture());
$user->setEmail($response->getEmail());
$user->setHash(md5(getenv('VK_CLIENT_ID').$response->getUsername().getenv('VK_SECRET_KEY')));
$wallet = new Wallet();
$wallet->setUserId($user->getUid());
$this->_em->persist($user);
$this->_em->persist($wallet);
$this->_em->flush();
return $user;
}
// /**
// * @return User[] Returns an array of User objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('u')
->andWhere('u.exampleField = :val')
->setParameter('val', $value)
->orderBy('u.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?User
{
return $this->createQueryBuilder('u')
->andWhere('u.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
<file_sep>/bin/double.php
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Repository\BetRepository;
use App\Repository\GameRepository;
use App\Repository\WalletRepository;
require dirname(__DIR__) . '/vendor/autoload.php';
$double = new \App\Services\DoubleGame();
$double->start();<file_sep>/src/Services/DoubleGame.php
<?php
/**
* Created by PhpStorm.
* User: andre
* Date: 10.09.2018
* Time: 23:32
*/
namespace App\Services;
use App\Entity\Game;
use App\Repository\BetRepository;
use App\Repository\GameRepository;
use App\Repository\UserRepository;
use App\Repository\WalletRepository;
use App\Service\GameService;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use WebSocket\Client;
use WebSocket\BadOpcodeException;
class DoubleGame extends GameService
{
private $socket;
private $round_time;
private $prize_segments = [
1 => 0,
2 => 1,
3 => 8,
4 => 2,
5 => 9,
6 => 3,
7 => 10,
8 => 4,
9 => 11,
10 => 5,
11 => 12,
12 => 6,
13 => 13,
14 => 7,
15 => 14
];
protected $gameRules = [
'green' => 14,
'red' => 2,
'black' => 2,
];
public function __construct(GameRepository $gameRepository, BetRepository $betRepository, WalletRepository $walletRepository)
{
$this->socket = new Client('ws://localhost:8080');
$this->round_time = 30;
parent::__construct($gameRepository, $walletRepository, $betRepository);
}
public function startGame()
{
try {
echo "New Game\n";
$game = $this->createNewGame();
$current_time = $this->round_time;
while ($current_time >= 0) {
$msg = DoubleGame::createMessage('double', ['timer' => $current_time]);
$this->socket->send($msg);
$current_time -= 1;
sleep(1);
}
$segment = $this->getPrizeSegment();
$this->closeGame($game, $this->prize_segments[$segment], $this->getColor($segment));
$msg = DoubleGame::createMessage('double', ['segment' => $segment]);
$this->socket->send($msg);
sleep(10);
$this->calculateRates($game);
$this->startGame();
} catch (BadOpcodeException $e) {
echo $e->getMessage();
} catch (\Exception $e) {
echo $e->getMessage();
} finally {
//$this->startGame();
}
}
public function getRandomNumber()
{
return rand(0, 14);
}
private function getPrizeSegment()
{
return array_search($this->getRandomNumber(), $this->prize_segments);
}
public function getMultiplier($event)
{
return $this->gameRules[$event];
}
public function getColor($segment)
{
if($this->prize_segments[$segment] == 0) {
return 'green';
}
if($this->prize_segments[$segment] <= 7) {
return 'red';
}
if ($this->prize_segments[$segment] >= 8) {
return 'black';
}
}
}<file_sep>/src/Entity/User.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUser;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $uid;
/**
* @ORM\Column(name="first_name", type="string", length=255)
*/
private $firstName;
/**
* @ORM\Column(name="last_name", type="string", length=255)
*/
private $lastName;
/**
* @ORM\Column(type="string", length=255)
*/
private $photo;
/**
* @ORM\Column(type="string", length=255)
*/
private $photo_rec;
/**
* @ORM\Column(type="string", length=255)
*/
private $hash;
/**
* @ORM\Column(name="email", type="string", length=255, unique=true)
*/
private $email;
/**
* @ORM\Column(type="array")
*/
private $roles = ['ROLE_USER'];
/**
* @ORM\Column(name="is_active", type="boolean")
*/
private $isActive = false;
/**
* @ORM\Column(name="is_test", type="boolean")
*/
private $isTest = false;
public function getId(): ?int
{
return $this->id;
}
public function getUid(): ?int
{
return $this->uid;
}
public function setUid(int $uid): self
{
$this->uid = $uid;
return $this;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(string $firstName): self
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(string $lastName): self
{
$this->lastName = $lastName;
return $this;
}
public function getPhoto(): ?string
{
return $this->photo;
}
public function setPhoto(string $photo): self
{
$this->photo = $photo;
return $this;
}
public function getPhotoRec(): ?string
{
return $this->photo_rec;
}
public function setPhotoRec(string $photo_rec): self
{
$this->photo_rec = $photo_rec;
return $this;
}
public function getHash(): ?string
{
return $this->hash;
}
public function setHash(string $hash): self
{
$this->hash = $hash;
return $this;
}
/**
* @return mixed
*/
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @return mixed
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive): void
{
$this->isActive = $isActive;
}
/**
* @return mixed
*/
public function getIsTest()
{
return $this->isTest;
}
/**
* @param mixed $isTest
*/
public function setIsTest($isTest): void
{
$this->isTest = $isTest;
}
/**
* @param mixed $roles
*/
public function setRoles($roles): void
{
$this->roles = $roles;
}
/** @see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->uid,
$this->firstName,
$this->lastName,
$this->photo,
$this->photo_rec,
$this->email,
$this->isTest,
$this->isActive,
$this->roles
// see section on salt below
// $this->salt,
));
}
/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->uid,
$this->firstName,
$this->lastName,
$this->photo,
$this->photo_rec,
$this->email,
$this->isTest,
$this->isActive,
$this->roles
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
public function getPassword()
{
// TODO: Implement getPassword() method.
}
public function getRoles()
{
return $this->roles;
}
public function getSalt()
{
// TODO: Implement getSalt() method.
}
public function getUsername()
{
return $this->getUid();
}
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
}
<file_sep>/src/Entity/Wallet.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\WalletRepository")
*/
class Wallet
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $user_id;
/**
* @ORM\Column(type="integer")
*/
private $balance = 0;
public function getId(): ?int
{
return $this->id;
}
public function getUserId(): ?int
{
return $this->user_id;
}
public function setUserId(int $user_id): self
{
$this->user_id = $user_id;
return $this;
}
public function getBalance(): ?int
{
return $this->balance;
}
public function setBalance(int $balance): self
{
$this->balance = $balance;
return $this;
}
}
<file_sep>/src/Controller/DefaultController.php
<?php
/**
* Created by PhpStorm.
* User: andre
* Date: 06.09.2018
* Time: 14:36
*/
namespace App\Controller;
use App\Entity\Wallet;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexRender()
{
return $this->render('default/index.html.twig', [
'wallet'=>$this->getUserWallet()
]);
}
/**
* @Route("/profile", name="profile")
*/
public function profileRender()
{
return $this->render('user/profile.html.twig', [
'wallet'=>$this->getUserWallet()
]);
}
/**
* @Route("/games", name="games")
*/
public function gamesRender()
{
return $this->render('default/games.html.twig', [
'wallet'=>$this->getUserWallet()
]);
}
/**
* @Route("/games/nvuti", name="nvuti")
*/
public function nvutiGameRender()
{
return $this->render('games/nvuti.html.twig', [
'wallet'=>$this->getUserWallet()
]);
}
/**
* @Route("/games/double", name="double")
*/
public function doubleGameRender()
{
return $this->render('games/double.html.twig', [
'wallet'=>$this->getUserWallet()
]);
}
/**
* @Route("/games/jackpot", name="jackpot")
*/
public function jackpotGameRender()
{
return $this->render('games/jackpot.html.twig', [
'wallet'=>$this->getUserWallet()
]);
}
public function getUserWallet()
{
$user = $this->getUser();
$uid = $user ? $user->getUid() : null;
$wallet = $this->getDoctrine()->getRepository(Wallet::class)->findOneBy(['user_id'=>$uid]);
return $wallet;
}
}<file_sep>/src/Command/DoubleGameCommand.php
<?php
/**
* Created by PhpStorm.
* User: andre
* Date: 23.09.2018
* Time: 18:53
*/
namespace App\Command;
use App\Repository\BetRepository;
use App\Repository\GameRepository;
use App\Repository\WalletRepository;
use App\Services\DoubleGame;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DoubleGameCommand extends Command
{
protected static $defaultName = 'double:start';
protected $gameRepository;
protected $betRepository;
protected $walletRepository;
public function __construct(GameRepository $gameRepository, BetRepository $betRepository, WalletRepository $walletRepository)
{
$this->gameRepository = $gameRepository;
$this->betRepository = $betRepository;
$this->walletRepository = $walletRepository;
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$double_game = new DoubleGame($this->gameRepository, $this->betRepository, $this->walletRepository);
$double_game->startGame();
}
}<file_sep>/src/Entity/Game.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\GameRepository")
*/
class Game
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\Column(type="datetime")
*/
private $time;
/**
* @ORM\Column(type="string", length=255)
*/
private $status;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $win_number;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $anticipated_event;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getTime(): ?\DateTime
{
return $this->time;
}
public function setTime(\DateTime $time): self
{
$this->time = $time;
return $this;
}
public function getStatus(): ?string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
public function getWinNumber(): ?int
{
return $this->win_number;
}
public function setWinNumber(?int $win_number): self
{
$this->win_number = $win_number;
return $this;
}
/**
* @return mixed
*/
public function getAnticipatedEvent()
{
return $this->anticipated_event;
}
/**
* @param mixed $anticipated_event
*/
public function setAnticipatedEvent($anticipated_event): void
{
$this->anticipated_event = $anticipated_event;
}
}
<file_sep>/src/Repository/BetRepository.php
<?php
namespace App\Repository;
use App\Entity\Bet;
use App\Entity\User;
use App\Entity\Wallet;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* @method Bet|null find($id, $lockMode = null, $lockVersion = null)
* @method Bet|null findOneBy(array $criteria, array $orderBy = null)
* @method Bet[] findAll()
* @method Bet[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class BetRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Bet::class);
}
public function createBetFromRequest(Request $request)
{
$bet = new Bet();
$user_id = $request->query->get('user_id');
$bet_amount = $request->query->get('bet_amount');
$bet->setUserId($user_id);
$bet->setGameType($request->query->get('game_type'));
$bet->setStake($bet_amount);
$bet->setStatus('pending');
$bet->setGameId($request->query->get('game_id'));
$bet->setAnticipatedEvent($request->query->get('anticipated_event'));
$this->_em->persist($bet);
$this->_em->getRepository(Wallet::class)->updateBalance($user_id, -$bet_amount);
$this->_em->flush();
return $bet;
}
public function updateBetStatus(Bet $bet, $status)
{
$bet->setStatus($status);
$this->_em->persist($bet);
$this->_em->flush();
}
}
<file_sep>/src/Service/GameService.php
<?php
/**
* Created by PhpStorm.
* User: andre
* Date: 23.09.2018
* Time: 18:04
*/
namespace App\Service;
use App\Entity\Bet;
use App\Entity\Game;
use App\Repository\BetRepository;
use App\Repository\GameRepository;
use App\Repository\WalletRepository;
abstract class GameService
{
protected $betRepository;
protected $walletRepository;
protected $gameRepository;
public function __construct(GameRepository $gameRepository, WalletRepository $walletRepository, BetRepository $betRepository)
{
$this->gameRepository = $gameRepository;
$this->walletRepository = $walletRepository;
$this->betRepository = $betRepository;
}
abstract function startGame();
abstract function getMultiplier($event);
public function createNewGame()
{
return $this->gameRepository->createGame();
}
public static function createMessage($msg, $data)
{
$message = [static::class, 'message' => $msg, 'data' => $data];
return json_encode($message);
}
public function calculateRates(Game $game)
{
$game_bets = $this->betRepository->findBy(['game_id' => $game->getId()]);
foreach ($game_bets as $bet) {
if ($this->isBetWin($bet, $game)){
$this->betRepository->updateBetStatus($bet, 'win');
$this->walletRepository->updateBalance($bet->getUserId(), $bet->getStake(),$this->getMultiplier($game->getAnticipatedEvent()));
} else {
$this->betRepository->updateBetStatus($bet, 'lost');
}
}
}
public function isBetWin(Bet $bet, Game $game)
{
return $bet->getAnticipatedEvent() == $game->getAnticipatedEvent() ? true : false;
}
public function closeGame(Game $game, $number, $color)
{
$game->setStatus('closed');
$game->setAnticipatedEvent($color);
$game->setWinNumber($number);
$this->gameRepository->updateGame($game);
}
}
|
12a34b569e37fd305100681a9b4ae1d635ea8c4f
|
[
"PHP"
] | 14
|
PHP
|
dentriger/game
|
3ed0fe29e77778c64fe4945d1dcfcc5c9abf6f81
|
8bec45dbd51678058965040e5190f618db699de9
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using EntityFramework.DynamicFilters;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DynamicFiltersTests
{
// Tests related to null comparisons and Nullable<T>.HasValue handling in lambda filters (issue #14)
[TestClass]
public class NullTests
{
/// <summary>
/// Tests a filter that contains an expression (a.DeleteTimestamp == null)
/// which needs to be translated into "is null" in SQL not "= null".
/// </summary>
[TestMethod]
public void NullComparison_EqualsNull()
{
using (var context = new TestContext())
{
var list = context.EntityASet.ToList();
Assert.IsTrue((list.Count == 1) && (list.FirstOrDefault().ID == 1));
}
}
/// <summary>
/// Tests a filter that contains an expression (a.DeleteTimestamp != null)
/// which needs to be translated into "is not null" in SQL not "<> null".
/// </summary>
[TestMethod]
public void NullComparison_NotEqualsNull()
{
using (var context = new TestContext())
{
var list = context.EntityBSet.ToList();
Assert.IsTrue((list.Count == 1) && (list.FirstOrDefault().ID == 2));
}
}
/// <summary>
/// Tests a filter that contains an expression (!a.DeleteTimestamp.HasValue)
/// which needs to be translated into "is null".
/// </summary>
[TestMethod]
public void NullableType_HasValue_NotHasValue()
{
using (var context = new TestContext())
{
var list = context.EntityCSet.ToList();
Assert.IsTrue((list.Count == 1) && (list.FirstOrDefault().ID == 1));
}
}
/// <summary>
/// Tests a filter that contains an expression a.DeleteTimestamp.HasValue
/// which needs to be translated into "is not null".
/// </summary>
[TestMethod]
public void NullableType_HasValue()
{
using (var context = new TestContext())
{
var list = context.EntityDSet.ToList();
Assert.IsTrue((list.Count == 1) && (list.FirstOrDefault().ID == 2));
}
}
#region Models
public class EntityBase
{
public EntityBase()
{
CreateTimestamp = DateTime.Now;
}
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
public DateTime CreateTimestamp { get; set; }
public DateTime? DeleteTimestamp { get; set; }
}
public class EntityA : EntityBase
{}
public class EntityB : EntityBase
{}
public class EntityC : EntityBase
{ }
public class EntityD : EntityBase
{ }
#endregion
#region TestContext
public class TestContext : DbContext
{
public DbSet<EntityA> EntityASet { get; set; }
public DbSet<EntityB> EntityBSet { get; set; }
public DbSet<EntityC> EntityCSet { get; set; }
public DbSet<EntityD> EntityDSet { get; set; }
public TestContext()
: base("TestContext")
{
Database.SetInitializer(new ContentInitializer<TestContext>());
Database.Log = log => System.Diagnostics.Debug.WriteLine(log);
Database.Initialize(false);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Filter to test translating "a.DeleteTimestamp == null" into "DeleteTimestamp is null"
modelBuilder.Filter("EntityAFilter",
(EntityA a, DateTime dt) => ((a.CreateTimestamp <= dt) && ((null == a.DeleteTimestamp) || (a.DeleteTimestamp > dt))),
() => DateTime.Now);
// Filter to test translating "b.DeleteTimestamp != null" into "not (DeleteTimestamp is null)"
// or (hopefully) "DeleteTimestamp is not null"
modelBuilder.Filter("EntityBFilter", (EntityB b) => (b.DeleteTimestamp != null));
// Filter to test translating "!a.DeleteTimestamp.HasValue" into "DeleteTimestamp is null"
modelBuilder.Filter("EntityCFilter",
(EntityC c, DateTime dt) => ((c.CreateTimestamp <= dt) && (!c.DeleteTimestamp.HasValue || (c.DeleteTimestamp > dt))),
() => DateTime.Now);
// Filter to test translating "b.DeleteTimestamp.HasValue" into "not (DeleteTimestamp is null)"
// or (hopefully) "DeleteTimestamp is not null".
// This filter also required special handling when cerating the filter to properly detect that this
// is a property accessor (and thus a lambda/predicate filter) and not a column name filter.
modelBuilder.Filter("EntityDFilter", (EntityD d) => d.DeleteTimestamp.HasValue);
}
}
public class ContentInitializer<T> : DropCreateDatabaseAlways<T>
where T : TestContext
{
protected override void Seed(T context)
{
context.EntityASet.Add(new EntityA { ID = 1 });
context.EntityASet.Add(new EntityA { ID = 2, DeleteTimestamp = DateTime.Now.AddMinutes(-1) });
context.EntityBSet.Add(new EntityB { ID = 1 });
context.EntityBSet.Add(new EntityB { ID = 2, DeleteTimestamp = DateTime.Now.AddMinutes(-1) });
context.EntityCSet.Add(new EntityC { ID = 1 });
context.EntityCSet.Add(new EntityC { ID = 2, DeleteTimestamp = DateTime.Now.AddMinutes(-1) });
context.EntityDSet.Add(new EntityD { ID = 1 });
context.EntityDSet.Add(new EntityD { ID = 2, DeleteTimestamp = DateTime.Now.AddMinutes(-1) });
context.SaveChanges();
}
}
#endregion
}
}
|
4770ef88eef52c8d853210e36311aa17be8afb02
|
[
"C#"
] | 1
|
C#
|
duanjian/EntityFramework.DynamicFilters
|
d74bee4290cb8cf800ae238f8aadd12236115007
|
91e746d577febfdd1cbac6c7a4961fd259996eac
|
refs/heads/master
|
<repo_name>wrcx/npm-vue-component-generator<file_sep>/plopfile.js
const config = require('./generator.config.js');
module.exports = function(plop) {
// Initialize generators
// ============================================
config.generators.forEach(function(generator) {
plop.setGenerator(generator.name, generator.generator);
})
};
<file_sep>/readme.md
## Vue generator
1.Install
`
npm install git+ssh://git@github.com:wrcx/npm-vue-component-generator.git --save
`
2.Create generator.config.json
```
{
"folder": "resources/assets/js/"
}
```
3.Add command to package.json
```
"custom": "cd ./node_modules/npm-vue-generator/ && npm run generator",
```<file_sep>/index.js
'use strict';
/*---------- Dependencies ----------*/
const path = require('path');
const yargs = require('yargs');
const plop = require('plop');
|
ebcfef7db8a29978de3e4aee5b361bcf317c3af1
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
wrcx/npm-vue-component-generator
|
67eff26fdd8f134df982e944544ef9a8ede94784
|
0b4ae4e9b6c4a5daab5deb8b82d2119ae34143fb
|
refs/heads/master
|
<repo_name>wbw20/scrapear<file_sep>/README.md
scrapear
========
A tool for easy web scraping.
<file_sep>/main.js
var request = require('request'),
cheerio = require('cheerio'),
async = require('async'),
format = require('util').format;
var concurrency = 2,
counter = 0,
map = {};
function done() {
console.log(map);
}
module.exports = {
map: function() {
return map;
},
expand: function(url, select, cb) {
counter++;
request(url, function (err, response, body) {
if (err) {
console.err('X');
return
}
var $ = cheerio.load(body);
async.eachLimit($(select), concurrency, function (element, next) {
cb($(element));
next();
});
counter--;
/* finished spidering */
if (counter === 0) {
done();
}
});
}
};
|
fbad0f75cd3ab3350971aef551a5d2b36e0b2157
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
wbw20/scrapear
|
3e1fdb836ccd58b26c0059ca9428481c82a203d8
|
20771766fb422a7dc3172da7490a3f1014ec9dc4
|
refs/heads/master
|
<repo_name>essantos97/projeto-ecompjr<file_sep>/Projeto front Johnny e Emanuel/_controller/adicionaMembroProjeto.php
<?php
require_once( '../_controller/controllerdados.php' );
$emailMembro = $_POST['email'];
$idProjeto = $_POST['idproject'];
$controller = Controllerdados::getInstance();
$controller->addMembro($emailMembro, $idProjeto);
?><file_sep>/Projeto front Johnny e Emanuel/_controller/login.php
<?php
//arquivo de login
// session_start inicia a sessão
if(!isset($_SESSION)){
session_start();
}
require_once( "Controllerdados.php" );
// as variáveis login e senha recebem os dados digitados na página inicial
$login = $_POST[ 'email' ];
$senha = $_POST[ '<PASSWORD>' ];
if (($senha != "" and $senha != null )and( $login != null and $login != "")){
$controller = Controllerdados::getInstance();
$controller->realizalogin($login, $senha);
}else{
header('location:../index.php');
}
<file_sep>/Projeto front Johnny e Emanuel/_util/userdao.php
<?php
if(!isset($_SESSION)){
session_start();
}
//include_once( "seguranca.php" );
require_once( "bd.php" );
class UserDao {
private $banc;
public function __construct() {
}
//READ
function ler( $email, $senha ) {
$banc = Bd::getInstance();
$banc->abrirconexao();
//$sql = pg_query( $obanco, "SELECT * FROM usuarios WHERE email = '{$email}' AND senha = '{$senha}' LIMIT 1 ;" );
$sql = "SELECT * FROM membro WHERE email = '{$email}' AND senha = '{$senha}';";
$resultado = pg_query($sql);
$login_check = pg_num_rows( $resultado );
if($login_check == 0 ){
$banc->fecharconexao();
return null;
}else{
//$resultado = pg_query($sql2);
$banc->fecharconexao();
return $resultado;
}
$banc->fecharconexao();
return null;
}
function cadastrar($nome, $email, $senhaCrip, $cargo, $pontos, $data_nascimento){
$banc = Bd::getInstance();
$obanco = $banc->abrirconexao();
$sql = "INSERT INTO membro(nome, email, senha, cargo, pontos, data_nascimento) VALUES ('$nome', '$email', '$senhaCrip', '$cargo', '$pontos', '$data_nascimento')";
$result = pg_query($obanco, $sql);
if ($result != false ) {
echo "Cadastrado com sucesso!";
$banc->fecharconexao();
return true;
} else {
$banc->fecharconexao();
return false;
echo "<script type='javascript'>alert('Cadastrado com Erro!');";
}
}
function cadastrarProjeto($nomeEmpresa, $precoProjeto, $nomeProjeto, $dataInicial, $dataTermino, $formaPagamento, $membros){
$banc = Bd::getInstance();
$obanco = $banc->abrirconexao();
//$sql2 = "ALTER TABLE projeto ADD COLUMN id Serial";
//$tr = pg_query($sql2);
$SQL = "SELECT nome FROM membro WHERE email = '{$membros}'";
$res = pg_query($SQL);
$r = pg_fetch_array($res);
$memb = $r['nome'];
$sq = "INSERT INTO projeto(empresa, preco, datainicio, datatermino, pagamento, nomeprojeto, membros) VALUES ('$nomeEmpresa', '$precoProjeto', '$dataInicial', '$dataTermino', '$formaPagamento', '$nomeProjeto', '$memb')";
$result = pg_query($obanco, $sq);
$sqlu = "SELECT projetos FROM membro WHERE email = '{$membros}'";
$resp = pg_query($sqlu);
$respo = pg_fetch_array($resp);
$membro = $respo['projetos'];
$projetos = $membro.' , '.$nomeProjeto;
$sql2 = "UPDATE membro SET projetos = '{$projetos}' WHERE email = '{$membros}' ";
$respos = pg_query($sql2);
if ($result != false ) {
echo "Cadastrado com sucesso!";
$banc->fecharconexao();
return true;
} else {
echo "não veio nada";
$banc->fecharconexao();
return false;
echo "<script type='javascript'>alert('Cadastrado com Erro!');";
}
}
function buscarDados(){
$banc = Bd::getInstance();
$obanco = $banc->abrirconexao();
$sql = "SELECT * FROM projeto";
$resultado = pg_query($obanco, $sql);
$banc->fecharconexao();
return $resultado;
}
function addMembro($email, $idProjeto){
$banc = Bd::getInstance();
$obanco = $banc->abrirconexao();
$SQL = "SELECT nome FROM membro WHERE email = '{$email}'";
$res = pg_query($SQL);
$r = pg_fetch_array($res);
$memb = $r['nome'];
$sql2 = "SELECT membros FROM projeto WHERE idprojeto = '{$idProjeto}'";
$resp = pg_query($sql2);
$rs = pg_fetch_array($resp);
$proj = $rs['membros'];
$membroNovo = $proj.' , '.$memb;
$sql3 = "UPDATE projeto set membros='{$membroNovo}' where idprojeto='{$idProjeto}'";
$resul = pg_query($sql3);
$sqlu = "SELECT projetos FROM membro WHERE email = '{$email}'";
$respost = pg_query($sqlu);
$respo = pg_fetch_array($respost);
$membro = $respo['projetos'];
$sqlt = "SELECT nomeprojeto FROM projeto WHERE idprojeto='{$idProjeto}'";
$respostas = pg_query($sqlt);
$respostt = pg_fetch_array($respostas);
$membrro = $respostt['nomeprojeto'];
$projetos = $membrro.' , '.$membro;
$sql2 = "UPDATE membro SET projetos = '{$projetos}' WHERE email = '{$email}' ";
$respos = pg_query($sql2);
if ($resul != false ) {
echo "Cadastrado com sucesso!";
$banc->fecharconexao();
return true;
} else {
echo "não veio nada";
$banc->fecharconexao();
return false;
}
}
//DELETE
function apagar( $SQL ) {
$banco = $this->conectar();
$Resultado = pg_query( $this->conectar(), $SQL );
pg_close( $this->conectar() );
return $Resultado;
}
//SELECT
}
<file_sep>/Projeto front Johnny e Emanuel/_controller/controllerdados.php
<?php
require_once( "../_util/userdao.php" );
class Controllerdados {
public static $instance = null;
private $user;
private function __construct() {
}
public static
function getInstance() {
if ( self::$instance == NULL ) {
self::$instance = new Controllerdados();
}
return self::$instance;
}
public static function zeraSingleton() {
self::$instance = new Controllerdados();
}
public function realizalogin( $email, $senha) {
$senhaCrip = md5($senha);
$userdao = new UserDao();
$resultado = $userdao->ler( $email, $senhaCrip);
if ( $resultado != null ) {
//$resultado = pg_query($sql);
$linha = pg_fetch_array( $resultado );
header('location:../_view/home.php');
} else {
echo "erro de senha ou email";
}
//echo "erro";
//header( 'location:errologin.html' );
}
public function cadastrarUsuario($nome, $email, $senha, $cargo, $pontos, $data_nascimento){
$senhaCrip = md5($senha);
$userdao = new UserDao();
$result = $userdao->cadastrar($nome, $email, $senhaCrip, $cargo, $pontos, $data_nascimento);
if ( $result == true ) {
//$resultado = pg_query($sql);
$linha = pg_fetch_array( $result );
echo 'Usuario cadastrado';
header('location:../_view/home.php');
} else {
echo "erro no cadastro";
}
}
public function cadastrarProjeto($nomeEmpresa, $precoProjeto, $nomeProjeto, $dataInicial, $dataTermino, $formaPagamento, $membros){
$userdao = new UserDao();
$result = $userdao->cadastrarProjeto($nomeEmpresa, $precoProjeto, $nomeProjeto, $dataInicial, $dataTermino, $formaPagamento, $membros);
if ( $result != null || $result != false) {
//$resultado = pg_query($sql);
echo 'Usuario cadastrado';
header('location:../_view/home.php');
} else {
echo "erro no cadastro";
}
}
public function addMembro($email, $idProjeto){
$userdao = new UserDao();
$result = $userdao->addMembro($email, $idProjeto);
header('location:../_view/home.php');
}
public function verDadosProjeto(){
$userdao = new UserDao();
$result = $userdao->buscarDados();
return $result;
}
}
?>
<file_sep>/Projeto front Johnny e Emanuel/_view/home.php
<?php
require_once( '../_controller/controllerdados.php' );
$controller = Controllerdados::getInstance();
$result = $controller->verDadosProjeto();
$tamanho = count($result);
?>
<!DOCTYPE html>
<html lang="PT-BR">
<head>
<title>Ecomp jr</title>
<meta name="description" content="">
<meta name="author" content="">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/animate.css">
<link rel="stylesheet" href="../css/font-awesome.min.css">
<link rel="stylesheet" href="../css/owl.theme.css">
<link rel="stylesheet" href="../css/owl.carousel.css">
<!-- Main css -->
<link rel="stylesheet" href="../css/style.css">
<!-- Google Font -->
<link href='https://fonts.googleapis.com/css?family=Poppins:400,500,600' rel='stylesheet' type='text/css'>
</head>
<body data-spy="scroll" data-offset="50" data-target=".navbar-collapse">
<!-- =========================
NAVIGATION LINKS
============================== -->
<div class="navbar navbar-fixed-top custom-navbar" role="navigation">
<div class="container">
<!-- navbar header -->
<div class="navbar-header">
<button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon icon-bar"></span>
<span class="icon icon-bar"></span>
<span class="icon icon-bar"></span>
</button>
<a href="#" class="navbar-brand">ECOMP JR</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="../index.html" class="smoothScroll">Home</a></li>
<li><a href="membros.html" class="smoothScroll">Membros</a></li>
<li><a href="projetos.html" class="smoothScroll">Projetos</a></li>
<li><a href="contatos.html" class="smoothScroll">Contatos</a></li>
</ul>
</div>
</div>
</div>
<!-- =========================
REGISTER SECTION
============================== -->
<section id="register" class="parallax-section">
<div class="container">
<div class="row">
<div class="wow fadeInUp col-md-7 col-sm-7" data-wow-delay="0.6s">
<h2>Cadastre um projeto</h2>
<h3>Nunc eu nibh vel augue mollis tincidunt id efficitur tortor. Sed pulvinar est sit amet tellus iaculis hendrerit.</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet. Dolore magna aliquam erat volutpat. Lorem ipsum dolor sit amet consectetuer diam nonummy.</p>
<div id="table-responsive">
<table class="table">
<tbody>
<tr>
<th>IdProjeto</th>
<th>Nome Projeto</th>
<th>Empresa</th>
<th>Data Inicio</th>
<th>Data Término</th>
<th>Pagamento</th>
<th>Preco</th>
<th>Membros</th>
</tr>
<?php
$i = 0;
while ($fetch = pg_fetch_row($result)) { ?>
<tr>
<td><?php echo $fetch[0]; ?> </td>
<td><?php echo $fetch[6]; ?> </td>
<td><?php echo $fetch[2]; ?> </td>
<td><?php echo $fetch[3]; ?> </td>
<td><?php echo $fetch[4]; ?> </td>
<td><?php echo $fetch[5]; ?> </td>
<td><?php echo "R$ ".$fetch[1]; ?> </td>
<td><?php echo $fetch[7]; ?> </td>
</tr>
<?php
}
?>
<tbody>
</table>
<form action="../_controller/adicionaMembroProjeto.php" method="POST">
<input name="email" type="email" class="form-control" required id="email" placeholder="Digite o Email do Membro Que Deseja Adicionar">
<input name="idproject" type="number" class="form-control" required id="idproject" value="idproject" placeholder="Digite o Id do Projeto no Qual Quer Adicioná-lo">
<input name="submit" type="submit" class="form-control" id="submit" value="Adicionar Membro">
</form>
</div>
</div>
<div class="wow fadeInUp col-md-5 col-sm-5" data-wow-delay="1s">
<form action="../_controller/cadastroProjeto.php" method="POST">
<div>
<input name="organizationname" type="text" required class="form-control" id="organizationname" placeholder="Nome da Empresa Contratante">
<input name="projectname" type="text" required class="form-control" id="projectname" placeholder="Nome do Projeto">
<input name="projectPrice" type="number" required class="form-control" id="projectPrice" step=".01" placeholder="Valor do projeto">
Data de Início<input name="initialDate" required type="date" class="form-control" id="intialDate" placeholder="Data de Inicio">
Data de Entrega<input name="dateLast" required type="date" class="form-control" id="dateLast" placeholder="Data de Término">
Membros Participantes<input name="organizationmember" required type="text" class="form-control" id="organizationmember"
placeholder="Digite o Email de Apenas 1(um) Membro do Projeto">Formas de Pagamento
<div>
<div class="col-md-6 col-lg-6 col-sm-12"><input required type="radio" value="Cartao" name="pagamento">Cartão</div>
<div class="col-md-6 col-lg-6 col-sm-12"><input required type="radio" value="Dinheiro" name="pagamento">Dinheiro</div>
</div>
</div>
<div class="col-md-offset-6 col-md-6 col-sm-offset-1 col-sm-10">
<input name="submit" type="submit" class="form-control" id="submit" value="REGISTRAR PROJETO">
</div>
</form>
<form action="../_controller/cadastro.php" method="POST">
<input name="name" required type="text" class="form-control" id="name" placeholder="Nome do Membro">
<input name="email" required type="email" class="form-control" id="email" placeholder="Email">
<input name="password" required type="<PASSWORD>" class="form-control" id="password" placeholder="<PASSWORD>">
<input name="confirmPassword" required type="<PASSWORD>" class="form-control" id="confirmPassword" placeholder="<PASSWORD>">
<input name="points" required type="number" class="form-control" id="points" placeholder="Pontos do Membro">
Data de Nascimento <input name="dateB" required type="date" class="form-control" id="dateB">
<input name="office" required type="text" class="form-control" id="office" placeholder="Cargo na Empresa">
<div class="col-md-offset-6 col-md-6 col-sm-offset-1 col-sm-10">
<input name="submit" type="submit" class="form-control" id="submit" value="CADASTRAR USUÁRIO">
</div>
</form>
</div>
<div class="col-md-1"></div>
</div>
</div>
</section>
<!-- =========================
FOOTER SECTION
============================== -->
<footer>
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12">
<p class="wow fadeInUp" data-wow-delay="0.6s">Copyright © 2017 Your Company | Design: <a rel="nofollow" href="http://www.templatemo.com/page/1" target="_parent">Templatemo</a></p>
<p class="wow fadeInUp" data-wow-delay="0.6s">Conheça a Ecomp Jr. +55 (75) 10100-1010</p>
<ul class="social-icon">
<li>
<a target="_blanck" href="https://www.facebook.com/ecompjr.uefs/" class="fa fa-facebook wow fadeInUp" data-wow-delay="1s"></a>
</li>
<li>
<a target="_blanck" href="https://twitter.com/EcompJr" class="fa fa-twitter wow fadeInUp" data-wow-delay="1.3s"></a>
</li>
<li>
<a target="_blanck" href="https://www.instagram.com/ecompjr/?hl=pt-br" class="fa fa-instagram wow fadeInUp" data-wow-delay="1.6s"></a>
</li>
<li>
<a target="_blanck" href="http://www.ecompjr.com.br" class="fa fa-envelope-o wow fadeInUp" data-wow-delay="1.9s"></a>
</li>
</ul>
</div>
</div>
</div>
</footer>
<!-- Back top -->
<a href="#back-top" class="go-top"><i class="fa fa-angle-up"></i></a>
<!-- =========================
SCRIPTS
============================== -->
<script src="../js/jquery.js"></script>
<script src="../js/script.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery.parallax.js"></script>
<script src="../js/owl.carousel.min.js"></script>
<script src="../js/smoothscroll.js"></script>
<script src="../js/wow.min.js"></script>
<script src="../js/custom.js"></script>
</body>
</html><file_sep>/Projeto front Johnny e Emanuel/_controller/logout.php
<?php
require_once( "Controllerdados.php" );
$controller = Controllerdados::getInstance();
$controller->realizalogout();
?><file_sep>/Projeto front Johnny e Emanuel/_controller/cadastro.php
<?php
//$bd = pg_connect("host=localhost port=5432 dbname=pbl user=lucas password=<PASSWORD>") or die ("Não foi possível conectar ao servidor PostGreSQL");
require_once( '../_controller/controllerdados.php' );
if ( ( isset( $_POST[ 'nome' ] ) == false )and( isset( $_POST[ 'email' ] ) == false )and( isset( $_POST[ 'senha' ] ) == false )and( isset( $_POST[ 'password' ] ) == false ) ) {
echo 'faltam dados';
} else {
$nome = $_POST[ 'name' ];
$email = $_POST[ 'email' ];
$senha = $_POST[ 'password' ];
$confirmaSenha = $_POST[ 'confirmPassword' ];
$cargo = $_POST['office'];
$pontos = $_POST['points'];
$data_nascimento = $_POST['dateB'];
if($senha == $confirmaSenha){
$controller = Controllerdados::getInstance();
$controller->cadastrarUsuario($nome, $email, $senha, $cargo, $pontos, $data_nascimento);
}else{
echo'Senhas diferem';
}
}
?><file_sep>/Projeto front Johnny e Emanuel/js/script.js
function mostraOculta(ID) {
if (document.getElementById(ID).style.display == "block") {
mostra(ID);
} else {
esconde(ID);
}
}
function mostra(TD) {
document.getElementById(TD).style.display = "none";
}
function esconde(TD) {
document.getElementById(TD).style.display = "block";
}
function exibe(id) {
if (document.getElementById(id).style.display == "none") {
document.getElementById(id).style.display = "inline";
} else {
document.getElementById(id).style.display = "none";
}
}<file_sep>/Projeto front Johnny e Emanuel/_controller/cadastroProjeto.php
<?php
if(!isset($_SESSION)){
session_start();
}
require_once( '../_controller/controllerdados.php' );
$nomeEmpresa = $_POST[ 'organizationname' ];
$precoProjeto = $_POST[ 'projectPrice' ];
$nomeProjeto = $_POST[ 'projectname' ];
$dataInicial = $_POST[ 'initialDate' ];
$dataTermino = $_POST['dateLast'];
$formaPagamento = $_POST['pagamento'];
$membros = $_POST['organizationmember'];
if (($nomeEmpresa != "" and $nomeEmpresa != null )and( $dataTermino != null and $dataTermino != "" ) ){
$controller = Controllerdados::getInstance();
$controller->cadastrarProjeto($nomeEmpresa, $precoProjeto, $nomeProjeto, $dataInicial, $dataTermino, $formaPagamento, $membros);
} else{
echo 'faltam dados';
}
?>
|
572b30243a639db4a20bbb6ae8f548d753e0f2e4
|
[
"JavaScript",
"PHP"
] | 9
|
PHP
|
essantos97/projeto-ecompjr
|
39f5b4c07ae78420097726df1d012ca2a7e0ef54
|
62c7cdd0ed428e633ed4cf9801d38a71ac24dc6f
|
refs/heads/master
|
<repo_name>sn0w/auto-proxy<file_sep>/README.md
# auto-proxy
[](https://nodei.co/npm/auto-proxy/) [](https://nodei.co/npm/auto-proxy/)
### Never care about proxies again!
AutoProxy is a nodejs module that ships with web-scrapers out-of-the-box!<br>
That means you don't have to spend hours goog'ling proxysites.<br>
Just fire up AutoProxy and let it search the proxies for you.<br>
However if you've still got one of these old-style `IP:PORT` lists on your 16MB flash-drive,
AutoProxy can handle that too.
#### Installation
```
npm i --save auto-proxy
```
### Usage
```javascript
const AutoProxy = require('auto-proxy');
```
<hr/>
### Got your own proxylist?
#### No problem!
#### AutoProxy can handle that!
Just create a new instance using `.new()` and pass the path to it
```javascript
// Parameters:
// 1st -> How many requests a proxy can handle before autoproxy swaps it
// 2nd -> Options
// 3rd -> Path to your proxylist
// 4th -> Whether to disable the crawler or not
AutoProxy.new(25, {}, '/path/to/proxy.list', false).then(function(proxy){
//PROFIT!
});
```
Note: This list **must** be in this format:
```
IP:PORT
IP:PORT
...
```
#### Just want to check if your list works?
[No problem either!](#i-just-want-to-check-if-my-proxies-work)
<hr/>
<br><br>[](https://lukas.moe/support)
<hr/>
### The "normal" API
The normal API is completely Promise/A+ based. If you don't like this you can use the `__simple__` API.
#### .new(interval, options, localProxylist, disableCrawling)
Creates an auto-proxy instance
```javascript
// The interval describes how many requests a proxy may handle before
// a new one will be used
//
// The options object takes as less or many options as you like, but you have to define it (empty object)
//
// Here you see how a full config looks like, and what the default options are
AutoProxy.new(25, {
enableLogging: false, //Wether to interact with the user or not
autoRefresh: false, //If enabled auto-proxy will reload the proxies as soon as there are no more in the pool.
//Please note that this may take up to a few minutes depending on your internet speed.
//While debugging this may seem like you program is stuck if you disable $enableLogging
reLoop: false //After there are no more proxies in the pool, just start over.
//You'd have to call .refillProxies() to crawl for new proxies
__simple__: { // The __simple__ API. For usage scroll down :)
reLoop: true // Works like the reloop option of auto-proxy.
// To refill, you'd have to call .refillProxies() and __simple__.refresh() afterwards
}
}).then(function(proxy) { //This proxy object is your instance
... // Use your instance
});
```
#### .refillProxies()
Loads new proxies from various proxylists
```javascript
proxy.refillProxies().then(function(){
// Proxies are now refilled.
// Use them!
...
});
```
#### .forceNext()
Force-switch to the next proxy. Resets the interval counter
```javascript
proxy.forceNext().then(function(){
// Proxy is switched!
// Use it!
...
});
```
#### .blockCurrent()
Blocks the current proxy, so that it won't be reLoop'ed or used again
```javascript
proxy.blockCurrent().then(function(){
// Proxy is blocked and switched!
// Use it!
...
});
```
#### .getCurrent(ignoreUsage)
Get the current proxy
```javascript
// Respects the proxy interval
proxy.getCurrent().then(function(ip) {
console.log(`The ip is ${ip}`);
});
// Ignores the proxy interval
proxy.getCurrent(true).then(function(ip) {
console.log(`The ip is ${ip}`);
});
```
#### .getPrefixedCurrent(ignoreUsage)
Works like `.getCurrent()` but prefixes the IP with `http://`.
### The `__simple__` API
The simple API is completely synchronous and does not refresh/re-scrape automatically.
#### .init()
Initializes the caches and prepares for usage
You should call this in the `AutoProxy.new().then()` callback.
#### .refresh()
This method will copy all proxies from the normal API into a seperate cache used only by `__simple__`.
You can clear this cache using `.__simple__.resetCache()`
#### .next()
Jumps to the next proxy and resets the interval
#### .get()
Returns the current proxy (repecting the interval)
#### .block()
Blocks the current proxy, so that it won't be reLoop'ed or used again
#### So how do i handle an empty proxy pool when i'm using the `__simple__` API?
Glad you asked :)
The `__simple__` API throws a `ProxiesEmptyException` when there are no more proxies.
Just catch it, load new proxies and refresh the cache. VOILA!
```javascript
let ip = null;
try {
ip = proxy.__simple__.get();
} catch (e) {
proxy.refillProxies().then(function(){
proxy.__simple__.refresh();
ip = proxy.__simple__.get();
});
}
```
#### I just want to check if my proxies work!
No problem!
```javascript
AutoProxy.new(1, {}, '/path/to/list.txt', true).then(function(proxy) {
require('fs').writeFileSync('checked_proxies.txt', JSON.stringify(proxy.proxyList));
});
```
<file_sep>/test.js
"use strict";
require('./index.js').new(25, {
enableLogging: true,
autoRefresh: true,
__simple__: {reLoop: false}
}, './proxies.txt', true).then(function (autoProxy) {
require('fs').writeFileSync('works.txt', JSON.stringify(autoProxy.proxyList));
});
<file_sep>/scrapers/nordvpn.com.js
"use strict";
module.exports = function (logger) {
logger('Scraping nordvpn.com ...');
const request = require('request');
const Q = require('q');
let proxies = [];
let defer = Q.defer();
// Share da cookiez!
let cookies = request.jar();
// Get Session
request.get('https://nordvpn.com/free-proxy-list/', {
jar: cookies
}, function (err) {
if (err === null || typeof err === typeof undefined) {
// Get proxies from API
request.post('https://nordvpn.com/wp-admin/admin-ajax.php?searchParameters%5B0%5D%5Bname%5D=proxy-country&searchParameters%5B0%5D%5Bvalue%5D=&searchParameters%5B1%5D%5Bname%5D=proxy-ports&searchParameters%5B1%5D%5Bvalue%5D=&offset=0&limit=1000&action=getProxies', {
jar: cookies
}, function (err, res) {
let result = JSON.parse(res.body);
for (let key in result) {
proxies.push(`${result[key]["ip"]}:${result[key]["port"]}`);
}
defer.resolve(proxies);
});
}
});
return defer.promise;
};
<file_sep>/scrapers/samair.ru.js
"use strict";
module.exports = function () {
const request = require('request');
const cheerio = require('cheerio');
const baseUri = 'http://www.samair.ru/proxy';
let proxies = [];
for (let page = 1; page <= 30; page++) {
let _page = page < 10 ? `0${page}` : page; //Add a 0 in front. \o/
let req = wait.for(request.get, `${baseUri}/proxy-${_page}.htm`);
let $ = cheerio.load(req.body);
let __req = wait.for(request.get, `${baseUri.replace('/proxy', '')}${$('#ipportonly').find('a').attr('href')}`);
let __$ = cheerio.load(__req.body);
let rawProxyList = __$('#content > pre').text().split('\n');
for (let z in rawProxyList) {
if (rawProxyList[z] !== "") {
proxies.push(rawProxyList[z]);
}
}
}
return proxies;
};<file_sep>/index.js
"use strict";
const ProxiesEmptyException = require('./exceptions/ProxiesEmptyException.js');
const request = require('request').defaults({
timeout: 5000
});
const progress = require('progress');
const array = require('array-walk');
const async = require('async');
const chalk = require('chalk');
const http = require('http');
const fs = require('fs');
const Q = require('q');
var AutoProxy = {
/**
* Create a new instance
*
* Usage:
* require('auto-proxy')
* .new()
* .then((proxy) => {
* proxy.doStuff();
* });
*
* @param interval How many a times a proxy can be used before it is swapped automagically
* @param config An object that overrides AutoProxy.config
* @param localList
* @param disableCrawling
* @returns Promise
*/
new: function (interval, config, localList, disableCrawling) {
// Promise
let defer = Q.defer();
// Default Settings
AutoProxy.proxyList = [];
AutoProxy.proxyCache = [];
AutoProxy.blockedProxies = [];
AutoProxy.usageCounter = 0;
AutoProxy.usageLimit = interval;
AutoProxy.config = {
enableLogging: false,
autoRefresh: false,
reLoop: false
};
// Update settings
for (let key in config) {
if (key === '__simple__') {
AutoProxy.__simple__.__config__ = config[key];
} else {
AutoProxy.config[key] = config[key];
}
}
// Set logger
AutoProxy.log = AutoProxy.config.enableLogging ? AutoProxy.logger : AutoProxy.noop;
if (disableCrawling === true) {
AutoProxy.loadProxyFile(localList);
AutoProxy.testProxies().then(function () {
defer.resolve(AutoProxy);
});
} else {
AutoProxy.refillProxies(true).then(function () {
AutoProxy.loadProxyFile(localList);
AutoProxy.testProxies().then(function () {
defer.resolve(AutoProxy);
});
});
}
// Promise to be ready soon
return defer.promise;
},
/**
* Load a local proxy file
* @param localList
*/
loadProxyFile: function (localList) {
if (typeof localList === typeof "") {
AutoProxy.log("Checking if passed proxyfile is accessible...");
try {
fs.accessSync(localList, fs.F_OK);
AutoProxy.log("Reading proxies from file...");
fs.readFileSync(localList).toString().split('\n').forEach((line) => {
AutoProxy.proxyList.push(line);
});
} catch (e) {
AutoProxy.log("Skipping proxyfile because node cannot access it!");
AutoProxy.log(require("util").inspect(e));
}
}
},
/**
* Tell AutoProxy to refill the proxy array
* @param firstExecution Wether this was called from .new() or not
* @returns Promise
*/
refillProxies: function (firstExecution) {
let defer = Q.defer();
AutoProxy.log('Refilling proxies...');
if (firstExecution === true) {
AutoProxy.crawl().then(function () {
if (AutoProxy.config.reLoop === true) {
AutoProxy.proxyCache = AutoProxy.proxyList;
}
defer.resolve();
});
} else {
if (AutoProxy.config.reLoop === true) {
AutoProxy.log("Re-Loop is enabled. Resetting proxies...");
AutoProxy.proxyList = AutoProxy.proxyCache;
defer.resolve();
} else if (AutoProxy.config.autoRefresh === true) {
AutoProxy.log("Auto-Refresh is enabled. Trying to get new proxies...");
AutoProxy.crawl().then(function () {
defer.resolve();
});
} else {
defer.reject(new ProxiesEmptyException());
}
}
return defer.promise;
},
/**
* Downloads new proxies and checks if they are online
*
* @returns {*|promise}
*/
crawl: function () {
let defer = Q.defer();
AutoProxy.log("Loading scrapers...");
let list = AutoProxy.proxyList;
const scrapers = [
require('./scrapers/proxy-listen.de.js'),
require('./scrapers/free-proxy-list.net.js'),
require('./scrapers/nordvpn.com.js')
//require('./scrapers/freeproxylists.com')
];
array.map(scrapers, function (scraper, next) {
scraper(AutoProxy.log).then(function (proxies) {
list = AutoProxy.arrayUniq(list.concat(proxies));
next();
});
}, function () {
AutoProxy.proxyList = list;
AutoProxy.log("Scraping done!");
AutoProxy.log(`Found ${AutoProxy.proxyList.length} Proxies!`);
AutoProxy.testProxies().then(function () {
defer.resolve();
});
});
return defer.promise;
},
/**
* Test all proxies by poking google.com
* @returns {*|promise}
*/
testProxies: function () {
let defer = Q.defer();
AutoProxy.log('Testing proxies by poking goo.gl');
let pb;
if (AutoProxy.config.enableLogging) {
pb = new progress(':percent :bar [:current of :total] [ON: :on] [ETA: :eta] [Current: :proxy] [:error]', {
total: AutoProxy.proxyList.length,
clear: false,
width: 50
});
}
let onlineCounter = 0;
async.mapLimit(AutoProxy.proxyList, 250, function (item, callback) {
try {
if (item.split(':')[1] >= 0 && item.split(':')[1] <= 65535) {
request.get('http://goo.gl/', {
proxy: `http://${item}`
}, function (err, res) {
if (AutoProxy.config.enableLogging) {
//noinspection JSUnresolvedFunction
pb.tick({
proxy: item,
error: err != null ? chalk.red(err['code']) : chalk.green('SUCCESS'),
on: onlineCounter
});
}
if (typeof err === typeof undefined || err === null) {
onlineCounter++;
callback(null, item);
} else {
callback(null, null);
}
});
} else {
pb.tick({
proxy: item,
error: chalk.red("PORT_RANGE_ERR"),
on: onlineCounter
});
callback(null, null);
}
} catch (e) {
console.error(e['code']);
}
}, function (err, res) {
let tmp = [];
for (let i = 0; i < res.length; i++) {
if (res[i] !== null) {
tmp.push(res[i]);
}
}
AutoProxy.proxyList = tmp;
AutoProxy.log(`After checking there are ${tmp.length} proxies left`);
defer.resolve();
});
return defer.promise;
},
/**
* Forces AutoProxy to switch to a new proxy before the usage counter is full
* Resets the counter to 0
*
* @returns {*|promise}
*/
forceNext: function () {
let defer = Q.defer();
if (AutoProxy.proxyList.length > 1) {
AutoProxy.proxyList.splice(0, 1);
AutoProxy.usageCounter = 0;
defer.resolve();
} else {
AutoProxy.log("No more cached proxies!");
if (AutoProxy.config.autoRefresh === true || AutoProxy.config.reLoop === true) {
AutoProxy.refillProxies().then(function () {
defer.resolve();
});
} else {
AutoProxy.log("Re-Loop and Auto-Refresh are disabled!");
defer.reject(new ProxiesEmptyException());
}
}
return defer.promise;
},
/**
* Marks the current proxy as "blocked" and switches to a new one
* @returns {Promise}
*/
blockCurrent: function () {
let defer = Q.defer();
AutoProxy.blockedProxies.push(AutoProxy.proxyList[0]);
AutoProxy.forceNext().then(function () {
defer.resolve();
});
return defer.promise;
},
/**
* Gets the current proxy (ip-only)
* @param ignoreUsage Wether to count this access or not
* @returns {*}
*/
getCurrent: function (ignoreUsage) {
let defer = Q.defer();
if (ignoreUsage !== true) {
AutoProxy.usageCounter++;
}
if (AutoProxy.usageCounter >= AutoProxy.usageLimit) {
AutoProxy.usageCounter = 0;
AutoProxy.forceNext().then(function () {
defer.resolve(AutoProxy.proxyList[0]);
});
}
AutoProxy.log(`Proxy ${AutoProxy.proxyList[0]} was used. [Usage ${AutoProxy.usageCounter} of ${AutoProxy.usageLimit}]`);
defer.resolve(AutoProxy.proxyList[0]);
return defer.promise;
},
/**
* Works like getCurrent() but prefixes the IP with "http://"
*
* @see getCurrent()
* @param ignoreUsage
* @returns {Promise}
*/
getPrefixedCurrent: function (ignoreUsage) {
let defer = Q.defer();
AutoProxy.getCurrent(ignoreUsage).then(function (ip) {
defer.resolve(ip);
});
return defer.promise;
},
/**
* The logger. Simple but effective
*
* @param msg
*/
logger: function (msg) {
console.log(`[AutoProxy] ${msg}`);
},
/**
* Remove duplicate items from $array and return a new cleaned one
* We should probably move this method somewhere else...
*
* @param array
* @returns {string|Buffer|Array.<T>}
*/
arrayUniq: function (array) {
let a = array.concat();
for (let i = 0; i < a.length; ++i) {
for (let j = i + 1; j < a.length; ++j) {
if (a[i] === a[j]) {
a.splice(j--, 1);
}
}
}
return a;
},
/**
* Literally does nothing. EVER.
*/
noop: function () {
},
/**
* The __simple__ API provides the most common methods as sync versions.
* However it does *not* support autoRefreshing and reLoops by design.
*
* __simple__ might come in handy where you need a way to access
* the proxies whithout starting hundrets of promises (e.g. a loop)
*
* If you need to get new proxies, you should tell AutoProxy to get them.
* After that call __simple__.refresh() to transfer the proxyList into cache.
*
* Example:
* AutoProxy.refillProxies().then(() => {
* AutoProxy.__simple__.refresh();
* });
*
* If you need to disable reLooping you can set __simple__.__config__.reLoop to false
* Note that in this case AutoProxy will throw a ProxiesEmptyException
* when it is told to leave the cache's bounds.
*
*/
__simple__: {
__storage__: [],
__cache__: [],
__blocked__: [],
__usageCounter__: 0,
__config__: {
reLoop: true
},
__isBlocked: function (ip) {
for (let key in AutoProxy.__simple__.__blocked__) {
if (AutoProxy.__simple__.__blocked__[key] === ip) {
return true;
break;
}
}
return false;
},
/**
* Convenience method to init the simple-cache
*/
init: function () {
AutoProxy.__simple__.refresh();
},
/**
* Refill the storage from proxyList
*/
refresh: function () {
AutoProxy.__simple__.__storage__ = AutoProxy.proxyList;
AutoProxy.__simple__.resetCache();
},
/**
* Refill the cache from storage
*/
resetCache: function () {
AutoProxy.__simple__.__cache__ = AutoProxy.__simple__.__storage__;
AutoProxy.__simple__.__blocked__ = [];
},
next: function () {
if (AutoProxy.__simple__.__cache__.length == 1) {
if (AutoProxy.__simple__.__config__.reLoop) {
AutoProxy.__simple__.resetCache();
} else {
throw new ProxiesEmptyException("AutoProxy.__simple__ was told to stop reLooping. \n However no one called .refresh() or .resetCache() so we hit the cache's bounds. \n That raised a ProxiesEmptyException. \n Please check if you refill the cache correctly or enable reLooping!");
}
} else {
AutoProxy.__simple__.__cache__.splice(0, 1);
AutoProxy.__simple__.__usageCounter__ = 0;
}
},
/**
* Get a proxy (respecting usage limits)
* @returns {*}
*/
get: function () {
// Check if this is the first run
if (
AutoProxy.__simple__.__storage__.length === 0 &&
AutoProxy.__simple__.__cache__.length === 0
) {
AutoProxy.__simple__.refresh();
}
// Respect the config limits!
AutoProxy.__simple__.__usageCounter__++;
if (AutoProxy.__simple__.__usageCounter__ > AutoProxy.config.usageLimit) {
AutoProxy.__simple__.next();
}
while (AutoProxy.__simple__.__isBlocked(AutoProxy.__simple__.__cache__[0])) {
AutoProxy.__simple__.next();
AutoProxy.__simple__.__usageCounter__ = 0;
}
// Get the proxy
return AutoProxy.__simple__.__cache__[0];
},
block: function () {
AutoProxy.__simple__.__blocked__.push(AutoProxy.__simple__.__cache__[0]);
AutoProxy.__simple__.next();
}
}
};
module.exports = AutoProxy;
|
2f6f90f52d3320d1e039652a215d6c98be1506e2
|
[
"Markdown",
"JavaScript"
] | 5
|
Markdown
|
sn0w/auto-proxy
|
b3a675ad40eb36425b5f0fbb86bbf7e32fcd7106
|
c72ba464f8687a7d0c24da86ff44573bcf9c97ed
|
refs/heads/master
|
<repo_name>KiSooLee/TnP_B<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/Efficiency/RD/MuTrg/TnPEffTrgDraw_for_B.C
#include <iostream>
#include <TSystem.h>
#include <TTree.h>
#include <TKey.h>
#include <TH1.h>
#include <TH2.h>
#include <TPave.h>
#include <TText.h>
#include <fstream>
#include <sstream>
#include <string.h>
#include <TROOT.h>
#include <TFile.h>
#include <TGraphAsymmErrors.h>
#include <TH1.h>
#include <TH2.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <RooFit.h>
#include <RooRealVar.h>
#include <RooDataSet.h>
#include <RooArgSet.h>
#include <TStyle.h>
#include <TLatex.h>
#include <TDirectory.h>
#include <TCollection.h>
#include <TPostScript.h>
using namespace RooFit;
using namespace std;
// Function Define
TH2F *plotEff2D(RooDataSet *a, TString b);
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa);
TGraphAsymmErrors *plotEffEta(RooDataSet *a, int aa);
void formatTH1F(TH1* a, int b, int c, int d);
void formatTGraph(TGraph* a, int b, int c, int d);
void formatTLeg(TLegend* a);
void TnPEffTrgDraw_for_B ();
// From here you need to set up your environments.
bool MC_ = false; // if the data set is real data, it should be false
bool Cent_ = false; // if the data is only one MinBias file, it shoud be false
const int maxFile_ = 1; // the number of data files, usually it should be 4 but 1 in the case of MinBias
int TrgMode_ = 1; // 1 = L1, 2 = L2
char *outfile_ = "Jpsi_pPb_RD_MuTrgNew2CS_CBGpExp_1st_Run_Eff_Mu3_for_B_test.root"; // L1 or L2
string dir_suffix = "_cbGaussPlusExpo"; // depends on which fit function is used for : eg) _gaussExpo, _gaussPol2
void TnPEffTrgDraw_for_B() {
gROOT->Macro("rootlogon.C");
char *files[maxFile_] = {
"../../Ana/RD/MuTrg/tnp_pPb_Ana_MuTrgNew2CS_CBGpExp_1st_Run_for_B_test.root"
};
TString outname_in, outname_mid, outname_out;
TString middle_name, middle_name2;
TString leg_title;
int Mode = 0;
TFile *outfile = new TFile(outfile_,"RECREATE");
for(int l = 0; l < maxFile_; l++){
char *infile = files[l];
TFile *f = new TFile(infile);
Mode = l;
if(Mode == 0){
middle_name = "All";
middle_name2 = "MinBias";
}else if(Mode == 1){
middle_name = "0005";
middle_name2 = "0 - 5 %";
}else if(Mode == 2){
middle_name = "0510";
middle_name2 = "5 - 10 %";
}else if(Mode == 3){
middle_name = "1020";
middle_name2 = "10 - 20 %";
}else if(Mode == 4){
middle_name = "2030";
middle_name2 = "20 - 30 %";
}else if(Mode == 5){
middle_name = "3040";
middle_name2 = "30 - 40 %";
}else if(Mode == 6){
middle_name = "4050";
middle_name2 = "40 - 50 %";
}else if(Mode == 7){
middle_name = "5060";
middle_name2 = "50 - 60 %";
}else if(Mode == 8){
middle_name = "60100";
middle_name2 = "60 - 100 %";
}
gROOT->SetStyle("Plain");
gStyle->SetOptStat(0);
gStyle->SetTitle(0);
// if you have only one file, should change the number 4 -> 1
TString mid_title = "Centrality : (" + middle_name2 + ")";
if(!MC_) leg_title = "Data Trigger Efficiency (" + middle_name2 + ")";
if(MC_) leg_title = "MC Trigger Efficiency (" + middle_name2 + ")";
TCanvas *c1 = new TCanvas("c1","",120,20,800,600);
f->cd();
RooDataSet *daTrgEta, *daTrgEta1bin;
if(TrgMode_ == 1){
daTrgEta = (RooDataSet*)f->Get("MuonTrgNew2CS/PAMu3_eta/fit_eff");
daTrgEta1bin = (RooDataSet*)f->Get("MuonTrgNew2CS/PAMu3_1bin_pt_eta/fit_eff");
}else{
daTrgEta = (RooDataSet*)f->Get("MuonTrgNew2/HLTL2_eta/fit_eff");
daTrgEta1bin = (RooDataSet*)f->Get("MuonTrgNew2/HLTL2_1bin_pt_eta/fit_eff");
}
TGraphAsymmErrors *Trg_eta = plotEffEta(daTrgEta, 1);
TGraphAsymmErrors *Trg_1bin_pt_eta = plotEffEta(daTrgEta1bin, 1);
double Trg[4];
Trg_1bin_pt_eta->GetPoint(0,Trg[0],Trg[1]);
Trg[2] = Trg_1bin_pt_eta->GetErrorYhigh(0);
Trg[3] = Trg_1bin_pt_eta->GetErrorYlow(0);
RooDataSet *daTrgPt;
if(TrgMode_ == 1) daTrgPt = (RooDataSet*)f->Get("MuonTrgNew2CS/PAMu3_pt/fit_eff");
if(TrgMode_ == 2) daTrgPt = (RooDataSet*)f->Get("MuonTrgNew2/HLTL2_pt/fit_eff");
TGraphAsymmErrors *Trg_pt = plotEffPt(daTrgPt, 1);
/*
RooDataSet *daTrgD = (RooDataSet*)f->Get("MuonTrg/HLTL1_pt_eta/fit_eff");
TString twoDName1 = "Trg_2d";
TH2F *Trg_2d = plotEff2D(daTrgD, twoDName1);
*/
Trg_eta->GetXaxis()->SetLabelSize(0.05);
Trg_eta->GetYaxis()->SetLabelSize(0.05);
Trg_eta->GetXaxis()->SetTitleSize(0.05);
Trg_eta->GetYaxis()->SetTitleSize(0.05);
Trg_eta->GetXaxis()->SetTitleOffset(0.9);
Trg_eta->GetYaxis()->SetTitleOffset(0.8);
Trg_eta->SetMarkerColor(kRed+2);
Trg_eta->Draw("apz");
char legs[512];
TLegend *leg1 = new TLegend(0.3054774,0.1567832,0.5429648,0.3858042,NULL,"brNDC");
leg1->SetFillStyle(0);
leg1->SetFillColor(0);
leg1->SetBorderSize(0);
leg1->SetTextSize(0.04);
leg1->SetHeader(leg_title);
sprintf(legs,"HLT_HIL1DoubleMuOpen : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[1],Trg[2],Trg[3]);
leg1->AddEntry(Trg_eta,legs,"pl");
leg1->Draw("same");
TString pic_name_png, pic_name_pdf;
if(MC_){
pic_name_png = "Jpsi_pPb_MC_Trg_New2CS_Mu3_" + middle_name + "_eta_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_MC_Trg_New2CS_Mu3_" + middle_name + "_eta_for_B_test.pdf";
}else{
pic_name_png = "Jpsi_pPb_RD_Trg_New2CS_1st_run_Mu3_" + middle_name + "_eta_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_RD_Trg_New2CS_1st_run_Mu3_" + middle_name + "_eta_for_B_test.pdf";
}
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
Trg_pt->GetXaxis()->SetLabelSize(0.05);
Trg_pt->GetYaxis()->SetLabelSize(0.05);
Trg_pt->GetXaxis()->SetTitleSize(0.05);
Trg_pt->GetYaxis()->SetTitleSize(0.05);
Trg_pt->GetXaxis()->SetTitleOffset(0.9);
Trg_pt->GetYaxis()->SetTitleOffset(0.8);
Trg_pt->SetMarkerColor(kRed+2);
Trg_pt->Draw("apz");
TLegend *leg2 = new TLegend(0.3454774,0.2167832,0.5429648,0.4458042,NULL,"brNDC");
leg2->SetFillStyle(0);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
leg2->SetTextSize(0.04);
leg2->SetHeader(leg_title);
// sprintf(legs,"HLT_HIL1DoubleMuOpen : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[1],Trg[2],Trg[3]);
sprintf(legs,"HLT_PASingleMu3 : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[1],Trg[2],Trg[3]);
leg2->AddEntry(Trg_pt,legs,"pl");
leg2->Draw("same");
if(MC_){
pic_name_png = "Jpsi_pPb_MC_Trg_New2CS_Mu3_" + middle_name + "_pt_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_MC_Trg_New2CS_Mu3_" + middle_name + "_pt_for_B_test.pdf";
}else{
pic_name_png = "Jpsi_pPb_RD_Trg_New2CS_1st_run_Mu3_" + middle_name + "_pt_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_RD_Trg_New2CS_1st_run_Mu3_" + middle_name + "_pt_for_B_test.pdf";
}
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
/*
Trg_2d->Draw();
pic_name_png = "Jpsi_MC_Trg_" + middle_name + "_2d.png";
pic_name_pdf = "Jpsi_MC_Trg_" + middle_name + "_2d.pdf";
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
c1->Print("Jpsi_MC_Trg_Eff_total.ps");
*/
TString Trgna1, Trgna2, Trgna3, Trgna4;
Trgna1 = "Trg_eta_" + middle_name;
Trgna2 = "Trg_1bin_pt_eta_" + middle_name;
Trgna3 = "Trg_pt_" + middle_name;
Trgna4 = "Trg_2d_" + middle_name;
Trg_eta->SetName(Trgna1);
Trg_1bin_pt_eta->SetName(Trgna2);
Trg_pt->SetName(Trgna3);
//Trg_2d->SetName(Trgna4);
outfile->cd();
Trg_eta->Write();
Trg_pt->Write();
Trg_1bin_pt_eta->Write();
//Trg_2d->Write();
}
// Comparing Plots as the Centralities
TH1F *hPadEta = new TH1F("hPadEta","",15,-2.4,2.4);
TH1F *hPadPt = new TH1F("hPadPt","",12,0,30);
TCanvas *c2 = new TCanvas("c2","",120,20,800,600);
//c2->cd();
TGraphAsymmErrors *gTrg[maxFile_];
TGraphAsymmErrors *gTrgEta[maxFile_];
TGraphAsymmErrors *gTrgPt[maxFile_];
double Trg[maxFile_][4];
for(int i = 0; i < maxFile_; i++){
TFile finput(files[i]);
finput.cd();
RooDataSet *dataTrg, *dataTrgEta, *dataTrgPt;
if(TrgMode_ == 1){
dataTrg = (RooDataSet*)finput.Get("MuonTrgNew2CS/PAMu3_1bin_pt_eta/fit_eff");
dataTrgEta = (RooDataSet*)finput.Get("MuonTrgNew2CS/PAMu3_eta/fit_eff");
dataTrgPt = (RooDataSet*)finput.Get("MuonTrgNew2CS/PAMu3_pt/fit_eff");
}else{
dataTrg = (RooDataSet*)finput.Get("MuonTrgNew2/HLTL2_1bin_pt_eta/fit_eff");
dataTrgEta = (RooDataSet*)finput.Get("MuonTrgNew2/HLTL2_eta/fit_eff");
dataTrgPt = (RooDataSet*)finput.Get("MuonTrgNew2/HLTL2_pt/fit_eff");
}
gTrg[i] = plotEffEta(dataTrg, 0);
gTrgEta[i] = plotEffEta(dataTrgEta, 0);
gTrgPt[i] = plotEffPt(dataTrgPt, 0);
gTrg[i]->GetPoint(0,Trg[i][0],Trg[i][1]);
Trg[i][2] = gTrg[i]->GetErrorYhigh(0);
Trg[i][3] = gTrg[i]->GetErrorYlow(0);
}
TGraphAsymmErrors *pCNT = new TGraphAsymmErrors(3);
TGraphAsymmErrors *pMBCNT = new TGraphAsymmErrors();
if(Cent_){
pCNT->SetPoint(0,10,Trg[1][1]);
pCNT->SetPointError(0,0,0,Trg[1][3],Trg[1][2]);
pCNT->SetPoint(1,20,Trg[2][1]);
pCNT->SetPointError(1,0,0,Trg[2][3],Trg[2][2]);
pCNT->SetPoint(2,30,Trg[3][1]);
pCNT->SetPointError(2,0,0,Trg[3][3],Trg[3][2]);
pCNT->SetPoint(3,40,Trg[4][1]);
pCNT->SetPointError(3,0,0,Trg[4][3],Trg[4][2]);
pCNT->SetPoint(4,50,Trg[4][1]);
pCNT->SetPointError(3,0,0,Trg[4][3],Trg[4][2]);
pCNT->SetPoint(5,60,Trg[5][1]);
pCNT->SetPointError(3,0,0,Trg[5][3],Trg[5][2]);
pCNT->SetPoint(6,70,Trg[6][1]);
pCNT->SetPointError(3,0,0,Trg[6][3],Trg[6][2]);
pCNT->SetPoint(7,80,Trg[7][1]);
pCNT->SetPointError(3,0,0,Trg[7][3],Trg[7][2]);
pCNT->SetPoint(8,90,Trg[8][1]);
pCNT->SetPointError(3,0,0,Trg[8][3],Trg[8][2]);
pCNT->SetMarkerColor(kRed+2);
pCNT->SetMarkerStyle(20);
}
pMBCNT->SetPoint(0,113.0558,Trg[0][1]);
pMBCNT->SetPointError(0,0,0,Trg[0][3],Trg[0][2]);
pMBCNT->SetMarkerColor(kRed+2);
pMBCNT->SetMarkerStyle(24);
gStyle->SetOptStat(0);
TH1F *hPad = new TH1F("hPad","",40,0,40);
hPad->SetTitle("");
formatTH1F(hPad,1,1,4);
hPad->Draw();
hPad->GetYaxis()->SetTitle("Efficiency");
hPad->GetXaxis()->SetTitle("Centrality bin");
if(Cent_) pCNT->Draw("pz same");
pMBCNT->Draw("pz same");
char legs[512];
TLegend *leg1 = new TLegend(0.369849,0.1853147,0.6809045,0.4527972,NULL,"brNDC"); // Size 0.03
leg1->SetFillStyle(0);
leg1->SetFillColor(0);
leg1->SetBorderSize(0);
leg1->SetTextSize(0.03);
leg1->SetHeader(leg_title);
if(Cent_) leg1->AddEntry(pCNT,"HLT_HIL1DoubleMuOpen","pl");
sprintf(legs,"HLT_HIL1DoubleMuOpen (MinBias) : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[0][1],Trg[0][2],Trg[0][3]);
leg1->AddEntry(pMBCNT,legs,"pl");
leg1->Draw("same");
if(MC_){
if(TrgMode_ == 1){
/*
c2->SaveAs("Jpsi_pPb_for_B_MC_Trg_New3_L1_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_MC_Trg_New3_L1_CNT.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_for_B_MC_Trg_New3_L2_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_MC_Trg_New3_L2_CNT.pdf");
*/
}
}else{
if(TrgMode_ == 1){
/*
c2->SaveAs("Jpsi_pPb_RD_TrgNew2Rfb_1st_run_L1_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_TrgNew2Rfb_1st_run_L1_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_TrgNew2Rfb_2nd_run_L1_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_TrgNew2Rfb_2nd_run_L1_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_TrgNew2CS_1st_run_L1_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_TrgNew2CS_1st_run_L1_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_TrgNew2CS_2nd_run_L1_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_TrgNew2CS_2nd_run_L1_CNT_test.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_for_B_RD_TrgNew2_L2_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_RD_TrgNew2_L2_CNT.pdf");
*/
}
}
if(Cent_) {
gTrgEta[1]->SetMarkerStyle(20);
gTrgEta[1]->SetMarkerColor(634);
gTrgEta[1]->GetXaxis()->SetTitle("#eta");;
gTrgEta[1]->GetXaxis()->CenterTitle();;
gTrgEta[2]->SetMarkerStyle(23);
gTrgEta[2]->SetMarkerColor(602);
gTrgEta[3]->SetMarkerStyle(24);
gTrgEta[3]->SetMarkerColor(618);
gTrgEta[4]->SetMarkerStyle(25);
gTrgEta[4]->SetMarkerColor(620);
gTrgEta[5]->SetMarkerStyle(26);
gTrgEta[5]->SetMarkerColor(621);
gTrgEta[6]->SetMarkerStyle(27);
gTrgEta[6]->SetMarkerColor(622);
gTrgEta[7]->SetMarkerStyle(28);
gTrgEta[7]->SetMarkerColor(623);
gTrgEta[8]->SetMarkerStyle(29);
gTrgEta[8]->SetMarkerColor(624);
gTrgEta[0]->SetMarkerStyle(21);
gTrgEta[0]->SetMarkerColor(802);
formatTH1F(hPadEta,1,1,2);
hPadEta->Draw();
gTrgEta[1]->SetMinimum(0.5);
gTrgEta[1]->SetMaximum(1.05);
gTrgEta[1]->Draw("pz same");
gTrgEta[2]->Draw("pz same");
gTrgEta[3]->Draw("pz same");
gTrgEta[4]->Draw("pz same");
gTrgEta[5]->Draw("pz same");
gTrgEta[6]->Draw("pz same");
gTrgEta[7]->Draw("pz same");
gTrgEta[8]->Draw("pz same");
gTrgEta[0]->Draw("pz same");
TLegend *leg2 = new TLegend(0.4899497,0.1678322,0.7876884,0.4947552,NULL,"brNDC"); // Size 0.03
leg2->SetFillStyle(0);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
leg2->SetTextSize(0.04);
if(MC_) leg2->SetHeader("MC Weighted HLT_HIL1DoubleMuOpen ");
if(!MC_) leg2->SetHeader("RD HLT_HIL1DoubleMuOpen ");
sprintf(legs,"0 - 5 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[1][1],Trg[1][2],Trg[1][3]);
leg2->AddEntry(gTrgEta[1],legs,"pl");
sprintf(legs,"5 - 10 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[2][1],Trg[2][2],Trg[2][3]);
leg2->AddEntry(gTrgEta[2],legs,"pl");
sprintf(legs,"10 - 20 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[3][1],Trg[3][2],Trg[3][3]);
leg2->AddEntry(gTrgEta[3],legs,"pl");
sprintf(legs,"20 - 30 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[4][1],Trg[4][2],Trg[4][3]);
leg2->AddEntry(gTrgEta[4],legs,"pl");
sprintf(legs,"30 - 40 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[5][1],Trg[5][2],Trg[5][3]);
leg2->AddEntry(gTrgEta[5],legs,"pl");
sprintf(legs,"40 - 50 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[6][1],Trg[6][2],Trg[6][3]);
leg2->AddEntry(gTrgEta[6],legs,"pl");
sprintf(legs,"50 - 60 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[7][1],Trg[7][2],Trg[7][3]);
leg2->AddEntry(gTrgEta[7],legs,"pl");
sprintf(legs,"60 - 100 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[8][1],Trg[8][2],Trg[8][3]);
leg2->AddEntry(gTrgEta[8],legs,"pl");
sprintf(legs,"MinBias : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[0][1],Trg[0][2],Trg[0][3]);
leg2->AddEntry(gTrgEta[0],legs,"pl");
leg2->Draw("same");
if(MC_){
if(TrgMode_ == 1){
/*
c2->SaveAs("Jpsi_pPb_for_B_MC_HLTL1_New3_eta_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_MC_HLTL1_New3_eta_CNT.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_for_B_MC_HLTL2_New3_eta_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_MC_HLTL2_New3_eta_CNT.pdf");
*/
}
}else{
if(TrgMode_ == 1){
/*
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2Rfb_1st_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2Rfb_1st_run_eta_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2Rfb_2nd_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2Rfb_2nd_run_eta_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2CS_1st_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2CS_1st_run_eta_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2CS_2nd_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2CS_2nd_run_eta_CNT_test.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_for_B_RD_HLTL2_New2_eta_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_RD_HLTL2_New2_eta_CNT.pdf");
*/
}
}
gTrgPt[1]->SetMarkerStyle(20);
gTrgPt[1]->SetMarkerColor(634);
gTrgPt[1]->GetXaxis()->SetTitle("p_{T} [GeV/c]");;
gTrgPt[1]->GetXaxis()->CenterTitle();;
gTrgPt[2]->SetMarkerStyle(23);
gTrgPt[2]->SetMarkerColor(602);
gTrgPt[3]->SetMarkerStyle(24);
gTrgPt[3]->SetMarkerColor(618);
gTrgPt[4]->SetMarkerStyle(25);
gTrgPt[4]->SetMarkerColor(620);
gTrgPt[5]->SetMarkerStyle(26);
gTrgPt[5]->SetMarkerColor(621);
gTrgPt[6]->SetMarkerStyle(27);
gTrgPt[6]->SetMarkerColor(622);
gTrgPt[7]->SetMarkerStyle(28);
gTrgPt[7]->SetMarkerColor(623);
gTrgPt[8]->SetMarkerStyle(29);
gTrgPt[8]->SetMarkerColor(624);
gTrgPt[0]->SetMarkerStyle(21);
gTrgPt[0]->SetMarkerColor(802);
formatTH1F(hPadPt,1,1,1);
hPadPt->Draw();
gTrgPt[1]->SetMinimum(0.5);
gTrgPt[1]->SetMaximum(1.05);
gTrgPt[1]->Draw("pz same");
gTrgPt[2]->Draw("pz same");
gTrgPt[3]->Draw("pz same");
gTrgPt[4]->Draw("pz same");
gTrgPt[5]->Draw("pz same");
gTrgPt[6]->Draw("pz same");
gTrgPt[7]->Draw("pz same");
gTrgPt[8]->Draw("pz same");
gTrgPt[0]->Draw("pz same");
TLegend *leg3 = new TLegend(0.4899497,0.1678322,0.7876884,0.4947552,NULL,"brNDC"); // Size 0.03
leg3->SetFillStyle(0);
leg3->SetFillColor(0);
leg3->SetBorderSize(0);
leg3->SetTextSize(0.04);
if(MC_) leg3->SetHeader("MC Weighted HLT_HIL1DoubleMuOpen ");
if(!MC_) leg3->SetHeader("RD HLT_HIL1DoubleMuOpen ");
sprintf(legs,"0 - 5 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[1][1],Trg[1][2],Trg[1][3]);
leg3->AddEntry(gTrgPt[1],legs,"pl");
sprintf(legs,"5 - 10 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[2][1],Trg[2][2],Trg[2][3]);
leg3->AddEntry(gTrgPt[2],legs,"pl");
sprintf(legs,"10 - 20 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[3][1],Trg[3][2],Trg[3][3]);
leg3->AddEntry(gTrgPt[3],legs,"pl");
sprintf(legs,"20 - 30 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[4][1],Trg[4][2],Trg[4][3]);
leg3->AddEntry(gTrgPt[4],legs,"pl");
sprintf(legs,"30 - 40 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[5][1],Trg[5][2],Trg[5][3]);
leg3->AddEntry(gTrgPt[5],legs,"pl");
sprintf(legs,"40 - 50 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[6][1],Trg[6][2],Trg[6][3]);
leg3->AddEntry(gTrgPt[6],legs,"pl");
sprintf(legs,"50 - 60 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[7][1],Trg[7][2],Trg[7][3]);
leg3->AddEntry(gTrgPt[7],legs,"pl");
sprintf(legs,"60 - 100 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[8][1],Trg[8][2],Trg[8][3]);
leg3->AddEntry(gTrgPt[8],legs,"pl");
sprintf(legs,"MinBias : %0.3f^{ +%0.4f}_{ -%0.4f}",Trg[0][1],Trg[0][2],Trg[0][3]);
leg3->AddEntry(gTrgPt[0],legs,"pl");
leg3->Draw("same");
if(MC_){
if(TrgMode_ == 1){
/*
c2->SaveAs("Jpsi_pPb_for_B_MC_HLTL1_New2_pt_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_MC_HLTL1_New2_pt_CNT.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_for_B_MC_HLTL2_New2_pt_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_MC_HLTL2_New2_pt_CNT.pdf");
*/
}
}else{
if(TrgMode_ == 1){
/*
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2Rfb_1st_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2Rfb_1st_run_pt_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2Rfb_2nd_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2Rfb_2nd_run_pt_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2CS_1st_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2CS_1st_run_pt_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2CS_2nd_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_HLTL1_New2CS_2nd_run_pt_CNT_test.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_for_B_RD_HLTL2_New2_pt_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_RD_HLTL2_New2_pt_CNT.pdf");
*/
}
}
}
outfile->cd();
if(Cent_){
gTrgPt[1]->SetName("gTrg0005Pt");
gTrgPt[2]->SetName("gTrg0510Pt");
gTrgPt[3]->SetName("gTrg1020Pt");
gTrgPt[4]->SetName("gTrg2030Pt");
gTrgPt[5]->SetName("gTrg3040Pt");
gTrgPt[6]->SetName("gTrg4050Pt");
gTrgPt[7]->SetName("gTrg5060Pt");
gTrgPt[8]->SetName("gTrg60100Pt");
gTrgEta[1]->SetName("gTrg0005Eta");
gTrgEta[2]->SetName("gTrg0510Eta");
gTrgEta[3]->SetName("gTrg1020Eta");
gTrgEta[4]->SetName("gTrg2030Eta");
gTrgEta[5]->SetName("gTrg3040Eta");
gTrgEta[6]->SetName("gTrg4050Eta");
gTrgEta[7]->SetName("gTrg5060Eta");
gTrgEta[8]->SetName("gTrg60100Eta");
gTrgPt[1]->Write();
gTrgPt[2]->Write();
gTrgPt[3]->Write();
gTrgPt[4]->Write();
gTrgPt[5]->Write();
gTrgPt[6]->Write();
gTrgPt[7]->Write();
gTrgPt[8]->Write();
gTrgEta[1]->Write();
gTrgEta[2]->Write();
gTrgEta[3]->Write();
gTrgEta[4]->Write();
gTrgEta[5]->Write();
gTrgEta[6]->Write();
gTrgEta[7]->Write();
gTrgEta[8]->Write();
}
gTrgPt[0]->SetName("gMBTrgPt");
gTrgEta[0]->SetName("gMBTrgEta");
gTrg[0]->SetName("gMBTrg");
pCNT->SetName("pCNT");
pMBCNT->SetName("pMBCNT");
gTrgPt[0]->Write();
gTrgEta[0]->Write();
gTrg[0]->Write();
pCNT->Write();
pMBCNT->Write();
outfile->Close();
//f->Close();
//files->Close();
}
void formatTH1F(TH1* a, int b, int c, int d){
a->SetLineWidth(2);
a->SetLineStyle(c);
a->SetMarkerSize(2);
a->SetLineColor(b);
a->SetMarkerColor(b);
a->GetYaxis()->SetTitle("Efficiency");
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} [GeV/c]");
}else if(d == 2){
a->GetXaxis()->SetTitle("#eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}
a->GetXaxis()->CenterTitle(true);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.05);
a->GetXaxis()->SetTitleOffset(0.9);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(0.8);
}
void formatTLeg(TLegend* a){
a->SetFillStyle(0);
a->SetFillColor(0);
a->SetBorderSize(0);
a->SetTextSize(0.03);
}
void formatTGraph(TGraph* a, int b, int c, int d)
{
a->SetMarkerStyle(c);
a->SetMarkerColor(b);
a->SetMarkerSize(1.0);
a->SetLineColor(b);
a->SetLineWidth(1);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.06);
a->GetXaxis()->SetTitleOffset(0.9);
a->GetYaxis()->SetTitle("Efficiency");
a->GetXaxis()->CenterTitle();
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} (GeV/c)");
}else if(d == 2){
a->GetXaxis()->SetTitle("eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}
a->GetYaxis()->SetRangeUser(0,1);
a->GetXaxis()->SetRangeUser(0,10);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(0.9);
}
TGraphAsymmErrors *plotEffEta(RooDataSet *a, int aa){
const RooArgSet *set = a->get();
RooRealVar *xAx = (RooRealVar*)set->find("eta");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
const int nbins = xAx->getBinning().numBins();
double tx[nbins], txhi[nbins], txlo[nbins];
double ty[nbins], tyhi[nbins], tylo[nbins];
for (int i=0; i<nbins; i++) {
a->get(i);
ty[i] = eff->getVal();
tx[i] = xAx->getVal();
txhi[i] = fabs(xAx->getErrorHi());
txlo[i] = fabs(xAx->getErrorLo());
tyhi[i] = fabs(eff->getErrorHi());
tylo[i] = fabs(eff->getErrorLo());
}
cout<<"NBins : "<<nbins<<endl;
const double *x = tx;
const double *xhi = txhi;
const double *xlo = txlo;
const double *y = ty;
const double *yhi = tyhi;
const double *ylo = tylo;
TGraphAsymmErrors *b = new TGraphAsymmErrors();
if(aa == 1) {*b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi);}
if(aa == 0) {*b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi);}
b->SetMaximum(1.1);
b->SetMinimum(0.0);
b->SetMarkerStyle(20);
b->SetMarkerColor(kRed+2);
b->SetMarkerSize(1.0);
b->SetTitle("");
b->GetXaxis()->SetTitleSize(0.05);
b->GetYaxis()->SetTitleSize(0.05);
b->GetXaxis()->SetTitle("#eta");
b->GetYaxis()->SetTitle("Efficiency");
b->GetXaxis()->CenterTitle();
//b->Draw("apz");
for (int i=0; i<nbins; i++) {
cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl;
}
return b;
}
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa){
const RooArgSet *set = a->get();
RooRealVar *xAx = (RooRealVar*)set->find("pt");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
const int nbins = xAx->getBinning().numBins();
double tx[nbins], txhi[nbins], txlo[nbins];
double ty[nbins], tyhi[nbins], tylo[nbins];
for (int i=0; i<nbins; i++) {
a->get(i);
ty[i] = eff->getVal();
tx[i] = xAx->getVal();
txhi[i] = fabs(xAx->getErrorHi());
txlo[i] = fabs(xAx->getErrorLo());
tyhi[i] = fabs(eff->getErrorHi());
tylo[i] = fabs(eff->getErrorLo());
}
cout<<"NBins : "<<nbins<<endl;
const double *x = tx;
const double *xhi = txhi;
const double *xlo = txlo;
const double *y = ty;
const double *yhi = tyhi;
const double *ylo = tylo;
TGraphAsymmErrors *b = new TGraphAsymmErrors();
if(aa == 1) {*b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi);}
if(aa == 0) {*b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi);}
b->SetMaximum(1.1);
b->SetMinimum(0.0);
b->SetMarkerStyle(20);
b->SetMarkerColor(kRed+2);
b->SetMarkerSize(1.0);
b->SetTitle("");
b->GetXaxis()->SetTitleSize(0.05);
b->GetYaxis()->SetTitleSize(0.05);
b->GetXaxis()->SetTitle("p_{T} [GeV/c]");
b->GetYaxis()->SetTitle("Efficiency");
b->GetXaxis()->CenterTitle();
//b->Draw("apz");
for (int i=0; i<nbins; i++) {
cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl;
}
return b;
}
TH2F *plotEff2D(RooDataSet *a, TString b){
const RooArgSet *set = a->get();
RooRealVar *yAx = (RooRealVar*)set->find("pt");
RooRealVar *xAx = (RooRealVar*)set->find("eta");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
//const int xnbins = xAx->getBinning().numBins();
//const int ynbins = yAx->getBinning().numBins();
const double *xvbins = xAx->getBinning().array();
const double *yvbins = yAx->getBinning().array();
TH2F* h = new TH2F(b, "", xAx->getBinning().numBins(), xvbins, yAx->getBinning().numBins(), yvbins);
gStyle->SetPaintTextFormat("5.2f");
gStyle->SetPadRightMargin(0.12);
gStyle->SetPalette(1);
h->SetOption("colztexte");
h->GetZaxis()->SetRangeUser(-0.001,1.001);
h->SetStats(kFALSE);
h->GetYaxis()->SetTitle("p_{T} [GeV/c]");
h->GetXaxis()->SetTitle("#eta");
h->GetXaxis()->CenterTitle();
h->GetYaxis()->CenterTitle();
h->GetXaxis()->SetTitleSize(0.05);
h->GetYaxis()->SetTitleSize(0.05);
h->GetYaxis()->SetTitleOffset(0.8);
h->GetXaxis()->SetTitleOffset(0.9);
for(int i=0; i<a->numEntries(); i++){
a->get(i);
h->SetBinContent(h->FindBin(xAx->getVal(), yAx->getVal()), eff->getVal());
h->SetBinError(h->FindBin(xAx->getVal(), yAx->getVal()), (eff->getErrorHi()-eff->getErrorLo())/2.);
}
return h;
}
<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/Efficiency/MC/MuID/TnPEffMuIdDraw_etabin2_for_B_GEN_matching.C
#include <iostream>
#include <TSystem.h>
#include <TTree.h>
#include <TKey.h>
#include <TH1.h>
#include <TH2.h>
#include <TPave.h>
#include <TText.h>
#include <fstream>
#include <sstream>
#include <string.h>
#include <TROOT.h>
#include <TFile.h>
#include <TGraphAsymmErrors.h>
#include <TH1.h>
#include <TH2.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <RooFit.h>
#include <RooRealVar.h>
#include <RooDataSet.h>
#include <RooArgSet.h>
#include <TStyle.h>
#include <TLatex.h>
#include <TDirectory.h>
#include <TCollection.h>
#include <TPostScript.h>
using namespace RooFit;
using namespace std;
// Function Define
TH2F *plotEff2D(RooDataSet *a, TString b);
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa);
TGraphAsymmErrors *plotEffEta(RooDataSet *a, int aa);
void formatTH1F(TH1* a, int b, int c, int d);
void formatTGraph(TGraph* a, int b, int c, int d);
void formatTLeg(TLegend* a);
void TnPEffMuIdDraw_etabin2_1st_for_B();
// From here you need to set up your environments.
bool MC_ = false; // if the data set is real data, it should be false
bool Cent_ = false; // if the data is only one MinBias file, it shoud be false
const int maxFile_ = 1; // the number of data files, usually it should be 4 but 1 in the case of MinBias
char *outfile_ = "Jpsi_pPb_RD_MuIdNew2etabin2CS_CBpPoly_1st_Run_Eff_for_B_test.root";
//char *outfile_ = "Jpsi_pPb_MC_MuIdNew2etabin2CS_CBpPoly_1st_Run_Eff_for_B_test.root";
string dir_suffix = "_CBPlusPoly"; // depends on which fit function is used for : eg) _gaussExpo, _gaussPol2
void TnPEffMuIdDraw_etabin2_1st_for_B() {
gROOT->Macro("rootlogon.C");
char *files[maxFile_] = {
"tnp_pPb_Ana_MuIdNew2etabin2CS_CBpPoly_1st_Run_All_for_B_test.root",
// "tnp_pPb_Ana_MuIdNew2etabin2CS_CBpPoly_MC_All_for_B_test.root",
};
TString outname_in, outname_mid, outname_out;
TString middle_name, middle_name2;
TString leg_title;
int Mode = 0;
TFile *outfile = new TFile(outfile_,"RECREATE");
for(int l = 0; l < maxFile_; l++){
char *infile = files[l];
TFile *f = new TFile(infile);
Mode = l;
if(Mode == 0){
middle_name = "All";
middle_name2 = "MinBias";
}else if(Mode == 1){
middle_name = "0005";
middle_name2 = "0 - 5 %";
}else if(Mode == 2){
middle_name = "0510";
middle_name2 = "5 - 10 %";
}else if(Mode == 3){
middle_name = "1020";
middle_name2 = "10 - 20 %";
}else if(Mode == 4){
middle_name = "2030";
middle_name2 = "20 - 30 %";
}else if(Mode == 5){
middle_name = "3040";
middle_name2 = "30 - 40 %";
}else if(Mode == 6){
middle_name = "4050";
middle_name2 = "40 - 50 %";
}else if(Mode == 7){
middle_name = "5060";
middle_name2 = "50 - 60 %";
}else if(Mode == 8){
middle_name = "60100";
middle_name2 = "60 - 100 %";
}
gROOT->SetStyle("Plain");
gStyle->SetOptStat(0);
gStyle->SetTitle(0);
// if you have only one file, should change the number 4 -> 1
TString mid_title = "Centrality : (" + middle_name2 + ")";
if(!MC_) leg_title = "Data MuId Efficiency (" + middle_name2 + ")";
if(MC_) leg_title = "MC MuId Efficiency (" + middle_name2 + ")";
TCanvas *c1 = new TCanvas("c1","",120,20,800,600);
f->cd();
RooDataSet *daMuIdEta1bin = (RooDataSet*)f->Get("MuonIDNew2etabin2CS/PassingTrk_1bin_eta_pt/fit_eff");
TGraphAsymmErrors *MuId_1bin_pt_eta = plotEffEta(daMuIdEta1bin, 1);
double Id[4];
MuId_1bin_pt_eta->GetPoint(0,Id[0],Id[1]);
Id[2] = MuId_1bin_pt_eta->GetErrorYhigh(0);
Id[3] = MuId_1bin_pt_eta->GetErrorYlow(0);
RooDataSet *daMuIdPt = (RooDataSet*)f->Get("MuonIDNew2etabin2CS/PassingTrk_pt/fit_eff");
TGraphAsymmErrors *MuId_pt = plotEffPt(daMuIdPt, 1);
/*
RooDataSet *daMuId2D = (RooDataSet*)f->Get("MuonID/PassingTrk_pt_eta/fit_eff");
TString twoDName1 = "MuId_2d";
TH2F *MuId_2d = plotEff2D(daMuId2D, twoDName1);
*/
char legs[512];
TString pic_name_png, pic_name_pdf;
MuId_pt->GetXaxis()->SetLabelSize(0.05);
MuId_pt->GetYaxis()->SetLabelSize(0.05);
MuId_pt->GetXaxis()->SetTitleSize(0.05);
MuId_pt->GetYaxis()->SetTitleSize(0.05);
MuId_pt->GetXaxis()->SetTitleOffset(0.9);
MuId_pt->GetYaxis()->SetTitleOffset(0.8);
MuId_pt->SetMarkerColor(kRed+2);
MuId_pt->Draw("apz");
TLegend *leg2 = new TLegend(0.3454774,0.2167832,0.5429648,0.4458042,NULL,"brNDC");
leg2->SetFillStyle(0);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
leg2->SetTextSize(0.04);
leg2->SetHeader(leg_title);
sprintf(legs,"MuId Efficiency: %0.3f^{ +%0.4f}_{ -%0.4f}",Id[1],Id[2],Id[3]);
leg2->AddEntry(MuId_pt,legs,"pl");
leg2->Draw("same");
if(MC_){
pic_name_png = "Jpsi_pPb_MC_MuIdNew2etabin2CS_" + middle_name + "_pt_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_MC_MuIdNew2etabin2CS_" + middle_name + "_pt_for_B_test.pdf";
}else{
pic_name_png = "Jpsi_pPb_RD_MuIdNew2etabin2CS_1st_run_" + middle_name + "_pt_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_RD_MuIdNew2etabin2CS_1st_run_" + middle_name + "_pt_for_B_test.pdf";
}
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
/*
MuId_2d->Draw();
pic_name_png = "Psi2s_MC_MuId_" + middle_name + "_2d.png";
pic_name_pdf = "Psi2s_MC_MuId_" + middle_name + "_2d.pdf";
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
c1->Print("Psi2s_MC_MuId_Eff_total.ps");
*/
TString Idna1, Idna2, Idna3, Idna4;
Idna1 = "MuId_eta_" + middle_name;
Idna2 = "MuId_1bin_pt_eta_" + middle_name;
Idna3 = "MuId_pt_" + middle_name;
Idna4 = "MuId_2d_" + middle_name;
MuId_1bin_pt_eta->SetName(Idna2);
MuId_pt->SetName(Idna3);
//MuId_2d->SetName(Idna4);
outfile->cd();
MuId_pt->Write();
MuId_1bin_pt_eta->Write();
//MuId_2d->Write();
}
// Comparing Plots as the Centralities
//c2->cd();
outfile->Close();
//f->Close();
//files->Close();
}
void formatTH1F(TH1* a, int b, int c, int d){
a->SetLineWidth(2);
a->SetLineStyle(c);
a->SetMarkerSize(2);
a->SetLineColor(b);
a->SetMarkerColor(b);
a->GetYaxis()->SetTitle("Efficiency");
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} [GeV/c]");
}else if(d == 2){
a->GetXaxis()->SetTitle("#eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}
a->GetXaxis()->CenterTitle(true);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.05);
a->GetXaxis()->SetTitleOffset(0.9);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(0.8);
}
void formatTLeg(TLegend* a){
a->SetFillStyle(0);
a->SetFillColor(0);
a->SetBorderSize(0);
a->SetTextSize(0.03);
}
void formatTGraph(TGraph* a, int b, int c, int d)
{
a->SetMarkerStyle(c);
a->SetMarkerColor(b);
a->SetMarkerSize(1.0);
a->SetLineColor(b);
a->SetLineWidth(1);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.06);
a->GetXaxis()->SetTitleOffset(0.9);
a->GetYaxis()->SetTitle("Efficiency");
a->GetXaxis()->CenterTitle();
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} (GeV/c)");
}else if(d == 2){
a->GetXaxis()->SetTitle("eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}
a->GetYaxis()->SetRangeUser(0,1);
a->GetXaxis()->SetRangeUser(0,10);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(0.9);
}
TGraphAsymmErrors *plotEffEta(RooDataSet *a, int aa){
const RooArgSet *set = a->get();
RooRealVar *xAx = (RooRealVar*)set->find("eta");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
const int nbins = xAx->getBinning().numBins();
double tx[nbins], txhi[nbins], txlo[nbins];
double ty[nbins], tyhi[nbins], tylo[nbins];
for (int i=0; i<nbins; i++) {
a->get(i);
ty[i] = eff->getVal();
tx[i] = xAx->getVal();
txhi[i] = fabs(xAx->getErrorHi());
txlo[i] = fabs(xAx->getErrorLo());
tyhi[i] = fabs(eff->getErrorHi());
tylo[i] = fabs(eff->getErrorLo());
}
cout<<"NBins : "<<nbins<<endl;
const double *x = tx;
const double *xhi = txhi;
const double *xlo = txlo;
const double *y = ty;
const double *yhi = tyhi;
const double *ylo = tylo;
TGraphAsymmErrors *b = new TGraphAsymmErrors();
if(aa == 1) {*b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi);}
if(aa == 0) {*b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi);}
b->SetMaximum(1.1);
b->SetMinimum(0.0);
b->SetMarkerStyle(20);
b->SetMarkerColor(kRed+2);
b->SetMarkerSize(1.0);
b->SetTitle("");
b->GetXaxis()->SetTitleSize(0.05);
b->GetYaxis()->SetTitleSize(0.05);
b->GetXaxis()->SetTitle("#eta");
b->GetYaxis()->SetTitle("Efficiency");
b->GetXaxis()->CenterTitle();
//b->Draw("apz");
for (int i=0; i<nbins; i++) {
cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl;
}
return b;
}
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa){
const RooArgSet *set = a->get();
RooRealVar *xAx = (RooRealVar*)set->find("pt");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
const int nbins = xAx->getBinning().numBins();
double tx[nbins], txhi[nbins], txlo[nbins];
double ty[nbins], tyhi[nbins], tylo[nbins];
for (int i=0; i<nbins; i++) {
a->get(i);
ty[i] = eff->getVal();
tx[i] = xAx->getVal();
txhi[i] = fabs(xAx->getErrorHi());
txlo[i] = fabs(xAx->getErrorLo());
tyhi[i] = fabs(eff->getErrorHi());
tylo[i] = fabs(eff->getErrorLo());
}
cout<<"NBins : "<<nbins<<endl;
const double *x = tx;
const double *xhi = txhi;
const double *xlo = txlo;
const double *y = ty;
const double *yhi = tyhi;
const double *ylo = tylo;
TGraphAsymmErrors *b = new TGraphAsymmErrors();
if(aa == 1) {*b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi);}
if(aa == 0) {*b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi);}
b->SetMaximum(1.1);
b->SetMinimum(0.0);
b->SetMarkerStyle(20);
b->SetMarkerColor(kRed+2);
b->SetMarkerSize(1.0);
b->SetTitle("");
b->GetXaxis()->SetTitleSize(0.05);
b->GetYaxis()->SetTitleSize(0.05);
b->GetXaxis()->SetTitle("p_{T} [GeV/c]");
b->GetYaxis()->SetTitle("Efficiency");
b->GetXaxis()->CenterTitle();
//b->Draw("apz");
for (int i=0; i<nbins; i++) {
cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl;
}
return b;
}
TH2F *plotEff2D(RooDataSet *a, TString b){
const RooArgSet *set = a->get();
RooRealVar *yAx = (RooRealVar*)set->find("pt");
RooRealVar *xAx = (RooRealVar*)set->find("eta");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
//const int xnbins = xAx->getBinning().numBins();
//const int ynbins = yAx->getBinning().numBins();
const double *xvbins = xAx->getBinning().array();
const double *yvbins = yAx->getBinning().array();
TH2F* h = new TH2F(b, "", xAx->getBinning().numBins(), xvbins, yAx->getBinning().numBins(), yvbins);
gStyle->SetPaintTextFormat("5.2f");
gStyle->SetPadRightMargin(0.12);
gStyle->SetPalette(1);
h->SetOption("colztexte");
h->GetZaxis()->SetRangeUser(-0.001,1.001);
h->SetStats(kFALSE);
h->GetYaxis()->SetTitle("p_{T} [GeV/c]");
h->GetXaxis()->SetTitle("#eta");
h->GetXaxis()->CenterTitle();
h->GetYaxis()->CenterTitle();
h->GetXaxis()->SetTitleSize(0.05);
h->GetYaxis()->SetTitleSize(0.05);
h->GetYaxis()->SetTitleOffset(0.8);
h->GetXaxis()->SetTitleOffset(0.9);
for(int i=0; i<a->numEntries(); i++){
a->get(i);
h->SetBinContent(h->FindBin(xAx->getVal(), yAx->getVal()), eff->getVal());
h->SetBinError(h->FindBin(xAx->getVal(), yAx->getVal()), (eff->getErrorHi()-eff->getErrorLo())/2.);
}
return h;
}
<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/Efficiency/MC/MuTrk/TnPEffTrkDraw_for_B_no_matching.C
#include <iostream>
#include <TSystem.h>
#include <TTree.h>
#include <TKey.h>
#include <TH1.h>
#include <TH2.h>
#include <TPave.h>
#include <TText.h>
#include <sstream>
#include <string.h>
#include <TROOT.h>
#include <TFile.h>
#include <TGraphAsymmErrors.h>
#include <TH1.h>
#include <TH2.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <RooFit.h>
#include <RooRealVar.h>
#include <RooDataSet.h>
#include <RooArgSet.h>
#include <TStyle.h>
#include <TLatex.h>
#include <TDirectory.h>
#include <TCollection.h>
#include <TPostScript.h>
using namespace RooFit;
using namespace std;
// Function Define
TH2F *plotEff2D(RooDataSet *a, TString b);
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa);
TGraphAsymmErrors *plotEffEta(RooDataSet *a, int aa);
void formatTH1F(TH1* a, int b, int c, int d);
void formatTGraph(TGraph* a, int b, int c, int d);
void formatTLeg(TLegend* a);
void TnPEffTrkDraw_for_B ();
// From here you need to set up your environments.
bool MC_ = false; // if the data set is real data, it should be false
bool Cent_ = false; // if the data is only one MinBias file, it shoud be false
const int maxFile_ = 1; // the number of data files, usually it should be 4 but 1 in the case of MinBias
char *outfile_ = "Jpsi_pPb_RD_MuTrk2_CBpPoly_1st_Run_Eff_for_B_test.root";
//char *outfile_ = "Jpsi_pPb_MC_MuTrk2_CBpPoly_1st_Run_Eff_for_B_test.root";
string dir_suffix = "_gaussPlusPoly"; // depends on which fit function is used for : eg) _gaussExpo, _gaussPol2
void TnPEffTrkDraw_for_B () {
gROOT->Macro("rootlogon.C");
// input your tnp_Ana_*.root files instead of "_input_file_"
char *files[maxFile_] = {
"tnp_pPb_Ana_MuTrk2_2GpP4_1st_Run_All_for_B_test.root",
// "tnp_pPb_Ana_MuTrk2_2GpP4_MC_All_for_B_test.root",
};
TString outname_in, outname_mid, outname_out;
TString middle_name, middle_name2;
TString leg_title;
int Mode = 0;
TFile *outfile = new TFile(outfile_,"RECREATE");
for(int l = 0; l < maxFile_; l++){
char *infile = files[l];
TFile *f = new TFile(infile);
Mode = l;
if(Mode == 0){
middle_name = "All";
middle_name2 = "MinBias";
}else if(Mode == 1){
middle_name = "0005";
middle_name2 = "0 - 5 %";
}else if(Mode == 2){
middle_name = "0510";
middle_name2 = "5 - 10 %";
}else if(Mode == 3){
middle_name = "1020";
middle_name2 = "10 - 20 %";
}else if(Mode == 4){
middle_name = "2030";
middle_name2 = "20 - 30 %";
}else if(Mode == 5){
middle_name = "3040";
middle_name2 = "30 - 40 %";
}else if(Mode == 6){
middle_name = "5050";
middle_name2 = "40 - 50 %";
}else if(Mode == 7){
middle_name = "5060";
middle_name2 = "50 - 60 %";
}else if(Mode == 8){
middle_name = "60100";
middle_name2 = "60 - 100 %";
}
gROOT->SetStyle("Plain");
gStyle->SetOptStat(0);
gStyle->SetTitle(0);
// if you have only one file, should change the number 4 -> 1
TString mid_title = "Centrality : (" + middle_name2 + ")";
if(!MC_) leg_title = "Data Inner Tracking Efficiency (" + middle_name2 + ")";
if(MC_) leg_title = "MC Inner Tracking Efficiency (" + middle_name2 + ")";
TCanvas *c1 = new TCanvas("c1","",120,20,800,600);
f->cd();
RooDataSet *daTrkEta = (RooDataSet*)f->Get("MuonTrk2/isTrk_eta/fit_eff");
RooDataSet *daTrkEta1bin = (RooDataSet*)f->Get("MuonTrk2/isTrk_1bin_pt_eta/fit_eff");
TGraphAsymmErrors *Trk_eta = plotEffEta(daTrkEta, 1);
TGraphAsymmErrors *Trk_1bin_pt_eta = plotEffEta(daTrkEta1bin, 1);
double Trk[4];
Trk_1bin_pt_eta->GetPoint(0,Trk[0],Trk[1]);
Trk[2] = Trk_1bin_pt_eta->GetErrorYhigh(0);
Trk[3] = Trk_1bin_pt_eta->GetErrorYlow(0);
RooDataSet *daTrkPt = (RooDataSet*)f->Get("MuonTrk2/isTrk_pt/fit_eff");
TGraphAsymmErrors *Trk_pt = plotEffPt(daTrkPt, 1);
/*
RooDataSet *daTrk2D = (RooDataSet*)f->Get("MuonTrk/is_Trk_pt_eta/fit_eff");
TString twoDName1 = "Trk_2d";
TH2F *Trk_2d = plotEff2D(daTrk2D, twoDName1);
*/
Trk_eta->GetXaxis()->SetLabelSize(0.05);
Trk_eta->GetYaxis()->SetLabelSize(0.05);
Trk_eta->GetXaxis()->SetTitleSize(0.05);
Trk_eta->GetYaxis()->SetTitleSize(0.05);
Trk_eta->GetXaxis()->SetTitleOffset(0.9);
Trk_eta->GetYaxis()->SetTitleOffset(0.8);
Trk_eta->SetMarkerColor(kRed+2);
Trk_eta->Draw("apz");
char legs[512];
TLegend *leg1 = new TLegend(0.3054774,0.1567832,0.5429648,0.3858042,NULL,"brNDC");
leg1->SetFillStyle(0);
leg1->SetFillColor(0);
leg1->SetBorderSize(0);
leg1->SetTextSize(0.04);
leg1->SetHeader(leg_title);
sprintf(legs,"Inner Tracking Efficiency: %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[1],Trk[2],Trk[3]);
leg1->AddEntry(Trk_eta,legs,"pl");
leg1->Draw("same");
TString pic_name_png, pic_name_pdf;
if(MC_){
pic_name_png = "Jpsi_pPb_MC_Trk2_" + middle_name + "_eta_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_MC_Trk2_" + middle_name + "_eta_for_B_test.pdf";
}else{
pic_name_png = "Jpsi_pPb_RD_Trk2_1st_run_" + middle_name + "_eta_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_RD_Trk2_1st_run_" + middle_name + "_eta_for_B_test.pdf";
}
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
Trk_pt->GetXaxis()->SetLabelSize(0.05);
Trk_pt->GetYaxis()->SetLabelSize(0.05);
Trk_pt->GetXaxis()->SetTitleSize(0.05);
Trk_pt->GetYaxis()->SetTitleSize(0.05);
Trk_pt->GetXaxis()->SetTitleOffset(0.9);
Trk_pt->GetYaxis()->SetTitleOffset(0.8);
Trk_pt->SetMarkerColor(kRed+2);
Trk_pt->Draw("apz");
TLegend *leg2 = new TLegend(0.3454774,0.2167832,0.5429648,0.4458042,NULL,"brNDC");
leg2->SetFillStyle(0);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
leg2->SetTextSize(0.04);
leg2->SetHeader(leg_title);
sprintf(legs,"Inner Tracking Efficiency: %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[1],Trk[2],Trk[3]);
leg2->AddEntry(Trk_pt,legs,"pl");
leg2->Draw("same");
if(MC_){
pic_name_png = "Jpsi_pPb_MC_Trk2_" + middle_name + "_pt_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_MC_Trk2_" + middle_name + "_pt_for_B_test.pdf";
}else{
pic_name_png = "Jpsi_pPb_RD_Trk2_1st_run_" + middle_name + "_pt_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_RD_Trk2_1st_run_" + middle_name + "_pt_for_B_test.pdf";
}
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
/*
Trk_2d->Draw();
pic_name_png = "Jpsi_pPb_MC_Trk_" + middle_name + "_2d.png";
pic_name_pdf = "Jpsi_pPb_MC_Trk_" + middle_name + "_2d.pdf";
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
c1->Print("Jpsi_pPb_MC_Trk_Eff_total.ps");
*/
TString Trkna1, Trkna2, Trkna3, Trkna4;
Trkna1 = "Trk_eta_" + middle_name;
Trkna2 = "Trk_1bin_pt_eta_" + middle_name;
Trkna3 = "Trk_pt_" + middle_name;
Trkna4 = "Trk_2d_" + middle_name;
Trk_eta->SetName(Trkna1);
Trk_1bin_pt_eta->SetName(Trkna2);
Trk_pt->SetName(Trkna3);
//Trk_2d->SetName(Trkna4);
outfile->cd();
Trk_eta->Write();
Trk_pt->Write();
Trk_1bin_pt_eta->Write();
//Trk_2d->Write();
}
// Comparing Plots as the Centralities
TH1F *hPadEta = new TH1F("hPadEta","",15,-2.4,2.4);
TH1F *hPadPt = new TH1F("hPadPt","",12,0,30);
TCanvas *c2 = new TCanvas("c2","",120,20,800,600);
//c2->cd();
TGraphAsymmErrors *gTrk[maxFile_];
TGraphAsymmErrors *gTrkEta[maxFile_];
TGraphAsymmErrors *gTrkPt[maxFile_];
double Trk[maxFile_][4];
for(int i = 0; i < maxFile_; i++){
TFile finput(files[i]);
finput.cd();
RooDataSet *dataTrk = (RooDataSet*)finput.Get("MuonTrk2/isTrk_1bin_pt_eta/fit_eff");
RooDataSet *dataTrkEta = (RooDataSet*)finput.Get("MuonTrk2/isTrk_eta/fit_eff");
RooDataSet *dataTrkPt = (RooDataSet*)finput.Get("MuonTrk2/isTrk_pt/fit_eff");
gTrk[i] = plotEffEta(dataTrk, 0);
gTrkEta[i] = plotEffEta(dataTrkEta, 0);
gTrkPt[i] = plotEffPt(dataTrkPt, 0);
gTrk[i]->GetPoint(0,Trk[i][0],Trk[i][1]);
Trk[i][2] = gTrk[i]->GetErrorYhigh(0);
Trk[i][3] = gTrk[i]->GetErrorYlow(0);
cout<<"Trk["<<i<<"][1] : "<<Trk[i][1]<<endl;
}
TGraphAsymmErrors *pCNT = new TGraphAsymmErrors(3);
TGraphAsymmErrors *pMBCNT = new TGraphAsymmErrors();
if(Cent_){
pCNT->SetPoint(0,10,Trk[1][1]);
pCNT->SetPointError(0,0,0,Trk[1][3],Trk[1][2]);
pCNT->SetPoint(1,20,Trk[2][1]);
pCNT->SetPointError(1,0,0,Trk[2][3],Trk[2][2]);
pCNT->SetPoint(2,30,Trk[3][1]);
pCNT->SetPointError(2,0,0,Trk[3][3],Trk[3][2]);
pCNT->SetPoint(3,40,Trk[4][1]);
pCNT->SetPointError(3,0,0,Trk[4][3],Trk[4][2]);
pCNT->SetPoint(4,50,Trk[5][1]);
pCNT->SetPointError(4,0,0,Trk[5][3],Trk[5][2]);
pCNT->SetPoint(5,60,Trk[6][1]);
pCNT->SetPointError(5,0,0,Trk[6][3],Trk[6][2]);
pCNT->SetPoint(6,70,Trk[7][1]);
pCNT->SetPointError(6,0,0,Trk[7][3],Trk[7][2]);
pCNT->SetPoint(7,80,Trk[8][1]);
pCNT->SetPointError(7,0,0,Trk[8][3],Trk[8][2]);
pCNT->SetMarkerColor(kRed+2);
pCNT->SetMarkerStyle(20);
}
pMBCNT->SetPoint(0,113.0528,Trk[0][1]);
pMBCNT->SetPointError(0,0,0,Trk[0][3],Trk[0][2]);
pMBCNT->SetMarkerColor(kRed+2);
pMBCNT->SetMarkerStyle(24);
gStyle->SetOptStat(0);
TH1F *hPad = new TH1F("hPad","",40,0,40);
hPad->SetTitle("");
formatTH1F(hPad,1,1,4);
hPad->Draw();
hPad->GetYaxis()->SetTitle("Efficiency");
hPad->GetXaxis()->SetTitle("Centrality bin");
if(Cent_) pCNT->Draw("pz same");
pMBCNT->Draw("pz same");
char legs[512];
TLegend *leg1 = new TLegend(0.369849,0.1853147,0.6809045,0.4527972,NULL,"brNDC"); // Size 0.03
leg1->SetFillStyle(0);
leg1->SetFillColor(0);
leg1->SetBorderSize(0);
leg1->SetTextSize(0.03);
leg1->SetHeader(leg_title);
if(Cent_) leg1->AddEntry(pCNT,"Inner Tracking Efficiency","pl");
sprintf(legs,"Inner Tracking Efficiency: %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[0][1],Trk[0][2],Trk[0][3]);
leg1->AddEntry(pMBCNT,legs,"pl");
leg1->Draw("same");
if(MC_){
/*
c2->SaveAs("Jpsi_pPb_for_B_MC_Trk_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_MC_Trk_CNT.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_RD_Trk_1st_run_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_Trk_1st_run_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_Trk2_1st_run_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_Trk2_1st_run_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_Trk_2nd_run_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_Trk_2nd_run_CNT_test.pdf");
*/
}
if(Cent_) {
gTrkEta[1]->SetMarkerStyle(20);
gTrkEta[1]->SetMarkerColor(634);
gTrkEta[1]->GetXaxis()->SetTitle("#eta");;
gTrkEta[1]->GetXaxis()->CenterTitle();;
gTrkEta[2]->SetMarkerStyle(23);
gTrkEta[2]->SetMarkerColor(602);
gTrkEta[3]->SetMarkerStyle(24);
gTrkEta[3]->SetMarkerColor(618);
gTrkEta[4]->SetMarkerStyle(25);
gTrkEta[4]->SetMarkerColor(620);
gTrkEta[5]->SetMarkerStyle(26);
gTrkEta[5]->SetMarkerColor(621);
gTrkEta[6]->SetMarkerStyle(27);
gTrkEta[6]->SetMarkerColor(622);
gTrkEta[7]->SetMarkerStyle(28);
gTrkEta[7]->SetMarkerColor(623);
gTrkEta[8]->SetMarkerStyle(29);
gTrkEta[8]->SetMarkerColor(624);
gTrkEta[0]->SetMarkerStyle(21);
gTrkEta[0]->SetMarkerColor(802);
formatTH1F(hPadEta,1,1,2);
hPadEta->Draw();
gTrkEta[1]->SetMinimum(0.5);
gTrkEta[1]->SetMaximum(1.05);
gTrkEta[1]->Draw("pz same");
gTrkEta[2]->Draw("pz same");
gTrkEta[3]->Draw("pz same");
gTrkEta[4]->Draw("pz same");
gTrkEta[5]->Draw("pz same");
gTrkEta[6]->Draw("pz same");
gTrkEta[7]->Draw("pz same");
gTrkEta[8]->Draw("pz same");
gTrkEta[0]->Draw("pz same");
TLegend *leg2 = new TLegend(0.4899497,0.1678322,0.7876884,0.4947552,NULL,"brNDC"); // Size 0.03
leg2->SetFillStyle(0);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
leg2->SetTextSize(0.04);
leg2->SetHeader(leg_title);
sprintf(legs,"0 - 5 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[1][1],Trk[1][2],Trk[1][3]);
leg2->AddEntry(gTrkEta[1],legs,"pl");
sprintf(legs,"5 - 10 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[2][1],Trk[2][2],Trk[2][3]);
leg2->AddEntry(gTrkEta[2],legs,"pl");
sprintf(legs,"10 - 20 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[3][1],Trk[3][2],Trk[3][3]);
leg2->AddEntry(gTrkEta[3],legs,"pl");
sprintf(legs,"20 - 30 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[4][1],Trk[4][2],Trk[4][3]);
leg2->AddEntry(gTrkEta[4],legs,"pl");
sprintf(legs,"30 - 40 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[5][1],Trk[5][2],Trk[5][3]);
leg2->AddEntry(gTrkEta[5],legs,"pl");
sprintf(legs,"40 - 50 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[6][1],Trk[6][2],Trk[6][3]);
leg2->AddEntry(gTrkEta[6],legs,"pl");
sprintf(legs,"50 - 60 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[7][1],Trk[7][2],Trk[7][3]);
leg2->AddEntry(gTrkEta[7],legs,"pl");
sprintf(legs,"60 - 100 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[8][1],Trk[8][2],Trk[8][3]);
leg2->AddEntry(gTrkEta[8],legs,"pl");
sprintf(legs,"MinBias : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[0][1],Trk[0][2],Trk[0][3]);
leg2->AddEntry(gTrkEta[0],legs,"pl");
leg2->Draw("same");
if(MC_){
/*
c2->SaveAs("Jpsi_pPb_for_B_MC_Trk_eta_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_MC_Trk_eta_CNT.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_RD_Trk_1st_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_Trk_1st_run_eta_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_Trk2_1st_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_Trk2_1st_run_eta_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_Trk_2nd_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_Trk_2nd_run_eta_CNT_test.pdf");
*/
}
gTrkPt[1]->SetMarkerStyle(20);
gTrkPt[1]->SetMarkerColor(634);
gTrkPt[1]->GetXaxis()->SetTitle("p_{T} [GeV/c]");;
gTrkPt[1]->GetXaxis()->CenterTitle();;
gTrkPt[2]->SetMarkerStyle(23);
gTrkPt[2]->SetMarkerColor(602);
gTrkPt[3]->SetMarkerStyle(24);
gTrkPt[3]->SetMarkerColor(618);
gTrkPt[4]->SetMarkerStyle(25);
gTrkPt[4]->SetMarkerColor(620);
gTrkPt[5]->SetMarkerStyle(26);
gTrkPt[5]->SetMarkerColor(621);
gTrkPt[6]->SetMarkerStyle(27);
gTrkPt[6]->SetMarkerColor(622);
gTrkPt[7]->SetMarkerStyle(28);
gTrkPt[7]->SetMarkerColor(623);
gTrkPt[8]->SetMarkerStyle(29);
gTrkPt[8]->SetMarkerColor(624);
gTrkPt[0]->SetMarkerStyle(21);
gTrkPt[0]->SetMarkerColor(802);
formatTH1F(hPadPt,1,1,1);
hPadPt->Draw();
gTrkPt[1]->SetMinimum(0.5);
gTrkPt[1]->SetMaximum(1.05);
gTrkPt[1]->Draw("pz same");
gTrkPt[2]->Draw("pz same");
gTrkPt[3]->Draw("pz same");
gTrkPt[4]->Draw("pz same");
gTrkPt[5]->Draw("pz same");
gTrkPt[6]->Draw("pz same");
gTrkPt[7]->Draw("pz same");
gTrkPt[8]->Draw("pz same");
gTrkPt[0]->Draw("pz same");
TLegend *leg3 = new TLegend(0.4899497,0.1678322,0.7876884,0.4947552,NULL,"brNDC"); // Size 0.03
leg3->SetFillStyle(0);
leg3->SetFillColor(0);
leg3->SetBorderSize(0);
leg3->SetTextSize(0.04);
leg3->SetHeader(leg_title);
sprintf(legs,"0 - 5 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[1][1],Trk[1][2],Trk[1][3]);
leg3->AddEntry(gTrkPt[1],legs,"pl");
sprintf(legs,"5 - 10 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[2][1],Trk[2][2],Trk[2][3]);
leg3->AddEntry(gTrkPt[2],legs,"pl");
sprintf(legs,"10 - 20 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[3][1],Trk[3][2],Trk[3][3]);
leg3->AddEntry(gTrkPt[3],legs,"pl");
sprintf(legs,"20 - 30 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[4][1],Trk[4][2],Trk[4][3]);
leg3->AddEntry(gTrkPt[4],legs,"pl");
sprintf(legs,"30 - 40 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[5][1],Trk[5][2],Trk[5][3]);
leg3->AddEntry(gTrkPt[5],legs,"pl");
sprintf(legs,"40 - 50 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[6][1],Trk[6][2],Trk[6][3]);
leg3->AddEntry(gTrkPt[6],legs,"pl");
sprintf(legs,"50 - 60 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[7][1],Trk[7][2],Trk[7][3]);
leg3->AddEntry(gTrkPt[7],legs,"pl");
sprintf(legs,"60 - 100 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[8][1],Trk[8][2],Trk[8][3]);
leg3->AddEntry(gTrkPt[8],legs,"pl");
sprintf(legs,"MinBias : %0.3f^{ +%0.4f}_{ -%0.4f}",Trk[0][1],Trk[0][2],Trk[0][3]);
leg3->AddEntry(gTrkPt[0],legs,"pl");
leg3->Draw("same");
if(MC_){
/*
c2->SaveAs("Jpsi_pPb_for_B_MC_Trk_pt_CNT.png");
c2->SaveAs("Jpsi_pPb_for_B_MC_Trk_pt_CNT.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_RD_Trk_1st_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_Trk_1st_run_pt_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_Trk2_1st_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_Trk2_1st_run_pt_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_Trk_2nd_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_Trk_2nd_run_pt_CNT_test.pdf");
*/
}
}
outfile->cd();
if(Cent_){
gTrkPt[1]->SetName("gTrk0005Pt");
gTrkPt[2]->SetName("gTrk0510Pt");
gTrkPt[3]->SetName("gTrk1020Pt");
gTrkPt[4]->SetName("gTrk2030Pt");
gTrkPt[5]->SetName("gTrk3040Pt");
gTrkPt[6]->SetName("gTrk4050Pt");
gTrkPt[7]->SetName("gTrk5060Pt");
gTrkPt[8]->SetName("gTrk60100Pt");
gTrkEta[1]->SetName("gTrk0005Eta");
gTrkEta[2]->SetName("gTrk0510Eta");
gTrkEta[3]->SetName("gTrk1020Eta");
gTrkEta[4]->SetName("gTrk2030Eta");
gTrkEta[5]->SetName("gTrk3040Eta");
gTrkEta[6]->SetName("gTrk4050Eta");
gTrkEta[7]->SetName("gTrk5060Eta");
gTrkEta[8]->SetName("gTrk60100Eta");
gTrkPt[1]->Write();
gTrkPt[2]->Write();
gTrkPt[3]->Write();
gTrkPt[4]->Write();
gTrkPt[5]->Write();
gTrkPt[6]->Write();
gTrkPt[7]->Write();
gTrkPt[8]->Write();
gTrkEta[1]->Write();
gTrkEta[2]->Write();
gTrkEta[3]->Write();
gTrkEta[4]->Write();
gTrkEta[5]->Write();
gTrkEta[6]->Write();
gTrkEta[7]->Write();
gTrkEta[8]->Write();
}
gTrkPt[0]->SetName("gMBTrkPt");
gTrkEta[0]->SetName("gMBTrkEta");
gTrk[0]->SetName("gMBTrk");
pCNT->SetName("pCNT");
pMBCNT->SetName("pMBCNT");
gTrkPt[0]->Write();
gTrkEta[0]->Write();
gTrk[0]->Write();
pCNT->Write();
pMBCNT->Write();
outfile->Close();
//f->Close();
//files->Close();
}
void formatTH1F(TH1* a, int b, int c, int d){
a->SetLineWidth(2);
a->SetLineStyle(c);
a->SetMarkerSize(2);
a->SetLineColor(b);
a->SetMarkerColor(b);
a->GetYaxis()->SetTitle("Efficiency");
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} [GeV/c]");
}else if(d == 2){
a->GetXaxis()->SetTitle("#eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}
a->GetXaxis()->CenterTitle(true);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.05);
a->GetXaxis()->SetTitleOffset(0.9);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(0.8);
}
void formatTLeg(TLegend* a){
a->SetFillStyle(0);
a->SetFillColor(0);
a->SetBorderSize(0);
a->SetTextSize(0.03);
}
void formatTGraph(TGraph* a, int b, int c, int d)
{
a->SetMarkerStyle(c);
a->SetMarkerColor(b);
a->SetMarkerSize(1.0);
a->SetLineColor(b);
a->SetLineWidth(1);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.06);
a->GetXaxis()->SetTitleOffset(0.9);
a->GetYaxis()->SetTitle("Efficiency");
a->GetXaxis()->CenterTitle();
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} (GeV/c)");
}else if(d == 2){
a->GetXaxis()->SetTitle("eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}
a->GetYaxis()->SetRangeUser(0,1);
a->GetXaxis()->SetRangeUser(0,10);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(0.9);
}
TGraphAsymmErrors *plotEffEta(RooDataSet *a, int aa){
const RooArgSet *set = a->get();
RooRealVar *xAx = (RooRealVar*)set->find("eta");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
const int nbins = xAx->getBinning().numBins();
double tx[nbins], txhi[nbins], txlo[nbins];
double ty[nbins], tyhi[nbins], tylo[nbins];
for (int i=0; i<nbins; i++) {
a->get(i);
ty[i] = eff->getVal();
tx[i] = xAx->getVal();
txhi[i] = fabs(xAx->getErrorHi());
txlo[i] = fabs(xAx->getErrorLo());
tyhi[i] = fabs(eff->getErrorHi());
tylo[i] = fabs(eff->getErrorLo());
}
cout<<"NBins : "<<nbins<<endl;
const double *x = tx;
const double *xhi = txhi;
const double *xlo = txlo;
const double *y = ty;
const double *yhi = tyhi;
const double *ylo = tylo;
TGraphAsymmErrors *b = new TGraphAsymmErrors();
if(aa == 1) {*b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi);}
if(aa == 0) {*b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi);}
b->SetMaximum(1.1);
b->SetMinimum(0.0);
b->SetMarkerStyle(20);
b->SetMarkerColor(kRed+2);
b->SetMarkerSize(1.0);
b->SetTitle("");
b->GetXaxis()->SetTitleSize(0.05);
b->GetYaxis()->SetTitleSize(0.05);
b->GetXaxis()->SetTitle("#eta");
b->GetYaxis()->SetTitle("Efficiency");
b->GetXaxis()->CenterTitle();
//b->Draw("apz");
for (int i=0; i<nbins; i++) {
cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl;
}
return b;
}
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa){
const RooArgSet *set = a->get();
RooRealVar *xAx = (RooRealVar*)set->find("pt");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
const int nbins = xAx->getBinning().numBins();
double tx[nbins], txhi[nbins], txlo[nbins];
double ty[nbins], tyhi[nbins], tylo[nbins];
for (int i=0; i<nbins; i++) {
a->get(i);
ty[i] = eff->getVal();
tx[i] = xAx->getVal();
txhi[i] = fabs(xAx->getErrorHi());
txlo[i] = fabs(xAx->getErrorLo());
tyhi[i] = fabs(eff->getErrorHi());
tylo[i] = fabs(eff->getErrorLo());
}
cout<<"NBins : "<<nbins<<endl;
const double *x = tx;
const double *xhi = txhi;
const double *xlo = txlo;
const double *y = ty;
const double *yhi = tyhi;
const double *ylo = tylo;
TGraphAsymmErrors *b = new TGraphAsymmErrors();
if(aa == 1) {*b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi);}
if(aa == 0) {*b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi);}
b->SetMaximum(1.1);
b->SetMinimum(0.0);
b->SetMarkerStyle(20);
b->SetMarkerColor(kRed+2);
b->SetMarkerSize(1.0);
b->SetTitle("");
b->GetXaxis()->SetTitleSize(0.05);
b->GetYaxis()->SetTitleSize(0.05);
b->GetXaxis()->SetTitle("p_{T} [GeV/c]");
b->GetYaxis()->SetTitle("Efficiency");
b->GetXaxis()->CenterTitle();
//b->Draw("apz");
for (int i=0; i<nbins; i++) {
cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl;
}
return b;
}
TH2F *plotEff2D(RooDataSet *a, TString b){
const RooArgSet *set = a->get();
RooRealVar *yAx = (RooRealVar*)set->find("pt");
RooRealVar *xAx = (RooRealVar*)set->find("eta");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
//const int xnbins = xAx->getBinning().numBins();
//const int ynbins = yAx->getBinning().numBins();
const double *xvbins = xAx->getBinning().array();
const double *yvbins = yAx->getBinning().array();
TH2F* h = new TH2F(b, "", xAx->getBinning().numBins(), xvbins, yAx->getBinning().numBins(), yvbins);
gStyle->SetPaintTextFormat("5.2f");
gStyle->SetPadRightMargin(0.12);
gStyle->SetPalette(1);
h->SetOption("colztexte");
h->GetZaxis()->SetRangeUser(-0.001,1.001);
h->SetStats(kFALSE);
h->GetYaxis()->SetTitle("p_{T} [GeV/c]");
h->GetXaxis()->SetTitle("#eta");
h->GetXaxis()->CenterTitle();
h->GetYaxis()->CenterTitle();
h->GetXaxis()->SetTitleSize(0.05);
h->GetYaxis()->SetTitleSize(0.05);
h->GetYaxis()->SetTitleOffset(0.8);
h->GetXaxis()->SetTitleOffset(0.9);
for(int i=0; i<a->numEntries(); i++){
a->get(i);
h->SetBinContent(h->FindBin(xAx->getVal(), yAx->getVal()), eff->getVal());
h->SetBinError(h->FindBin(xAx->getVal(), yAx->getVal()), (eff->getErrorHi()-eff->getErrorLo())/2.);
}
return h;
}
<file_sep>/HiSkim/HiOnia2MuMu/python/onia2MuMuPAT_GEN_matching_cff.py
import FWCore.ParameterSet.Config as cms
from PhysicsTools.PatAlgos.tools.helpers import *
def onia2MuMuPAT(process, GlobalTag, MC=False, HLT='HLT', Filter=True):
# Setup the process
process.options = cms.untracked.PSet(
wantSummary = cms.untracked.bool(True),
# fileMode = cms.untracked.string('MERGE'),
)
process.load("FWCore.MessageService.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = 100
process.load('Configuration.StandardSequences.GeometryRecoDB_cff')
process.load("Configuration.StandardSequences.Reconstruction_cff")
process.load("Configuration.StandardSequences.MagneticField_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
process.GlobalTag.globaltag = GlobalTag
# Drop the DQM stuff on input
process.source = cms.Source("PoolSource",
inputCommands = cms.untracked.vstring("keep *", "drop *_MEtoEDMConverter_*_*"),
fileNames = cms.untracked.vstring()
)
# Scraping filter
process.scrapingFilter = cms.EDFilter("FilterOutScraping",
applyfilter = cms.untracked.bool(True),
debugOn = cms.untracked.bool(False),
numtrack = cms.untracked.uint32(10),
thresh = cms.untracked.double(0.25)
)
IN_ACCEPTANCE = '((abs(eta) <= 1.3 && pt > 3.3) || (1.3 < abs(eta) <= 2.2 && p > 2.9) || (2.2 < abs(eta) <= 2.4 && pt > 0.8))'
# Merge muons, calomuons in a single collection for T&P
process.mergedMuons = cms.EDProducer("CaloMuonMerger",
muons = cms.InputTag("muons"),
muonsCut = cms.string(""),
mergeCaloMuons = cms.bool(True), ### NEEDED TO RUN ON AOD
caloMuons = cms.InputTag("calomuons"),
caloMuonsCut = cms.string(IN_ACCEPTANCE),
minCaloCompatibility = cms.double(0.6),
mergeTracks = cms.bool(False),
tracks = cms.InputTag("generalTracks"),
tracksCut = cms.string(IN_ACCEPTANCE),
)
# Prune generated particles to muons and their parents
process.genMuons = cms.EDProducer("GenParticlePruner",
#src = cms.InputTag("genParticles"),
src = cms.InputTag("hiGenParticles"),
select = cms.vstring(
"drop * ", # this is the default
"++keep abs(pdgId) = 13", # keep muons and their parents
"drop pdgId == 21 && status = 2" # remove intermediate qcd spam carrying no flavour info
)
)
# Make PAT Muons
process.load("MuonAnalysis.MuonAssociators.patMuonsWithTrigger_cff")
from MuonAnalysis.MuonAssociators.patMuonsWithTrigger_cff import addMCinfo, changeRecoMuonInput, useL1MatchingWindowForSinglets, changeTriggerProcessName, switchOffAmbiguityResolution
# with some customization
if MC:
addMCinfo(process)
# since we match inner tracks, keep the matching tight and make it one-to-one
process.muonMatch.maxDeltaR = 0.05
process.muonMatch.resolveByMatchQuality = True
process.muonMatch.matched = "genMuons"
changeTriggerProcessName(process, HLT)
switchOffAmbiguityResolution(process) # Switch off ambiguity resolution: allow multiple reco muons to match to the same trigger muon
#useL1MatchingWindowForSinglets(process)
process.muonL1Info.maxDeltaR = 0.3
process.muonL1Info.fallbackToME1 = True
process.muonMatchHLTL1.maxDeltaR = 0.3
process.muonMatchHLTL1.fallbackToME1 = True
process.muonMatchHLTL2.maxDeltaR = 0.3
process.muonMatchHLTL2.maxDPtRel = 10.0
process.muonMatchHLTL3.maxDeltaR = 0.1
process.muonMatchHLTL3.maxDPtRel = 10.0
process.muonMatchHLTCtfTrack.maxDeltaR = 0.1
process.muonMatchHLTCtfTrack.maxDPtRel = 10.0
process.muonMatchHLTTrackMu.maxDeltaR = 0.1
process.muonMatchHLTTrackMu.maxDPtRel = 10.0
# Make a sequence
process.patMuonSequence = cms.Sequence(
process.hltOniaHI *
process.PAcollisionEventSelection *
process.genMuons *
process.patMuonsWithTriggerSequence
)
if not MC:
process.patMuonSequence.remove(process.genMuons)
# Make dimuon candidates
process.onia2MuMuPatTrkTrk = cms.EDProducer('HiOnia2MuMuPAT',
muons = cms.InputTag("patMuonsWithTrigger"),
beamSpotTag = cms.InputTag("offlineBeamSpot"),
primaryVertexTag = cms.InputTag("offlinePrimaryVertices"),
# At least one muon must pass this selection
higherPuritySelection = cms.string("(isGlobalMuon || isTrackerMuon || (innerTrack.isNonnull && genParticleRef(0).isNonnull)) && abs(innerTrack.dxy)<4 && abs(innerTrack.dz)<35"),
# BOTH muons must pass this selection
lowerPuritySelection = cms.string("(isGlobalMuon || isTrackerMuon || (innerTrack.isNonnull && genParticleRef(0).isNonnull)) && abs(innerTrack.dxy)<4 && abs(innerTrack.dz)<35"),
dimuonSelection = cms.string(""), ## The dimuon must pass this selection before vertexing
addCommonVertex = cms.bool(True), ## Embed the full reco::Vertex out of the common vertex fit
addMuonlessPrimaryVertex = cms.bool(True), ## Embed the primary vertex re-made from all the tracks except the two muons
addMCTruth = cms.bool(MC), ## Add the common MC mother of the two muons, if any
resolvePileUpAmbiguity = cms.bool(True) ## Order PVs by their vicinity to the J/psi vertex, not by sumPt
)
# check if there is at least one (inclusive) tracker+tracker di-muon
process.onia2MuMuPatTrkTrkFilter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('onia2MuMuPatTrkTrk'),
minNumber = cms.uint32(1),
)
process.onia2MuMuPatGlbGlb = cms.EDProducer('HiOnia2MuMuPAT',
muons = cms.InputTag("patMuonsWithTrigger"),
beamSpotTag = cms.InputTag("offlineBeamSpot"),
primaryVertexTag = cms.InputTag("hiSelectedVertex"),
# At least one muon must pass this selection
higherPuritySelection = cms.string("(isGlobalMuon || (innerTrack.isNonnull && genParticleRef(0).isNonnull)) && abs(innerTrack.dxy)<4 && abs(innerTrack.dz)<35"),
# BOTH muons must pass this selection
lowerPuritySelection = cms.string("(isGlobalMuon || (innerTrack.isNonnull && genParticleRef(0).isNonnull)) && abs(innerTrack.dxy)<4 && abs(innerTrack.dz)<35"),
dimuonSelection = cms.string(""), ## The dimuon must pass this selection before vertexing
addCommonVertex = cms.bool(True), ## Embed the full reco::Vertex out of the common vertex fit
addMuonlessPrimaryVertex = cms.bool(True), ## Embed the primary vertex re-made from all the tracks except the two muons
addMCTruth = cms.bool(MC), ## Add the common MC mother of the two muons, if any
resolvePileUpAmbiguity = cms.bool(True) ## Order PVs by their vicinity to the J/psi vertex, not by sumPt
)
# check if there is at least one (inclusive) tracker+tracker di-muon
process.onia2MuMuPatGlbGlbFilter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('onia2MuMuPatGlbGlb'),
minNumber = cms.uint32(1),
)
# the onia2MuMu path
process.Onia2MuMuPAT = cms.Path(
process.patMuonSequence *
process.onia2MuMuPatGlbGlb *
process.onia2MuMuPatTrkTrk *
process.onia2MuMuPatTrkTrkFilter *
process.onia2MuMuPatGlbGlbFilter
)
#process.Onia2MuMuPAT = cms.Path(process.patMuonSequence)
# Make Tag and Probe pairs for efficiency measurements
TRACK_CUTS = "(track.hitPattern.trackerLayersWithMeasurement > 5 && track.normalizedChi2 < 1.8 && track.hitPattern.pixelLayersWithMeasurement > 1 && abs(dB) < 3 && abs(track.dz) < 30)"
GLB_CUTS = "(isTrackerMuon && muonID('TrackerMuonArbitrated') && muonID('TMOneStationTight'))"
QUALITY_CUTS = "(" + GLB_CUTS + ' && ' + TRACK_CUTS + ")"
process.tagMuonsSglTrg = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string(QUALITY_CUTS + ' && ' + IN_ACCEPTANCE + " && (!triggerObjectMatchesByPath('HLT_PAMu3_v*',1,0).empty() || !triggerObjectMatchesByPath('HLT_PAMu7_v*',1,0).empty() || !triggerObjectMatchesByPath('HLT_PAMu12_v*',1,0).empty())")
)
process.tagMuonsDblTrg = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string(QUALITY_CUTS + ' && ' + IN_ACCEPTANCE + " && !triggerObjectMatchesByPath('HLT_PAL1DoubleMuOpen_v*',1,0).empty()")
)
# produce patMuons that use the STA momentum information
process.patMuonsWithTriggerSta = cms.EDProducer("RedefineMuonP4FromTrackPAT",
src = cms.InputTag("patMuonsWithTrigger"),
track = cms.string("outer")
)
# must be STA, so we can measure inner tracking efficiency
### probes for inner tracking efficiency
process.probeMuonsSta = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTriggerSta"),
cut = cms.string("outerTrack.isNonnull")
)
process.probeMuonsSta2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTriggerSta"),
cut = cms.string("outerTrack.isNonnull"+"&&"+"-2.4 < eta && eta < 2.4")
)
process.probeMuonsStaetabin1 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTriggerSta"),
cut = cms.string("outerTrack.isNonnull"+"&&"+"-2.4 < eta && eta < -0.8")
)
process.probeMuonsStaetabin2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTriggerSta"),
cut = cms.string("outerTrack.isNonnull"+"&&"+"-0.8 < eta && eta < 0.8")
)
process.probeMuonsStaetabin3 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTriggerSta"),
cut = cms.string("outerTrack.isNonnull"+"&&"+"0.8 < eta && eta < 2.4")
)
### pairs for inner tracking efficiency
process.tpPairsSta = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.0 < mass < 5.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsSta@-')
)
process.tpPairsSta2 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.0 < mass < 5.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsSta2@-')
)
process.tpPairsStaetabin1 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.0 < mass < 5.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsStaetabin1@-')
)
process.tpPairsStaetabin2 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.0 < mass < 5.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsStaetabin2@-')
)
process.tpPairsStaetabin3 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.0 < mass < 5.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsStaetabin3@-')
)
# must be a GLB to measure trigger efficiency
### probe muons for trigger efficiency
process.probeMuons = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string(QUALITY_CUTS + ' && ' + IN_ACCEPTANCE)
)
process.probeMuons2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string(QUALITY_CUTS + ' && ' + IN_ACCEPTANCE+'&&'+'-2.4 < eta && eta < 2.4')
)
process.probeMuonsetabin1 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string(QUALITY_CUTS + ' && ' + IN_ACCEPTANCE+'&&'+'-2.4 < eta && eta < -0.8')
)
process.probeMuonsetabin2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string(QUALITY_CUTS + ' && ' + IN_ACCEPTANCE+'&&'+'-0.8 < eta && eta < 0.8')
)
process.probeMuonsetabin3 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string(QUALITY_CUTS + ' && ' + IN_ACCEPTANCE+'&&'+'0.8 < eta && eta < 2.4')
)
### pairs for trigger efficiency
process.tpPairsTrig = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuons@-')
)
process.tpPairsTrig2 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0'+'&&'+'pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuons2@-')
)
process.tpPairsTrigetabin1 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0'+'&&'+'pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsetabin1@-')
)
process.tpPairsTrigetabin2 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0'+'&&'+'pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsetabin2@-')
)
process.tpPairsTrigetabin3 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0'+'&&'+'pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsetabin3@-')
)
# must be tracker muon, so we can measure the muon reco efficiency
# since we're using tracker muons this year, we should use calo muons as probes here
### probe muons for muon ID efficiency
process.probeMuonsTrk = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string("isCaloMuon && " + TRACK_CUTS)
)
process.probeMuonsTrk2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string("isCaloMuon && " + TRACK_CUTS + "&&" +"-2.4 < eta && eta < 2.4")
)
process.probeMuonsTrketabin1 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string("isCaloMuon && " + TRACK_CUTS + "&&" +"-2.4 < eta && eta < -0.8")
)
process.probeMuonsTrketabin2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string("isCaloMuon && " + TRACK_CUTS + "&&" +"-0.8 < eta && eta < 0.8")
)
process.probeMuonsTrketabin3 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("patMuonsWithTrigger"),
cut = cms.string("isCaloMuon && " + TRACK_CUTS + "&&" +"0.8 < eta && eta < 2.4")
)
### pairs for muon ID efficiency
process.tpPairsTracks = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsTrk@-')
)
process.tpPairsTracks2 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0'+'&&'+'pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsTrk2@-')
)
process.tpPairsTracksetabin1 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0'+'&&'+'pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsTrketabin1@-')
)
process.tpPairsTracksetabin2 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0'+'&&'+'pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsTrketabin2@-')
)
process.tpPairsTracksetabin3 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0'+'&&'+'pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsTrketabin3@-')
)
# check if there is at least one Tag and Probe pair
### filter for inner tracking efficiency
process.tpPairsStaFilter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsSta'),
minNumber = cms.uint32(1),
)
process.tpPairsSta2Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsSta2'),
minNumber = cms.uint32(1),
)
process.tpPairsStaetabin1Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsStaetabin1'),
minNumber = cms.uint32(1),
)
process.tpPairsStaetabin2Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsStaetabin2'),
minNumber = cms.uint32(1),
)
process.tpPairsStaetabin3Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsStaetabin3'),
minNumber = cms.uint32(1),
)
### filter for trigger efficiency
process.tpPairsTrigFilter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsTrig'),
minNumber = cms.uint32(1),
)
process.tpPairsTrig2Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsTrig2'),
minNumber = cms.uint32(1),
)
process.tpPairsTrigetabin1Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsTrigetabin1'),
minNumber = cms.uint32(1),
)
process.tpPairsTrigetabin2Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsTrigetabin2'),
minNumber = cms.uint32(1),
)
process.tpPairsTrigetabin3Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsTrigetabin3'),
minNumber = cms.uint32(1),
)
### filter for Muon ID efficiency
process.tpPairsTracksFilter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsTracks'),
minNumber = cms.uint32(1),
)
process.tpPairsTracks2Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsTracks2'),
minNumber = cms.uint32(1),
)
process.tpPairsTracksetabin1Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsTracksetabin1'),
minNumber = cms.uint32(1),
)
process.tpPairsTracksetabin2Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsTracksetabin2'),
minNumber = cms.uint32(1),
)
process.tpPairsTracksetabin3Filter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('tpPairsTracksetabin3'),
minNumber = cms.uint32(1),
)
# the Tag and Probe path
### path for inner tracking efficiency
process.tnpSta = cms.Sequence(
process.probeMuonsSta *
process.tpPairsSta *
process.tpPairsStaFilter
)
process.tnpSta2 = cms.Sequence(
process.probeMuonsSta2 *
process.tpPairsSta2 *
process.tpPairsSta2Filter
)
process.tnpStaetabin1 = cms.Sequence(
process.probeMuonsStaetabin1 *
process.tpPairsStaetabin1 *
process.tpPairsStaetabin1Filter
)
process.tnpStaetabin2 = cms.Sequence(
process.probeMuonsStaetabin2 *
process.tpPairsStaetabin2 *
process.tpPairsStaetabin2Filter
)
process.tnpStaetabin3 = cms.Sequence(
process.probeMuonsStaetabin3 *
process.tpPairsStaetabin3 *
process.tpPairsStaetabin3Filter
)
### path for trigger efficiency
process.tnpTrig = cms.Sequence(
process.probeMuons *
process.tpPairsTrig *
process.tpPairsTrigFilter
)
process.tnpTrig2 = cms.Sequence(
process.probeMuons2 *
process.tpPairsTrig2 *
process.tpPairsTrig2Filter
)
process.tnpTrigetabin1 = cms.Sequence(
process.probeMuonsetabin1 *
process.tpPairsTrigetabin1 *
process.tpPairsTrigetabin1Filter
)
process.tnpTrigetabin2 = cms.Sequence(
process.probeMuonsetabin2 *
process.tpPairsTrigetabin2 *
process.tpPairsTrigetabin2Filter
)
process.tnpTrigetabin3 = cms.Sequence(
process.probeMuonsetabin3 *
process.tpPairsTrigetabin3 *
process.tpPairsTrigetabin3Filter
)
### path for Muon ID efficiency
process.tnpMuID = cms.Sequence(
process.probeMuonsTrk *
process.tpPairsTracks *
process.tpPairsTracksFilter
)
process.tnpMuID2 = cms.Sequence(
process.probeMuonsTrk2 *
process.tpPairsTracks2 *
process.tpPairsTracks2Filter
)
process.tnpMuIDetabin1 = cms.Sequence(
process.probeMuonsTrketabin1 *
process.tpPairsTracksetabin1 *
process.tpPairsTracksetabin1Filter
)
process.tnpMuIDetabin2 = cms.Sequence(
process.probeMuonsTrketabin2 *
process.tpPairsTracksetabin2 *
process.tpPairsTracksetabin2Filter
)
process.tnpMuIDetabin3 = cms.Sequence(
process.probeMuonsTrketabin3 *
process.tpPairsTracksetabin3 *
process.tpPairsTracksetabin3Filter
)
# inner track reco efficiency
process.TagAndProbeSta = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.patMuonsWithTriggerSta *
process.tnpSta
)
process.TagAndProbeSta2 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.patMuonsWithTriggerSta *
process.tnpSta2
)
process.TagAndProbeStaetabin1 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.patMuonsWithTriggerSta *
process.tnpStaetabin1
)
process.TagAndProbeStaetabin2 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.patMuonsWithTriggerSta *
process.tnpStaetabin2
)
process.TagAndProbeStaetabin3 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.patMuonsWithTriggerSta *
process.tnpStaetabin3
)
# muon reco and ID efficiency
process.TagAndProbeMuID = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.tnpMuID
)
process.TagAndProbeMuID2 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.tnpMuID2
)
process.TagAndProbeMuIDetabin1 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.tnpMuIDetabin1
)
process.TagAndProbeMuIDetabin2 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.tnpMuIDetabin2
)
process.TagAndProbeMuIDetabin3 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.tnpMuIDetabin3
)
# muon trigger efficiency
process.TagAndProbeTrig = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.tnpTrig
)
process.TagAndProbeTrig2 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.tnpTrig2
)
process.TagAndProbeTrigetabin1 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.tnpTrigetabin1
)
process.TagAndProbeTrigetabin2 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.tnpTrigetabin2
)
process.TagAndProbeTrigetabin3 = cms.Path(
process.patMuonSequence *
process.tagMuonsSglTrg *
process.tnpTrigetabin3
)
if MC:
process.tagMuonsDblTrgMCMatch = process.muonMatch.clone(src = "tagMuonsDblTrg")
process.tagMuonsSglTrgMCMatch = process.muonMatch.clone(src = "tagMuonsSglTrg")
process.probeMuonsStaMCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsSta") # inner tracking eff
process.probeMuonsSta2MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsSta2") # inner tracking eff
process.probeMuonsStaetabin1MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsStaetabin1") # inner tracking eff
process.probeMuonsStaetabin2MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsStaetabin2") # inner tracking eff
process.probeMuonsStaetabin3MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsStaetabin3") # inner tracking eff
process.probeMuonsTrkMCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsTrk") # Muon reco and ID eff
process.probeMuonsTrk2MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsTrk2") # Muon reco and ID eff
process.probeMuonsTrketabin1MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsTrketabin1") # Muon reco and ID eff
process.probeMuonsTrketabin2MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsTrketabin2") # Muon reco and ID eff
process.probeMuonsTrketabin3MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsTrketabin3") # Muon reco and ID eff
process.probeMuonsMCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuons") # muon trigger eff
process.probeMuons2MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuons2") # muon trigger eff
process.probeMuonsetabin1MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsetabin1") # muon trigger eff
process.probeMuonsetabin2MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsetabin2") # muon trigger eff
process.probeMuonsetabin3MCMatch = process.tagMuonsSglTrgMCMatch.clone(src = "probeMuonsetabin3") # muon trigger eff
process.TagAndProbeSta.replace(process.tpPairsSta, process.tagMuonsSglTrgMCMatch * process.probeMuonsStaMCMatch * process.tpPairsSta)
process.TagAndProbeSta2.replace(process.tpPairsSta2, process.tagMuonsSglTrgMCMatch * process.probeMuonsSta2MCMatch * process.tpPairsSta2)
process.TagAndProbeStaetabin1.replace(process.tpPairsStaetabin1, process.tagMuonsSglTrgMCMatch * process.probeMuonsStaetabin1MCMatch * process.tpPairsStaetabin1)
process.TagAndProbeStaetabin2.replace(process.tpPairsStaetabin2, process.tagMuonsSglTrgMCMatch * process.probeMuonsStaetabin2MCMatch * process.tpPairsStaetabin2)
process.TagAndProbeStaetabin3.replace(process.tpPairsStaetabin3, process.tagMuonsSglTrgMCMatch * process.probeMuonsStaetabin3MCMatch * process.tpPairsStaetabin3)
process.TagAndProbeMuID.replace(process.tpPairsTracks, process.tagMuonsSglTrgMCMatch * process.probeMuonsTrkMCMatch * process.tpPairsTracks)
process.TagAndProbeMuID2.replace(process.tpPairsTracks2, process.tagMuonsSglTrgMCMatch * process.probeMuonsTrk2MCMatch * process.tpPairsTracks2)
process.TagAndProbeMuIDetabin1.replace(process.tpPairsTracksetabin1, process.tagMuonsSglTrgMCMatch * process.probeMuonsTrketabin1MCMatch * process.tpPairsTracksetabin1)
process.TagAndProbeMuIDetabin2.replace(process.tpPairsTracksetabin2, process.tagMuonsSglTrgMCMatch * process.probeMuonsTrketabin2MCMatch * process.tpPairsTracksetabin2)
process.TagAndProbeMuIDetabin3.replace(process.tpPairsTracksetabin3, process.tagMuonsSglTrgMCMatch * process.probeMuonsTrketabin3MCMatch * process.tpPairsTracksetabin3)
process.TagAndProbeTrig.replace(process.tpPairsTrig, process.tagMuonsSglTrgMCMatch * process.probeMuonsMCMatch * process.tpPairsTrig)
process.TagAndProbeTrig2.replace(process.tpPairsTrig2, process.tagMuonsSglTrgMCMatch * process.probeMuons2MCMatch * process.tpPairsTrig2)
process.TagAndProbeTrigetabin1.replace(process.tpPairsTrigetabin1, process.tagMuonsSglTrgMCMatch * process.probeMuonsetabin1MCMatch * process.tpPairsTrigetabin1)
process.TagAndProbeTrigetabin2.replace(process.tpPairsTrigetabin2, process.tagMuonsSglTrgMCMatch * process.probeMuonsetabin2MCMatch * process.tpPairsTrigetabin2)
process.TagAndProbeTrigetabin3.replace(process.tpPairsTrigetabin3, process.tagMuonsSglTrgMCMatch * process.probeMuonsetabin3MCMatch * process.tpPairsTrigetabin3)
# output
process.load('Configuration.EventContent.EventContent_cff')
process.outOnia2MuMu = cms.OutputModule("PoolOutputModule",
fileName = cms.untracked.string('onia2MuMuPAT.root'),
outputCommands = cms.untracked.vstring('drop *'),
SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('Onia2MuMuPAT') ) if Filter else cms.untracked.PSet()
)
process.outOnia2MuMu.outputCommands.extend(cms.untracked.vstring(
'keep *_mergedtruth_*_*', # tracking particles and tracking vertices for hit by hit matching
'keep *_genParticles_*_*', # generated particles
'keep *_genMuons_*_Onia2MuMuPAT', # generated muons and parents
'keep patMuons_patMuonsWithTrigger_*_Onia2MuMuPAT', # All PAT muons including matches to triggers
'keep patCompositeCandidates_*__Onia2MuMuPAT', # PAT di-muons
'keep *_offlinePrimaryVertices_*_*', # Primary vertices: you want these to compute impact parameters
'keep *_offlineBeamSpot_*_*', # Beam spot: you want this for the same reason
'keep edmTriggerResults_TriggerResults_*_*', # HLT info, per path (cheap)
'keep l1extraL1MuonParticles_hltL1extraParticles_*_*', # L1 info (cheap)
'keep l1extraL1MuonParticles_l1extraParticles_*_*', # L1 info (cheap)
'keep *_offlinePrimaryVertices_*_*',
'keep *_pACentrality_*_*',
'keep *_generalTracks_*_*',
'keep *_standAloneMuons_*_*')
),
process.outTnP = cms.OutputModule("PoolOutputModule",
fileName = cms.untracked.string('tnp.root'),
outputCommands = cms.untracked.vstring('drop *',
#'keep *_genParticles_*_*', # generated particles
'keep *_hiGenParticles_*_*', # embedded particles
'keep *_genMuons_*_Onia2MuMuPAT', # generated muons and parents
'keep *_tagMuonsDblTrgMCMatch__Onia2MuMuPAT', # tagMuons MC matches for efficiency
'keep *_tagMuonsSglTrgMCMatch__Onia2MuMuPAT', # tagMuons MC matches for efficiency
'keep *_probeMuonsMCMatch__Onia2MuMuPAT', # probeMuons MC matches for efficiency
'keep *_probeMuons2MCMatch__Onia2MuMuPAT', # probeMuons MC matches for efficiency
'keep *_probeMuonsetabin1MCMatch__Onia2MuMuPAT', # probeMuons MC matches for efficiency
'keep *_probeMuonsetabin2MCMatch__Onia2MuMuPAT', # probeMuons MC matches for efficiency
'keep *_probeMuonsetabin3MCMatch__Onia2MuMuPAT', # probeMuons MC matches for efficiency
'keep *_probeMuonsStaMCMatch__Onia2MuMuPAT', # probeMuons MC matches for efficiency
'keep *_probeMuonsSta2MCMatch__Onia2MuMuPAT', # probeMuons MC matches for efficiency
'keep *_probeMuonsStaetabin1MCMatch__Onia2MuMuPAT', # probeMuons MC matches for efficiency
'keep *_probeMuonsStaetabin2MCMatch__Onia2MuMuPAT', # probeMuons MC matches for efficiency
'keep *_probeMuonsStaetabin3MCMatch__Onia2MuMuPAT', # probeMuons MC matches for efficiency
'keep *_probeMuonsTrkMCMatch__Onia2MuMuPAT', # probeTacks MC matches for efficiency
'keep *_probeMuonsTrk2MCMatch__Onia2MuMuPAT', # probeTacks MC matches for efficiency
'keep *_probeMuonsTrketabin1MCMatch__Onia2MuMuPAT', # probeTacks MC matches for efficiency
'keep *_probeMuonsTrketabin2MCMatch__Onia2MuMuPAT', # probeTacks MC matches for efficiency
'keep *_probeMuonsTrketabin3MCMatch__Onia2MuMuPAT', # probeTacks MC matches for efficiency
'keep patMuons_patMuonsWithTriggerSta__Onia2MuMuPAT', # All PAT muons including matches to triggers
'keep patMuons_tagMuonsDblTrg__Onia2MuMuPAT', # tagMuons for efficiency
'keep patMuons_tagMuonsSglTrg__Onia2MuMuPAT', # tagMuons for efficiency
'keep patMuons_probeMuonsSta__Onia2MuMuPAT', # probeMuons for efficiency
'keep patMuons_probeMuonsSta2__Onia2MuMuPAT', # probeMuons for efficiency
'keep patMuons_probeMuonsStaetabin1__Onia2MuMuPAT', # probeMuons for efficiency
'keep patMuons_probeMuonsStaetabin2__Onia2MuMuPAT', # probeMuons for efficiency
'keep patMuons_probeMuonsStaetabin3__Onia2MuMuPAT', # probeMuons for efficiency
'keep patMuons_probeMuonsTrk__Onia2MuMuPAT', # probeTracks for efficiency
'keep patMuons_probeMuonsTrk2__Onia2MuMuPAT', # probeTracks for efficiency
'keep patMuons_probeMuonsTrketabin1__Onia2MuMuPAT', # probeTracks for efficiency
'keep patMuons_probeMuonsTrketabin2__Onia2MuMuPAT', # probeTracks for efficiency
'keep patMuons_probeMuonsTrketabin3__Onia2MuMuPAT', # probeTracks for efficiency
'keep patMuons_probeMuons__Onia2MuMuPAT', # probeMuons for efficiency
'keep patMuons_probeMuons2__Onia2MuMuPAT', # probeMuons for efficiency
'keep patMuons_probeMuonsetabin1__Onia2MuMuPAT', # probeMuons for efficiency
'keep patMuons_probeMuonsetabin2__Onia2MuMuPAT', # probeMuons for efficiency
'keep patMuons_probeMuonsetabin3__Onia2MuMuPAT', # probeMuons for efficiency
'keep recoCompositeCandidates_tpPairsSta__Onia2MuMuPAT', # RECO di-muons, tpPairs for tracking efficiency
'keep recoCompositeCandidates_tpPairsSta2__Onia2MuMuPAT', # RECO di-muons, tpPairs for tracking efficiency
'keep recoCompositeCandidates_tpPairsStaetabin1__Onia2MuMuPAT', # RECO di-muons, tpPairs for tracking efficiency
'keep recoCompositeCandidates_tpPairsStaetabin2__Onia2MuMuPAT', # RECO di-muons, tpPairs for tracking efficiency
'keep recoCompositeCandidates_tpPairsStaetabin3__Onia2MuMuPAT', # RECO di-muons, tpPairs for tracking efficiency
'keep recoCompositeCandidates_tpPairsTracks__Onia2MuMuPAT', # RECO di-muons, tpPairs for muon ID and reco efficiency
'keep recoCompositeCandidates_tpPairsTracks2__Onia2MuMuPAT', # RECO di-muons, tpPairs for muon ID and reco efficiency
'keep recoCompositeCandidates_tpPairsTracksetabin1__Onia2MuMuPAT', # RECO di-muons, tpPairs for muon ID and reco efficiency
'keep recoCompositeCandidates_tpPairsTracksetabin2__Onia2MuMuPAT', # RECO di-muons, tpPairs for muon ID and reco efficiency
'keep recoCompositeCandidates_tpPairsTracksetabin3__Onia2MuMuPAT', # RECO di-muons, tpPairs for muon ID and reco efficiency
'keep recoCompositeCandidates_tpPairsTrig__Onia2MuMuPAT', # RECO di-muons, tpPairs for trigger efficiency
'keep recoCompositeCandidates_tpPairsTrig2__Onia2MuMuPAT', # RECO di-muons, tpPairs for trigger efficiency
'keep recoCompositeCandidates_tpPairsTrigetabin1__Onia2MuMuPAT', # RECO di-muons, tpPairs for trigger efficiency
'keep recoCompositeCandidates_tpPairsTrigetabin2__Onia2MuMuPAT', # RECO di-muons, tpPairs for trigger efficiency
'keep recoCompositeCandidates_tpPairsTrigetabin3__Onia2MuMuPAT', # RECO di-muons, tpPairs for trigger efficiency
'keep *_offlinePrimaryVertices_*_*', # Primary vertices: you want these to compute impact parameters
'keep *_offlineBeamSpot_*_*', # Beam spot: you want this for the same reason
'keep edmTriggerResults_TriggerResults_*_*', # HLT info, per path (cheap)
'keep l1extraL1MuonParticles_hltL1extraParticles_*_*', # L1 info (cheap)
'keep l1extraL1MuonParticles_l1extraParticles_*_*', # L1 info (cheap)
'keep *_pACentrality_*_*',
'keep *_generalTracks_*_*',
'keep *_standAloneMuons_*_*' # standAloneMuon track collection, to be on the safe side
),
SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('TagAndProbeSta','TagAndProbeSta2','TagAndProbeStaetabin1','TagAndProbeStaetabin2','TagAndProbeStaetabin3','TagAndProbeMuID','TagAndProbeMuID2','TagAndProbeMuIDetabin1','TagAndProbeMuIDetabin2','TagAndProbeMuIDetabin3','TagAndProbeTrig','TagAndProbeTrig2','TagAndProbeTrigetabin1','TagAndProbeTrigetabin2','TagAndProbeTrigetabin3') ) if Filter else cms.untracked.PSet()
)
process.e = cms.EndPath(process.outOnia2MuMu + process.outTnP)
<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/ProdMerge/pARun_TnP_Prd_1st_7run_for_B.py
import FWCore.ParameterSet.Config as cms
process = cms.Process("TnPProd")
process.load('FWCore.MessageService.MessageLogger_cfi')
process.options = cms.untracked.PSet(
wantSummary = cms.untracked.bool(True),
SkipEvent = cms.untracked.vstring('ProductNotFound')
)
process.MessageLogger.cerr.FwkReport.reportEvery = 1000
process.load("Configuration.StandardSequences.MagneticField_cff")
process.load("Configuration.StandardSequences.GeometryRecoDB_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
process.GlobalTag.globaltag = 'GR_P_V43F::All'
from HeavyIonsAnalysis.Configuration.CommonFunctions_cff import *
overrideCentrality(process)
process.HeavyIonGlobalParameters = cms.PSet(
centralityVariable = cms.string("HFtowersPlusTrunc"),
nonDefaultGlauberModel = cms.string(""),
centralitySrc = cms.InputTag("pACentrality"),
pPbRunFlip = cms.ubtracked.unit32(211313)
)
process.load('RecoHI.HiCentralityAlgos.HiCentrality_cfi')
process.load("RecoHI.HiCentralityAlgos.CentralityFilter_cfi")
process.centralityFilter.selectedBins = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99] # 0 - 100 %
process.source = cms.Source("PoolSource",
# duplicateCheckMode = cms.untracked.string('noDuplicateCheck'),
fileNames = cms.untracked.vstring(
# _input_
),
)
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(-1),
)
TRACK_CUTS = "track.hitPattern.trackerLayersWithMeasurement > 5 && track.normalizedChi2 < 1.8 && track.hitPattern.pixelLayersWithMeasurement > 1 && abs(dB) < 3 && abs(track.dz) < 30"
GLB_CUTS_1 = "isTrackerMuon && muonID('TrackerMuonArbitrated') && muonID('TMOneStationTight')"
GLB_CUTS_2 = "isTrackerMuon"
QUALITY_CUTS_1 = GLB_CUTS_1 + ' && ' + TRACK_CUTS#PbPb
QUALITY_CUTS_2 = GLB_CUTS_2 + ' && ' + TRACK_CUTS#pp
IN_ACCEPTANCE2 = '( (abs(eta)<1.0 && pt>=3.4) || (1.0<=abs(eta)<1.5 && pt>=5.8-2.4*abs(eta)) || (1.5<=abs(eta)<2.4 && pt>=3.3667-7.0/9.0*abs(eta)) )' ## PbPb
IN_ACCEPTANCE = '[((abs(eta) <= 1.3 && pt > 3.3) || (1.3 < abs(eta) <= 2.2 && p > 2.9) || (2.2 < abs(eta) <= 2.4 && pt > 0.8))]' ## pp
#trigger efficiency probes
process.probeMuons2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuons"),
cut = cms.string("-2.4 < eta && eta < 2.4"),
)
process.probeMuonsetabin1 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuons"),
cut = cms.string("-2.4 < eta && eta < -0.8"),
)
process.probeMuonsetabin2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuons"),
cut = cms.string("-0.8 < eta && eta < 0.8"),
)
process.probeMuonsetabin3 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuons"),
cut = cms.string("0.8 < eta && eta < 2.4"),
)
#trigger efficiency pairs
process.tpPairsTrigNew2CS = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0 && pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuons2@-')
)
process.tpPairsTrigNew2etabin1CS = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0 && pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsetabin1@-')
)
process.tpPairsTrigNew2etabin2CS = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0 && pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsetabin2@-')
)
process.tpPairsTrigNew2etabin3CS = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0 && pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsetabin3@-')
)
#tracking efficiency probes
process.probeMuonsSta2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuonsSta"),
cut = cms.string("-2.4 < eta && eta < 2.4"),
)
process.probeMuonsStaetabin1 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuonsSta"),
cut = cms.string("-2.4 < eta && eta < -0.8"),
)
process.probeMuonsStaetabin2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuonsSta"),
cut = cms.string("-0.8 < eta && eta < 0.8"),
)
process.probeMuonsStaetabin3 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuonsSta"),
cut = cms.string("0.8 < eta && eta < 2.4"),
)
#tracking efficiency pairs
process.tpPairsSta2 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.0 < mass < 5.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsSta2@-')
)
process.tpPairsStaetabin1 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.0 < mass < 5.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsStaetabin1@-')
)
process.tpPairsStaetabin2 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.0 < mass < 5.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsStaetabin2@-')
)
process.tpPairsStaetabin3 = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.0 < mass < 5.0'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsStaetabin3@-')
)
#MuId efficiency probes
process.probeMuonsTrk2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuonsTrk"),
cut = cms.string("-2.4 < eta && eta < 2.4"),
)
process.probeMuonsTrk2etabin1 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuonsTrk"),
cut = cms.string("-2.4 < eta && eta < -0.8"),
)
process.probeMuonsTrk2etabin2 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuonsTrk"),
cut = cms.string("-0.8 < eta && eta < 0.8"),
)
process.probeMuonsTrk2etabin3 = cms.EDFilter("PATMuonSelector",
src = cms.InputTag("probeMuonsTrk"),
cut = cms.string("0.8 < eta && eta < 2.4"),
)
#MuId efficiency pairs
process.tpPairsTracksNewCS = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0 && pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsTrk2@-')
)
process.tpPairsTracksNewetabin1CS = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0 && pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsTrk2etabin1@-')
)
process.tpPairsTracksNewetabin2CS = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0 && pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsTrk2etabin2@-')
)
process.tpPairsTracksNewetabin3CS = cms.EDProducer("CandViewShallowCloneCombiner",
cut = cms.string('2.6 < mass < 4.0 && pt > 3.0 && -2.4 < y && y < 2.4'),
decay = cms.string('tagMuonsSglTrg@+ probeMuonsTrk2etabin3@-')
)
# Make the fit tree and save it in the "MuonID" directory
process.MuonTrgNew2CS = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsTrigNew2CS"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
HLTL1HighQ = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMu0_HighQ_v1',1,0).empty()"),
HLTL1Open = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMuOpen_v1',1,0).empty()"),
HLTL2 = cms.string("!triggerObjectMatchesByPath('HLT_PAL2DoubleMu3_v1',1,0).empty()"),
PAMu3 = cms.string("!triggerObjectMatchesByPath('HLT_PAMu3_v1',1,0).empty()"),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
HLTL1HighQ = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMu0_HighQ_v1',1,0).empty()"),
HLTL1Open = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMuOpen_v1',1,0).empty()"),
HLTL2 = cms.string("!triggerObjectMatchesByPath('HLT_PAL2DoubleMu3_v1',1,0).empty()"),
PAMu3 = cms.string("!triggerObjectMatchesByPath('HLT_PAMu3_v1',1,0).empty()"),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
TRK = cms.string("isTrackerMuon"),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatch"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(False),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuons2"),
#addRunLumiInfo = cms.bool(True),
)
process.MuonTrgNew2etabin1CS = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsTrigNew2etabin1CS"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
HLTL1HighQ = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMu0_HighQ_v1',1,0).empty()"),
HLTL1Open = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMuOpen_v1',1,0).empty()"),
HLTL2 = cms.string("!triggerObjectMatchesByPath('HLT_PAL2DoubleMu3_v1',1,0).empty()"),
PAMu3 = cms.string("!triggerObjectMatchesByPath('HLT_PAMu3_v1',1,0).empty()"),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
HLTL1HighQ = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMu0_HighQ_v1',1,0).empty()"),
HLTL1Open = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMuOpen_v1',1,0).empty()"),
HLTL2 = cms.string("!triggerObjectMatchesByPath('HLT_PAL2DoubleMu3_v1',1,0).empty()"),
PAMu3 = cms.string("!triggerObjectMatchesByPath('HLT_PAMu3_v1',1,0).empty()"),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
TRK = cms.string("isTrackerMuon"),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatch"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(False),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsetabin1"),
#addRunLumiInfo = cms.bool(True),
)
process.MuonTrgNew2etabin2CS = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsTrigNew2etabin2CS"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
HLTL1HighQ = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMu0_HighQ_v1',1,0).empty()"),
HLTL1Open = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMuOpen_v1',1,0).empty()"),
HLTL2 = cms.string("!triggerObjectMatchesByPath('HLT_PAL2DoubleMu3_v1',1,0).empty()"),
PAMu3 = cms.string("!triggerObjectMatchesByPath('HLT_PAMu3_v1',1,0).empty()"),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
HLTL1HighQ = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMu0_HighQ_v1',1,0).empty()"),
HLTL1Open = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMuOpen_v1',1,0).empty()"),
HLTL2 = cms.string("!triggerObjectMatchesByPath('HLT_PAL2DoubleMu3_v1',1,0).empty()"),
PAMu3 = cms.string("!triggerObjectMatchesByPath('HLT_PAMu3_v1',1,0).empty()"),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
TRK = cms.string("isTrackerMuon"),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatch"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(False),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsetabin2"),
#addRunLumiInfo = cms.bool(True),
)
process.MuonTrgNew2etabin3CS = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsTrigNew2etabin3CS"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
HLTL1HighQ = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMu0_HighQ_v1',1,0).empty()"),
HLTL1Open = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMuOpen_v1',1,0).empty()"),
HLTL2 = cms.string("!triggerObjectMatchesByPath('HLT_PAL2DoubleMu3_v1',1,0).empty()"),
PAMu3 = cms.string("!triggerObjectMatchesByPath('HLT_PAMu3_v1',1,0).empty()"),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
HLTL1HighQ = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMu0_HighQ_v1',1,0).empty()"),
HLTL1Open = cms.string("!triggerObjectMatchesByPath('HLT_PAL1DoubleMuOpen_v1',1,0).empty()"),
HLTL2 = cms.string("!triggerObjectMatchesByPath('HLT_PAL2DoubleMu3_v1',1,0).empty()"),
PAMu3 = cms.string("!triggerObjectMatchesByPath('HLT_PAMu3_v1',1,0).empty()"),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
TRK = cms.string("isTrackerMuon"),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatch"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(False),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsetabin3"),
#addRunLumiInfo = cms.bool(True),
)
#tracking efficiency fit tree
process.MuonTrk2 = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsSta2"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatchSta"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsSta2"),
)
process.MuonTrketabin1 = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsStaetabin1"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatchSta"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsStaetabin1"),
)
process.MuonTrketabin2 = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsStaetabin2"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatchSta"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsStaetabin2"),
)
process.MuonTrketabin3 = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsStaetabin3"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
isTrk = cms.string(QUALITY_CUTS_2),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatchSta"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsStaetabin3"),
)
process.MuonIDNew2CS = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsTracksNewCS"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatch"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsTrk2"),
)
process.MuonIDNew2etabin1CS = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsTracksNewetabin1CS"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatch"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsTrk2etabin1"),
)
process.MuonIDNew2etabin2CS = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsTracksNewetabin2CS"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatch"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsTrk2etabin2"),
)
process.MuonIDNew2etabin3CS = cms.EDAnalyzer("TagProbeFitTreeProducer",
tagProbePairs = cms.InputTag("tpPairsTracksNewetabin3CS"),
arbitration = cms.string("OneProbe"),
variables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
flags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
tagVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
tagFlags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
pairVariables = cms.PSet(
pt = cms.string("pt"),
phi = cms.string("phi"),
eta = cms.string("eta"),
abseta = cms.string("abs(eta)"),
y = cms.string("rapidity"),
absy = cms.string("abs(rapidity)"),
),
pairFlags = cms.PSet(
PassingTrk = cms.string(QUALITY_CUTS_1),
),
isMC = cms.bool(False),
#tagMatches = cms.InputTag("tagMuonsMCMatch"),
#probeMatches = cms.InputTag("probeMuonsMCMatch"),
#motherPdgId = cms.int32(23),
#makeMCUnbiasTree = cms.bool(True),
#checkMotherInUnbiasEff = cms.bool(True),
allProbes = cms.InputTag("probeMuonsTrk2etabin3"),
)
process.tnpSimpleSequence = cms.Sequence(
process.probeMuons2 *
process.probeMuonsetabin1 *
process.probeMuonsetabin2 *
process.probeMuonsetabin3 *
process.probeMuonsSta2 *
process.probeMuonsStaetabin1 *
process.probeMuonsStaetabin2 *
process.probeMuonsStaetabin3 *
process.probeMuonsTrk2 *
process.probeMuonsTrk2etabin1 *
process.probeMuonsTrk2etabin2 *
process.probeMuonsTrk2etabin3 *
process.tpPairsTrigNew2CS *
process.tpPairsTrigNew2etabin1CS *
process.tpPairsTrigNew2etabin2CS *
process.tpPairsTrigNew2etabin3CS *
process.tpPairsSta2 *
process.tpPairsStaetabin1 *
process.tpPairsStaetabin2 *
process.tpPairsStaetabin3 *
process.tpPairsTracksNewCS *
process.tpPairsTracksNewetabin1CS *
process.tpPairsTracksNewetabin2CS *
process.tpPairsTracksNewetabin3CS *
process.MuonTrgNew2CS *
process.MuonTrgNew2etabin1CS *
process.MuonTrgNew2etabin2CS *
process.MuonTrgNew2etabin3CS *
process.MuonTrk2 *
process.MuonTrketabin1 *
process.MuonTrketabin2 *
process.MuonTrketabin3 *
process.MuonIDNew2CS *
process.MuonIDNew2etabin1CS *
process.MuonIDNew2etabin2CS *
process.MuonIDNew2etabin3CS
)
process.tagAndProbe = cms.Path(
process.centralityFilter *
process.tnpSimpleSequence
)
process.TFileService = cms.Service("TFileService", fileName = cms.string("tnp_pA_1st_7run_Prod_Merge_for_B_test.root"))
<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/Efficiency/RD/MuID/TnPEffMuIdDraw_for_B.C
#include <iostream>
#include <TSystem.h>
#include <TTree.h>
#include <TKey.h>
#include <TH1.h>
#include <TH2.h>
#include <TPave.h>
#include <TText.h>
#include <fstream>
#include <sstream>
#include <string.h>
#include <TROOT.h>
#include <TFile.h>
#include <TGraphAsymmErrors.h>
#include <TH1.h>
#include <TH2.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <RooFit.h>
#include <RooRealVar.h>
#include <RooDataSet.h>
#include <RooArgSet.h>
#include <TStyle.h>
#include <TLatex.h>
#include <TDirectory.h>
#include <TCollection.h>
#include <TPostScript.h>
using namespace RooFit;
using namespace std;
// Function Define
TH2F *plotEff2D(RooDataSet *a, TString b);
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa);
TGraphAsymmErrors *plotEffEta(RooDataSet *a, int aa);
void formatTH1F(TH1* a, int b, int c, int d);
void formatTGraph(TGraph* a, int b, int c, int d);
void formatTLeg(TLegend* a);
void TnPEffMuIdDraw_for_B ();
// From here you need to set up your environments.
bool MC_ = false; // if the data set is real data, it should be false
bool Cent_ = false; // if the data is only one MinBias file, it shoud be false
const int maxFile_ = 1; // the number of data files, usually it should be 4 but 1 in the case of MinBias
char *outfile_ = "Jpsi_pPb_RD_MuIdNew2CS_CBpPoly_1st_Run_Eff_for_B_test.root";
string dir_suffix = "_CBPlusPoly"; // depends on which fit function is used for : eg) _gaussExpo, _gaussPol2
void TnPEffMuIdDraw_for_B() {
gROOT->Macro("rootlogon.C");
char *files[maxFile_] = {
"../../Ana/RD/MuID/tnp_pPb_Ana_MuIdNew2CS_CBpPoly_1st_Run_for_B_test.root",
};
TString outname_in, outname_mid, outname_out;
TString middle_name, middle_name2;
TString leg_title;
int Mode = 0;
TFile *outfile = new TFile(outfile_,"RECREATE");
for(int l = 0; l < maxFile_; l++){
char *infile = files[l];
TFile *f = new TFile(infile);
Mode = l;
if(Mode == 0){
middle_name = "All";
middle_name2 = "MinBias";
}else if(Mode == 1){
middle_name = "0005";
middle_name2 = "0 - 5 %";
}else if(Mode == 2){
middle_name = "0510";
middle_name2 = "5 - 10 %";
}else if(Mode == 3){
middle_name = "1020";
middle_name2 = "10 - 20 %";
}else if(Mode == 4){
middle_name = "2030";
middle_name2 = "20 - 30 %";
}else if(Mode == 5){
middle_name = "3040";
middle_name2 = "30 - 40 %";
}else if(Mode == 6){
middle_name = "4050";
middle_name2 = "40 - 50 %";
}else if(Mode == 7){
middle_name = "5060";
middle_name2 = "50 - 60 %";
}else if(Mode == 8){
middle_name = "60100";
middle_name2 = "60 - 100 %";
}
gROOT->SetStyle("Plain");
gStyle->SetOptStat(0);
gStyle->SetTitle(0);
// if you have only one file, should change the number 4 -> 1
TString mid_title = "Centrality : (" + middle_name2 + ")";
if(!MC_) leg_title = "Data MuId Efficiency (" + middle_name2 + ")";
if(MC_) leg_title = "MC MuId Efficiency (" + middle_name2 + ")";
TCanvas *c1 = new TCanvas("c1","",120,20,800,600);
f->cd();
RooDataSet *daMuIdEta = (RooDataSet*)f->Get("MuonIDNew2CS/PassingTrk_eta/fit_eff");
RooDataSet *daMuIdEta1bin = (RooDataSet*)f->Get("MuonIDNew2CS/PassingTrk_1bin_eta_pt/fit_eff");
TGraphAsymmErrors *MuId_eta = plotEffEta(daMuIdEta, 1);
TGraphAsymmErrors *MuId_1bin_pt_eta = plotEffEta(daMuIdEta1bin, 1);
double Id[4];
MuId_1bin_pt_eta->GetPoint(0,Id[0],Id[1]);
Id[2] = MuId_1bin_pt_eta->GetErrorYhigh(0);
Id[3] = MuId_1bin_pt_eta->GetErrorYlow(0);
RooDataSet *daMuIdPt = (RooDataSet*)f->Get("MuonIDNew2CS/PassingTrk_pt/fit_eff");
TGraphAsymmErrors *MuId_pt = plotEffPt(daMuIdPt, 1);
/*
RooDataSet *daMuId2D = (RooDataSet*)f->Get("MuonID/PassingTrk_pt_eta/fit_eff");
TString twoDName1 = "MuId_2d";
TH2F *MuId_2d = plotEff2D(daMuId2D, twoDName1);
*/
MuId_eta->GetXaxis()->SetLabelSize(0.05);
MuId_eta->GetYaxis()->SetLabelSize(0.05);
MuId_eta->GetXaxis()->SetTitleSize(0.05);
MuId_eta->GetYaxis()->SetTitleSize(0.05);
MuId_eta->GetXaxis()->SetTitleOffset(0.9);
MuId_eta->GetYaxis()->SetTitleOffset(0.8);
MuId_eta->SetMarkerColor(kRed+2);
MuId_eta->Draw("apz");
char legs[512];
TLegend *leg1 = new TLegend(0.3054774,0.1567832,0.5429648,0.3858042,NULL,"brNDC");
leg1->SetFillStyle(0);
leg1->SetFillColor(0);
leg1->SetBorderSize(0);
leg1->SetTextSize(0.04);
leg1->SetHeader(leg_title);
sprintf(legs,"MuId Efficiency: %0.3f^{ +%0.4f}_{ -%0.4f}",Id[1],Id[2],Id[3]);
leg1->AddEntry(MuId_eta,legs,"pl");
leg1->Draw("same");
TString pic_name_png, pic_name_pdf;
if(MC_){
pic_name_png = "Jpsi_pPb_MC_MuIdNew2CS_" + middle_name + "_eta_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_MC_MuIdNew2CS_" + middle_name + "_eta_for_B_test.pdf";
}else{
pic_name_png = "Jpsi_pPb_RD_MuId_New2CS_1st_run_" + middle_name + "_eta_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_RD_MuId_New2CS_1st_run_" + middle_name + "_eta_for_B_test.pdf";
}
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
MuId_pt->GetXaxis()->SetLabelSize(0.05);
MuId_pt->GetYaxis()->SetLabelSize(0.05);
MuId_pt->GetXaxis()->SetTitleSize(0.05);
MuId_pt->GetYaxis()->SetTitleSize(0.05);
MuId_pt->GetXaxis()->SetTitleOffset(0.9);
MuId_pt->GetYaxis()->SetTitleOffset(0.8);
MuId_pt->SetMarkerColor(kRed+2);
MuId_pt->Draw("apz");
TLegend *leg2 = new TLegend(0.3454774,0.2167832,0.5429648,0.4458042,NULL,"brNDC");
leg2->SetFillStyle(0);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
leg2->SetTextSize(0.04);
leg2->SetHeader(leg_title);
sprintf(legs,"MuId Efficiency: %0.3f^{ +%0.4f}_{ -%0.4f}",Id[1],Id[2],Id[3]);
leg2->AddEntry(MuId_pt,legs,"pl");
leg2->Draw("same");
if(MC_){
pic_name_png = "Jpsi_pPb_MC_MuIdNew2CS_" + middle_name + "_pt_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_MC_MuIdNew2CS_" + middle_name + "_pt_for_B_test.pdf";
}else{
pic_name_png = "Jpsi_pPb_RD_MuIdNew2CS_1st_run_" + middle_name + "_pt_for_B_test.png";
pic_name_pdf = "Jpsi_pPb_RD_MuIdNew2CS_1st_run_" + middle_name + "_pt_for_B_test.pdf";
}
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
/*
MuId_2d->Draw();
pic_name_png = "Psi2s_MC_MuId_" + middle_name + "_2d.png";
pic_name_pdf = "Psi2s_MC_MuId_" + middle_name + "_2d.pdf";
c1->SaveAs(pic_name_png);
c1->SaveAs(pic_name_pdf);
c1->Print("Psi2s_MC_MuId_Eff_total.ps");
*/
TString Idna1, Idna2, Idna3, Idna4;
Idna1 = "MuId_eta_" + middle_name;
Idna2 = "MuId_1bin_pt_eta_" + middle_name;
Idna3 = "MuId_pt_" + middle_name;
Idna4 = "MuId_2d_" + middle_name;
MuId_eta->SetName(Idna1);
MuId_1bin_pt_eta->SetName(Idna2);
MuId_pt->SetName(Idna3);
//MuId_2d->SetName(Idna4);
outfile->cd();
MuId_eta->Write();
MuId_pt->Write();
MuId_1bin_pt_eta->Write();
//MuId_2d->Write();
}
// Comparing Plots as the Centralities
TH1F *hPadEta = new TH1F("hPadEta","",6,-2.4,2.4);
TH1F *hPadPt = new TH1F("hPadPt","",6,0,20);
TCanvas *c2 = new TCanvas("c2","",120,20,800,600);
//c2->cd();
TGraphAsymmErrors *gMuId[maxFile_];
TGraphAsymmErrors *gMuIdEta[maxFile_];
TGraphAsymmErrors *gMuIdPt[maxFile_];
double MuId[9][4];
for(int i = 0; i < maxFile_; i++){
TFile finput(files[i]);
finput.cd();
RooDataSet *dataMuId = (RooDataSet*)finput.Get("MuonIDNew2CS/PassingTrk_1bin_eta_pt/fit_eff");
RooDataSet *dataMuIdEta = (RooDataSet*)finput.Get("MuonIDNew2CS/PassingTrk_eta/fit_eff");
RooDataSet *dataMuIdPt = (RooDataSet*)finput.Get("MuonIDNew2CS/PassingTrk_pt/fit_eff");
gMuId[i] = plotEffEta(dataMuId, 0);
gMuIdEta[i] = plotEffEta(dataMuIdEta, 0);
gMuIdPt[i] = plotEffPt(dataMuIdPt, 0);
gMuId[i]->GetPoint(0,MuId[i][0],MuId[i][1]);
MuId[i][2] = gMuId[i]->GetErrorYhigh(0);
MuId[i][3] = gMuId[i]->GetErrorYlow(0);
}
TGraphAsymmErrors *pCNT = new TGraphAsymmErrors(3);
TGraphAsymmErrors *pMBCNT = new TGraphAsymmErrors();
if(Cent_){
pCNT->SetPoint(0,10,MuId[1][1]);
pCNT->SetPointError(0,0,0,MuId[1][3],MuId[1][2]);
pCNT->SetPoint(1,20,MuId[2][1]);
pCNT->SetPointError(1,0,0,MuId[2][3],MuId[2][2]);
pCNT->SetPoint(2,30,MuId[3][1]);
pCNT->SetPointError(2,0,0,MuId[3][3],MuId[3][2]);
pCNT->SetPoint(3,40,MuId[4][1]);
pCNT->SetPointError(3,0,0,MuId[4][3],MuId[4][2]);
pCNT->SetPoint(4,50,MuId[5][1]);
pCNT->SetPointError(4,0,0,MuId[5][3],MuId[5][2]);
pCNT->SetPoint(5,60,MuId[6][1]);
pCNT->SetPointError(5,0,0,MuId[6][3],MuId[6][2]);
pCNT->SetPoint(6,70,MuId[7][1]);
pCNT->SetPointError(6,0,0,MuId[7][3],MuId[7][2]);
pCNT->SetPoint(7,80,MuId[8][1]);
pCNT->SetPointError(7,0,0,MuId[8][3],MuId[8][2]);
pCNT->SetMarkerColor(kRed+2);
pCNT->SetMarkerStyle(20);
}
pMBCNT->SetPoint(0,113.0558,MuId[0][1]);
pMBCNT->SetPointError(0,0,0,MuId[0][3],MuId[0][2]);
pMBCNT->SetMarkerColor(kRed+2);
pMBCNT->SetMarkerStyle(24);
gStyle->SetOptStat(0);
TH1F *hPad = new TH1F("hPad","",40,0,40);
hPad->SetTitle("");
formatTH1F(hPad,1,1,4);
hPad->Draw();
hPad->GetYaxis()->SetTitle("Efficiency");
hPad->GetXaxis()->SetTitle("Centrality bin");
if(Cent_) pCNT->Draw("pz same");
pMBCNT->Draw("pz same");
char legs[512];
TLegend *leg1 = new TLegend(0.369849,0.1853147,0.6809045,0.4527972,NULL,"brNDC"); // Size 0.03
leg1->SetFillStyle(0);
leg1->SetFillColor(0);
leg1->SetBorderSize(0);
leg1->SetTextSize(0.03);
leg1->SetHeader(leg_title);
if(Cent_) leg1->AddEntry(pCNT,"MuId Efficiency","pl");
sprintf(legs,"MuId Efficiency: %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[0][1],MuId[0][2],MuId[0][3]);
leg1->AddEntry(pMBCNT,legs,"pl");
leg1->Draw("same");
if(MC_){
/*
c2->SaveAs("Jpsi_pPb_MC_MuId_New_CNT.png");
c2->SaveAs("Jpsi_pPb_MC_MuId_New_CNT.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_1st_run_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_1st_run_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_2nd_run_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_2nd_run_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_1st_run_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_1st_run_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_2nd_run_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_2nd_run_CNT_test.pdf");
*/
}
if(Cent_) {
gMuIdEta[1]->SetMarkerStyle(20);
gMuIdEta[1]->SetMarkerColor(634);
gMuIdEta[1]->GetXaxis()->SetTitle("#eta");;
gMuIdEta[1]->GetXaxis()->CenterTitle();;
gMuIdEta[2]->SetMarkerStyle(23);
gMuIdEta[2]->SetMarkerColor(602);
gMuIdEta[3]->SetMarkerStyle(24);
gMuIdEta[3]->SetMarkerColor(618);
gMuIdEta[4]->SetMarkerStyle(25);
gMuIdEta[4]->SetMarkerColor(620);
gMuIdEta[5]->SetMarkerStyle(26);
gMuIdEta[5]->SetMarkerColor(621);
gMuIdEta[6]->SetMarkerStyle(27);
gMuIdEta[6]->SetMarkerColor(622);
gMuIdEta[7]->SetMarkerStyle(28);
gMuIdEta[7]->SetMarkerColor(623);
gMuIdEta[8]->SetMarkerStyle(29);
gMuIdEta[8]->SetMarkerColor(624);
gMuIdEta[0]->SetMarkerStyle(21);
gMuIdEta[0]->SetMarkerColor(802);
formatTH1F(hPadEta,1,1,2);
hPadEta->Draw();
gMuIdEta[1]->SetMinimum(0.5);
gMuIdEta[1]->SetMaximum(1.05);
gMuIdEta[1]->Draw("pz same");
gMuIdEta[2]->Draw("pz same");
gMuIdEta[3]->Draw("pz same");
gMuIdEta[4]->Draw("pz same");
gMuIdEta[5]->Draw("pz same");
gMuIdEta[6]->Draw("pz same");
gMuIdEta[7]->Draw("pz same");
gMuIdEta[8]->Draw("pz same");
gMuIdEta[0]->Draw("pz same");
TLegend *leg2 = new TLegend(0.4899497,0.1678322,0.7876884,0.4947552,NULL,"brNDC"); // Size 0.03
leg2->SetFillStyle(0);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
leg2->SetTextSize(0.04);
leg2->SetHeader(leg_title);
sprintf(legs,"0 - 5 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[1][1],MuId[1][2],MuId[1][3]);
leg2->AddEntry(gMuIdEta[1],legs,"pl");
sprintf(legs,"5 - 10 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[2][1],MuId[2][2],MuId[2][3]);
leg2->AddEntry(gMuIdEta[2],legs,"pl");
sprintf(legs,"10 - 20 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[3][1],MuId[3][2],MuId[3][3]);
leg2->AddEntry(gMuIdEta[3],legs,"pl");
sprintf(legs,"20 - 30 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[4][1],MuId[4][2],MuId[4][3]);
leg2->AddEntry(gMuIdEta[4],legs,"pl");
sprintf(legs,"30 - 40 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[5][1],MuId[5][2],MuId[5][3]);
leg2->AddEntry(gMuIdEta[5],legs,"pl");
sprintf(legs,"40 - 50 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[6][1],MuId[6][2],MuId[6][3]);
leg2->AddEntry(gMuIdEta[6],legs,"pl");
sprintf(legs,"50 - 60 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[7][1],MuId[7][2],MuId[7][3]);
leg2->AddEntry(gMuIdEta[7],legs,"pl");
sprintf(legs,"60 - 100 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[8][1],MuId[8][2],MuId[8][3]);
leg2->AddEntry(gMuIdEta[8],legs,"pl");
sprintf(legs,"MinBias : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[0][1],MuId[0][2],MuId[0][3]);
leg2->AddEntry(gMuIdEta[0],legs,"pl");
leg2->Draw("same");
if(MC_){
/*
c2->SaveAs("Jpsi_pPb_MC_MuId_New_eta_CNT.png");
c2->SaveAs("Jpsi_pPb_MC_MuId_New_eta_CNT.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_1st_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_1st_run_eta_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_2nd_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_2nd_run_eta_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_1st_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_1st_run_eta_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_2nd_run_eta_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_2nd_run_eta_CNT_test.pdf");
*/
}
gMuIdPt[1]->SetMarkerStyle(20);
gMuIdPt[1]->SetMarkerColor(634);
gMuIdPt[1]->GetXaxis()->SetTitle("p_{T} [GeV/c]");;
gMuIdPt[1]->GetXaxis()->CenterTitle();;
gMuIdPt[2]->SetMarkerStyle(23);
gMuIdPt[2]->SetMarkerColor(602);
gMuIdPt[3]->SetMarkerStyle(24);
gMuIdPt[3]->SetMarkerColor(618);
gMuIdPt[4]->SetMarkerStyle(25);
gMuIdPt[4]->SetMarkerColor(620);
gMuIdPt[5]->SetMarkerStyle(26);
gMuIdPt[5]->SetMarkerColor(621);
gMuIdPt[6]->SetMarkerStyle(27);
gMuIdPt[6]->SetMarkerColor(622);
gMuIdPt[7]->SetMarkerStyle(28);
gMuIdPt[7]->SetMarkerColor(623);
gMuIdPt[8]->SetMarkerStyle(29);
gMuIdPt[8]->SetMarkerColor(624);
gMuIdPt[0]->SetMarkerStyle(21);
gMuIdPt[0]->SetMarkerColor(802);
formatTH1F(hPadPt,1,1,1);
hPadPt->Draw();
gMuIdPt[1]->SetMinimum(0.5);
gMuIdPt[1]->SetMaximum(1.05);
gMuIdPt[1]->Draw("pz same");
gMuIdPt[2]->Draw("pz same");
gMuIdPt[3]->Draw("pz same");
gMuIdPt[4]->Draw("pz same");
gMuIdPt[5]->Draw("pz same");
gMuIdPt[6]->Draw("pz same");
gMuIdPt[7]->Draw("pz same");
gMuIdPt[8]->Draw("pz same");
gMuIdPt[0]->Draw("pz same");
TLegend *leg3 = new TLegend(0.4899497,0.1678322,0.7876884,0.4947552,NULL,"brNDC"); // Size 0.03
leg3->SetFillStyle(0);
leg3->SetFillColor(0);
leg3->SetBorderSize(0);
leg3->SetTextSize(0.04);
leg3->SetHeader(leg_title);
sprintf(legs,"0 - 5 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[1][1],MuId[1][2],MuId[1][3]);
leg3->AddEntry(gMuIdPt[1],legs,"pl");
sprintf(legs,"5 - 10 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[2][1],MuId[2][2],MuId[2][3]);
leg3->AddEntry(gMuIdPt[2],legs,"pl");
sprintf(legs,"10 - 20 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[3][1],MuId[3][2],MuId[3][3]);
leg3->AddEntry(gMuIdPt[3],legs,"pl");
sprintf(legs,"20 - 30 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[4][1],MuId[4][2],MuId[4][3]);
leg3->AddEntry(gMuIdPt[4],legs,"pl");
sprintf(legs,"30 - 40 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[5][1],MuId[5][2],MuId[5][3]);
leg3->AddEntry(gMuIdPt[5],legs,"pl");
sprintf(legs,"40 - 50 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[6][1],MuId[6][2],MuId[6][3]);
leg3->AddEntry(gMuIdPt[6],legs,"pl");
sprintf(legs,"50 - 60 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[7][1],MuId[7][2],MuId[7][3]);
leg3->AddEntry(gMuIdPt[7],legs,"pl");
sprintf(legs,"60 - 100 %% : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[8][1],MuId[8][2],MuId[8][3]);
leg3->AddEntry(gMuIdPt[8],legs,"pl");
sprintf(legs,"MinBias : %0.3f^{ +%0.4f}_{ -%0.4f}",MuId[0][1],MuId[0][2],MuId[0][3]);
leg3->AddEntry(gMuIdPt[0],legs,"pl");
leg3->Draw("same");
if(MC_){
/*
c2->SaveAs("Jpsi_pPb__MC_MuId_New_pt_CNT.png");
c2->SaveAs("Jpsi_pPb__MC_MuId_New_pt_CNT.pdf");
*/
}else{
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_1st_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_1st_run_pt_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_2nd_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2Rfb_2nd_run_pt_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_1st_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_1st_run_pt_CNT_test.pdf");
*/
/*
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_2nd_run_pt_CNT_test.png");
c2->SaveAs("Jpsi_pPb_RD_MuIdNew2CS_2nd_run_pt_CNT_test.pdf");
*/
}
}
outfile->cd();
if(Cent_){
gMuIdPt[1]->SetName("gCNT0005Pt");
gMuIdPt[2]->SetName("gCNT0510Pt");
gMuIdPt[3]->SetName("gCNT1020Pt");
gMuIdPt[4]->SetName("gCNT2030Pt");
gMuIdPt[5]->SetName("gCNT3040Pt");
gMuIdPt[6]->SetName("gCNT4050Pt");
gMuIdPt[7]->SetName("gCNT5060Pt");
gMuIdPt[8]->SetName("gCNT60100Pt");
gMuIdEta[1]->SetName("gCNT0005Eta");
gMuIdEta[2]->SetName("gCNT0510Eta");
gMuIdEta[3]->SetName("gCNT1020Eta");
gMuIdEta[4]->SetName("gCNT2030Eta");
gMuIdEta[5]->SetName("gCNT3040Eta");
gMuIdEta[6]->SetName("gCNT4050Eta");
gMuIdEta[7]->SetName("gCNT5060Eta");
gMuIdEta[8]->SetName("gCNT60100Eta");
gMuIdPt[1]->Write();
gMuIdPt[2]->Write();
gMuIdPt[3]->Write();
gMuIdPt[4]->Write();
gMuIdPt[5]->Write();
gMuIdPt[6]->Write();
gMuIdPt[7]->Write();
gMuIdPt[8]->Write();
gMuIdEta[1]->Write();
gMuIdEta[2]->Write();
gMuIdEta[3]->Write();
gMuIdEta[4]->Write();
gMuIdEta[5]->Write();
gMuIdEta[6]->Write();
gMuIdEta[7]->Write();
gMuIdEta[8]->Write();
}
gMuIdPt[0]->SetName("gMBCNTPt");
gMuIdEta[0]->SetName("gMBCNTEta");
gMuId[0]->SetName("gMBCNT");
pCNT->SetName("pCNT");
pMBCNT->SetName("pMBCNT");
gMuIdPt[0]->Write();
gMuIdEta[0]->Write();
gMuId[0]->Write();
pCNT->Write();
pMBCNT->Write();
outfile->Close();
//f->Close();
//files->Close();
}
void formatTH1F(TH1* a, int b, int c, int d){
a->SetLineWidth(2);
a->SetLineStyle(c);
a->SetMarkerSize(2);
a->SetLineColor(b);
a->SetMarkerColor(b);
a->GetYaxis()->SetTitle("Efficiency");
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} [GeV/c]");
}else if(d == 2){
a->GetXaxis()->SetTitle("#eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}
a->GetXaxis()->CenterTitle(true);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.05);
a->GetXaxis()->SetTitleOffset(0.9);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(0.8);
}
void formatTLeg(TLegend* a){
a->SetFillStyle(0);
a->SetFillColor(0);
a->SetBorderSize(0);
a->SetTextSize(0.03);
}
void formatTGraph(TGraph* a, int b, int c, int d)
{
a->SetMarkerStyle(c);
a->SetMarkerColor(b);
a->SetMarkerSize(1.0);
a->SetLineColor(b);
a->SetLineWidth(1);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.06);
a->GetXaxis()->SetTitleOffset(0.9);
a->GetYaxis()->SetTitle("Efficiency");
a->GetXaxis()->CenterTitle();
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} (GeV/c)");
}else if(d == 2){
a->GetXaxis()->SetTitle("eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}
a->GetYaxis()->SetRangeUser(0,1);
a->GetXaxis()->SetRangeUser(0,10);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(0.9);
}
TGraphAsymmErrors *plotEffEta(RooDataSet *a, int aa){
const RooArgSet *set = a->get();
RooRealVar *xAx = (RooRealVar*)set->find("eta");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
const int nbins = xAx->getBinning().numBins();
double tx[nbins], txhi[nbins], txlo[nbins];
double ty[nbins], tyhi[nbins], tylo[nbins];
for (int i=0; i<nbins; i++) {
a->get(i);
ty[i] = eff->getVal();
tx[i] = xAx->getVal();
txhi[i] = fabs(xAx->getErrorHi());
txlo[i] = fabs(xAx->getErrorLo());
tyhi[i] = fabs(eff->getErrorHi());
tylo[i] = fabs(eff->getErrorLo());
}
cout<<"NBins : "<<nbins<<endl;
const double *x = tx;
const double *xhi = txhi;
const double *xlo = txlo;
const double *y = ty;
const double *yhi = tyhi;
const double *ylo = tylo;
TGraphAsymmErrors *b = new TGraphAsymmErrors();
if(aa == 1) {*b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi);}
if(aa == 0) {*b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi);}
b->SetMaximum(1.1);
b->SetMinimum(0.0);
b->SetMarkerStyle(20);
b->SetMarkerColor(kRed+2);
b->SetMarkerSize(1.0);
b->SetTitle("");
b->GetXaxis()->SetTitleSize(0.05);
b->GetYaxis()->SetTitleSize(0.05);
b->GetXaxis()->SetTitle("#eta");
b->GetYaxis()->SetTitle("Efficiency");
b->GetXaxis()->CenterTitle();
//b->Draw("apz");
for (int i=0; i<nbins; i++) {
cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl;
}
return b;
}
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa){
const RooArgSet *set = a->get();
RooRealVar *xAx = (RooRealVar*)set->find("pt");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
const int nbins = xAx->getBinning().numBins();
double tx[nbins], txhi[nbins], txlo[nbins];
double ty[nbins], tyhi[nbins], tylo[nbins];
for (int i=0; i<nbins; i++) {
a->get(i);
ty[i] = eff->getVal();
tx[i] = xAx->getVal();
txhi[i] = fabs(xAx->getErrorHi());
txlo[i] = fabs(xAx->getErrorLo());
tyhi[i] = fabs(eff->getErrorHi());
tylo[i] = fabs(eff->getErrorLo());
}
cout<<"NBins : "<<nbins<<endl;
const double *x = tx;
const double *xhi = txhi;
const double *xlo = txlo;
const double *y = ty;
const double *yhi = tyhi;
const double *ylo = tylo;
TGraphAsymmErrors *b = new TGraphAsymmErrors();
if(aa == 1) {*b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi);}
if(aa == 0) {*b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi);}
b->SetMaximum(1.1);
b->SetMinimum(0.0);
b->SetMarkerStyle(20);
b->SetMarkerColor(kRed+2);
b->SetMarkerSize(1.0);
b->SetTitle("");
b->GetXaxis()->SetTitleSize(0.05);
b->GetYaxis()->SetTitleSize(0.05);
b->GetXaxis()->SetTitle("p_{T} [GeV/c]");
b->GetYaxis()->SetTitle("Efficiency");
b->GetXaxis()->CenterTitle();
//b->Draw("apz");
for (int i=0; i<nbins; i++) {
cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl;
}
return b;
}
TH2F *plotEff2D(RooDataSet *a, TString b){
const RooArgSet *set = a->get();
RooRealVar *yAx = (RooRealVar*)set->find("pt");
RooRealVar *xAx = (RooRealVar*)set->find("eta");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
//const int xnbins = xAx->getBinning().numBins();
//const int ynbins = yAx->getBinning().numBins();
const double *xvbins = xAx->getBinning().array();
const double *yvbins = yAx->getBinning().array();
TH2F* h = new TH2F(b, "", xAx->getBinning().numBins(), xvbins, yAx->getBinning().numBins(), yvbins);
gStyle->SetPaintTextFormat("5.2f");
gStyle->SetPadRightMargin(0.12);
gStyle->SetPalette(1);
h->SetOption("colztexte");
h->GetZaxis()->SetRangeUser(-0.001,1.001);
h->SetStats(kFALSE);
h->GetYaxis()->SetTitle("p_{T} [GeV/c]");
h->GetXaxis()->SetTitle("#eta");
h->GetXaxis()->CenterTitle();
h->GetYaxis()->CenterTitle();
h->GetXaxis()->SetTitleSize(0.05);
h->GetYaxis()->SetTitleSize(0.05);
h->GetYaxis()->SetTitleOffset(0.8);
h->GetXaxis()->SetTitleOffset(0.9);
for(int i=0; i<a->numEntries(); i++){
a->get(i);
h->SetBinContent(h->FindBin(xAx->getVal(), yAx->getVal()), eff->getVal());
h->SetBinError(h->FindBin(xAx->getVal(), yAx->getVal()), (eff->getErrorHi()-eff->getErrorLo())/2.);
}
return h;
}
<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/Ana/MC/MuTrg/tp_Ana_Trg_RD_CS_no_matching_for_B.py
import FWCore.ParameterSet.Config as cms
process = cms.Process("TagProbe")
process.load('FWCore.MessageService.MessageLogger_cfi')
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) )
PDFName = "cbGaussPlusExpo"
#PDFName = "gaussPlusExpo"
#PDFName = "cbPlusExpo"
process.TagProbeFitTreeAnalyzer = cms.EDAnalyzer("TagProbeFitTreeAnalyzer",
# IO parameters:
InputFileNames = cms.vstring("/afs/cern.ch/work/k/kilee/tutorial/cms538_pPb/src/UserCode/HiTagAndProbe/test/TnP2013/ProdMerge/MC/20140730_B/tnp_pA_MC_Prod_Merge_for_B_no_matching_20140730.root"),
InputDirectoryName = cms.string("MuonTrgNew2CS"),
InputTreeName = cms.string("fitter_tree"),
OutputFileName = cms.string("tnp_pPb_Ana_MuTrgNew2CS_CBGpExp_MC_for_B_no_matching_test.root"),
#numbrer of CPUs to use for fitting
NumCPU = cms.uint32(1),
# specifies wether to save the RooWorkspace containing the data for each bin and
# the pdf object with the initial and final state snapshots
SaveWorkspace = cms.bool(True),
binsForMassPlots = cms.uint32(52),
#WeightVariable = cms.string("weight"),
# defines all the real variables of the probes available in the input tree and intended for use in the efficiencies
Variables = cms.PSet(
mass = cms.vstring("Tag-Probe Mass", "2.6", "3.5", "GeV/c^{2}"),
pt = cms.vstring("Probe p_{T}", "0", "1000", "GeV/c"),
# p = cms.vstring("Probe p", "0", "1000", "GeV/c"),
eta = cms.vstring("Probe #eta", "-2.5", "2.5", ""),
abseta = cms.vstring("Probe |#eta|", "0", "2.5", ""),
tag_pt = cms.vstring("Tag p_{T}", "2.6", "1000", "GeV/c"),
#weight = cms.vstring("weight","0.0","10000.0",""),
),
# defines all the discrete variables of the probes available in the input tree and intended for use in the efficiency calculations
Categories = cms.PSet(
HLTL1Open = cms.vstring("HLTL1Open", "dummy[true=1,false=0]"),
# HLTL1HighQ = cms.vstring("HLTL1HighQ", "dummy[true=1,false=0]"),
HLTL2 = cms.vstring("HLTL2", "dummy[true=1,false=0]"),
PAMu3 = cms.vstring("PAMu3", "dummy[true=1,false=0]"),
),
# defines all the PDFs that will be available for the efficiency calculations; uses RooFit's "factory" syntax;
# each pdf needs to define "signal", "backgroundPass", "backgroundFail" pdfs, "efficiency[0.9,0,1]" and "signalFractionInPassing[0.9]" are used for initial values
PDFs = cms.PSet(
cbPlusExpo = cms.vstring(
"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.05,0.01,0.1], alpha[1.0, 0.2, 3.0], n[2, 0.5, 100.])",
"Exponential::backgroundPass(mass, lp[0,-5,5])",
"Exponential::backgroundFail(mass, lf[0,-5,5])",
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
cbGaussPlusExpo = cms.vstring(
"CBShape::signal1(mass, mean[3.1,3.0,3.2], sigma1[0.01,0.01,0.1], alpha[0.5, 0.2, 3.0], n[2, 0.5, 100.])",
"Gaussian::signal2(mass, mean[3.1, 3.0, 3.2], sigma2[0.04,0.01,0.1])",
"SUM::signal(signal1,vFrac[0.8,0,1]*signal2)",
"Exponential::backgroundPass(mass, lp[0,-5,5])",
"Exponential::backgroundFail(mass, lf[0,-5,5])",
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
),
# defines a set of efficiency calculations, what PDF to use for fitting and how to bin the data;
# there will be a separate output directory for each calculation that includes a simultaneous fit, side band subtraction and counting.
Efficiencies = cms.PSet(
#the name of the parameter set becomes the name of the directory
PAMu3_pt = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("PAMu3","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
pt = cms.vdouble(0.0, 1.5, 3.0, 4.5, 6.0, 9.0, 20, 30),
),
BinToPDFmap = cms.vstring(PDFName)
),
PAMu3_eta = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("PAMu3","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
eta = cms.vdouble(-2.4, -1.5, -0.5, 0.5, 1.5, 2.4),
),
BinToPDFmap = cms.vstring(PDFName)
),
PAMu3_1bin_eta = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("PAMu3","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
eta = cms.vdouble(-2.4, 2.4),
),
BinToPDFmap = cms.vstring(PDFName)
),
PAMu3_1bin_pt_eta = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("PAMu3","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
pt = cms.vdouble(0., 30),
eta = cms.vdouble(-2.4, 2.4),
),
BinToPDFmap = cms.vstring(PDFName)
),
## HLT L2 DoubleMu3
HLTL2_pt = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("HLTL2","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
pt = cms.vdouble(0.0, 1.5, 3.0, 4.5, 6.0, 9.0, 20, 30),
),
BinToPDFmap = cms.vstring(PDFName)
),
HLTL2_eta = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("HLTL2","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
eta = cms.vdouble(-2.4, -1.5, -0.5, 0.5, 1.5, 2.4),
),
BinToPDFmap = cms.vstring(PDFName)
),
HLTL2_1bin_eta = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("HLTL2","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
eta = cms.vdouble(-2.4, 2.4),
),
BinToPDFmap = cms.vstring(PDFName)
),
HLTL2_1bin_pt_eta = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("HLTL2","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
pt = cms.vdouble(0.0, 30),
eta = cms.vdouble(-2.4, 2.4),
),
BinToPDFmap = cms.vstring(PDFName)
),
)
)
process.fitness = cms.Path(
process.TagProbeFitTreeAnalyzer
)
<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/Ana/RD/MuID/tp_Ana_MuId_TM_Dbl_etabin3_CS_1st_for_B.py
import FWCore.ParameterSet.Config as cms
process = cms.Process("TagProbe")
process.load('FWCore.MessageService.MessageLogger_cfi')
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) )
#PDFName = "cbPlusExpo"
#PDFName = "gaussPlusExpo"
PDFName = "cbPlusPoly"
process.TagProbeFitTreeAnalyzer = cms.EDAnalyzer("TagProbeFitTreeAnalyzer",
# IO parameters:
InputFileNames = cms.vstring("/afs/cern.ch/work/k/kilee/tutorial/cms538_pPb/src/UserCode/HiTagAndProbe/test/TnP2013/ProdMerge/RD/20140725_B/tnp_pA_1st_all_run_Prod_Merge_for_B_20140725.root"),
InputDirectoryName = cms.string("MuonIDNew2etabin3CS"),
InputTreeName = cms.string("fitter_tree"),
OutputFileName = cms.string("tnp_pPb_Ana_MuIdNew2etabin3CS_CBpPoly_1st_Run_for_B_test.root"),
#numbrer of CPUs to use for fitting
NumCPU = cms.uint32(1),
# specifies wether to save the RooWorkspace containing the data for each bin and
# the pdf object with the initial and final state snapshots
#binnedFit = cms.bool(True),
#binsForFit = cms.uint32(30),
binsForMassPlots = cms.uint32(50),
binnedFit = cms.bool(True),
binsForFit = cms.uint32(50),
# defines all the real variables of the probes available in the input tree and intended for use in the efficiencies
Variables = cms.PSet(
mass = cms.vstring("Tag-Probe Mass", "2.6", "3.5", "GeV/c^{2}"),
pt = cms.vstring("Probe p_{T}", "0", "1000", "GeV/c"),
p = cms.vstring("Probe p", "0", "1000", "GeV/c"),
eta = cms.vstring("Probe #eta", "-2.5", "2.5", ""),
abseta = cms.vstring("Probe |#eta|", "0", "2.5", ""),
tag_pt = cms.vstring("Tag p_{T}", "2.6", "1000", "GeV/c"),
),
# defines all the discrete variables of the probes available in the input tree and intended for use in the efficiency calculations
Categories = cms.PSet(
#mcTrue = cms.vstring("MC true", "dummy[true=1,false=0]"),
PassingTrk = cms.vstring("PassingTrk", "dummy[true=1,false=0]"),
),
# defines all the PDFs that will be available for the efficiency calculations; uses RooFit's "factory" syntax;
# each pdf needs to define "signal", "backgroundPass", "backgroundFail" pdfs, "efficiency[0.9,0,1]" and "signalFractionInPassing[0.9]" are used for initial values
PDFs = cms.PSet(
cbPlusExpo = cms.vstring(
"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.5], alpha[2.0, 0.2, 4.0], n[4, 0.5, 100.])",
#"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.02,0.02,0.1], alpha[1.0, 0.2, 3.0], n[4, 0.5, 100.])",
"Exponential::backgroundPass(mass, lp[0,-5,5])",
"Exponential::backgroundFail(mass, lf[0,-5,5])",
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
cbPlusPoly = cms.vstring(
"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.02, 0.01, 0.1], alpha[2.0, 1.0, 5.0], n[1, 0.5, 100.])",
#"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.02, 0.01, 0.1], alpha[1.0, 0.5, 4.0], n[1, 0.5, 100.])",
"Chebychev::backgroundPass(mass, {cPass[0,-1.0,1.0], cPass2[0,-1.0,1.0]})",
"Chebychev::backgroundFail(mass, {cFail[0,-1.0,1.0], cFail2[0,-1.0,1.0]})",
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
gaussPlusExpo = cms.vstring(
"Gaussian::signal(mass, mean[3.1,3.0,3.2], sigma[0.02, 0.01, 0.1])",
#"Gaussian::signal(mass, mean[3.1,3.0,3.2], sigma[0.04])",
"Chebychev::backgroundPass(mass, {cPass[0,-1.0,1.0], cPass2[0,-1.0,1.0]})",
"Chebychev::backgroundFail(mass, {cFail[0,-1.0,1.0], cFail2[0,-1.0,1.0]})",
#"Exponential::backgroundPass(mass, lp[0,-5,5])",
#"Exponential::backgroundFail(mass, lf[0,-5,5])", # same slope, they're both muons
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
),
# defines a set of efficiency calculations, what PDF to use for fitting and how to bin the data;
# there will be a separate output directory for each calculation that includes a simultaneous fit, side band subtraction and counting.
Efficiencies = cms.PSet(
#the name of the parameter set becomes the name of the directory
PassingTrk_pt = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("PassingTrk","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
pt = cms.vdouble(0.0, 1.5, 3.0, 4.5, 6.0, 9.0, 20, 30),
),
BinToPDFmap = cms.vstring(PDFName)
),
PassingTrk_1bin_eta_pt = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("PassingTrk","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
pt = cms.vdouble(0.0,30),
eta = cms.vdouble(0.8, 2.4),
),
BinToPDFmap = cms.vstring(PDFName)
),
)
)
process.fitness = cms.Path(
process.TagProbeFitTreeAnalyzer
)
<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/Efficiency/MC/MuTrk/TnPDrawMass_etabin2_for_B_no_matching.C
#include <TROOT.h>
#include <TFile.h>
#include <iostream>
#include <TSystem.h>
#include <TTree.h>
#include <TKey.h>
#include <TH1.h>
#include <TH2.h>
#include <TPave.h>
#include <TText.h>
#include <sstream>
#include <string.h>
#include <TFile.h>
#include <TGraphAsymmErrors.h>
#include <TH1.h>
#include <TH2.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <RooFit.h>
#include <RooRealVar.h>
#include <RooDataSet.h>
#include <RooArgSet.h>
#include <TStyle.h>
#include <TLatex.h>
#include <TDirectory.h>
#include <TCollection.h>
#include <TPostScript.h>
using namespace RooFit;
using namespace std;
// Function Define
TH2F *plotEff2D(RooDataSet *a, TString b);
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa);
TGraphAsymmErrors *plotEffEta(RooDataSet *a, int aa);
void formatTH1F(TH1* a, int b, int c, int d);
void formatTGraph(TGraph* a, int b, int c, int d);
void formatTLeg(TLegend* a);
void TnPDrawMass_etabin2_1st_for_B();
int Mode_ = 2; // 1 - Trg, 2 - Trk, 3 - MuId
const int maxfile_ = 1;
const int ptBins = 7;
TString Cat1 = "MC"; // MC or RD
TString Cat2 = "Trk"; // Trg, Trk or MuId
TString Cat3 = "Tracker"; // Trigger, Inner Tracker or Muon Id
TString data_set = "Data Set : Prompt Reco pPb 2013"; // ReReco, Prompt Reco or MC weighted
int TrgBit_ = 1; // 1 - L1DoubleMuOpen, 2 - L1DoubleMuHighQ, 3 - L2DoubleMu3
TString outfile_ = "Jpsi_pPb_MC_MuTrketabin2_2GpP4_Eff_Mass_Plots_total_for_B_no_matching_test.ps";
void TnPDrawMass_etabin2_1st_for_B() {
gROOT->Macro("rootlogon.C");
char *infile;
char *files[maxfile_] = {
"../../Ana/MC/MuTrk/tnp_pPb_Ana_MuTrketabin2_2GpP4_MC_for_B_no_matching_test.root",
};
TString outname_in, outname_mid, outname_out;
TString middle_name, middle_name2;
int Mode = 0;
gROOT->SetStyle("Plain");
gStyle->SetOptStat(0);
gStyle->SetTitle(0);
gStyle->SetPaperSize(20,26);
TCanvas *c1 = new TCanvas();
Int_t type = 112;
TString out1 = outfile_ + "[";
c1->Print(out1);
for(int l = 0; l < maxfile_; l++){
infile = files[l];
TFile *f = new TFile(infile);
//TFile finput(infile);
Mode = l;
if(Mode == 0){
middle_name = "All";
middle_name2 = "MinBias";
}else if(Mode == 1){
middle_name = "0005";
middle_name2 = "0 - 5 %";
}else if(Mode == 2){
middle_name = "0510";
middle_name2 = "5 - 10 %";
}else if(Mode == 3){
middle_name = "1020";
middle_name2 = "10 - 20 %";
}else if(Mode == 4){
middle_name = "2030";
middle_name2 = "20 - 30 %";
}else if(Mode == 5){
middle_name = "3040";
middle_name2 = "30 - 40 %";
}else if(Mode == 6){
middle_name = "4050";
middle_name2 = "40 - 50 %";
}else if(Mode == 7){
middle_name = "5060";
middle_name2 = "50 - 60 %";
}else if(Mode == 8){
middle_name = "60100";
middle_name2 = "60 - 100 %";
}
outname_in = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps[";
outname_mid = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps";
outname_out = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps]";
cout<<" Out Name : "<<outname_in<<" "<<outname_mid<<" "<<outname_in<<endl;
TString tot_dir, dir_pt, dir_eta, dir_suffix, intg;
TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
"pt_bin5_", "pt_bin6_"};
if(Mode_ == 1) {
if(TrgBit_ == 1){
dir_pt = "MuonTrgNew2etabin2CS/PAMu3_pt/";
intg = "MuonTrgNew2etabin2CS/PAMu3_1bin_pt_eta/eta_bin0__pt_bin0_";
dir_suffix = "_cbCaussPlusExpo";
}else if(TrgBit_ == 2){
dir_pt = "MuonTrgNew/HLTL1HighQ_pt/";
dir_eta = "MuonTrgNew/HLTL1HighQ_eta/";
dir_suffix = "_cbPlusExpo";
intg = "MuonTrgNew/HLTL1HighQ_1bin_pt_eta/pt_bin0__eta_bin0_";
}else if(TrgBit_ == 3){
dir_pt = "MuonTrgNew/HLTL2_pt/";
dir_eta = "MuonTrgNew/HLTL2_eta/";
dir_suffix = "_cbPlusExpo";
intg = "MuonTrgNew/HLTL2_1bin_pt_eta/pt_bin0__eta_bin0_";
}
}else if (Mode_ == 2){
dir_pt = "MuonTrketabin2/isTrk_pt/";
intg = "MuonTrketabin2/isTrk_1bin_pt_eta/eta_bin0__eta_bin0_";
dir_suffix = "_twoGaussPlusPoly4";
}else if (Mode_ == 3){
dir_pt = "MuonIDNew2etabin2CS/PassingTrk_pt/";
intg = "/MuonIDNew2etabin2CS/PassingTrk_1bin_eta_pt/eta_bin0__pt_bin0_";
dir_suffix = "_cbPlusPoly";
}
///*
cout<<" Total directory : "<<tot_dir<<endl;
gStyle->SetPaperSize(20,26);
Int_t type = 112;
c1->Print(outname_in);
int cnt = 0;
TCanvas *tmp1 = new TCanvas();
tmp1->cd();
TString title;
title = "J/#psi " + Cat3 + " Efficiency Heavy Ion TnP Result (" + middle_name2 + ")";
TLatex fitInfo;
fitInfo.SetTextAlign(13);
fitInfo.SetTextSize(0.05);
fitInfo.DrawLatex(0.05,0.95, title);
fitInfo.DrawLatex(0.05,0.90, data_set);
fitInfo.SetTextSize(0.04);
fitInfo.DrawLatex(0.05,0.80, "FitFunction Condition");
fitInfo.SetTextSize(0.03);
if(Mode_ == 1){
fitInfo.DrawLatex(0.1,0.60,"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.05,0.01,0.1], alpha[1.0, 0.2, 2.0], n[2, 0.5, 100.])");
fitInfo.DrawLatex(0.1,0.55,"Exponential::backgroundPass(mass, lp[0,-5,5])");
fitInfo.DrawLatex(0.1,0.50,"Exponential::backgroundFail(mass, lf[0,-5,5])");
}else if(Mode_ == 2) {
fitInfo.DrawLatex(0.1,0.70,"Gaussian::G1(mass, mean, sigma1[0.15,0.05,0.25])");
fitInfo.DrawLatex(0.1,0.65,"Gaussian::G2(mass, mean, sigma2[0.02,0.01,0.1])");
fitInfo.DrawLatex(0.1,0.60,"SUM::signal(coef[0.1,0,1]*G1,G2)");
fitInfo.DrawLatex(0.1,0.55,"Chebychev::backgroundPass(mass, {cPass[0,-0.5,0.5], cPass2[0,-0.5,0.5]})");
fitInfo.DrawLatex(0.1,0.50,"Chebychev::backgroundFail(mass, {cFail[0,-0.5,0.5], cFail2[0,-0.5,0.5]})");
}else{
fitInfo.DrawLatex(0.1,0.60,"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.05,0.01,0.1], alpha[1.0, 0.2, 3.0], n[1, 1.0, 100.])");
fitInfo.DrawLatex(0.1,0.55,"Chebychev::backgroundPass(mass, {cPass[0,-0.5,0.5], cPass2[0,-0.5,0.5]})");
fitInfo.DrawLatex(0.1,0.50,"Chebychev::backgroundFail(mass, {cFail[0,-0.5,0.5], cFail2[0,-0.5,0.5]})");
}
fitInfo.SetTextSize(0.04);
fitInfo.DrawLatex(0.05,0.40,"Bin Information");
fitInfo.SetTextSize(0.03);
fitInfo.DrawLatex(0.1,0.30,"#eta : -2.4,-1.97,-1.72,-1.47,-1.22,-0.97,-0.72,0.47,0.22,0.03,0.28,0.53,0.78,1.03,1.46");
fitInfo.DrawLatex(0.1,0.25,"p_{T} [GeV/c] : 6.5,7.5,8.5,9.5,11,14,30");
c1 = (TCanvas *)tmp1->Clone();
c1->Print(outname_mid);
c1->Print(outfile_);
TString mid_title = "Centrality : (" + middle_name2 + ")";
TString leg_title = Cat2 + " " + Cat3 + " Efficiency (" + middle_name2 + ")";
if(Mode < 1) {
// pt
for(int j = 0; j < ptBins; j++){
cout<<" dir_pt : "<<dir_pt<<", ptbins : "<<ptbins[j]<<", dir_suffix : "<<dir_suffix<<endl;
TString tot_dir = dir_pt + ptbins[j] + dir_suffix;
f->cd(tot_dir);
cout<<" tot_dir : "<<tot_dir<<endl;
TDirectory *root_dir = gDirectory;
TIter rootnextkey( root_dir->GetListOfKeys() );
root_dir->cd();
TKey *rootkey;
TCanvas *ctmp = new TCanvas();
ctmp->cd();
TLatex l;
l.SetTextAlign(13);
l.SetTextSize(0.06);
l.DrawLatex(0.1,0.8,mid_title);
l.DrawLatex(0.1,0.6,"Bin : ");
l.SetTextSize(0.04);
l.DrawLatex(0.1,0.5,tot_dir);
ctmp->Update();
c1 = (TCanvas *)ctmp->Clone();
c1->Print(outname_mid);
c1->Print(outfile_);
while( rootkey = (TKey*)rootnextkey() )
{
TObject *rootobj = rootkey->ReadObj();
TDirectory *rdir = gDirectory;
TIter rdirnextkey(rdir->GetListOfKeys());
rdir->cd();
TKey *dir_key;
while( dir_key = (TKey*)rdirnextkey())
{
if (rootobj->IsA()->InheritsFrom("TCanvas")){
c1 = (TCanvas *)rootobj;
c1->Print(outname_mid);
c1->Print(outfile_);
cnt++;
cout<<"Count : "<<cnt<<endl;
if(cnt > 0) break;
}
}
}
}
}
tot_dir = intg + dir_suffix;
f->cd(tot_dir);
cout<<" tot_dir : "<<tot_dir<<endl;
TDirectory *root_dir = gDirectory;
TIter rootnextkey( root_dir->GetListOfKeys() );
root_dir->cd();
TKey *rootkey;
TCanvas *ctmp = new TCanvas();
ctmp->cd();
TLatex l;
l.SetTextAlign(13);
l.SetTextSize(0.06);
l.DrawLatex(0.1,0.8,mid_title);
l.DrawLatex(0.1,0.6,"Bin : ");
l.SetTextSize(0.04);
l.DrawLatex(0.1,0.5,tot_dir);
ctmp->Update();
c1 = (TCanvas *)ctmp->Clone();
c1->Print(outname_mid);
c1->Print(outfile_);
while( rootkey = (TKey*)rootnextkey() )
{
TObject *rootobj = rootkey->ReadObj();
TDirectory *rdir = gDirectory;
TIter rdirnextkey(rdir->GetListOfKeys());
rdir->cd();
TKey *dir_key;
while( dir_key = (TKey*)rdirnextkey())
{
if (rootobj->IsA()->InheritsFrom("TCanvas")){
c1 = (TCanvas *)rootobj;
c1->Print(outname_mid);
c1->Print(outfile_);
cnt++;
cout<<"Count : "<<cnt<<endl;
if(cnt > 0) break;
}
}
}
}
c1->Print(outname_out);
TString out2 = outfile_ + "]";
c1->Print(out2);
}
void formatTH1F(TH1* a, int b, int c, int d){
a->SetLineWidth(2);
a->SetLineStyle(c);
a->SetMarkerSize(2);
a->SetLineColor(b);
a->SetMarkerColor(b);
a->GetYaxis()->SetTitle("Efficiency");
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} [GeV/c]");
}else if(d == 2){
a->GetXaxis()->SetTitle("#eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}
a->GetXaxis()->CenterTitle(true);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.05);
a->GetXaxis()->SetTitleOffset(0.9);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(0.8);
}
void formatTLeg(TLegend* a){
a->SetFillStyle(0);
a->SetFillColor(0);
a->SetBorderSize(0);
a->SetTextSize(0.03);
}
void formatTGraph(TGraph* a, int b, int c, int d)
{
a->SetMarkerStyle(c);
a->SetMarkerColor(b);
a->SetMarkerSize(1.0);
a->SetLineColor(b);
a->SetLineWidth(1);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.06);
a->GetXaxis()->SetTitleOffset(0.9);
a->GetYaxis()->SetTitle("Efficiency");
a->GetXaxis()->CenterTitle();
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} (GeV/c)");
}else if(d == 2){
a->GetXaxis()->SetTitle("eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}
a->GetYaxis()->SetRangeUser(0,1);
a->GetXaxis()->SetRangeUser(0,10);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(0.9);
}
TGraphAsymmErrors *plotEffEta(RooDataSet *a, int aa){
const RooArgSet *set = a->get();
RooRealVar *xAx = (RooRealVar*)set->find("eta");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
const int nbins = xAx->getBinning().numBins();
double tx[nbins], txhi[nbins], txlo[nbins];
double ty[nbins], tyhi[nbins], tylo[nbins];
for (int i=0; i<nbins; i++) {
a->get(i);
ty[i] = eff->getVal();
tx[i] = xAx->getVal();
txhi[i] = fabs(xAx->getErrorHi());
txlo[i] = fabs(xAx->getErrorLo());
tyhi[i] = fabs(eff->getErrorHi());
tylo[i] = fabs(eff->getErrorLo());
}
cout<<"NBins : "<<nbins<<endl;
const double *x = tx;
const double *xhi = txhi;
const double *xlo = txlo;
const double *y = ty;
const double *yhi = tyhi;
const double *ylo = tylo;
TGraphAsymmErrors *b = new TGraphAsymmErrors();
if(aa == 1) {*b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi);}
if(aa == 0) {*b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi);}
b->SetMaximum(1.1);
b->SetMinimum(0.0);
b->SetMarkerStyle(20);
b->SetMarkerColor(kRed+2);
b->SetMarkerSize(1.0);
b->SetTitle("");
b->GetXaxis()->SetTitleSize(0.05);
b->GetYaxis()->SetTitleSize(0.05);
b->GetXaxis()->SetTitle("#eta");
b->GetYaxis()->SetTitle("Efficiency");
b->GetXaxis()->CenterTitle();
//b->Draw("apz");
for (int i=0; i<nbins; i++) {
cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl;
}
return b;
}
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa){
const RooArgSet *set = a->get();
RooRealVar *xAx = (RooRealVar*)set->find("pt");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
const int nbins = xAx->getBinning().numBins();
double tx[nbins], txhi[nbins], txlo[nbins];
double ty[nbins], tyhi[nbins], tylo[nbins];
for (int i=0; i<nbins; i++) {
a->get(i);
ty[i] = eff->getVal();
tx[i] = xAx->getVal();
txhi[i] = fabs(xAx->getErrorHi());
txlo[i] = fabs(xAx->getErrorLo());
tyhi[i] = fabs(eff->getErrorHi());
tylo[i] = fabs(eff->getErrorLo());
}
cout<<"NBins : "<<nbins<<endl;
const double *x = tx;
const double *xhi = txhi;
const double *xlo = txlo;
const double *y = ty;
const double *yhi = tyhi;
const double *ylo = tylo;
TGraphAsymmErrors *b = new TGraphAsymmErrors();
if(aa == 1) {*b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi);}
if(aa == 0) {*b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi);}
b->SetMaximum(1.1);
b->SetMinimum(0.0);
b->SetMarkerStyle(20);
b->SetMarkerColor(kRed+2);
b->SetMarkerSize(1.0);
b->SetTitle("");
b->GetXaxis()->SetTitleSize(0.05);
b->GetYaxis()->SetTitleSize(0.05);
b->GetXaxis()->SetTitle("p_{T} [GeV/c]");
b->GetYaxis()->SetTitle("Efficiency");
b->GetXaxis()->CenterTitle();
//b->Draw("apz");
for (int i=0; i<nbins; i++) {
cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl;
}
return b;
}
TH2F *plotEff2D(RooDataSet *a, TString b){
const RooArgSet *set = a->get();
RooRealVar *yAx = (RooRealVar*)set->find("pt");
RooRealVar *xAx = (RooRealVar*)set->find("eta");
RooRealVar *eff = (RooRealVar*)set->find("efficiency");
// const int xnbins = xAx->getBinning().numBins();
// const int ynbins = yAx->getBinning().numBins();
//double xbins[] = {-2.4, -1.6, -0.8, 0.0, 0.8, 1.6, 2.4};
//double ybins[] = {0, 2, 3, 5, 8, 10, 20};
const double *xvbins = xAx->getBinning().array();
const double *yvbins = yAx->getBinning().array();
TH2F* h = new TH2F(b, "", xAx->getBinning().numBins(), xvbins, yAx->getBinning().numBins(), yvbins);
gStyle->SetPaintTextFormat("5.2f");
gStyle->SetPadRightMargin(0.12);
gStyle->SetPalette(1);
h->SetOption("colztexte");
h->GetZaxis()->SetRangeUser(-0.001,1.001);
h->SetStats(kFALSE);
h->GetYaxis()->SetTitle("p_{T} [GeV/c]");
h->GetXaxis()->SetTitle("#eta");
h->GetXaxis()->CenterTitle();
h->GetYaxis()->CenterTitle();
h->GetXaxis()->SetTitleSize(0.05);
h->GetYaxis()->SetTitleSize(0.05);
h->GetYaxis()->SetTitleOffset(0.8);
h->GetXaxis()->SetTitleOffset(0.9);
for(int i=0; i<a->numEntries(); i++){
a->get(i);
h->SetBinContent(h->FindBin(xAx->getVal(), yAx->getVal()), eff->getVal());
h->SetBinError(h->FindBin(xAx->getVal(), yAx->getVal()), (eff->getErrorHi()-eff->getErrorLo())/2.);
}
return h;
}
<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/Efficiency/Comp/MuID/CompMuId_etabin3_1st_no_matching.C
//////////////////////////////////////////////////////////////////////////////////
//This code compare RD and MC("and" or "or" pp). //
// //
// 2013-12-21 //
// by <NAME> //
//////////////////////////////////////////////////////////////////////////////////
#include <TROOT.h>
#include <TFile.h>
#include <TNtuple.h>
#include <TCanvas.h>
#include <TProfile.h>
#include <TGraph.h>
#include <TH1D.h>
#include <TH2D.h>
#include <TGraphAsymmErrors.h>
#include <TLegend.h>
#include <TLatex.h>
#include <TMath.h>
#include <TSystem.h>
#include <TStyle.h>
#include <Riostream.h>
#include <TString.h>
#include <TInterpreter.h>
#include <TBrowser.h>
void CalEffErr(TGraph *a, double *b);
TGraphAsymmErrors *getEff(TH1F *h1, TH1F *h2);
TGraphAsymmErrors *calcEff(TH1* h1, TH1* h2);
void formatTGraph(TGraph* a, int b, int c, int d);
void formatTCanv(TCanvas* a);
void formatTLeg(TLegend* a);
void formatTH1F(TH1* a, int b, int c, int d);
void CompMuId_etabin_1st()
{
gROOT->Macro("rootlogon.C");
gStyle->SetOptStat(0);
gStyle->SetPadBottomMargin(0.13);
gStyle->SetPadLeftMargin(0.13);
gStyle->SetTitleYOffset(1.0);
/*
TFile *f1 = new TFile("Jpsi_pPb_RD_MuIdNew2etabin1Rfb_CBpPoly_1st_Run_Eff_test.root", "READ");
TFile *f2 = new TFile("Jpsi_pPb_MC_MuIdNew2etabin1Rfb_CBpPoly_1st_Run_Eff_test.root", "READ");
*/
TFile *f1 = new TFile("Jpsi_pPb_RD_MuIdNew2etabin1CS_CBpPoly_1st_Run_Eff_test.root", "READ");
TFile *f2 = new TFile("Jpsi_pPb_MC_MuIdNew2etabin1CS_CBpPoly_1st_Run_Eff_test.root", "READ");
/*
TFile *f1 = new TFile("Jpsi_pPb_RD_MuIdNew2etabin1CS_CBpPoly_1st_Run_Eff_for_B_test.root", "READ");
TFile *f2 = new TFile("Jpsi_pPb_MC_MuIdNew2etabin1CS_CBpPoly_1st_Run_Eff_for_B_test.root", "READ");
*/
TGraph *gMuId1Pt = (TGraph*) f1->Get("MuId_pt_All");
TGraph *gMuId2Pt = (TGraph*) f2->Get("MuId_pt_All");
TCanvas *c1 = new TCanvas("c1","",700,600);
TH1F *hPad2 = new TH1F("hPad2","",12,0,30);
hPad2->GetYaxis()->CenterTitle();
TLatex *lt1 = new TLatex();
lt1->SetNDC();
formatTH1F(hPad2,1,1,1);
hPad2->GetYaxis()->SetTitleOffset(1.2);
char legs[512];
formatTGraph(gMuId1Pt,859,21,1);
gMuId1Pt->SetMarkerSize(1.2);
formatTGraph(gMuId2Pt,809,20,1);
gMuId2Pt->SetMarkerSize(1.4);
hPad2->SetMinimum(0.50);
hPad2->SetMaximum(1.05);
hPad2->Draw();
gMuId1Pt->Draw("pz same");
gMuId2Pt->Draw("pz same");
TLegend *leg2 = new TLegend(0.29,0.17,0.63,0.40,NULL,"brNDC");
leg2->SetFillStyle(0);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
leg2->SetTextSize(0.040);
leg2->SetHeader("Muon ID Efficiency");
sprintf(legs,"MC (PYTHIA+EvtGen)");
leg2->AddEntry(gMuId2Pt,legs,"pl");
sprintf(legs,"Data(pPb)");
leg2->AddEntry(gMuId1Pt,legs,"pl");
leg2->Draw();
lt1->SetTextSize(0.035);
/*
lt1->DrawLatex(0.20,0.54,"(6.5 < p_{T}^{J/#psi} < 30.0 && -1.97 < y^{J/#psi} < 1.03) ||");
lt1->DrawLatex(0.20,0.48,"(3.0 < p_{T}^{J/#psi} < 30.0 && ((-2.4 < y^{J/#psi} < -1.97)||(1.03 < y^{J/#psi} < 1.46)))");
*/
lt1->DrawLatex(0.40,0.60,"(6.5 < p_{T}^{J/#psi} < 30.0 && -1.97 < y^{J/#psi} < 1.03) ||");
lt1->DrawLatex(0.40,0.54,"(0.0 < p_{T}^{J/#psi} < 30.0 && -2.4 < y^{J/#psi} < -1.97) ||");
lt1->DrawLatex(0.40,0.48,"(3.0 < p_{T}^{J/#psi} < 30.0 && 1.03 < y^{J/#psi} < 1.93)");
lt1->DrawLatex(0.50,0.42,"-2.4 < y^{J/#psi} < 1.93, -2.4 < #eta^{#mu} < -0.8");
// lt1->DrawLatex(0.50,0.42,"-2.4 < y^{J/#psi} < 1.93, -0.8 < #eta^{#mu} < 0.8");
// lt1->DrawLatex(0.50,0.42,"-2.4 < y^{J/#psi} < 1.93, 0.8 < #eta^{#mu} < 1.93");
lt1->SetTextSize(0.05);
// lt1->DrawLatex(0.50,0.7,"CMS Preliminary");
lt1->DrawLatex(0.50,0.63,"pPb #sqrt{s_{NN}} = 5 TeV");
lt1->SetTextSize(0.04);
/*
c1->SaveAs("Jpsi_MuIdNew2etabin1Rfb_Comp_pPb_MC_pt_test.png");
c1->SaveAs("Jpsi_MuIdNew2etabin1Rfb_Comp_pPb_MC_pt_test.pdf");
*/
c1->SaveAs("Jpsi_MuIdNew2etabin1CS_Comp_pPb_MC_pt_test.png");
c1->SaveAs("Jpsi_MuIdNew2etabin1CS_Comp_pPb_MC_pt_test.pdf");
/*
c1->SaveAs("Jpsi_MuIdNew2etabin1CS_Comp_pPb_MC_pt_for_B_test.png");
c1->SaveAs("Jpsi_MuIdNew2etabin1CS_Comp_pPb_MC_pt_for_B_test.pdf");
*/
}
//(TH1, color, style, pt, eta, rapidity)
void formatTH1F(TH1* a, int b, int c, int d){
a->SetLineWidth(2);
a->SetLineStyle(c);
a->SetMarkerSize(2);
a->SetLineColor(b);
a->SetMarkerColor(b);
a->GetYaxis()->SetTitle("Single #mu Efficiency");
if(d == 1){
a->GetXaxis()->SetTitle("p_{T}^{#mu} (GeV/c)");
}else if(d == 2){
a->GetXaxis()->SetTitle("#eta^{#mu}");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity^{#mu}");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}else if(d == 5){
a->GetXaxis()->SetTitle("Centrality (%)");
}
a->GetXaxis()->CenterTitle(true);
}
void formatTLeg(TLegend* a){
a->SetFillStyle(0);
a->SetFillColor(0);
a->SetBorderSize(0);
a->SetTextSize(0.03);
}
void formatTCanv(TCanvas* a){
a->SetBorderSize(2);
a->SetFrameFillColor(0);
a->cd();
a->SetGrid(1);
a->SetTickx();
a->SetTicky();
}
void formatTGraph(TGraph* a, int b, int c, int d)
{
a->SetMarkerStyle(c);
a->SetMarkerColor(b);
a->SetMarkerSize(1.0);
a->SetLineColor(b);
a->SetLineWidth(1);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.06);
a->GetXaxis()->SetTitleOffset(1.0);
a->GetYaxis()->SetTitle("Efficiency");
//a->GetXaxis()->CenterTitle();
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} (GeV/c)");
}else if(d == 2){
a->GetXaxis()->SetTitle("eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}
a->GetYaxis()->SetRangeUser(0,1);
a->GetXaxis()->SetRangeUser(0,10);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(1.3);
}
TGraphAsymmErrors *calcEff(TH1* h1, TH1* h2)
{
TGraphAsymmErrors *gEfficiency = new TGraphAsymmErrors();
gEfficiency->BayesDivide(h1,h2);
return gEfficiency;
}
TGraphAsymmErrors *getEff(TH1F *h1, TH1F *h2)
{
h1->Sumw2();
h2->Sumw2();
TGraphAsymmErrors *result = calcEff(h1,h2);
return result;
}
void CalEffErr(TGraph *a, double *b){
const int nbins = 100;
double x[nbins], y[nbins];
double sum = 0, errHighSum = 0, errLowSum = 0, sqSumHigh = 0, sqSumLow = 0;
//double b[3] = 0;
int nBins = a->GetN();
for(int i=0;i<a->GetN();i++){
a->GetPoint(i,x[i],y[i]);
//cout<<"Eff x = "<<x[i]<<" y = "<<y[i]<<endl;
double eHigh = a->GetErrorYhigh(i);
double eLow = a->GetErrorYlow(i);
//cout<<"Err high = "<<eHigh<<" low = "<<eLow<<endl;
sum += y[i];
errHighSum += eHigh;
sqSumHigh += eHigh*eHigh;
errLowSum += eLow;
sqSumLow += eLow*eLow;
}
b[0] = sum/nBins;
b[1] = sqrt(sqSumHigh)/nBins;
b[2] = sqrt(sqSumLow)/nBins;
//cout<<"b1 : "<<b[0]<<", b2 : "<<b[1]<<", b3 : "<<b[2]<<endl;
cout<<b[0]<<"^{"<<b[1]<<"}_{"<<b[2]<<"}"<<endl;
//return b[3];
}
<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/Ana/MC/MuTrk/tp_Ana_Trk_RD_Dbl_GEN_matching_for_B.py
import FWCore.ParameterSet.Config as cms
process = cms.Process("TagProbe")
process.load('FWCore.MessageService.MessageLogger_cfi')
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) )
#PDFName = "twoGaussPlusExPoly6"
#PDFName = "twoGaussPlusPoly6"
PDFName = "twoGaussPlusPoly4"
#PDFName = "twoGaussPlusPoly3"
#PDFName = "gaussPlusPoly"
#PDFName = "gaussPlusExp"
process.TagProbeFitTreeAnalyzer = cms.EDAnalyzer("TagProbeFitTreeAnalyzer",
# IO parameters:
InputFileNames = cms.vstring("/afs/cern.ch/work/k/kilee/tutorial/cms538_pPb/src/UserCode/HiTagAndProbe/test/TnP2013/ProdMerge/MC/20140730_B/tnp_pA_MC_Prod_Merge_for_B_GEN_matching_20140730.root"),
InputDirectoryName = cms.string("MuonTrk2"),
InputTreeName = cms.string("fitter_tree"),
OutputFileName = cms.string("tnp_pPb_Ana_MuTrk2_2GpP4_MC_for_B_GEN_matching_test.root"),
NumCPU = cms.uint32(1),
SaveWorkspace = cms.bool(True),
binsForMassPlots = cms.uint32(50),
binnedFit = cms.bool(True),
binsForFit = cms.uint32(50),
# defines all the real variables of the probes available in the input tree and intended for use in the efficiencies
Variables = cms.PSet(
mass = cms.vstring("Tag-Probe Mass", "2", "5", "GeV/c^{2}"),
pt = cms.vstring("Probe p_{T}", "0", "1000", "GeV/c"),
p = cms.vstring("Probe p", "0", "1000", "GeV/c"),
eta = cms.vstring("Probe #eta", "-2.5", "2.5", ""),
abseta = cms.vstring("Probe |#eta|", "0", "2.5", ""),
tag_pt = cms.vstring("Tag p_{T}", "0", "1000", "GeV/c"),
#pair_pt = cms.vstring("Pair p_{T}", "6.5", "30", "GeV/c"),
),
# defines all the discrete variables of the probes available in the input tree and intended for use in the efficiency calculations
Categories = cms.PSet(
#mcTrue = cms.vstring("MC true", "dummy[true=1,false=0]"),
isTrk = cms.vstring("isTrk", "dummy[true=1,false=0]"),
),
# defines all the PDFs that will be available for the efficiency calculations; uses RooFit's "factory" syntax;
# each pdf needs to define "signal", "backgroundPass", "backgroundFail" pdfs, "efficiency[0.9,0,1]" and "signalFractionInPassing[0.9]" are used for initial values
PDFs = cms.PSet(
gaussPlusPoly = cms.vstring(
"Gaussian::signal(mass, mean[3.1,3.0,3.2], sigma[0.200])",
#"Gaussian::signal(mass, mean[3.1,3.0,3.2], sigma[0.15,0.05,0.25])",
"Chebychev::backgroundPass(mass, {cPass[0,-0.5,0.5], cPass2[0,-0.5,0.5], cPass3[0,-0.5,0.5]})",
"Chebychev::backgroundFail(mass, {cFail[0,-0.5,0.5], cFail2[0,-0.5,0.5], cFail3[0,-0.5,0.5]})",
#"Chebychev::backgroundPass(mass, {cPass[0,-0.5,0.5], cPass2[0,-0.5,0.5]})",
#"Chebychev::backgroundFail(mass, {cFail[0,-0.5,0.5], cFail2[0,-0.5,0.5]})",
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
twoGaussPlusPoly3 = cms.vstring(
"Gaussian::signal1(mass, mean[3.1,3.0,3.2], sigma[0.10,0.05,1.00])",
#"Gaussian::signal1(mass, mean[3.1,3.0,3.2], sigma[0.10,0.05,0.30])",
"Gaussian::signal2(mass, mean1[3.7,3.5,3.9], sigma2[0.15,0.05,1.00])",
#"Gaussian::signal2(mass, mean1[3.1,3.0,3.2], sigma2[0.15,0.05,0.50])",
#"Gaussian::signal2(mass, mean, sigma2[0.15,0.05,0.30])",
"SUM::signal(vFrac[0.8,0,1]*signal1, signal2)",
"Chebychev::backgroundPass(mass, {cPass[0,-0.5,0.5], cPass2[0,-1.0,1.0], cPass3[0,-0.5,0.5]})",
"Chebychev::backgroundFail(mass, {cFail[0,-0.5,0.5], cFail2[0,-1.0,1.0], cFail3[0,-0.5,0.5]})",
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
oneGaussPlusPoly6 = cms.vstring(
"Gaussian::signal(mass, mean[3.1,3.0,3.2], sigma[0.10,0.05,0.250])",
#"Gaussian::signal1(mass, mean[3.1,3.0,3.2], sigma[0.10,0.05,0.250])",
#"Gaussian::signal2(mass, mean2[3.15,3.0,3.3], sigma2[0.10,0.05,0.250])",
#"SUM::signal(vfrac[0.5,0.01,1.0]*signal1,signal2)",
"Chebychev::backgroundPass1(mass,{cP1[-0.06,-1.0,1.0],cP2[-0.12,-1.0,1.0],cP3[-0.03,-1.0,1.0],cP4[0.019,-1.0,1.0],cP5[-0.0004,-1.0,1.0],cP6[-0.01,-1.0,1.0]})",
"Exponential::backgroundPass2(mass, lp[0,-0.1,0.1])",
"SUM::backgroundPass(b1frac[0.5,0.01,1.0]*backgroundPass1,backgroundPass2)",
#"Chebychev::backgroundPass(mass,{cP1[0,-1.0,1.0],cP2[0,-1.0,1.0],cP3[0,-1.0,1.0],cP4[0,-1.0,1.0],cP5[0,-1.0,1.0],cP6[0,-1.0,1.0]})",
"Chebychev::backgroundFail1(mass,{cF1[-0.06,-1.0,1.0],cF2[-0.12,-1.0,1.0],cF3[-0.03,-1.0,1.0],cF4[0.019,-1.0,1.0],cF5[-0.0004,-1.0,1.0],cF6[-0.01,-1.0,1.0]})",
"Exponential::backgroundFail2(mass, lf[0,-0.1,0.1])",
"SUM::backgroundFail(b2frac[0.5,0.01,1.0]*backgroundFail1,backgroundFail2)",
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
twoGaussPlusExPoly6 = cms.vstring(
"Gaussian::signal1(mass, mean[3.1,3.0,3.2], sigma[0.10,0.05,0.250])",
"Gaussian::signal2(mass, mean2[3.15,3.0,3.3], sigma2[0.10,0.05,0.250])",
"SUM::signal(vfrac[0.5,0.01,1.0]*signal1,signal2)",
"Chebychev::backgroundPass1(mass,{cP1[-0.06,-1.0,1.0],cP2[-0.12,-1.0,1.0],cP3[-0.03,-1.0,1.0],cP4[0.019,-1.0,1.0],cP5[-0.0004,-1.0,1.0],cP6[-0.01,-1.0,1.0]})",
"Exponential::backgroundPass2(mass, lp[0,-0.1,0.1])",
"SUM::backgroundPass(b1frac[0.5,0.01,1.0]*backgroundPass1,backgroundPass2)",
"Chebychev::backgroundFail1(mass,{cF1[-0.06,-1.0,1.0],cF2[-0.12,-1.0,1.0],cF3[-0.03,-1.0,1.0],cF4[0.019,-1.0,1.0],cF5[-0.0004,-1.0,1.0],cF6[-0.01,-1.0,1.0]})",
"Exponential::backgroundFail2(mass, lf[0,-0.1,0.1])",
"SUM::backgroundFail(b2frac[0.5,0.01,1.0]*backgroundFail1,backgroundFail2)",
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
twoGaussPlusPoly6 = cms.vstring(
"Gaussian::signal1(mass, mean[3.1,3.0,3.2], sigma[0.10,0.05,0.250])",
"Gaussian::signal2(mass, mean2[3.15,3.0,3.3], sigma2[0.10,0.05,0.250])",
"SUM::signal(vfrac[0.5,0.01,1.0]*signal1,signal2)",
# "Chebychev::backgroundPass(mass,{cP1[-0.06,-1.0,1.0],cP2[-0.12,-1.0,1.0],cP3[-0.03,-1.0,1.0],cP4[0.019,-1.0,1.0],cP5[-0.0004,-1.0,1.0],cP6[-0.01,-1.0,1.0]})",
# "Chebychev::backgroundFail(mass,{cF1[-0.06,-1.0,1.0],cF2[-0.12,-1.0,1.0],cF3[-0.03,-1.0,1.0],cF4[0.019,-1.0,1.0],cF5[-0.0004,-1.0,1.0],cF6[-0.01,-1.0,1.0]})",
"Chebychev::backgroundPass(mass,{cP1[-0.48,-1.0,1.0],cP2[-0.03,-1.0,1.0],cP3[-0.07,-1.0,1.0],cP4[0.06,-1.0,1.0],cP5[-0.01,-1.0,1.0],cP6[-0.02,-1.0,1.0]})",
"Chebychev::backgroundFail(mass,{cF1[-0.48,-1.0,1.0],cF2[-0.03,-1.0,1.0],cF3[-0.07,-1.0,1.0],cF4[0.06,-1.0,1.0],cF5[-0.01,-1.0,1.0],cF6[-0.02,-1.0,1.0]})",
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
twoGaussPlusPoly4 = cms.vstring(
"Gaussian::signal1(mass, mean[3.1,3.0,3.2], sigma[0.10,0.05,0.250])",
"Gaussian::signal2(mass, mean2[3.15,3.0,3.3], sigma2[0.10,0.05,0.250])",
"SUM::signal(vfrac[0.5,0.01,1.0]*signal1,signal2)",
"Chebychev::backgroundPass(mass,{cP1[-0.5,-1.0,1.0],cP2[-0.1,-1.0,1.0],cP3[0.2,-1.0,1.0],cP4[-0.05,-1.0,1.0]})",
"Chebychev::backgroundFail(mass,{cF1[-0.5,-1.0,1.0],cF2[-0.1,-1.0,1.0],cF3[0.2,-1.0,1.0],cF4[-0.05,-1.0,1.0]})",
"efficiency[0.9,0,1]",
"signalFractionInPassing[0.9]"
),
),
# defines a set of efficiency calculations, what PDF to use for fitting and how to bin the data;
# there will be a separate output directory for each calculation that includes a simultaneous fit, side band subtraction and counting.
Efficiencies = cms.PSet(
#the name of the parameter set becomes the name of the directory
isTrk_pt = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("isTrk","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
pt = cms.vdouble(0.0, 1.5, 3.0, 4.5, 6.0, 9.0, 20, 30),
),
BinToPDFmap = cms.vstring(PDFName)
),
isTrk_eta = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("isTrk","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
eta = cms.vdouble(-2.4, -1.5, -0.5, 0.5, 1.5, 2.4),
),
BinToPDFmap = cms.vstring(PDFName)
),
isTrk_1bin_pt_eta = cms.PSet(
EfficiencyCategoryAndState = cms.vstring("isTrk","true"),
UnbinnedVariables = cms.vstring("mass"),
BinnedVariables = cms.PSet(
pt = cms.vdouble(0.0,30),
eta = cms.vdouble(-2.4,2.4),
),
BinToPDFmap = cms.vstring(PDFName)
),
)
)
process.fitness = cms.Path(
process.TagProbeFitTreeAnalyzer
)
<file_sep>/UserCode/DonghoMoon/HiTagAndProbe/test/TnP2013/Efficiency/Comp/MuID/CompMuId_GEN_matching.C
//////////////////////////////////////////////////////////////////////////////////
//This code compare RD and MC("and" or "or" pp). //
// //
// 2013-12-21 //
// by <NAME> //
//////////////////////////////////////////////////////////////////////////////////
#include <TROOT.h>
#include <TFile.h>
#include <TNtuple.h>
#include <TCanvas.h>
#include <TProfile.h>
#include <TGraph.h>
#include <TH1D.h>
#include <TH2D.h>
#include <TGraphAsymmErrors.h>
#include <TLegend.h>
#include <TLatex.h>
#include <TMath.h>
#include <TSystem.h>
#include <TStyle.h>
#include <Riostream.h>
#include <TString.h>
#include <TInterpreter.h>
#include <TBrowser.h>
void CalEffErr(TGraph *a, double *b);
TGraphAsymmErrors *getEff(TH1F *h1, TH1F *h2);
TGraphAsymmErrors *calcEff(TH1* h1, TH1* h2);
void formatTGraph(TGraph* a, int b, int c, int d);
void formatTCanv(TCanvas* a);
void formatTLeg(TLegend* a);
void formatTH1F(TH1* a, int b, int c, int d);
void CompMuId()
{
gROOT->Macro("rootlogon.C");
gStyle->SetOptStat(0);
gStyle->SetPadBottomMargin(0.13);
gStyle->SetPadLeftMargin(0.13);
gStyle->SetTitleYOffset(1.0);
/*
TFile *f1 = new TFile("Jpsi_pPb_RD_MuIdNew2Rfb_CBpPoly_1st_Run_Eff_test.root", "READ");
TFile *f2 = new TFile("Jpsi_pPb_MC_MuIdNew2Rfb_CBpPoly_1st_Run_Eff_test.root", "READ");
*/
TFile *f1 = new TFile("Jpsi_pPb_RD_MuIdNew2CS_CBpPoly_1st_Run_Eff_test.root", "READ");
TFile *f2 = new TFile("Jpsi_pPb_MC_MuIdNew2CS_CBpPoly_1st_Run_Eff_test.root", "READ");
/*
TFile *f1 = new TFile("Jpsi_pPb_RD_MuIdNew2CS_CBpPoly_1st_Run_Eff_for_B_test.root", "READ");
TFile *f2 = new TFile("Jpsi_pPb_MC_MuIdNew2CS_CBpPoly_1st_Run_Eff_for_B_test.root", "READ");
*/
TGraph *gMuId1Eta = (TGraph*) f1->Get("MuId_eta_All");
TGraph *gMuId1IntEta = (TGraph*) f1->Get("MuId_1bin_pt_eta_All");
TGraph *gMuId1Pt = (TGraph*) f1->Get("MuId_pt_All");
TGraph *gMuId2Eta = (TGraph*) f2->Get("MuId_eta_All");
TGraph *gMuId2IntEta = (TGraph*) f2->Get("MuId_1bin_pt_eta_All");
TGraph *gMuId2Pt = (TGraph*) f2->Get("MuId_pt_All");
TGraph *gMuId1CNT = (TGraph*) f1->Get("pCNT");
TGraph *gMuId1MBCNT = (TGraph*) f1->Get("pMBCNT");
TGraph *gMuId2CNT = (TGraph*) f2->Get("pCNT");
TGraph *gMuId2MBCNT = (TGraph*) f2->Get("pMBCNT");
TCanvas *c1 = new TCanvas("c1","",700,600);
TH1F *hPad1 = new TH1F("hPad1","",15,-2.4,1.93);
TH1F *hPad2 = new TH1F("hPad2","",12,0,30);
TH1F *hPad3 = new TH1F("hPad3","",10,0,100);
hPad1->GetYaxis()->CenterTitle();
hPad2->GetYaxis()->CenterTitle();
hPad3->GetYaxis()->CenterTitle();
double MuId1Eta[4];
CalEffErr(gMuId1IntEta, MuId1Eta);
double MuId2Eta[4];
CalEffErr(gMuId2IntEta, MuId2Eta);
TLatex *lt1 = new TLatex();
lt1->SetNDC();
formatTH1F(hPad1,1,1,2);
formatTH1F(hPad2,1,1,1);
formatTH1F(hPad3,1,1,5);
formatTGraph(gMuId1Eta,859,21,2);
gMuId1Eta->SetMarkerSize(1.2);
formatTGraph(gMuId2Eta,809,20,2);
gMuId2Eta->SetMarkerSize(1.4);
hPad1->SetMaximum(1.05);
hPad1->SetMinimum(0.50);
hPad1->GetYaxis()->SetTitleOffset(1.2);
hPad2->GetYaxis()->SetTitleOffset(1.2);
hPad3->GetYaxis()->SetTitleOffset(1.2);
hPad1->Draw();
gMuId1Eta->Draw("pz same");
gMuId2Eta->Draw("pz same");
char legs[512];
TLegend *leg1 = new TLegend(0.29,0.17,0.63,0.40);
leg1->SetFillStyle(0);
leg1->SetFillColor(0);
leg1->SetBorderSize(0);
leg1->SetTextSize(0.040);
leg1->SetHeader("Muon ID Efficiency");
sprintf(legs,"MC (PYTHIA+EvtGen): %.3f^{ + %.4f}_{ - %.4f}", MuId2Eta[0], MuId2Eta[1], MuId2Eta[2]);
leg1->AddEntry(gMuId2Eta,legs,"pl");
sprintf(legs,"Data(pPb): %.3f^{ + %.4f}_{ - %.4f}", MuId1Eta[0], MuId1Eta[1], MuId1Eta[2]);
leg1->AddEntry(gMuId1Eta,legs,"pl");
leg1->Draw();
lt1->SetTextSize(0.035);
/*
lt1->DrawLatex(0.50,0.48,"6.5 < p_{T}^{J/#psi} < 30.0, 1.47 < |y| < 2.4");
lt1->DrawLatex(0.50,0.42,"-2.4 < y^{J/#psi} < 1.47, -2.4 < #eta^{#mu} < 1.47");
*/
/*
lt1->DrawLatex(0.20,0.54,"(6.5 < p_{T}^{J/#psi} < 30.0 && -1.97 < y^{J/#psi} < 1.03) ||");
lt1->DrawLatex(0.20,0.48,"(3.0 < p_{T}^{J/#psi} < 30.0 && ((-2.4 < y^{J/#psi} < -1.97)||(1.03 < y^{J/#psi} < 1.46)))");
*/
lt1->DrawLatex(0.40,0.60,"(6.5 < p_{T}^{J/#psi} < 30.0 && -1.97 < y^{J/#psi} < 1.03) ||");
lt1->DrawLatex(0.40,0.54,"(0.0 < p_{T}^{J/#psi} < 30.0 && -2.4 < y^{J/#psi} < -1.97) ||");
lt1->DrawLatex(0.40,0.48,"(3.0 < p_{T}^{J/#psi} < 30.0 && 1.03 < y^{J/#psi} < 1.93)");
lt1->SetTextSize(0.05);
// lt1->DrawLatex(0.50,0.7,"CMS Preliminary");
lt1->DrawLatex(0.50,0.63,"pPb #sqrt{s_{NN}} = 5 TeV");
lt1->SetTextSize(0.04);
/*
c1->SaveAs("Jpsi_MuIdNew2Rfb_Comp_pPb_MC_eta_test.png");
c1->SaveAs("Jpsi_MuIdNew2Rfb_Comp_pPb_MC_eta_test.pdf");
*/
c1->SaveAs("Jpsi_MuIdNew2CS_Comp_pPb_MC_eta_test.png");
c1->SaveAs("Jpsi_MuIdNew2CS_Comp_pPb_MC_eta_test.pdf");
/*
c1->SaveAs("Jpsi_MuIdNew2CS_Comp_pPb_MC_eta_for_B_test.png");
c1->SaveAs("Jpsi_MuIdNew2CS_Comp_pPb_MC_eta_for_B_test.pdf");
*/
formatTGraph(gMuId1Pt,859,21,1);
gMuId1Pt->SetMarkerSize(1.2);
formatTGraph(gMuId2Pt,809,20,1);
gMuId2Pt->SetMarkerSize(1.4);
hPad2->SetMinimum(0.40);
hPad2->SetMaximum(1.05);
hPad2->Draw();
gMuId1Pt->Draw("pz same");
gMuId2Pt->Draw("pz same");
TLegend *leg2 = new TLegend(0.29,0.17,0.63,0.40,NULL,"brNDC");
leg2->SetFillStyle(0);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
leg2->SetTextSize(0.040);
leg2->SetHeader("Muon ID Efficiency");
sprintf(legs,"MC (PYTHIA+EvtGen): %.3f^{ + %.4f}_{ - %.4f}", MuId2Eta[0], MuId2Eta[1], MuId2Eta[2]);
leg2->AddEntry(gMuId2Pt,legs,"pl");
sprintf(legs,"Data(pPb): %.3f^{ + %.4f}_{ - %.4f}", MuId1Eta[0], MuId1Eta[1], MuId1Eta[2]);
leg2->AddEntry(gMuId1Pt,legs,"pl");
leg2->Draw();
lt1->SetTextSize(0.035);
/*
lt1->DrawLatex(0.50,0.48,"6.5 < p_{T}^{J/#psi} < 30.0, 1.47 < |y| < 2.4");
lt1->DrawLatex(0.50,0.42,"-2.4 < y^{J/#psi} < 1.47, -2.4 < #eta^{#mu} < 1.47");
*/
/*
lt1->DrawLatex(0.20,0.54,"(6.5 < p_{T}^{J/#psi} < 30.0 && -1.97 < y^{J/#psi} < 1.03) ||");
lt1->DrawLatex(0.20,0.48,"(3.0 < p_{T}^{J/#psi} < 30.0 && ((-2.4 < y^{J/#psi} < -1.97)||(1.03 < y^{J/#psi} < 1.46)))");
*/
lt1->DrawLatex(0.40,0.60,"(6.5 < p_{T}^{J/#psi} < 30.0 && -1.97 < y^{J/#psi} < 1.03) ||");
lt1->DrawLatex(0.40,0.54,"(0.0 < p_{T}^{J/#psi} < 30.0 && -2.4 < y^{J/#psi} < -1.97) ||");
lt1->DrawLatex(0.40,0.48,"(3.0 < p_{T}^{J/#psi} < 30.0 && 1.03 < y^{J/#psi} < 1.93)");
lt1->SetTextSize(0.05);
// lt1->DrawLatex(0.50,0.7,"CMS Preliminary");
lt1->DrawLatex(0.50,0.63,"pPb #sqrt{s_{NN}} = 5 TeV");
lt1->SetTextSize(0.04);
/*
c1->SaveAs("Jpsi_MuIdNew2Rfb_Comp_pPb_MC_pt_test.png");
c1->SaveAs("Jpsi_MuIdNew2Rfb_Comp_pPb_MC_pt_test.pdf");
*/
c1->SaveAs("Jpsi_MuIdNew2CS_Comp_pPb_MC_pt_test.png");
c1->SaveAs("Jpsi_MuIdNew2CS_Comp_pPb_MC_pt_test.pdf");
/*
c1->SaveAs("Jpsi_MuIdNew2CS_Comp_pPb_MC_pt_for_B_test.png");
c1->SaveAs("Jpsi_MuIdNew2CS_Comp_pPb_MC_pt_for_B_test.pdf");
*/
formatTGraph(gMuId1CNT,859,21,1);
gMuId1CNT->SetMarkerSize(1.4);
formatTGraph(gMuId1MBCNT,859,25,1);
gMuId1MBCNT->SetMarkerSize(1.4);
formatTGraph(gMuId2CNT,809,20,1);
gMuId2CNT->SetMarkerSize(1.4);
formatTGraph(gMuId2MBCNT,809,24,1);
gMuId2MBCNT->SetMarkerSize(1.4);
hPad3->SetMinimum(0.50);
hPad3->SetMaximum(1.05);
hPad3->GetXaxis()->SetTitle("Centrality Bin");
hPad3->Draw();
gMuId1CNT->Draw("pz same");
gMuId1MBCNT->Draw("pz same");
gMuId2MBCNT->Draw("pz same");
TLegend *leg3 = new TLegend(0.29,0.17,0.63,0.40);
leg3->SetFillStyle(0);
leg3->SetFillColor(0);
leg3->SetBorderSize(0);
leg3->SetTextSize(0.040);
leg3->SetHeader("Muon ID Efficiency");
sprintf(legs,"MC (PYTHIA+EvtGen): %.3f^{ + %.4f}_{ - %.4f}", MuId2Eta[0], MuId2Eta[1], MuId2Eta[2]);
leg3->AddEntry(gMuId2MBCNT,legs,"pl");
sprintf(legs,"Data(pPb): %.3f^{ + %.4f}_{ - %.4f}", MuId1Eta[0], MuId1Eta[1], MuId1Eta[2]);
leg3->AddEntry(gMuId1MBCNT,legs,"pl");
leg3->Draw();
lt1->SetTextSize(0.035);
/*
lt1->DrawLatex(0.50,0.48,"6.5 < p_{T}^{J/#psi} < 30.0, 1.47 < |y| < 2.4");
lt1->DrawLatex(0.50,0.42,"-2.4 < y^{J/#psi} < 1.47, -2.4 < #eta^{#mu} < 1.47");
*/
/*
lt1->DrawLatex(0.20,0.54,"(6.5 < p_{T}^{J/#psi} < 30.0 && -1.97 < y^{J/#psi} < 1.03) ||");
lt1->DrawLatex(0.20,0.48,"(3.0 < p_{T}^{J/#psi} < 30.0 && ((-2.4 < y^{J/#psi} < -1.97)||(1.03 < y^{J/#psi} < 1.46)))");
*/
lt1->DrawLatex(0.40,0.60,"(6.5 < p_{T}^{J/#psi} < 30.0 && -1.97 < y^{J/#psi} < 1.03) ||");
lt1->DrawLatex(0.40,0.54,"(0.0 < p_{T}^{J/#psi} < 30.0 && -2.4 < y^{J/#psi} < -1.97) ||");
lt1->DrawLatex(0.40,0.48,"(3.0 < p_{T}^{J/#psi} < 30.0 && 1.03 < y^{J/#psi} < 1.93)");
lt1->SetTextSize(0.05);
// lt1->DrawLatex(0.50,0.7,"CMS Preliminary");
lt1->DrawLatex(0.50,0.63,"pPb #sqrt{s_{NN}} = 5 TeV");
lt1->SetTextSize(0.04);
/*
c1->SaveAs("Jpsi_MuIdNew2Rfb_Comp_pPb_MC_CNT_test.png");
c1->SaveAs("Jpsi_MuIdNew2Rfb_Comp_pPb_MC_CNT_test.pdf");
*/
/*
c1->SaveAs("Jpsi_MuIdNew2CS_Comp_pPb_MC_CNT_test.png");
c1->SaveAs("Jpsi_MuIdNew2CS_Comp_pPb_MC_CNT_test.pdf");
*/
}
//(TH1, color, style, pt, eta, rapidity)
void formatTH1F(TH1* a, int b, int c, int d){
a->SetLineWidth(2);
a->SetLineStyle(c);
a->SetMarkerSize(2);
a->SetLineColor(b);
a->SetMarkerColor(b);
a->GetYaxis()->SetTitle("Single #mu Efficiency");
if(d == 1){
a->GetXaxis()->SetTitle("p_{T}^{#mu} (GeV/c)");
}else if(d == 2){
a->GetXaxis()->SetTitle("#eta^{#mu}");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity^{#mu}");
}else if(d == 4){
a->GetXaxis()->SetTitle("Centrality");
}else if(d == 5){
a->GetXaxis()->SetTitle("Centrality (%)");
}
a->GetXaxis()->CenterTitle(true);
}
void formatTLeg(TLegend* a){
a->SetFillStyle(0);
a->SetFillColor(0);
a->SetBorderSize(0);
a->SetTextSize(0.03);
}
void formatTCanv(TCanvas* a){
a->SetBorderSize(2);
a->SetFrameFillColor(0);
a->cd();
a->SetGrid(1);
a->SetTickx();
a->SetTicky();
}
void formatTGraph(TGraph* a, int b, int c, int d)
{
a->SetMarkerStyle(c);
a->SetMarkerColor(b);
a->SetMarkerSize(1.0);
a->SetLineColor(b);
a->SetLineWidth(1);
a->GetXaxis()->SetLabelSize(0.05);
a->GetXaxis()->SetTitleSize(0.06);
a->GetXaxis()->SetTitleOffset(1.0);
a->GetYaxis()->SetTitle("Efficiency");
//a->GetXaxis()->CenterTitle();
if(d == 1){
a->GetXaxis()->SetTitle("p_{T} (GeV/c)");
}else if(d == 2){
a->GetXaxis()->SetTitle("eta");
}else if(d == 3){
a->GetXaxis()->SetTitle("rapidity");
}
a->GetYaxis()->SetRangeUser(0,1);
a->GetXaxis()->SetRangeUser(0,10);
a->GetYaxis()->SetLabelSize(0.05);
a->GetYaxis()->SetTitleSize(0.05);
a->GetYaxis()->SetTitleOffset(1.3);
}
TGraphAsymmErrors *calcEff(TH1* h1, TH1* h2)
{
TGraphAsymmErrors *gEfficiency = new TGraphAsymmErrors();
gEfficiency->BayesDivide(h1,h2);
return gEfficiency;
}
TGraphAsymmErrors *getEff(TH1F *h1, TH1F *h2)
{
h1->Sumw2();
h2->Sumw2();
TGraphAsymmErrors *result = calcEff(h1,h2);
return result;
}
void CalEffErr(TGraph *a, double *b){
const int nbins = 100;
double x[nbins], y[nbins];
double sum = 0, errHighSum = 0, errLowSum = 0, sqSumHigh = 0, sqSumLow = 0;
//double b[3] = 0;
int nBins = a->GetN();
for(int i=0;i<a->GetN();i++){
a->GetPoint(i,x[i],y[i]);
//cout<<"Eff x = "<<x[i]<<" y = "<<y[i]<<endl;
double eHigh = a->GetErrorYhigh(i);
double eLow = a->GetErrorYlow(i);
//cout<<"Err high = "<<eHigh<<" low = "<<eLow<<endl;
sum += y[i];
errHighSum += eHigh;
sqSumHigh += eHigh*eHigh;
errLowSum += eLow;
sqSumLow += eLow*eLow;
}
b[0] = sum/nBins;
b[1] = sqrt(sqSumHigh)/nBins;
b[2] = sqrt(sqSumLow)/nBins;
//cout<<"b1 : "<<b[0]<<", b2 : "<<b[1]<<", b3 : "<<b[2]<<endl;
cout<<b[0]<<"^{"<<b[1]<<"}_{"<<b[2]<<"}"<<endl;
//return b[3];
}
|
95ffee70e900385e875ac5e387fe1d1ca70fd26b
|
[
"C",
"Python"
] | 12
|
C
|
KiSooLee/TnP_B
|
2503678e3f9d983edabbc97ae46639584faa177a
|
814382cd547c1827690f957716b053187e4f44e0
|
refs/heads/master
|
<repo_name>aqianglala/MusicPlayer<file_sep>/app/src/main/java/com/example/admin/musicplayer/bean/AudioItem.java
package com.example.admin.musicplayer.bean;
import android.database.Cursor;
import java.io.Serializable;
public class AudioItem implements Serializable {
// Media._ID, Media.TITLE, Media.ARTIST, Media.DATA
private String title;
private String artist;
private String path;
private String songId;
public static AudioItem fromCursor(Cursor cursor) {
AudioItem item = new AudioItem();
item.setTitle(cursor.getString(1));
item.setArtist(cursor.getString(2));
item.setPath(cursor.getString(3));
return item;
}
public static AudioItem fromBean(HotBean.ShowapiResBodyEntity.PagebeanEntity
.SonglistEntity data) {
AudioItem item = new AudioItem();
item.setTitle(data.getSongname());
item.setArtist(data.getSingername());
item.setPath(data.getUrl());
item.setSongId(data.getSongid()+"");
return item;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getSongId() {
return songId;
}
public void setSongId(String songId) {
this.songId = songId;
}
}
<file_sep>/app/src/main/java/com/example/admin/musicplayer/interfaces/Keys.java
package com.example.admin.musicplayer.interfaces;
public interface Keys {
String ITEM_LIST = "itemList";
String CURRENT_POSITION = "currentPosition";
String CURRENT_PLAY_MODE = "currentPlayMode";
String WHAT = "what";
String Url_Hot="http://route.showapi.com/213-4";
String Url_Search_Lyric="http://route.showapi.com/213-2";
String Url_Search_Song="http://route.showapi.com/213-1";
/**
* showapi的信息
*/
String showapi_appid="15869";
String showapi_sign="5ea357d154694ad1a58d0a8287dd6f6c";
/**
* 每次访问网络所要提交的必须字段名
*/
String SHOWAPI_APPID="showapi_appid";
String SHOWAPI_SIGN="showapi_sign";
String SHOWAPI_TIMESTAMP="showapi_timestamp";
}
|
abf6814ca9003dd094ff24093dd3d6de271eef77
|
[
"Java"
] | 2
|
Java
|
aqianglala/MusicPlayer
|
ff8443119621c12c8342561fe8ab020194d9d5f4
|
2d2f3ff01ed6f21309afdbac5e0830fa15c4c17c
|
refs/heads/master
|
<repo_name>kwanpham/OrderFoodDemo2<file_sep>/app/src/main/java/com/example/mypc/orderfooddemo2/SuaBanAnActivity.java
package com.example.mypc.orderfooddemo2;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.mypc.orderfooddemo2.DAO.BanAnDAO;
import com.example.mypc.orderfooddemo2.FragmentApp.HienThiBanAnFragment;
/**
* Created by MyPC on 24/02/2018.
*/
public class SuaBanAnActivity extends AppCompatActivity {
Button btnDongYSua;
EditText edSuaTenBan;
BanAnDAO banAnDAO;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_suabanan);
btnDongYSua = (Button) findViewById(R.id.btnSuaBanAn);
edSuaTenBan = (EditText) findViewById(R.id.edSuaBanAn);
banAnDAO = new BanAnDAO(this);
final int maban = getIntent().getIntExtra("maban", 0);
btnDongYSua.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tenban = edSuaTenBan.getText().toString().trim();
if (tenban.equals("")) {
Toast.makeText(SuaBanAnActivity.this, getResources().getString(R.string.vuilongnhapdulieu), Toast.LENGTH_SHORT).show();
} else {
boolean kiemtra = banAnDAO.CapNhapLaiTenBan(maban, tenban);
Intent intent = new Intent();
intent.putExtra("kiemtra", kiemtra);
setResult(HienThiBanAnFragment.RESQUEST_CODE_SUA, intent);
finish();
}
}
});
}
}
<file_sep>/app/src/main/java/com/example/mypc/orderfooddemo2/ThanhToanActivity.java
package com.example.mypc.orderfooddemo2;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mypc.orderfooddemo2.CustomAdapter.AdapterHienThiThanhToan;
import com.example.mypc.orderfooddemo2.DAO.BanAnDAO;
import com.example.mypc.orderfooddemo2.DAO.GoiMonDAO;
import com.example.mypc.orderfooddemo2.DTO.ThanhToanDTO;
import com.example.mypc.orderfooddemo2.FragmentApp.HienThiBanAnFragment;
import com.example.mypc.orderfooddemo2.FragmentApp.HienThiDanhSachMonAnFragment;
import com.example.mypc.orderfooddemo2.FragmentApp.HienThiThucDonFragment;
import java.util.List;
/**
* Created by MyPC on 21/02/2018.
*/
public class ThanhToanActivity extends AppCompatActivity implements View.OnClickListener {
GridView gridView;
Button btnThanhToan , btnThoat;
TextView tvTongTien;
GoiMonDAO goiMonDAO;
BanAnDAO banAnDAO;
AdapterHienThiThanhToan adapterHienThiThanhToan;
List<ThanhToanDTO> thanhToanDTOList ;
private long tongtien = 0;
private int maban = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_thanhtoan);
gridView = (GridView) findViewById(R.id.gvThanhToan);
btnThanhToan = (Button) findViewById(R.id.btnThanhToan);
btnThoat = (Button) findViewById(R.id.btnThoatThanhToan);
tvTongTien = (TextView) findViewById(R.id.tvTongTien);
goiMonDAO = new GoiMonDAO(this);
banAnDAO = new BanAnDAO(this);
maban = getIntent().getIntExtra("maban" , 0); // gán mặc đinh mã ban = 0
if(maban !=0){
hienThiThanhToan();
for (int i = 0 ; i < thanhToanDTOList.size() ; i++){
int soluong = thanhToanDTOList.get(i).getSoLuong();
int giatien = thanhToanDTOList.get(i).getGiaTien();
tongtien += (soluong*giatien);
}
tvTongTien.setText(getResources().getString(R.string.tongcong) + " " + tongtien);
btnThanhToan.setOnClickListener(this);
btnThoat.setOnClickListener(this);
}
}
private void hienThiThanhToan(){
int magoimon = (int) goiMonDAO.LayMaGoiMonTheoMaBan(maban, "false");
thanhToanDTOList = goiMonDAO.LayDanhSachMonAnTheoMaGoiMon(magoimon);
adapterHienThiThanhToan = new AdapterHienThiThanhToan(this , thanhToanDTOList);
gridView.setAdapter(adapterHienThiThanhToan);
adapterHienThiThanhToan.notifyDataSetChanged();
}
@Override
public void onClick(View v) {
switch ( v.getId() ){
case R.id.btnThanhToan:
boolean kiemTraBanAn = banAnDAO.CapNhapLaiTinhTrangBan(maban , "false");
boolean kiemTraGoiMon = goiMonDAO.CapNhatTrangThaiGoiMonTheoMaBan(maban , "true");
if(kiemTraBanAn && kiemTraGoiMon){
Intent trangChuIntent = new Intent(this, TrangchuActivity.class);
startActivity(trangChuIntent);
finish();
Toast.makeText(this, "Thanh Toán Thành Công", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Thanh Toán Lỗi !", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnThoatThanhToan:
finish();
break;
}
}
}
<file_sep>/app/src/main/java/com/example/mypc/orderfooddemo2/ThemBanAnActivity.java
package com.example.mypc.orderfooddemo2;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.mypc.orderfooddemo2.DAO.BanAnDAO;
public class ThemBanAnActivity extends AppCompatActivity implements View.OnClickListener{
EditText edThemBanAn;
Button btnThemBanAn;
BanAnDAO banAnDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_thembanan);
edThemBanAn = (EditText) findViewById(R.id.edThemBanAn);
btnThemBanAn = (Button) findViewById(R.id.btnThemBanAn);
banAnDAO = new BanAnDAO(this);
btnThemBanAn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnThemBanAn:
String sTenBanAn = edThemBanAn.getText().toString().trim();
if(!sTenBanAn.equals("")){
boolean kiemtra = banAnDAO.ThemBanAn(sTenBanAn);
Intent intent = new Intent();
intent.putExtra("ketquathem", kiemtra);
setResult(RESULT_OK , intent);
finish();
}
}
}
}
|
ce36191bcc890957450f9bd349ea137f13921951
|
[
"Java"
] | 3
|
Java
|
kwanpham/OrderFoodDemo2
|
f7b2b857513561729e93c5096dab3fa77e1907dd
|
9abe7d616da7e6402c80b067857509ab5c6f44d2
|
refs/heads/master
|
<repo_name>serinline/test-app<file_sep>/src/main/java/com/example/calculator/models/exceptions/InputError.java
package com.example.calculator.models.exceptions;
public class InputError extends RuntimeException{
private String exceptionMsg;
public InputError(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
public String getExceptionMsg(){
return this.exceptionMsg;
}
public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
}<file_sep>/src/main/java/com/example/calculator/service/ShuntingYard.java
package com.example.calculator.service;
import org.springframework.stereotype.Component;
@Component
public class ShuntingYard {
public ShuntingYard(){}
private enum Precedence {
LPAREN(0),
RPAREN(1),
PLUS(2),
MINUS(3),
DIV(4),
MUL(5),
EOS(7),
OPERAND(8);
private int index;
Precedence(int index) {
this.index = index;
}
public int getIndex(){
return index;
}
}
private static final int[] stackPrecedence = {0, 19, 12, 12, 13, 13, 13, 0};
private static final int[] characterPrecedence = {20, 19, 12, 12, 13, 13, 0};
private static final char[] operators = {'(', ')', '+', '-', '/', '*', ' '};
private Precedence[] stack;
private int top;
private Precedence pop() {
return stack[top--];
}
private void push(Precedence ele) {
stack[++top] = ele;
}
private Precedence getToken(char symbol) {
switch (symbol) {
case '(' :
return Precedence.LPAREN;
case ')' :
return Precedence.RPAREN;
case '+' :
return Precedence.PLUS;
case '-' :
return Precedence.MINUS;
case '/' :
return Precedence.DIV;
case '*' :
return Precedence.MUL;
case ' ' :
return Precedence.EOS;
default :
return Precedence.OPERAND;
}
}
public String postfix(String infix) {
StringBuilder postfix = new StringBuilder();
top = 0;
stack = new Precedence[infix.length()];
stack[0] = Precedence.EOS;
Precedence token;
for (int i = 0; i < infix.length(); i++) {
token = getToken(infix.charAt(i));
if (token == Precedence.OPERAND)
postfix.append(infix.charAt(i));
else if (token == Precedence.RPAREN)
{
while (stack[top] != Precedence.LPAREN)
postfix.append(operators[pop().getIndex()]);
pop();
}
else {
while (stackPrecedence[stack[top].getIndex()] >= characterPrecedence[token.getIndex()])
postfix.append(operators[pop().getIndex()]);
push(token);
}
}
while ((token = pop()) != Precedence.EOS)
postfix.append(operators[token.getIndex()]);
return postfix.toString();
}
}
<file_sep>/src/main/java/com/example/calculator/service/ParallelCalculation.java
package com.example.calculator.service;
import com.example.calculator.models.Expression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;
@Component
public class ParallelCalculation extends RecursiveTask <HashMap<Integer, Double>> {
@Autowired
private CalculatorService calculatorService;
@Autowired
private ShuntingYard shuntingYard;
private ArrayList<Character> expressionList;
private HashMap<Integer, Double> resultSet;
private int subtaskIndex;
public ParallelCalculation(){}
public ParallelCalculation(Expression expression){
this.expressionList = getPolishNotationOfExpression(expression);
this.resultSet = new HashMap<>();
}
public ParallelCalculation(ArrayList<Character> expression){
this.expressionList = expression;
this.resultSet = new HashMap<>();
}
private ParallelCalculation(ArrayList<Character> expression, int index){
this.expressionList = expression;
this.resultSet = new HashMap<>();
this.subtaskIndex = index;
}
@Override
protected HashMap<Integer, Double> compute() {
if (expressionList.size() > 3) {
List<Integer> indexes = getIndexOfSubArray(expressionList);
List<ArrayList<Character>> subTasks = createSubtaskHelper(expressionList);
Collection<ParallelCalculation> tasks = createSubtask(subTasks, indexes);
for (ParallelCalculation p : tasks) {
p.fork();
resultSet.putAll(p.join());
}
return resultSet;
}
else {
resultSet.put(this.subtaskIndex, calculateHelper(this.expressionList));
return resultSet;
}
}
private Collection<ParallelCalculation> createSubtask(List<ArrayList<Character>> list, List<Integer> indexes) {
List<ParallelCalculation> dividedTasks = new ArrayList<>();
for (ArrayList<Character> l : list){
dividedTasks.add(new ParallelCalculation(l, indexes.get(list.indexOf(l))));
}
return dividedTasks;
}
private Double calculateHelper(ArrayList<Character> expression) {
List<Double> values = Arrays.asList(Double.parseDouble(String.valueOf(expression.get(0))),
Double.parseDouble(String.valueOf(expression.get(1))));
return calculatorService.calculate(values, expression.get(2));
}
private List<ArrayList<Character>> createSubtaskHelper(List<Character> expression){
List<ArrayList<Character>> tasks = new ArrayList<>();
for (int i = 2; i < expression.size(); ++i){
if (Character.isDigit(expression.get(i-2)) && Character.isDigit(expression.get(i-1)) && !Character.isDigit(expression.get(i))){
ArrayList<Character> subTask = new ArrayList<>();
subTask.add(expression.get(i-2));
subTask.add(expression.get(i-1));
subTask.add(expression.get(i));
tasks.add(subTask);
}
}
return tasks;
}
private List<Integer> getIndexOfSubArray(List<Character> expression) {
List<Integer> indexes = new ArrayList<>();
for (int i = 2; i < expression.size(); ++i) {
if (Character.isDigit(expression.get(i - 2)) && Character.isDigit(expression.get(i - 1)) && !Character.isDigit(expression.get(i))) {
indexes.add(i-2);
}
}
return indexes;
}
private int findList(List<Character> longExpression, ArrayList<Character> shortExpression) {
return Collections.indexOfSubList(Arrays.asList(longExpression), Arrays.asList(shortExpression));
}
private ArrayList<Character> generateNewExpression(ArrayList<Character> expression, Map<Integer, Double> valuesToAdd){
ArrayList<Character> newExpression = expression;
valuesToAdd = sortArray(valuesToAdd);
for (Map.Entry<Integer, Double> entry : valuesToAdd.entrySet()){
double value = entry.getValue();
newExpression.add(entry.getKey(), (char) value);
newExpression.remove(entry.getKey()+1);
newExpression.remove(entry.getKey()+2);
newExpression.remove(entry.getKey()+3);
}
return newExpression;
}
private ArrayList<Character> getPolishNotationOfExpression(Expression expression){
return (ArrayList<Character>) shuntingYard.postfix(expression.getExpression())
.chars()
.mapToObj(e -> (char) e)
.collect(Collectors.toList());
}
private HashMap<Integer, Double> sortArray(Map<Integer, Double> map){
return map.entrySet()
.stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
.collect( Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e2,
LinkedHashMap::new));
}
public char getResult(Expression expression){
ArrayList<Character> expList = getPolishNotationOfExpression(expression);
if (expression.getExpression().length() == 1){
return expression.getExpression().toCharArray()[0];
}
else {
ForkJoinPool pool = new ForkJoinPool();
ParallelCalculation task = new ParallelCalculation(expression);
Map<Integer, Double> results = pool
.invoke(task);
expList = generateNewExpression(expList, results);
}
return expList.get(0);
}
}
|
62200c39e0b1cebb33efd7ef9b5dabe70d6b8734
|
[
"Java"
] | 3
|
Java
|
serinline/test-app
|
b5f165ce88ca42a7cba63afc365727b4b83505b7
|
7ecfa15fa18bbe2d9b4cd8859b9d2ef79959d5cd
|
refs/heads/master
|
<file_sep>import React from "react";
import ecomweb from "../../image/ecommerce.png";
import covidTrack from "../../image/covidtracker.jpg";
import chat from "../../image/Chat.jpg";
import mobileecom from "../../image/mobileecom.jpg";
const Projects = () => {
return (
<div className='bg-gray-100'>
<div className='container p-2 mt-20' id='project'>
<h1 className='text-4xl font-bold mt-10'>Personal Projects</h1>
{/* Project One */}
<div className='my-20 p-2 grid grid-cols-1 md:grid-cols-2 gap-6'>
<div className='col-span-2 row-start-2 col-start-1 lg:row-auto lg:col-auto'>
<div className='text-2xl font-bold '>Shoppholic</div>
<div className='text-gray-400 '>E-commerce Website</div>
<ul className='my-5 text-gray-600'>
<li className='py-2 my-5'>
An E-commerce website for buying and selling your clothes with
reasonable price and various other options.
</li>
<li className='py-2 my-5'>
Made using HTML,CSS,Javascript and php and mysql in backend and
also integrated Razorpay payment gateway and also Oauth 2.0 and
Open ID connect Protocol for fast signing in.
</li>
<li className='py-2 my-5'>
We also take all information regarding ip address and give real
time analytics regarding our website.
</li>
</ul>
</div>
<div className='col-span-2 col-start-1 row-start-1 row-span-1 lg:col-auto lg:row-auto rounded-t-xl '>
<img clasName='rounded-t-lg' src={ecomweb} alt='' />
</div>
</div>
{/* *********************************************** Project-2 ************************************************************ */}
<div className='my-20 p-2 grid grid-cols-1 md:grid-cols-2 gap-6'>
<div className='col-span-2 row-start-2 col-start-1 lg:row-auto lg:col-auto'>
<div className='text-2xl font-bold '>Covid-19 Tracker</div>
<div className='text-gray-400 '>
Nodejs,mongodB,redis,cron jobs backup
</div>
<ul className='my-5 text-gray-600'>
<li className='py-2 my-5'>
It’s a COVID-19 tracker which shows real data using graphs with
chart.js and map using mappa.js.
</li>
<li className='py-2 my-5'>
It also uses mongodb for storing user information and we also
used cron jobs to automatically take backup of our data using
spawn child process and uses redis as a cache.
</li>
</ul>
</div>
<div className='col-span-2 col-start-1 row-start-1 row-span-1 lg:col-auto lg:row-auto rounded-t-xl '>
<img clasName='rounded-t-lg' src={covidTrack} alt='' />
</div>
</div>
{/* ***********************************************Project-3 *********************************************** */}
<div className='my-20 p-2 grid grid-cols-1 md:grid-cols-2 gap-6'>
<div className='col-span-2 row-start-2 col-start-1 lg:row-auto lg:col-auto'>
<div className='text-2xl font-bold '>
Real time chatting Application
</div>
<div className='text-gray-400 '>
Websocket, HAPROXY , DOCKER, REDIS, EC2 INSTANCE , NODEJS
</div>
<ul className='my-5 text-gray-600'>
<li className='py-2 my-5'>
Used HAPROXY as a reverse proxy and also websocket autoscaling
and multiple docker containers running nodejs for high
availability and also docker compose for running multiple
containers.
</li>
<li className='py-2 my-5'>
Used Redis as a publisher subscriber model to publish to a
channel and get messages from it and works over HTTP1.1.
</li>
</ul>
</div>
<div className='col-span-2 col-start-1 row-start-1 row-span-1 lg:col-auto lg:row-auto rounded-t-xl '>
<img clasName='rounded-t-lg' src={chat} alt='' />
</div>
</div>
{/* ************************************************Project-4******************************************************** */}
<div className='my-20 p-2 grid grid-cols-1 md:grid-cols-2 gap-6'>
<div className='col-span-2 row-start-2 col-start-1 lg:row-auto lg:col-auto'>
<div className='text-2xl font-bold '>Bahi-E-Khaata Grocery</div>
<div className='text-gray-400 '>
(Android App for E-commerce Platform
</div>
<ul className='my-5 text-gray-600'>
<li className='py-2 my-5'>
An E-commerce app for my fathers business regarding groceries
and other food items.
</li>
<li className='py-2 my-5'>
Used Firebase as a solution to backend and Android Studio as a
tool for developing it
</li>
</ul>
</div>
<div className='col-span-2 col-start-1 row-start-1 row-span-1 lg:col-auto lg:row-auto rounded-t-xl '>
<img
clasName='rounded-t-lg '
style={({ maxHeight: "60%" }, { maxWidth: "100%" })}
src={mobileecom}
alt=''
/>
</div>
</div>
</div>
</div>
);
};
export default Projects;
<file_sep>import React from "react";
import img from "../../image/20943391.jpg";
import { ColouredButton, PlainButton } from "./Button";
import { Link } from "react-scroll";
const Header = () => {
return (
<div
className='container grid grid-cols-1 md:grid-cols-2 gap-4 p-4 my-6 pt-20 md:pt-4 '
id='home'
>
{/* Introduction div */}
<div className='py-2 md:py-6 my-2 md:mt-20'>
{/* Introductions */}
<div className='my-2'>
<h4 className='text-2xl'>
Hi, my name is <span className='font-bold'><NAME></span>.
</h4>
</div>
<div className='py-2 mb-6 mt-2'>
<h2 className='text-3xl font-medium'>
I'm a webdeveloper and a Computer Science undergraduate.{" "}
</h2>
</div>
{/* buttons */}
<div className='md:mt-35 mt-20'>
<span>
<Link to='work' spy={true} smooth={true}>
<PlainButton />
</Link>
</span>
<span>
<Link to='contact' spy={true} smooth={true}>
<ColouredButton />
</Link>
</span>
</div>
</div>
{/* Dummy SVG */}
<div className='min-w-full md:min-w-0'>
<img src={img} alt='' />
</div>
</div>
);
};
export default Header;
<file_sep>[build.environment]
NODE_VERSION = "12.16.1"
YARN_VERSION = "1.10.1"
NPM_VERSION = "6.13.4"<file_sep>import { useEffect, useState } from "react";
import { Link } from "react-scroll";
import Logo from "../../image/Logo.png";
const Mobnav = () => {
const [mobtoggle, setMobtoggle] = useState({
class: "hidden ",
toggle: {
hidden: "hidden",
block: "block",
},
});
// const [active, setActive] = useState(false);
const handleonclick = () => {
if (mobtoggle.class === "hidden") {
setMobtoggle({ ...mobtoggle, class: mobtoggle.toggle.block });
// setActive(true);
} else {
setMobtoggle({ ...mobtoggle, class: mobtoggle.toggle.hidden });
// setActive(false);
}
};
return (
<div>
<nav className='borderb-2 md:border-0 py-2 absolute max-w-full min-w-full bg-white overflow-hidden '>
<div className=' px-3 mx-2'>
<div className='grid '>
<div>
<span>
<img className='w-10 m-auto' src={Logo} alt='' />
</span>
<span
className='order-last cursor-pointer p-1 flex justify-end -mt-8 '
onClick={handleonclick}
>
<svg
xmlns='http://www.w3.org/2000/svg'
className='h-6 w-6'
fill='none'
viewBox='0 0 24 24'
stroke='currentColor'
>
<path
strokeLinecap='round'
strokeLinejoin='round'
strokeWidth='2'
d='M4 6h16M4 12h16M4 18h16'
/>
</svg>
</span>
</div>
</div>
<div className={mobtoggle.class}>
<ul className='flex flex-col h-screen'>
<Link
className='m-3 text-xl bold-text p-3 font-semibold text-center'
onClick={handleonclick}
to='home'
activeClass='active'
spy={true}
smooth={true}
>
Home
</Link>
<Link
className='m-3 text-xl bold-text p-3 font-semibold text-center'
onClick={handleonclick}
to='work'
activeClass='active'
spy={true}
smooth={true}
>
Work
</Link>
<Link
to='project'
activeClass='active'
spy={true}
smooth={true}
className='m-3 text-xl bold-text p-3 font-semibold text-center'
onClick={handleonclick}
>
Projects
</Link>
<Link
to='contact'
activeClass='active'
spy={true}
smooth={true}
className='m-3 text-xl bold-text p-3 font-semibold text-center'
onClick={handleonclick}
>
Contact
</Link>
</ul>
</div>
</div>
</nav>
{/* {active ? (
<div onClick={handleonclick}>
<Overlay />
</div>
) : null} */}
</div>
);
};
const DesktopNavbar = () => {
return (
<div>
<nav className='border-2 md:border-0 py-8'>
<div>
<ul className='flex flex-row justify-end mr-10 '>
<Link
className=' cursor-pointer mx-6 text-lg text-gray-500 bold-text hover:text-indigo-600 font-bold text-center'
to='home'
activeClass='active'
spy={true}
smooth={true}
>
Home
</Link>
<Link
className=' cursor-pointer mx-6 text-lg bold-text text-gray-500 hover:text-indigo-600 font-bold text-center'
to='work'
activeClass='active'
spy={true}
smooth={true}
>
Work
</Link>
<Link
to='project'
activeClass='active'
spy={true}
smooth={true}
className='cursor-pointer mx-6 text-lg bold-text text-gray-500 hover:text-indigo-600 font-bold text-center'
>
Projects
</Link>
<Link
to='contact'
activeClass='active'
spy={true}
smooth={true}
className='cursor-pointer mx-6 text-lg bold-text text-gray-500 hover:text-indigo-600 font-bold text-center'
>
Contact
</Link>
</ul>
</div>
</nav>
</div>
);
};
const Navbar = () => {
const [isMobile, setIsMobile] = useState(
window.matchMedia("(max-width:768px)").matches
);
useEffect(() => {
window.addEventListener("resize", () => {
setIsMobile(window.matchMedia("(max-width:768px)").matches);
});
});
// return (
// <div>
// <Mobnav />
// </div>
// );
return <div>{isMobile ? <Mobnav /> : <DesktopNavbar />}</div>;
};
export default Navbar;
<file_sep>import React from "react";
const Work = (props) => {
return (
<div
id={props.name}
className='container px-4 py-10 mb-10 md:pr-40 lg:pr-20 '
>
<div className='text-4xl font-bold py-5 my-10'>Work Experience</div>
{/* Project-1 starts */}
<div className='grid grid-col-1 mt-20'>
<div>
<div className='text-2xl font-bold'>Focuses PVT Limited</div>
<div className='text-gray-400 '>As Web Developer</div>
<div className='text-gray-300 text-xs '>Oct -2020 to Nov-2020</div>
<div className='text-gray-500 mt-10'>
Worked as a Web Developer Intern for building website for their
company. I used Nodejs and mongoDB with features like Oauth 2.0 and
Open ID connect. Involved in improving the security of the website
using AWS inspector and AWS cloudwatch
</div>
{/* <div className='my-10 grid grid-cols-3 sm:grid-cols-8'>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600 '>
MongoDB
</span>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600'>
Nodejs
</span>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600'>
Oauth 2.0
</span>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600'>
AWS inspector
</span>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600 '>
AWS cloudwatch
</span>
</div> */}
</div>
</div>
{/* Project-2 starts */}
<div className='grid grid-col-1 mt-20'>
<div>
<div className='text-2xl font-bold'>Applex.in </div>
<div className='text-gray-400 '>As Andorid App Developer</div>
<div className='text-gray-300 text-xs '>feb-2021 to march-2021</div>
<div className='text-gray-500 mt-10'>
Worked as an Android App Developer intern and creating a feature in
an app like Facebook Marketplace with Firebase as a backend. Lead a
team of 6 developers to complete this project.
</div>
{/* <div className='my-10 grid grid-cols-3 sm:grid-cols-8'>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600'>
Android App
</span>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600'>
Firebase
</span>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600'>
Facebook Marketplace
</span>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600'>
Backend
</span>
</div> */}
</div>
</div>
{/* Project-3 */}
<div className='grid grid-col-1 mt-20'>
<div>
<div className='text-2xl font-bold'>FEPSI </div>
<div className='text-gray-400 '>NGO and health care</div>
<div className='text-gray-300 text-xs '>Oct -2020 to Nov-2020</div>
<div className='text-gray-500 mt-10'>
Core Committee Member - Contributed majorly to the finance
department by collecting funds and sponsorships for different
events.
</div>
{/* <div className='my-10 grid grid-cols-3 sm:grid-cols-8'>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600 md:-mx-2 lg:m-2'>
Contribution
</span>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600 md:-mx-2 lg:m-2'>
teamwork
</span>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600 md:-mx-2 lg:m-2'>
management
</span>
<span className='border p-2 m-2 rounded-lg font-medium text-xs text-white bg-indigo-600 md:-mx-2 lg:m-2'>
NGO
</span>
</div> */}
</div>
</div>
</div>
);
};
export default Work;
<file_sep>import React from "react";
const Overlay = () => {
return (
<div
className='blur min-h-screen min-w-screen zindex2 bg-indigo-50'
style={{
zIndex: "2",
}}
></div>
);
};
export default Overlay;
<file_sep>import React from "react";
import Contact from "./Components/contact/contact";
import Footer from "./Components/footer/footer";
import Header from "./Components/Header/header";
import Navbar from "./Components/Navbar/Dropdown";
import Projects from "./Components/Projects/project";
import Skills from "./Components/Skills/Skiil";
import Work from "./Components/Work/Work";
function App() {
return (
<div className='App text-gray-900 font-sans'>
<Navbar />
<Header />
<Skills />
<Work name={"work"} />
<Projects />
<Contact />
<Footer />
</div>
);
}
export default App;
|
c586786a02fd8586bcc633d036230ec606226534
|
[
"JavaScript",
"TOML"
] | 7
|
JavaScript
|
theashishmaurya/rishav
|
7f3c5a464d17d2c4974b8a8295a6454ca6078190
|
b2d1262df6da5e026644c1f1537cb7c9e3704b8a
|
refs/heads/main
|
<repo_name>chronoby/crowdfunding-ETH<file_sep>/src/ui/pages/all.js
import React from 'react';
import { Layout, Breadcrumb, Typography, Table, Tag, Modal, Form, Button, Input, Col, Row } from 'antd';
const { Header, Content, Footer } = Layout;
class All extends React.Component {
constructor() {
super();
this.state = {
columns: [],
visible: false,
ind: -1,
};
}
showModal = (index) => {
this.setState({
visible: true,
ind: index,
});
}
handleCancel = () => {
this.setState({
visible: false,
index: -1,
});
}
onFinish = (values) => {
this.props.Participate(this.state.ind, values.amount);
this.setState({ visible: false });
};
componentDidMount() {
this.props.refresh_account();
this.setState({
columns: [
{
title: 'ID',
dataIndex: 'index',
key: 'index',
render: (text, record, index) => {
const url = '/project/' + (record.index);
return (
<a href={url}>{text}</a>
);
}
},
{ title: '发起人', dataIndex: 'address', key: 'address' },
{ title: '金额', dataIndex: 'amount', key: 'amount' },
{ title: '已筹集金额', dataIndex: 'amount_get', key: 'amount_get' },
{ title: '开始时间', dataIndex: 'start_time', key: 'start_time' },
{ title: '结束时间', dataIndex: 'end_time', key: 'end_time' },
{
title: '状态',
dataIndex: 'status',
key: 'status',
render: (text, record) => {
let color = 'geekblue';
var content = "Processing"
if (text == 0) { content = "Processing"; color = 'green'; }
else if (text == 2) { content = "Failed"; color = 'volcano'; }
else if (text == 1) { content = "Success"; color = 'gold'; }
return (
<Tag color={color} key={text}>
{content}
</Tag>
);
},
},
{
title: '操作',
dataIndex: '',
key: 'x',
render: (text, record, index) => {
if (this.props.current_account != record.address) {
// console.log(record.address);
// console.log(this.props.current_account);
if (record.status == 0 && record.address != this.props.current_account) return (
<div>
<a onClick={() => this.showModal(index)}>Contribute</a>
<Modal
title="Contribute"
visible={this.state.visible}
onCancel={this.handleCancel}
footer={null}
width="400px"
destroyOnClose="true" >
<Form name="nest-messages" onFinish={this.onFinish} preserve={false}>
<Form.Item name={['amount']} label="Amount" rules={[]}>
<Input suffix="ETH" />
</Form.Item>
<Form.Item wrapperCol={{ span: 0, offset: 5 }}>
<Row>
<Col span={12}>
<Button onClick={this.handleCancel}>
Cancel
</Button>
</Col>
<Col span={12}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Col>
</Row>
</Form.Item>
</Form>
</Modal>
</div>
);
else if (record.status == 1) return (<></>);
else if (record.status == 2) return (<></>);
}
},
},
],
});
}
render() {
return (
<Layout className="site-layout">
<Header className="site-layout-background" style={{ padding: 0 }} />
<Content style={{ margin: '0 16px' }}>
<Breadcrumb style={{ margin: '16px 0' }}>
<Breadcrumb.Item>首页</Breadcrumb.Item>
<Breadcrumb.Item>所有众筹</Breadcrumb.Item>
</Breadcrumb>
<Table
columns={this.state.columns}
dataSource={this.props.fundings_info}
/>
</Content>
<Footer style={{ textAlign: 'center' }}>Crowdfunding-ETH ©2021 Created by chronoby</Footer>
</Layout>
)
}
}
export default All;
<file_sep>/src/ui/pages/home.js
import React from 'react';
import { Layout, Breadcrumb, Typography } from 'antd';
const { Title, Paragraph } = Typography;
const { Header, Content, Footer } = Layout;
class Home extends React.Component {
render() {
return (
<Layout className="site-layout">
<Header className="site-layout-background" style={{ padding: 0 }} />
<Content style={{ margin: '0 16px' }}>
<Breadcrumb style={{ margin: '16px 0' }}>
<Breadcrumb.Item>首页</Breadcrumb.Item>
</Breadcrumb>
</Content>
<body>
<Typography>
<Title style={{ textAlign: 'center' }}>Crowdfunding-ETH</Title>
<Paragraph>
Crowdfunding-ETH 是一个基于以太坊的 DApp,你可以
</Paragraph>
<Paragraph>
- 发起众筹
</Paragraph>
<Paragraph>
- 发起众筹
</Paragraph>
<Paragraph>
- 查看所有众筹
</Paragraph>
<Paragraph>
- 查看我发起的众筹
</Paragraph>
<Paragraph>
- 查看我投资的众筹
</Paragraph>
<Paragraph>
Have fun!
</Paragraph>
</Typography>
</body>
<Footer style={{ textAlign: 'center' }}>Crowdfunding-ETH ©2021 Created by chronoby</Footer>
</Layout>
)
}
}
export default Home
<file_sep>/src/ui/pages/participating.js
import React from 'react';
import { Layout, Breadcrumb, Typography, Table, Tag, Modal, Space } from 'antd';
const { Paragraph, Text } = Typography;
const { Header, Content, Footer } = Layout;
let crowdfundingIns = require("../../eth/crowdfunding")
let web3 = require('../../utils/InitWeb3')
class Participating extends React.Component {
constructor() {
super();
this.state = {
requests_info: [],
columns: [],
columns_in: [],
visible: false,
ind: -1,
};
}
getRequest = async (id) => {
var tmp_requests = [];
console.log('get request');
var num_request = await crowdfundingIns.methods.get_num_request(id).call();
for (var i = 0; i < num_request; i++) {
var r_info = await crowdfundingIns.methods.get_request(id, i, this.props.current_account).call();
var request_info = new Object();
request_info.index = i;
request_info.purpose = r_info[0];
request_info.amount = web3.utils.fromWei(r_info[1]) + ' ETH';
request_info.status = r_info[2];
request_info.reply_status = r_info[3];
tmp_requests.push(request_info);
}
this.setState({ requests_info: tmp_requests });
}
reply = async (index, agree) => {
console.log('reply');
console.log(index);
try {
crowdfundingIns.methods.reply(this.state.ind, index, agree).send({
from: this.props.current_account,
gas: '3000000'
});
alert("Reply succeeded")
} catch (e) {
console.log(e);
alert('Reply failed');
}
this.getRequest(this.state.ind);
}
showModal = (index) => {
this.getRequest(index);
this.setState({
visible: true,
ind: index,
});
}
handleCancel = () => {
this.setState({
visible: false,
index: -1,
});
}
onFinish = (values) => {
this.props.createRequest(this.state.ind, values.purpose, values.amount);
this.setState({ visible: false });
};
componentDidMount() {
this.props.refresh_account();
this.setState({
columns: [
{
title: 'ID',
dataIndex: 'index',
key: 'index',
render: (text, record, index) => {
const url = '/project/' + (record.index);
return (
<a href={url}>{text}</a>
);
}
},
{ title: '发起人', dataIndex: 'address', key: 'address' },
{ title: '金额', dataIndex: 'amount', key: 'amount' },
{ title: '已筹集金额', dataIndex: 'amount_get', key: 'amount_get' },
{ title: '开始时间', dataIndex: 'start_time', key: 'start_time' },
{ title: '结束时间', dataIndex: 'end_time', key: 'end_time' },
{
title: '状态',
dataIndex: 'status',
key: 'status',
render: (text, record) => {
let color = 'geekblue';
var content = "Processing"
//console.log(text);
if (text == 0) { content = "Processing"; color = 'green'; }
else if (text == 2) { content = "Failed"; color = 'volcano'; }
else if (text == 1) { content = "Success"; color = 'gold'; }
return (
<Tag color={color} key={text}>
{content}
</Tag>
);
},
},
{
title: '操作',
dataIndex: '',
key: 'x',
render: (text, record, index) => {
//console.log(record.status);
if (record.status == 1) return (
<div>
<a onClick={() => this.showModal(record.index)}>查看资金请求</a>
<Modal
title="Contribute"
visible={this.state.visible}
onCancel={this.handleCancel}
footer={null}
width="10000px"
destroyOnClose="true" >
<Table
columns={this.state.columns_in}
dataSource={this.state.requests_info}
/>
</Modal>
</div>
);
else if (record.status == 1) return (<></>);
else if (record.status == 2) return (<></>);
},
},
],
columns_in: [
{ title: '序号', dataIndex: 'index', key: 'index' },
{ title: '金额', dataIndex: 'amount', key: 'amount' },
{ title: '目的', dataIndex: 'purpose', key: 'purpose' },
{
title: '状态',
dataIndex: 'status',
key: 'status',
render: (text) => {
let color = 'geekblue';
var cont = "Processing";
if (text == 0) { cont = "Processing"; color = 'green'; }
else if (text == 1) { cont = "Success"; color = 'volcano'; }
else if (text == 2) { cont = "Failed"; color = 'gold'; }
return (
<Tag color={color} key={text}>
{cont}
</Tag>
);
},
},
{
title: '操作',
dataIndex: '',
key: 'x',
render: (text, record, index) => {
if (record.status == 0 && record.reply_status == 0) return (
<Space size="middle">
<a onClick={() => this.reply(index, true)}>接受</a>
<a onClick={() => this.reply(index, false)}>拒绝</a>
</Space>
); else if (record.reply_status == 1) return (
<Space size="middle">
<a >已接受</a>
</Space>
); else if (record.reply_status == 2) return (
<Space size="middle">
<a >已拒绝</a>
</Space>
)
else return (<></>);
}
},
],
});
}
render() {
return (
<Layout className="site-layout">
<Header className="site-layout-background" style={{ padding: 0 }} />
<Content style={{ margin: '0 16px' }}>
<Breadcrumb style={{ margin: '16px 0' }}>
<Breadcrumb.Item>首页</Breadcrumb.Item>
<Breadcrumb.Item>我发起的众筹</Breadcrumb.Item>
</Breadcrumb>
<Table
columns={this.state.columns}
expandable={{
expandedRowRender: record => <div>
<Typography>
<Paragraph>
<Text strong>Title:</Text> {record.title}
</Paragraph>
<Paragraph>
<Text strong>Your Contribution:</Text> {record.contribution}
</Paragraph>
<Paragraph>
<Text strong>Description:</Text> {record.info}
</Paragraph>
</Typography>
</div>
}}
dataSource={this.props.part_fundings_info}
/>
</Content>
<Footer style={{ textAlign: 'center' }}>Crowdfunding-ETH ©2021 Created by chronoby</Footer>
</Layout>
)
}
}
export default Participating;
<file_sep>/src/App.js
import React from 'react';
import UI from './ui/ui';
import './App.css';
import moment from 'moment';
let web3 = require('./utils/InitWeb3')
let crowdfundingIns = require("./eth/crowdfunding")
class App extends React.Component {
constructor() {
super();
this.state = {
current_account: '',
fundings_info: [],
my_fundings_info: [],
part_fundings_info: [],
num_fundings: 0,
}
}
getFundings = async () => {
var tmp_fundings_info = [];
var num_fundings = await crowdfundingIns.methods.get_num_fundings().call();
for (var i = 0; i < num_fundings; i++) {
var ins = await crowdfundingIns.methods.get_funding(i).call();
var funding_info = new Object();
funding_info.index = ins[0];
funding_info.address = ins[1];
funding_info.amount = web3.utils.fromWei(ins[2]) + ' ETH';
funding_info.amount_get = web3.utils.fromWei(ins[3]) + ' ETH';
funding_info.start_time = moment.unix(ins[4]).format("MMMM Do YYYY, HH:mm:ss");
funding_info.end_time = moment.unix(ins[5]).format("MMMM Do YYYY, HH:mm:ss");
funding_info.status = ins[6];
if (ins[6] == 0 && ins[5] < moment().format('X')) {
funding_info.status = 2;
}
//console.log(funding_info.status);
funding_info.info = ins[7];
funding_info.title = ins[8];
tmp_fundings_info.push(funding_info);
}
this.setState({ fundings_info: tmp_fundings_info });
}
getMyFundings = async () => {
var tmp_my_fundings_info = [];
var num_fundings = await crowdfundingIns.methods.get_num_fundings().call();
for (var i = 0; i < num_fundings; i++) {
var ins = await crowdfundingIns.methods.get_funding(i).call();
var funding_info = new Object();
funding_info.index = ins[0];
funding_info.address = ins[1];
if (funding_info.address == this.state.current_account) {
funding_info.amount = web3.utils.fromWei(ins[2]) + ' ETH';
funding_info.amount_get = web3.utils.fromWei(ins[3]) + ' ETH';
funding_info.start_time = moment.unix(ins[4]).format("MMMM Do YYYY, HH:mm:ss");
funding_info.end_time = moment.unix(ins[5]).format("MMMM Do YYYY, HH:mm:ss");
funding_info.status = ins[6];
if (ins[6] == 0 && ins[5] < moment().format('X')) {
funding_info.status = 2;
}
//console.log(funding_info.status);
funding_info.info = ins[7];
funding_info.title = ins[8];
tmp_my_fundings_info.push(funding_info);
}
}
this.setState({ my_fundings_info: tmp_my_fundings_info });
}
getPartFundings = async () => {
var tmp_part_fundings_info = [];
var num_fundings = await crowdfundingIns.methods.get_num_fundings().call();
for (var i = 0; i < num_fundings; i++) {
var part_in = await crowdfundingIns.methods.check_part(i, this.state.current_account).call();
if (part_in == false) {
continue;
}
var ins = await crowdfundingIns.methods.get_funding_con(i, this.state.current_account).call();
var funding_info = new Object();
funding_info.index = ins[0];
funding_info.address = ins[1];
funding_info.amount = web3.utils.fromWei(ins[2]) + ' ETH';
funding_info.amount_get = web3.utils.fromWei(ins[3]) + ' ETH';
funding_info.start_time = moment.unix(ins[4]).format("MMMM Do YYYY, HH:mm:ss");
funding_info.end_time = moment.unix(ins[5]).format("MMMM Do YYYY, HH:mm:ss");
funding_info.status = ins[6];
if (ins[6] == 0 && ins[5] < moment().format('X')) {
funding_info.status = 2;
}
console.log(funding_info.status);
funding_info.info = ins[7];
funding_info.title = ins[8];
funding_info.contribution = web3.utils.fromWei(ins[9]) + ' ETH';
tmp_part_fundings_info.push(funding_info);
}
this.setState({ part_fundings_info: tmp_part_fundings_info });
}
refresh_account = async () => {
const accounts = await web3.eth.getAccounts();
this.setState({ current_account: accounts[0] });
}
createFunding = async (title, info, end_time, amount) => {
try {
console.log('create a funding');
var id = await crowdfundingIns.methods.create_funding(
title, info, end_time, web3.utils.toWei(amount.toString())
).send({
from: this.state.current_account,
gas: '3000000',
});
alert('Create succeeded');
} catch (e) {
console.log(e);
alert('Create failed');
}
this.getFundings();
}
createRequest = async (id, purpose, amount) => {
try {
console.log('create a request');
await crowdfundingIns.methods.create_request(
id, purpose, web3.utils.toWei(amount.toString())
).send({
from: this.state.current_account,
gas: '3000000',
});
alert('Create succeeded');
} catch (e) {
console.log(e);
alert('Create failed');
}
this.getFundings();
}
Participate = async (index, amount) => {
try {
console.log('participate');
await crowdfundingIns.methods.participant_funding(index).send({
from: this.state.current_account,
value: web3.utils.toWei(amount, 'ether'),
gas: '3000000',
})
alert('Participate succeeded');
} catch (e) {
console.log(e);
alert('Participate failed');
}
this.getFundings();
this.getMyFundings();
this.getPartFundings();
}
async componentDidMount() {
this.timer = setInterval(() => {
this.refresh_account();
this.getFundings();
this.getMyFundings();
this.getPartFundings();
}, 1000);
}
render() {
return (
<UI
current_account={this.state.current_account}
fundings_info={this.state.fundings_info}
my_fundings_info={this.state.my_fundings_info}
part_fundings_info={this.state.part_fundings_info}
getFundings={this.getFundings}
getMyFundings={this.getMyFundings}
getPartFundings={this.getPartFundings}
refresh_account={this.refresh_account}
createFunding={this.createFunding}
createRequest={this.createRequest}
Participate={this.Participate}
></UI>
);
}
}
export default App;<file_sep>/src/eth/crowdfunding.js
let web3 = require('../utils/InitWeb3')
let abi =
[
{
"inputs": [
{
"internalType": "uint256",
"name": "fundingID",
"type": "uint256"
}
],
"name": "check_goal_reached",
"outputs": [
{
"internalType": "bool",
"name": "reached",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "index",
"type": "uint256"
},
{
"internalType": "address",
"name": "addr",
"type": "address"
}
],
"name": "check_part",
"outputs": [
{
"internalType": "bool",
"name": "r",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "fundingID",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "requestID",
"type": "uint256"
}
],
"name": "check_pass",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "check_time",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "string",
"name": "title",
"type": "string"
},
{
"internalType": "string",
"name": "info",
"type": "string"
},
{
"internalType": "uint256",
"name": "e_time",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "create_funding",
"outputs": [
{
"internalType": "uint256",
"name": "fundingID",
"type": "uint256"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "fundingID",
"type": "uint256"
},
{
"internalType": "string",
"name": "p",
"type": "string"
},
{
"internalType": "uint256",
"name": "a",
"type": "uint256"
}
],
"name": "create_request",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "index",
"type": "uint256"
}
],
"name": "get_funding",
"outputs": [
{
"internalType": "uint256",
"name": "id",
"type": "uint256"
},
{
"internalType": "address payable",
"name": "creator",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "amount_get",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "start_time",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "end_time",
"type": "uint256"
},
{
"internalType": "enum crowdfunding.Status",
"name": "status",
"type": "uint8"
},
{
"internalType": "string",
"name": "info",
"type": "string"
},
{
"internalType": "string",
"name": "title",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "index",
"type": "uint256"
},
{
"internalType": "address payable",
"name": "s",
"type": "address"
}
],
"name": "get_funding_con",
"outputs": [
{
"internalType": "uint256",
"name": "id",
"type": "uint256"
},
{
"internalType": "address payable",
"name": "creator",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "amount_get",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "start_time",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "end_time",
"type": "uint256"
},
{
"internalType": "enum crowdfunding.Status",
"name": "status",
"type": "uint8"
},
{
"internalType": "string",
"name": "info",
"type": "string"
},
{
"internalType": "string",
"name": "title",
"type": "string"
},
{
"internalType": "uint256",
"name": "contribution",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "get_num_fundings",
"outputs": [
{
"internalType": "uint256",
"name": "n",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "id",
"type": "uint256"
}
],
"name": "get_num_request",
"outputs": [
{
"internalType": "uint256",
"name": "n",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "index",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "rid",
"type": "uint256"
},
{
"internalType": "address payable",
"name": "inv",
"type": "address"
}
],
"name": "get_request",
"outputs": [
{
"internalType": "string",
"name": "purpose",
"type": "string"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
},
{
"internalType": "enum crowdfunding.Status",
"name": "status",
"type": "uint8"
},
{
"internalType": "uint256",
"name": "r",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "fundingID",
"type": "uint256"
}
],
"name": "participant_funding",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "fundingID",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "requestID",
"type": "uint256"
},
{
"internalType": "bool",
"name": "agree",
"type": "bool"
}
],
"name": "reply",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "fundingID",
"type": "uint256"
}
],
"name": "return_eth",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]
const address = '0x3E18DA3B478408fdD28Afd84a34FF73218143e44';
const instance = new web3.eth.Contract(abi, address);
module.exports = instance;
<file_sep>/README.md
# crowdfunding-ETH
A crowdfunding DApp based on Ethereum.
## Environment
- Node.js 14.15.4
## Request
To run the project, you need to install
- MetaMask
- Ganache
## Build
1. open Ganache and start a workspace with host ip and port 8545
2. Configure the `truffle-config.js` by adding
```javascript
development: {
host: "127.0.0.1",
port: 8545,
network_id: "*",
}
```
3. Deploy a chain and modify the contract address in `src/eth/crowdfunding.js`
4. Run in terminal
```bash
yarn install
yarn start
```
Have fun!<file_sep>/src/ui/pages/create.js
import React from 'react';
import { Layout, Breadcrumb, Button, Form, Input, DatePicker, Col, Row } from 'antd';
import moment from 'moment';
const { Header, Content, Footer } = Layout;
const time_rule = {
type: 'object',
required: true,
message: 'Please select time!'
};
class Create extends React.Component {
constructor() {
super();
this.state = {
}
}
onFinish = (values) => {
console.log(values.title);
console.log(values.info);
console.log(moment(values.end_time).format('X'));
console.log(values.amount);
this.props.createFunding(values.title, values.info, moment(values.end_time).format('X'), values.amount);
};
onReset = () => {
this.resetFields();
};
render() {
return (
<Layout className="site-layout">
<Header className="site-layout-background" style={{ padding: 0 }} />
<Content style={{ margin: '0 16px' }}>
<Breadcrumb style={{ margin: '16px 0' }}>
<Breadcrumb.Item>首页</Breadcrumb.Item>
<Breadcrumb.Item>发起众筹</Breadcrumb.Item>
</Breadcrumb>
<div style={{ margin: '16px 0' }}>
<Form name="nest-messages" onFinish={this.onFinish} preserve={false}>
<Form.Item name={['title']} label="标题" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name={['amount']} label="金额" rules={[{ required: true }]}>
<Input suffix="ETH" />
</Form.Item>
<Form.Item name={['end_time']} label="截止时间" rules={[time_rule]}>
<DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
</Form.Item>
<Form.Item name={['info']} label="详细描述" rules={[{ required: true }]}>
<Input.TextArea rows={8} />
</Form.Item>
<Form.Item wrapperCol={{ offset: 8 }}>
<Row>
<Col span={12}>
<Button >
Reset
</Button>
</Col>
<Col span={12}>
<Button type="primary" htmlType="submit" >
提交
</Button>
</Col>
</Row>
</Form.Item>
</Form>
</div>
</Content>
<Footer style={{ textAlign: 'center' }}>Crowdfunding-ETH ©2021 Created by chronoby</Footer>
</Layout>
)
}
}
export default Create;
|
fe109b0e9815aca4b9c480f8c7bf16cf59926d47
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
chronoby/crowdfunding-ETH
|
af47bbcbbb8d3ed423f3950ecf85589d0ee24ca0
|
839bcdc5c956fb5696db0af225ac32c42892c722
|
refs/heads/master
|
<repo_name>justrmarks/go-harm-reduction-scraper<file_sep>/db/EntryModel.go
package db
type Entry struct {
SamplePhoto []byte `json:"samplePhoto"`
SampleName string `json:"sampleName"`
SubstanceRatio map[string]int `json:"substanceRatio"`
DatePublished string `json:"datePublished"`
DateTested string `json:"dateTested"`
Location string `json:"location"`
SampleSize string `json:"sampleSize"`
DataSource string `json:"dataSource"`
}
<file_sep>/data-drugs-scraper.go
package main
import (
"fmt"
"time"
"github.com/gocolly/colly"
"github.com/gocolly/colly/debug"
"github.com/gocolly/colly/extensions"
)
func main() {
url := "https://www.ecstasydata.org/"
// Instantiate default collector
c := colly.NewCollector(
// Turn on asynchronous requests
colly.Async(true),
// Attach a debugger to the collector
colly.Debugger(&debug.LogDebugger{}),
// colly.AllowedDomains("ecstasydata.org"),
// Allow visiting the same page multiple times
colly.AllowURLRevisit(),
// Allow crawling to be done in parallel / async
colly.Async(true),
)
extensions.RandomUserAgent(c)
extensions.Referer(c)
// Limit the number of threads started by colly to two
// when visiting links which domains' matches "*httpbin.*" glob
c.Limit(&colly.LimitRule{
DomainGlob: "*.ecstasydata.org",
Parallelism: 2,
Delay: 1 * time.Second,
RandomDelay: 1 * time.Second,
})
c.OnRequest(func(r *colly.Request) {
fmt.Println("Visiting", r.URL)
})
c.OnError(func(_ *colly.Response, err error) {
fmt.Println("Something went wrong:", err)
})
c.OnResponse(func(r *colly.Response) {
fmt.Println("Visited", r.Request.URL, r.StatusCode)
})
c.OnHTML("tr", func(e *colly.HTMLElement) {
fmt.Println(e.Text)
})
// Wait until threads are finished
err := c.Visit(url)
if err != nil {
fmt.Println(err)
}
c.Wait()
}
<file_sep>/README.md
# Go Harm Reduction Scraper
A Go web scraper to populate and update a mongo database with reports of substances tested for safety in the field using drugsdata.org
## background
This project is established to centralize knowledge and reports related to drug screenings for dangerous substances into a simple and accessible API with the idea that making this information more readily accessible will aid safer drug use in populations around the world by flagging dangerous supplies.
## Roadmap
1. Establish a microservice to create and maintain a reliable dataset
* starting with scraping DrugsData.org responsibly and efficiently
|
f10f57bbf49d7ac80cb5bcd327b98cb9b5b8dfdf
|
[
"Markdown",
"Go"
] | 3
|
Go
|
justrmarks/go-harm-reduction-scraper
|
7da0d6c95a8f6681ff8af8c5ed47ea74e9d94ec7
|
d1fbb10db638722dcdd379170518abccdb66ab79
|
refs/heads/master
|
<repo_name>Davelek/Grafika1<file_sep>/src/utils/Vypocty.java
package utils;
import drawable.Point;
import java.util.ArrayList;
import java.util.List;
public class Vypocty {
public static double vypocetVzdalenosti(int x1, int y1, int x2, int y2) {
return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1));
}
public static List<Point> getPolygon(Point point1, Point point2, int count){
int x1 = point1.getX();
int y1 = point1.getY();
int x2 = point2.getX();
int y2 = point2.getY();
double x0 = x2 - x1;
double y0 = y2 - y1;
double circleRadius = 2 * Math.PI;
List<Point> points = new ArrayList<>();
double step = circleRadius / (double) count;
for (double i = 0; i < circleRadius; i += step) {
double x = x0 * Math.cos(step) + y0 * Math.sin(step);
double y = y0 * Math.cos(step) - x0 * Math.sin(step);
//lineDDA((int) x0 + x1, (int) y0 + y1, (int) x + x1, (int) y + y1, color);
points.add(new Point((int)x0+x1,(int)y0+y1));
points.add(new Point((int)x+x1,(int)y+y1));
x0 = x;
y0 = y;
}
return points;
}
public static List<Integer> bubbleSort(List<Integer> points){
int temp;
boolean is_sorted;
for (int i = 0; i < points.size(); i++) {
is_sorted = true;
for (int j = 1; j < (points.size() - i); j++) {
if (points.get(j-1) > points.get(j)) {
temp = points.get(j-1);
points.set(j-1,points.get(j));
points.set(j,temp);
is_sorted = false;
}
}
// is sorted? then break it, avoid useless loop.
if (is_sorted) break;
}
return points;
}
}
<file_sep>/src/masek_PGRF2/controller/sipkaY.java
package masek_PGRF2.controller;
import masek_PGRF2.model.Vertex;
import transforms.Mat4RotXYZ;
import transforms.Point3D;
import java.awt.*;
import java.util.List;
public class sipkaY {
public int count = 18;
public sipkaY() {
}
public sipkaY(java.util.List<Vertex> vb, List<Integer> ib, int index, Color color) {
vb.add(new Vertex(new Point3D(0, 0, 0), color));
vb.add(new Vertex(new Point3D(0, 1, 0), color));
vb.add(new Vertex(new Point3D(0.1, 0.5, 0), color));
vb.add(new Vertex(new Point3D(-0.1, 0.5, 0), color));
vb.add(new Vertex(new Point3D(0, 0.5, 0.1), color));
vb.add(new Vertex(new Point3D(0, 0.5, -0.1), color));
ib.add(0 + index);
ib.add(1 + index);
ib.add(1 + index);
ib.add(2 + index);
ib.add(1 + index);
ib.add(3 + index);
ib.add(1 + index);
ib.add(4 + index);
ib.add(1 + index);
ib.add(5 + index);
ib.add(5 + index);
ib.add(3 + index);
ib.add(2 + index);
ib.add(4 + index);
ib.add(4 + index);
ib.add(3 + index);
ib.add(5 + index);
ib.add(2 + index);
for (int i = vb.size() - 5; i < vb.size(); i++) {
vb.get(i).setTransofmable(false);
}
}
}
<file_sep>/README.txt
Klávesa s - seedFiller
Klávesa A - ScanLine
ve scan line přepínáme mezi objeky pomocí šipky nahoru a entrem to podvrdíme
---------------------------------------------------------------------------
Ovládání:
Spacebar: výběr módu(line,Nuhelnik,Polygon,kružnice, segment kružnice)
klávesa C: změna barvy
Klávesy L,P,N,K,S: přepínání mezi mody linie, polygon ,n-úhelník, kružnice a segment kružnice
U polygonu lze zvýšit počet stran pomocí šipek nahoru a dolů nebo kolečkem myši (+ a - také fungují)
Lze ukončit n-úhelník pomocí pravé klávesy
pokud klikneme pravým tlačítkem na myši před dokončení úsečky, polygonu, kruhu či segmentu, daný objekt se neuloží
Klávesa H: otevře help
Tlačítkem R se resetuje paleta<file_sep>/src/masek_PGRF2/helper/Utils.java
package masek_PGRF2.helper;
import transforms.Point3D;
public class Utils {
static public boolean fastCut(Point3D a) {
return !(-a.getW() >= a.getX() || -a.getW() >= a.getY() || a.getX() >= a.getW() || a.getY() >= a.getW()
|| 0 >= a.getZ() || a.getZ() >= a.getW());
}
}
<file_sep>/src/filler/Filler.java
package filler;
import utils.Renderer;
import java.awt.*;
public interface Filler {
void fill();
int getColor();
void setColor(Color Color);
void setRaster(Renderer renderer);
}
<file_sep>/src/masek_PGRF2/renderer/RenderLine.java
package masek_PGRF2.renderer;
import masek_PGRF2.helper.Utils;
import masek_PGRF2.model.Vertex;
import masek_PGRF2.view.Raster;
import transforms.Vec3D;
import javax.rmi.CORBA.Util;
import java.awt.*;
import java.util.Optional;
public class RenderLine extends Renderer3D {
public RenderLine(Raster raster) {
super(raster);
}
public void prepareTriangleWithnoutFill(Vertex v1, Vertex v2, Vertex v3) {
if (Utils.fastCut(v1.getPoint())&& Utils.fastCut(v2.getPoint()) && Utils.fastCut(v3.getPoint())) {
drawLine(v1, v2, Color.white);
drawLine(v2, v3, Color.white);
drawLine(v3, v1, Color.white);
}
}
public void drawLine(Vertex a, Vertex b, Color color) {
if (Utils.fastCut(a.getPoint())&& Utils.fastCut(b.getPoint())){
Optional<Vec3D> d1 = a.getPoint().dehomog();
Optional<Vec3D> d2 = b.getPoint().dehomog();
// zahodit trojúhelník, pokud některý vrchol má w==0 (nelze provést dehomogenizaci)
if (!d1.isPresent() || !d2.isPresent()) return;
Vec3D v1 = d1.get();
Vec3D v2 = d2.get();
v1 = transformToWindow(v1);
v2 = transformToWindow(v2);
DDA(v1, v2, color);
}
}
private void DDA(Vec3D v1, Vec3D v2, Color c1) {
int dx, dy;
boolean ridiciX;
float x, y, k, G, H;
int x1 = (int) Math.round(v1.getX());
int y1 = (int) Math.round(v1.getY());
int x2 = (int) Math.round(v2.getX());
int y2 = (int) Math.round(v2.getY());
dx = x2 - x1;
dy = y2 - y1;
k = dy / (float) dx;
if (Math.abs(dx) > Math.abs(dy)) {
ridiciX = true;
G = 1;
H = k;
if (x1 >= x2) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
} else {
ridiciX = false;
G = 1 / k;
H = 1;
if (y1 > y2) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
}
x = x1;
y = y1;
int max = Math.max(Math.abs(dx), Math.abs(dy));
for (int i = 0; i <= max; i++) {
if (ridiciX) {
double t1 = (x - x1) / (x2 - x1);
Vec3D vertexAB = v1.mul(1 - t1).add(v2.mul(t1));
drawPixel(Math.round(x), Math.round(y), vertexAB.getZ(), c1);
} else {
double t1 = (y - v1.getY()) / (v2.getY() - v1.getY());
Vec3D vertexAB = v1.mul(1 - t1).add(v2.mul(t1));
drawPixel(Math.round(x), Math.round(y), vertexAB.getZ(), c1);
}
x = x + G;
y = y + H;
}
double t1 = (x - v1.getX()) / (v2.getX() - v1.getX());
Vec3D vertexAB = v1.mul(1 - t1).add(v2.mul(t1));
drawPixel(Math.round(x), Math.round(y), vertexAB.getZ(), c1);
}
}
<file_sep>/src/masek_PGRF2/controller/Controller3D.java
package masek_PGRF2.controller;
import masek_PGRF2.model.Element;
import masek_PGRF2.model.ElementType;
import masek_PGRF2.model.Vertex;
import masek_PGRF2.renderer.GPURenderer;
import masek_PGRF2.renderer.Renderer3D;
import masek_PGRF2.view.Raster;
import transforms.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
public class Controller3D {
private GPURenderer renderer3D;
private Camera camera;
private int click;
private int mousePositionX;
private int mousePositionY;
private int newMousePosX;
private int newMousePosY;
private boolean fill = true;
private boolean perspektiv = true;
private int mx, my;
private int clickX, clickY, klick = 0;
private List<Element> elements;
private List<Vertex> vb;
private List<Integer> ib;
public Controller3D(Raster raster) {
initObjects(raster);
initListeners(raster);
}
private void display() {
renderer3D.clear();
renderer3D.setModel(new Mat4Identity());
renderer3D.setView(camera.getViewMatrix());
renderer3D.draw(elements, vb, ib, fill);
renderer3D.setModel(new Mat4Transl(5, 0, 0));
}
private void initObjects(Raster raster) {
renderer3D = new Renderer3D(raster);
resetCamera();
ib = new ArrayList<>();
vb = new ArrayList<>();
elements = new ArrayList<>();
elements.add(new Element(ElementType.TRIANGLE, new Cube().count, 0));
elements.add(new Element(ElementType.LINE, new sipkaX().count, 36));
elements.add(new Element(ElementType.LINE, new sipkaY().count, 36 + 18));
elements.add(new Element(ElementType.LINE, new sipkaZ().count, 36 + 18 + 18));
elements.add(new Element(ElementType.TRIANGLE, new Jehlan().count, 36 + 18 + 18 + 18));
new Cube(vb, ib, 0);
new sipkaX(vb, ib, 14, Color.red);
new sipkaY(vb, ib, 20, Color.GREEN);
new sipkaZ(vb, ib, 26, Color.blue);
new Jehlan(vb, ib, 26 + 6);
Mat4Transl mat4Scale6 = new Mat4Transl(2, 1, 0);
for (int i = vb.size() - 5; i < vb.size(); i++) {
vb.get(i).setTransform(vb.get(i).getTransform().mul(mat4Scale6));
}
Mat4Transl mat4Scale2 = new Mat4Transl(-2, -1, 0);
for (int i = 0; i <= 13; i++) {
vb.get(i).setTransform(vb.get(i).getTransform().mul(mat4Scale2));
}
renderer3D.draw(elements, vb, ib, fill);
}
private void resetCamera() {
camera = new Camera().withPosition(new Vec3D(0, -6, 0))
.withAzimuth(Math.toRadians(90)).withZenith(Math.toRadians(0));
renderer3D.setView(camera.getViewMatrix());
}
private void initListeners(Raster raster) {
raster.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
mx = e.getX();
my = e.getY();
klick = 1;
}
if (e.getButton() == MouseEvent.BUTTON3) {
clickX = e.getX();
clickY = e.getY();
klick = 2;
}
}
@Override
public void mouseReleased(MouseEvent e) {
klick = 0;
}
});
raster.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent f) {
if (klick == 1) {
for (Vertex vertex : vb
) {
Mat4RotXYZ rot = new Mat4RotXYZ(-(mx - f.getX()) * 0.02, -(f.getY() - my) * (0.02), 0);
if (vertex.isTransofmable())
vertex.setTransform(vertex.getTransform().mul(rot));
}
display();
mx = f.getX();
my = f.getY();
}
if (klick == 2) {
camera = camera.addAzimuth((f.getX() - clickX) * (0.002)).addZenith((f.getY() - clickY) * (0.002));
clickX = f.getX();
clickY = f.getY();
display();
}
}
});
raster.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_P:
camera = new Camera().withPosition(new Vec3D(0, -6, 0))
.withAzimuth(Math.toRadians(90)).withZenith(Math.toRadians(0));
renderer3D.setView(camera.getViewMatrix());
if (perspektiv)
renderer3D.setProjection(new Mat4OrthoRH(5, 5, 0.01, 15));
else
renderer3D.setProjection(new Mat4PerspRH(0.7853981633974483D, ((float) raster.getHeight() / (float) raster.getWidth()), 0.01D, 100.0D));
perspektiv = !perspektiv;
display();
break;
case KeyEvent.VK_UP:
camera = camera.up(0.1);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_W:
camera = camera.forward(0.1);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_DOWN:
camera = camera.down(0.1);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_M:
fill = !fill;
display();
break;
case KeyEvent.VK_S:
camera = camera.backward(0.1);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_RIGHT:
camera = camera.right(0.1);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_D:
camera = camera.right(0.1);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_LEFT:
camera = camera.left(0.1);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_E:
camera = camera.addAzimuth(-0.1);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_Q:
camera = camera.addAzimuth(0.1);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_SUBTRACT:
Mat4Scale mat4Scale = new Mat4Scale(0.8, 0.8, 0.8);
for (Vertex vertex : vb
) {
if (vertex.isTransofmable()) {
vertex.setTransform(vertex.getTransform().mul(mat4Scale));
}
}
display();
break;
case KeyEvent.VK_ADD:
Mat4Scale mat4Scale2 = new Mat4Scale(1.2, 1.2, 1.2);
for (Vertex vertex : vb
) {
if (vertex.isTransofmable())
vertex.setTransform(vertex.getTransform().mul(mat4Scale2));
}
display();
break;
case KeyEvent.VK_A:
camera = camera.left(0.1);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_NUMPAD1:
camera = camera.addAzimuth(-0.01);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_NUMPAD2:
camera = camera.addZenith(-0.01);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_NUMPAD4:
camera = camera.addAzimuth(0.01);
renderer3D.setView(camera.getViewMatrix());
display();
break;
case KeyEvent.VK_NUMPAD5:
camera = camera.addZenith(0.01);
renderer3D.setView(camera.getViewMatrix());
display();
break;
}
}
});
}
}
<file_sep>/src/masek_PGRF2/model/Vertex.java
package masek_PGRF2.model;
import transforms.Mat4;
import transforms.Mat4Identity;
import transforms.Point3D;
import java.awt.*;
public class Vertex {
private final Point3D point;
private final Color color;
public final double x, y, z, w;
private Mat4 transform = new Mat4Identity();
private boolean isTransofmable = true;
public boolean isTransofmable() {
return isTransofmable;
}
public void setTransofmable(boolean transofmable) {
isTransofmable = transofmable;
}
public Mat4 getTransform() {
return transform;
}
public void setTransform(Mat4 transform) {
this.transform = transform;
}
public Vertex(Point3D point, Color color) {
this.point = point;
this.color = color;
x = point.getX();
y = point.getY();
z = point.getZ();
w = point.getW();
}
public Vertex setPoint(Point3D point, Color color) {
return new Vertex(point, color);
}
public Point3D getPoint() {
return point;
}
public Color getColor() {
return color;
}
}
<file_sep>/src/utils/Renderer.java
package utils;
import drawable.Point;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;
import static utils.Vypocty.getPolygon;
public class Renderer {
BufferedImage img;
private boolean dashed = false;
public Renderer(BufferedImage img) {
this.img = img;
}
public int getWidth(){
return img.getWidth();
}
public int getHeight(){
return img.getHeight();
}
public int getPixel(int x, int y){
return img.getRGB(x, y);
}
public void drawPixel(int x, int y, Color color1) {
if (x < 0 || x >= img.getWidth()) return;
;
if (y < 0 || y >= img.getHeight()) return;
;
img.setRGB(x, y, color1.getRGB());
}
private void drawPixelDashed(int x, int y, int d, Color color1) {
if (x < 0 || x >= 800) return;
;
if (y < 0 || y >= 600) return;
;
if (d % 4 < 0) {
} else {
dashed = !dashed;
}
if (dashed) {
img.setRGB(x, y, color1.getRGB());
}
}
public void drawDashedLine(int x1, int y1, int x2, int y2, Color color) {
float[] floats = doDDA(x1, y1, x2, y2);
int max = (int) floats[0];
float x = floats[1];
float y = floats[2];
float G = floats[3];
float H = floats[4];
for (int i = 0; i <= max; i++) {
drawPixelDashed(Math.round(x), Math.round(y), i, color);
x = x + G;
y = y + H;
}
}
public void lineTrivial(int x1, int y1, int x2, int y2, Color color) {
int dx = x1 - x2;
int dy = y1 - y2;
if (Math.abs(dx) > Math.abs(dy)) {
if (x1 > x2) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
double k, q;
k = dy / (double) dx;
for (int x = x1; x < x2; x++) {
int y = y1 + (int) (k * (x - x1));
drawPixel(x, y, color);
}
} else {
//řídící osa y
if (y1 > y2) {
// int temp = x1;
x1 = x2;
// x2 = temp;
int temp = y1;
y1 = y2;
y2 = temp;
}
double k, q;
k = dx / (double) dy;
for (int y = y1; y < y2; y++) {
int x = x1 + (int) (k * (y - y1));
drawPixel(x, y, color);
}
}
}
public void lineDDA(int x1, int y1, int x2, int y2, Color color) {
float[] floats = doDDA(x1, y1, x2, y2);
// nechám to redudantí kvůly přehlednosti
int max = (int) floats[0];
float x = floats[1];
float y = floats[2];
float G = floats[3];
float H = floats[4];
for (int i = 0; i <= max; i++) {
drawPixel(Math.round(x), Math.round(y), color);
x = x + G;
y = y + H;
}
}
private float[] doDDA(int x1, int y1, int x2, int y2) {
float[] helfer = new float[10];
int dx, dy;
float x, y, k, G, H;
dx = x2 - x1;
dy = y2 - y1;
k = dy / (float) dx;
if (Math.abs(dx) > Math.abs(dy)) {
G = 1;
H = k;
if (x1 > x2) {
// int temp = x1;
x1 = x2;
// x2 = temp;
// temp = y1;
y1 = y2;
// y2 = temp;
}
} else {
G = 1 / k;
H = 1;
if (y1 > y2) {
// int temp = x1;
x1 = x2;
// x2 = temp;
// temp = y1;
y1 = y2;
// y2 = temp;
}
}
x = x1;
y = y1;
int max = Math.max(Math.abs(dx), Math.abs(dy));
helfer[0] = max;
helfer[1] = x;
helfer[2] = y;
helfer[3] = G;
helfer[4] = H;
return helfer;
}
public void polygon(int x1, int y1, int x2, int y2, int count, Color color) {
List<Point> points = getPolygon(new Point(x1,y1),new Point(x2,y2),count);
for (int i = 0; i < points.size()-1; i++) {
lineDDA(points.get(i).getX(), points.get(i).getY(), points.get(i+1).getX(), points.get(i+1).getY(), color);
}
}
public void circle(int x1, int y1, int x2, int y2, Color color) {
double r = Vypocty.vypocetVzdalenosti(x1, y1, x2, y2);
r = r * 2;
int x = x1 - ((int) Math.round(r / 2));
int y = y1 - ((int) Math.round(r / 2));
Graphics g = img.getGraphics();
g.setColor(color);
g.drawOval(x, y, (int) r, (int) r);
}
public void circleSegment(int x1, int y1, int x2, int y2, double alpha, Color color) {
double r = Vypocty.vypocetVzdalenosti(x1, y1, x2, y2);
r = r * 2;
int[] bod = circleHelper(x1, y1, r);
Graphics g = img.getGraphics();
g.setColor(color);
g.drawArc(bod[0], bod[1], (int) r, (int) r, 0, (int) alpha);
}
private int[] circleHelper(int x1, int y1, double r) {
int[] bod = new int[2];
bod[0] = x1 - ((int) Math.round(r / 2));
bod[1] = y1 - ((int) Math.round(r / 2));
return bod;
}
}
<file_sep>/src/filler/SeedFiller.java
package filler;
import utils.Renderer;
import java.awt.*;
import drawable.Point;
public class SeedFiller implements Filler {
private Color color;
private Renderer renderer;
private Point seed;
private Color bgColor;
public void setBgColor(Color bgColor) {
this.bgColor = bgColor;
}
public SeedFiller(Renderer renderer, Color color, Point point) {
setRaster(renderer);
setSeed(new Point(point.getX(),point.getY()));
this.color = color;
}
public void setSeed(Point point){
setBgColor(new Color(renderer.getPixel(point.getX(),point.getY())));
this.seed = point;
}
private void seedFill(int startX, int z) {
int x = startX;
int y = z;
int leftX = 0;
int rightX = renderer.getWidth()-1;
for (int i = x; i >= 0; i--) {
leftX = i;
if (renderer.getPixel(i,y) != bgColor.getRGB()){
break;
}
}
for (int i = x; i < renderer.getWidth() ; i++) {
rightX = i;
if (renderer.getPixel(i,y) != bgColor.getRGB()){
break;
}
}
renderer.lineDDA(leftX,y,rightX,y,color);
for (int i = leftX+1; i < rightX-1; i++) {
if (y+1 < renderer.getHeight() && renderer.getPixel(i,(y+1)) == bgColor.getRGB()){
x=i;
seedFill(i,y+1);
}
if (y-1 >=0 && renderer.getPixel(i, y-1) == bgColor.getRGB()){
seedFill(i,y-1);
}
}
}
@Override
public void fill() {
seedFill(seed.getX(),seed.getY());
}
@Override
public int getColor() {
return 0;
}
@Override
public void setColor(Color color) {
this.color = color;
}
@Override
public void setRaster(Renderer renderer) {
this.renderer = renderer;
}
}
<file_sep>/src/masek_PGRF2/main/AppStart.java
package masek_PGRF2.main;
import masek_PGRF2.controller.Controller3D;
import masek_PGRF2.view.PGRFWindow;
import javax.swing.*;
public class AppStart {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
PGRFWindow window = new PGRFWindow();
new Controller3D(window.getRaster());
window.setVisible(true);
});
}
}
|
75ce97f3841d5a60222594a880de4dee1dde1d62
|
[
"Java",
"Text"
] | 11
|
Java
|
Davelek/Grafika1
|
59cb9312201d2362b768d4137088fe03d114ecfc
|
49adaf5a863fbe30753ca6f5ead093f1510e62dc
|
refs/heads/master
|
<file_sep>using System;
using System.Activities.DurableInstancing;
using System.Runtime.DurableInstancing;
using EasyNetQ;
using EasyNetQ.DI;
using EasyNetQ.Wf;
using EasyNetQ.Wf.AutoConsumers;
using Ninject;
namespace ExampleTest
{
class Program
{
private static void Main(string[] args)
{
IKernel kernel = new StandardKernel();
kernel.Bind<InstanceStore>()
.ToMethod(
ctx =>
new SqlWorkflowInstanceStore("Server=.\\SQL2012;Initial Catalog=WorkflowInstances;Integrated Security=SSPI")
{
InstanceCompletionAction = InstanceCompletionAction.DeleteAll,
InstanceLockedExceptionAction = InstanceLockedExceptionAction.AggressiveRetry
})
.InSingletonScope();
RabbitHutch.SetContainerFactory(()=>new NinjectAdapter(kernel));
using (var bus = RabbitHutch.CreateBus("host=localhost;virtualHost=/;username=test;password=<PASSWORD>", (s)=> s.UseWorkflowOrchestration()))
{
bus.SubscribeForOrchestration<ExampleWorkflow>("wf-ExampleWorkflow");
bus.SubscribeConsumer<AdvancedExampleConsumer>("wf-autosubscriber-example");
Console.WriteLine("Bus listening...");
Console.WriteLine();
Console.Write("Enter your name: ");
string name = Console.ReadLine();
bus.Publish(new ExampleMessage() { Name = name}, "ExampleWorkflow");
Console.ReadLine();
}
}
}
}
<file_sep>using System;
using System.Activities;
namespace EasyNetQ.Wf.Activities
{
public sealed class BusSubscribe<TMessage> : NativeActivity<TMessage>, IMessageReceiveActivity
where TMessage:class
{
protected override bool CanInduceIdle
{
get { return true; }
}
protected override void Execute(NativeActivityContext context)
{
var hostBehavior = context.GetExtension<IWorkflowApplicationHostBehavior>();
var bookmarkName = hostBehavior.GetBookmarkNameFromMessageType(typeof (TMessage));
context.CreateBookmark(bookmarkName, OnBookmarkResume);
}
private void OnBookmarkResume(NativeActivityContext context, Bookmark bookmark, object value)
{
var messageBody = (TMessage) value;
Result.Set(context, messageBody);
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
using EasyNetQ.AutoSubscribe;
namespace EasyNetQ.Wf.AutoConsumers
{
public interface IConsumerMessageDispatcher
{
void Consume<TMessage, TConsumer>(TMessage message)
where TMessage : class
where TConsumer : IConsume<TMessage>;
Task ConsumeAsync<TMessage, TConsumer>(TMessage message)
where TMessage : class
where TConsumer : IConsumeAsync<TMessage>;
void ConsumeAdvanced<TMessage, TConsumer>(IMessage<TMessage> message, MessageReceivedInfo info)
where TMessage : class
where TConsumer : IConsumeAdvanced<TMessage>;
Task ConsumeAdvancedAsync<TMessage, TConsumer>(IMessage<TMessage> message, MessageReceivedInfo info)
where TMessage : class
where TConsumer : IConsumeAdvancedAsync<TMessage>;
TResponse Respond<TRequest, TResponse, TConsumer>(TRequest request)
where TRequest : class
where TResponse : class
where TConsumer : IRespond<TRequest, TResponse>;
Task<TResponse> RespondAsync<TRequest, TResponse, TConsumer>(TRequest request)
where TRequest : class
where TResponse : class
where TConsumer : IRespondAsync<TRequest, TResponse>;
}
}<file_sep>using System;
using System.Linq;
using Telerik.OpenAccess;
using Telerik.OpenAccess.Metadata;
namespace EasyNetQ.Wf.DurableInstancing.Data
{
public interface IWorkflowDurableInstancingUnitOfWork : IUnitOfWork
{
IQueryable<DefinitionIdentity> DefinitionIdentities { get; }
IQueryable<Instance> Instances { get; }
IQueryable<LockOwner> LockOwners { get; }
}
public class WorkflowDurableInstancingDataContext : OpenAccessContext, IWorkflowDurableInstancingUnitOfWork
{
private static readonly string DefaultConnectionStringName = "WorkflowDurableInstancingConnection";
private static readonly BackendConfiguration DefaultBackend = GetBackendConfiguration();
private static readonly MetadataSource DefaultMetadataSource = new WorkflowDurableInstancingFluentMetadataSource();
public WorkflowDurableInstancingDataContext() : this(DefaultConnectionStringName, DefaultBackend, DefaultMetadataSource) { }
public WorkflowDurableInstancingDataContext(string connectionString) : this(connectionString, DefaultBackend, DefaultMetadataSource) { }
public WorkflowDurableInstancingDataContext(string connectionString, BackendConfiguration backend, MetadataSource metadataSource)
: base(connectionString, backend, metadataSource)
{
var schemaHandler = GetSchemaHandler();
string script = null;
if (schemaHandler.DatabaseExists())
{
script = schemaHandler.CreateUpdateDDLScript(null);
}
else
{
schemaHandler.CreateDatabase();
script = schemaHandler.CreateDDLScript();
}
if (!String.IsNullOrEmpty(script))
{
schemaHandler.ExecuteDDLScript(script);
}
}
public static BackendConfiguration GetBackendConfiguration()
{
var backendConfig = new BackendConfiguration()
{
Backend = "MsSql",
ProviderName = "System.Data.SqlClient",
};
return backendConfig;
}
public IQueryable<DefinitionIdentity> DefinitionIdentities { get { return this.GetAll<DefinitionIdentity>(); } }
public IQueryable<Instance> Instances { get { return this.GetAll<Instance>(); } }
public IQueryable<LockOwner> LockOwners { get { return this.GetAll<LockOwner>(); } }
}
}<file_sep>using System;
using System.Activities;
using System.Linq;
using System.Reflection;
namespace EasyNetQ.Wf.AutoConsumers
{
[Serializable]
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class CorrelateUsingAttribute : Attribute
{
private static PropertyInfo FindCorrelatesOnProperty(object message, BindingFlags bindingFlags, bool required=true)
{
if (message == null) throw new ArgumentNullException("message");
// inspect for known attribute
foreach (var propertyInfo in message.GetType().GetProperties(bindingFlags))
{
var correlationAttribute = propertyInfo.GetCustomAttributes(typeof(CorrelateUsingAttribute), true).Cast<CorrelateUsingAttribute>().SingleOrDefault();
if (correlationAttribute != null)
{
return propertyInfo;
}
}
if(required)
throw new WorkflowHostException(String.Format("Correlation Key expected but not found on type {0}. Use [CorrelateUsing] attribute to specify a Correlation Key", message.GetType().FullName));
return null;
}
internal static string GetCorrelatesOnValue(object message)
{
var correlatesOnProperty = FindCorrelatesOnProperty(message, BindingFlags.Public | BindingFlags.Instance, required:false);
if (correlatesOnProperty == null)
return null;
return (correlatesOnProperty.GetValue(message
#if NET4
, null
#endif
) as string);
}
internal static bool TryGetCorrelatesOnValue(object message, out string value)
{
value = null;
try
{
value = GetCorrelatesOnValue(message);
if (String.IsNullOrWhiteSpace(value))
{
value = null;
return false;
}
}
catch (Exception)
{
value = null;
return false;
}
return true;
}
internal static string GetMessageCorrelatesOnTopic(object message)
{
string correlatesOnValue = null;
if (TryGetCorrelatesOnValue(message, out correlatesOnValue))
{
return correlatesOnValue.Split(new[] { '|' })[1];
}
return correlatesOnValue;
}
internal static void SetCorrelatesOnValue(object message, Guid workflowInstanceId, string workflowRouteTopic)
{
FindCorrelatesOnProperty(message, BindingFlags.Public | BindingFlags.Instance, required:true).SetValue(message, String.Format("{0}|{1}", workflowInstanceId, workflowRouteTopic)
#if NET4
, null
#endif
);
}
}
}<file_sep>using System;
using System.Xml.Linq;
namespace EasyNetQ.Wf
{
public static class WorkflowNamespaces
{
public static readonly XNamespace Workflow45Namespace = XNamespace.Get("urn:schemas-microsoft-com:System.Activities/4.5/properties");
public static readonly XNamespace Workflow40Namespace = XNamespace.Get("urn:schemas-microsoft-com:System.Activities/4.0/properties");
public static readonly XName WorkflowHostTypePropertyName = Workflow40Namespace.GetName("WorkflowHostType");
public static readonly XName DefinitionIdentityFilterName = Workflow45Namespace.GetName("DefinitionIdentityFilter");
public static readonly XName WorkflowApplicationName = Workflow45Namespace.GetName("WorkflowApplication");
public static readonly XName DefinitionIdentitiesName = Workflow45Namespace.GetName("DefinitionIdentities");
}
}<file_sep>using System;
using System.Activities;
using System.Collections.Generic;
using System.IO;
namespace EasyNetQ.Wf
{
public interface IWorkflowDefinitionRepository
{
IEnumerable<IWorkflowDefinition> Get(WorkflowIdentity identity);
}
public interface IWorkflowDefinition
{
string Name { get; }
Activity RootActivity { get; }
WorkflowIdentity Identity { get; }
string Hosts { get; }
}
#if NET4
// Shim class definition for System.Activities.WorkflowIdentity
// This does not mean that side-by-side versioning will be available in WF4
public class WorkflowIdentity
{
public string Name {get;set;}
public string Package {get;set;}
public Version Version {get;set;}
}
#endif
}<file_sep>using System;
using System.Runtime.Serialization;
namespace EasyNetQ.Wf
{
[Serializable]
public class WorkflowHostException : ApplicationException
{
public WorkflowHostException(string message) : base(message) { }
public WorkflowHostException(string message, Exception innerException) : base(message, innerException) { }
public WorkflowHostException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}<file_sep>using System;
using System.Activities;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.DurableInstancing;
using System.Text;
using System.Threading.Tasks;
using EasyNetQ.Consumer;
using EasyNetQ.FluentConfiguration;
using EasyNetQ.Wf.Activities;
using EasyNetQ.Wf.AutoConsumers;
using EasyNetQ.NonGeneric;
using EasyNetQ.Producer;
using EasyNetQ.Topology;
namespace EasyNetQ.Wf
{
public static class WorkflowBusExtensions
{
#region WorkflowApplicationHost Registry
private readonly static List<IWorkflowApplicationHost> _workflowApplicationHostRegistry = new List<IWorkflowApplicationHost>();
public static IEnumerable<IWorkflowApplicationHost> GetWorkflowApplicationHosts(this IBus bus)
{
return _workflowApplicationHostRegistry.ToArray();
}
internal static void RemoveWorkflowApplicationHost(IWorkflowApplicationHost host)
{
_workflowApplicationHostRegistry.Remove(host);
}
#endregion
public static void UseWorkflowOrchestration(this IServiceRegister serviceRegister)
{
// register default components
serviceRegister.RegisterConsumers(); // TODO: RegisterConsumers may not be needed here
serviceRegister.Register<IWorkflowApplicationHostInstanceStore, DefaultWorkflowApplicationHostInstanceStore>();
serviceRegister.Register<IWorkflowApplicationHostPerformanceMonitor, DefaultWorkflowApplicationHostPerformanceMonitor>();
serviceRegister.Register<IWorkflowApplicationHost, DefaultWorkflowApplicationHost>();
}
#region Publish With Workflow Correlation methods
public static void PublishEx<TMessage>(this IBus bus, TMessage message, string topic = null) where TMessage : class
{
PublishEx(bus, typeof(TMessage), message, topic);
}
public static Task PublishExAsync<TMessage>(this IBus bus, TMessage message, string topic = null) where TMessage : class
{
return PublishExAsync(bus, typeof(TMessage), message, topic);
}
public static void PublishEx(this IBus bus, Type messageType, object message, string topic = null)
{
// Find the correlation property
topic = topic ?? (CorrelateUsingAttribute.GetMessageCorrelatesOnTopic(message) ?? AdvancedBusConsumerExtensions.GetTopicForMessage(message));
// Sync publish
if (!String.IsNullOrWhiteSpace(topic))
bus.Publish(message.GetType(), message, topic);
else
bus.Publish(message.GetType(), message);
}
public static Task PublishExAsync(this IBus bus, Type messageType, object message, string topic = null)
{
// Find the correlation property
topic = topic ?? (CorrelateUsingAttribute.GetMessageCorrelatesOnTopic(message) ?? AdvancedBusConsumerExtensions.GetTopicForMessage(message));
// Async publish
if (!String.IsNullOrWhiteSpace(topic))
return bus.PublishAsync(message.GetType(), message, topic);
return bus.PublishAsync(message.GetType(), message);
}
#endregion
#region SubscribeWorkflow methods
private static void SubscribeForOrchestration(this IBus bus, IDictionary<WorkflowIdentity, Activity> workflowVersionMap, string subscriptionId, Func<IWorkflowApplicationHost> createWorkflowHost, Action<ISubscriptionConfiguration> config = null, bool subscribeAsync=true, bool autoStart=true)
{
if (workflowVersionMap == null || !workflowVersionMap.Any()) throw new ArgumentNullException("workflowActivity");
if (String.IsNullOrWhiteSpace(subscriptionId)) throw new ArgumentNullException("subscriptionId");
Activity workflowActivity = workflowVersionMap.OrderByDescending(item => item.Key.Version).First().Value;
Action<ISubscriptionConfiguration> subscriptionConfig = (s) =>
{
// allow customized configuration if it is passed
if (config != null)
config(s);
// assign the Workflow Topic routing key
s.WithTopic(workflowActivity.GetType().Name);
};
// NOTE: Convention for the RootWorkflowActivity InArgument is InArgument<TMessage>
var initialArgumentInfo = GetInArgumentsFromActivity(workflowActivity).SingleOrDefault();
if (initialArgumentInfo == null)
{
// convention is that a Workflow must have a single InArgument<TMessage> that will be used to initiate the workflow
throw new InvalidOperationException(String.Format("Workflow type {0} cannot be subscribed without an InArgument with a valid message type", workflowActivity.GetType().FullName));
}
// create a new WorkflowApplicationHost as a consumer
var workflowApplicationHost = createWorkflowHost();
workflowApplicationHost.Initialize(workflowVersionMap);
// add the WorkflowApplicationHost to the registry
_workflowApplicationHostRegistry.Add(workflowApplicationHost);
// Advanced Bus Method
var queue = bus.DeclareMessageQueue(workflowActivity.GetType(), subscriptionId);
bus.Advanced.Consume(queue, handlers =>
{
var logger = bus.Advanced.Container.Resolve<IEasyNetQLogger>();
logger.InfoWrite("Workflow {0} subscribing to messages using queue {1}:", workflowActivity.GetType().Name, queue.Name);
logger.InfoWrite("{0} on topic {1}", initialArgumentInfo.InArgumentType.FullName, workflowActivity.GetType().Name);
// declare and bind the message exchange to the workflow queue
var exchange = bus.DeclareMessageExchange(initialArgumentInfo.InArgumentType);
bus.BindMessageExchangeToQueue(exchange, queue, subscriptionConfig);
// add an initiated by handler
if (subscribeAsync)
handlers.Add(initialArgumentInfo.InArgumentType, (msg,info)=> workflowApplicationHost.OnDispatchMessageAsync(msg.GetBody()));
else
handlers.Add(initialArgumentInfo.InArgumentType, (msg, info) => workflowApplicationHost.OnDispatchMessage(msg.GetBody()));
foreach (var activity in GetMatchingActivities<IMessageReceiveActivity>(workflowActivity))
{
var activityType = activity.GetType();
var messageType = activityType.GetGenericArguments()[0];
logger.InfoWrite("{0} on topic {1}", messageType.FullName, workflowActivity.GetType().Name);
// declare and bind the message exchange to the workflow queue
exchange = bus.DeclareMessageExchange(messageType);
bus.BindMessageExchangeToQueue(exchange, queue, subscriptionConfig);
// add consumed by handler
if (subscribeAsync)
handlers.Add(messageType, (msg, info) => workflowApplicationHost.OnDispatchMessageAsync(msg.GetBody()));
else
handlers.Add(messageType, (msg, info) => workflowApplicationHost.OnDispatchMessage(msg.GetBody()));
}
});
if (autoStart)
{
workflowApplicationHost.Start();
}
}
private static IHandlerRegistration Add(this IHandlerRegistration handlerRegistration, Type messageType, Action<IMessage,MessageReceivedInfo> handler)
{
var addHandlerMethod = handlerRegistration.GetType().GetMethods().SingleOrDefault(x => x.Name == "Add" && x.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof (Action<,>));
if (addHandlerMethod == null)
{
throw new EasyNetQException("API change? IHandlerRegistration.Add(Action<IMessage<T>,MessageReceivedInfo> handler) method not found on IBus.Advanced");
}
return (IHandlerRegistration) addHandlerMethod.MakeGenericMethod(messageType).Invoke(handlerRegistration, new object[] {handler});
}
private static IHandlerRegistration Add(this IHandlerRegistration handlerRegistration, Type messageType, Func<IMessage, MessageReceivedInfo, Task> handler)
{
var addHandlerMethod = handlerRegistration.GetType().GetMethods().SingleOrDefault(x => x.Name == "Add" && x.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(Func<,,>));
if (addHandlerMethod == null)
{
throw new EasyNetQException("API change? IHandlerRegistration.Add(Func<IMessage<T>,MessageReceivedInfo,Task> handler) method not found on IBus.Advanced");
}
return (IHandlerRegistration)addHandlerMethod.MakeGenericMethod(messageType).Invoke(handlerRegistration, new object[] { handler });
}
public static void SubscribeForOrchestration<TWorkflow>(this IBus bus, string subscriptionId, Action<ISubscriptionConfiguration> subscriptionConfig = null, bool subscribeAsync = true, bool autoStart = true)
where TWorkflow : Activity, new()
{
TWorkflow workflowActivity = new TWorkflow();
bus.SubscribeForOrchestration(
new Dictionary<WorkflowIdentity, Activity>() { { null, workflowActivity} },
subscriptionId,
() => bus.Advanced.Container.Resolve<IWorkflowApplicationHost>(),
subscriptionConfig,
subscribeAsync,
autoStart
);
}
public static void SubscribeForOrchestration(this IBus bus, WorkflowIdentity workflowIdentity, string subscriptionId, Action<ISubscriptionConfiguration> subscriptionConfig = null, bool subscribeAsync = true, bool autoStart = true)
{
var repository = bus.Advanced.Container.Resolve<IWorkflowDefinitionRepository>();
if (repository == null) throw new NullReferenceException("An IWorkflowDefinitionRepository cannot be found");
// support for Workflow Side-By-Side Versioning (see: https://msdn.microsoft.com/en-us/library/system.activities.workflowidentity(v=vs.110).aspx)
var workflowMap = new Dictionary<WorkflowIdentity, Activity>();
var workflowDefinitions = repository.Get(workflowIdentity);
foreach (var definition in workflowDefinitions)
{
workflowMap.Add(definition.Identity, definition.RootActivity);
}
if(!workflowMap.Any()) throw new NullReferenceException(String.Format("A valid workflow activity [{0}] cannot be loaded", workflowIdentity.Name));
bus.SubscribeForOrchestration(
workflowMap,
subscriptionId,
() => bus.Advanced.Container.Resolve<IWorkflowApplicationHost>(),
subscriptionConfig,
subscribeAsync,
autoStart
);
}
#endregion
#region Activity Helper methods
internal class InArgumentInfo
{
public string InArgumentName { get; set; }
public bool InArgumentIsRequired { get; set; }
public Type InArgumentType { get; set; }
}
internal static IEnumerable<InArgumentInfo> GetInArgumentsFromActivity(Activity activity)
{
var args = new List<InArgumentInfo>();
var properties = activity.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => typeof (InArgument).IsAssignableFrom(p.PropertyType))
.ToList();
foreach (var property in properties)
{
if (!property.PropertyType.IsGenericType) continue;
bool isRequired = property
.GetCustomAttributes(false)
.OfType<RequiredArgumentAttribute>()
.Any();
Type argumentType = property.PropertyType.GetGenericArguments()[0];
args.Add(new InArgumentInfo
{
InArgumentName = property.Name,
InArgumentIsRequired = isRequired,
InArgumentType = argumentType
});
}
return args;
}
private static IEnumerable<Activity> GetMatchingActivities<T>(Activity rootActivity)
{
var activities = new List<Activity>();
activities.AddActivities<T>(rootActivity);
return activities;
}
/// <summary>
/// Recursively inspect nodes of an Activity, and Add matching Activities of type T to an IList
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="root"></param>
private static void AddActivities<T>(this IList<Activity> items, Activity root)
{
if (root is T) items.Add(root);
var nodes = WorkflowInspectionServices.GetActivities(root);
foreach (var c1 in nodes)
{
if (c1 != root)
{
items.AddActivities<T>(c1);
}
}
}
#endregion
}
}<file_sep>using System;
namespace EasyNetQ.Wf.AutoConsumers
{
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class QueueAttribute : Attribute
{
public string Name { get; set; }
public QueueAttribute(string queue)
{
Name = queue;
}
}
}<file_sep>using System;
using System.Threading.Tasks;
namespace EasyNetQ.Wf.AutoConsumers
{
public interface IConsumeAdvanced<in TMessage> where TMessage : class
{
void Consume(IMessage<TMessage> messageContext, MessageReceivedInfo messageInfo);
}
public interface IConsumeAdvancedAsync<in TMessage> where TMessage : class
{
Task ConsumeAsync(IMessage<TMessage> messageContext, MessageReceivedInfo messageInfo);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Telerik.OpenAccess.Metadata.Fluent;
namespace EasyNetQ.Wf.DurableInstancing.Data
{
public class WorkflowDurableInstancingFluentMetadataSource : FluentMetadataSource
{
protected override IList<MappingConfiguration> PrepareMapping()
{
var configurations = new List<MappingConfiguration>();
var instanceConfig = new MappingConfiguration<Instance>();
configurations.Add(instanceConfig);
var definitionIdentityConfig = new MappingConfiguration<DefinitionIdentity>();
configurations.Add(definitionIdentityConfig);
var lockOwnerConfig = new MappingConfiguration<LockOwner>();
configurations.Add(lockOwnerConfig);
return configurations;
}
}
}
<file_sep># EasyNetQ.Wf
EasyNetQ extensions for Windows Workflow
TODO: Examples and documentation coming soon
<file_sep>using System;
namespace EasyNetQ.Wf
{
/// <summary>
/// Interface for monitoring performance of WorkflowApplicationHosts
/// </summary>
public interface IWorkflowApplicationHostPerformanceMonitor
{
void MessageConsumed(string workflowName);
void WorkflowFaulted(string workflowName);
void WorkflowStarted(string workflowName);
void WorkflowResumed(string workflowName);
void WorkflowRunning(string workflowName);
void WorkflowCompleted(string workflowName);
void WorkflowDuration(string workflowName, TimeSpan duration);
}
public class DefaultWorkflowApplicationHostPerformanceMonitor : IWorkflowApplicationHostPerformanceMonitor
{
public DefaultWorkflowApplicationHostPerformanceMonitor() { }
public virtual void MessageConsumed(string workflowName) { }
public virtual void WorkflowFaulted(string workflowName) { }
public virtual void WorkflowStarted(string workflowName) { }
public virtual void WorkflowResumed(string workflowName) { }
public virtual void WorkflowRunning(string workflowName) { }
public virtual void WorkflowCompleted(string workflowName) { }
public virtual void WorkflowDuration(string workflowName, TimeSpan duration) { }
}
}<file_sep>using System;
using System.Activities;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace EasyNetQ.Wf
{
public interface IWorkflowApplicationHost : IDisposable
{
event EventHandler<RequestAdditionalTimeEventArgs> RequestAdditionalTime;
IWorkflowApplicationHostInstanceStore WorkflowInstanceStore { get; }
Activity WorkflowDefinition { get; }
void Initialize(IDictionary<WorkflowIdentity, Activity> workflowVersionMap);
bool IsRunning { get; }
void Start();
void Stop();
IEnumerable<ISubscriptionResult> GetSubscriptions();
void AddSubscription(ISubscriptionResult subscription);
void CancelSubscription(ISubscriptionResult subscription);
void OnDispatchMessage(object message);
Task OnDispatchMessageAsync(object message);
}
public sealed class RequestAdditionalTimeEventArgs : EventArgs
{
public TimeSpan Timeout { get; set; }
public RequestAdditionalTimeEventArgs(TimeSpan timeout)
{
Timeout = timeout;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EasyNetQ.Wf.DurableInstancing
{
class InstanceStoreLock
{
private object _syncLock = new object();
// Tasks to Handle while Lock is Valid
private Task LockRenewalTask { get; set; }
}
}
<file_sep>using System;
using System.Activities.DurableInstancing;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.DurableInstancing;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using EasyNetQ.Wf.DurableInstancing.Data;
using Telerik.OpenAccess;
namespace EasyNetQ.Wf.DurableInstancing
{
public class TelerikDataAccessWorkflowInstanceStore : InstanceStore
{
private static readonly object _syncLock = new object();
private readonly WorkflowInstanceCommands Commands;
private readonly IEasyNetQLogger Log;
public TelerikDataAccessWorkflowInstanceStore(IEasyNetQLogger logger, WorkflowInstanceCommands commands) : base()
{
Log = logger;
Commands = commands;
}
protected override void OnFreeInstanceHandle(InstanceHandle instanceHandle, object userContext)
{
base.OnFreeInstanceHandle(instanceHandle, userContext);
}
protected override object OnNewInstanceHandle(InstanceHandle instanceHandle)
{
return base.OnNewInstanceHandle(instanceHandle);
}
protected override IAsyncResult BeginTryCommand(InstancePersistenceContext context, InstancePersistenceCommand command, TimeSpan timeout, AsyncCallback callback, object state)
{
if(context == null) throw new ArgumentNullException("context");
if(command == null) throw new ArgumentNullException("command");
// Log which commands we are receiving
Debug.WriteLine("InstanceStore::BeginTryCommand::{0} received", command.GetType().Name);
IAsyncResult result = null;
// validate the store lock
if (command is CreateWorkflowOwnerCommand)
{
result = CreateWorkflowOwner(context, (CreateWorkflowOwnerCommand) command, timeout, callback, state);
}
if (result == null)
{
// Log which commands we are not handling
Debug.WriteLine("InstanceStore::BeginTryCommand::{0} was not implemented", command.GetType().Name);
// The base.BeginTryCommand will return a false (unhandled) return value
return base.BeginTryCommand(context, command, timeout, callback, state);
}
return result;
}
private IAsyncResult CreateWorkflowOwner(InstancePersistenceContext context, CreateWorkflowOwnerCommand command, TimeSpan timeout, AsyncCallback callback, object state)
{
var owner = new LockOwner()
{
Id = Guid.NewGuid(),
};
// TODO: map fields into the owner entity
Debug.WriteLine("CreateWorkflowOwner::InstanceOwnerMetadata: ");
Debug.Indent();
foreach (var key in command.InstanceOwnerMetadata.Keys)
{
Debug.WriteLine("[{0}]=[{1}]", key, command.InstanceOwnerMetadata[key].Value);
}
Debug.Unindent();
//context.BindInstanceOwner(owner.Id, owner.Id);
//context.BindEvent(HasRunnableWorkflowEvent.Value);
//return new CompletedAsyncResult(callback, state);
return null;
}
protected override bool EndTryCommand(IAsyncResult result)
{
var handledCommand = result as CompletedAsyncResult;
if (handledCommand == null)
return base.EndTryCommand(result);
// complete the handled command
CompletedAsyncResult.End(result);
return true;
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
using EasyNetQ.AutoSubscribe;
namespace EasyNetQ.Wf.AutoConsumers
{
public class DefaultConsumerMessageDispatcher : IConsumerMessageDispatcher
{
protected virtual TConsumer GetConsumer<TConsumer>()
{
TConsumer consumer = (TConsumer)Activator.CreateInstance(typeof(TConsumer));
return consumer;
}
public virtual void Consume<TMessage, TConsumer>(TMessage message)
where TMessage : class
where TConsumer : IConsume<TMessage>
{
var consumer = (IConsume<TMessage>)GetConsumer<TConsumer>();
consumer.Consume(message);
}
public virtual Task ConsumeAsync<TMessage, TConsumer>(TMessage message)
where TMessage : class
where TConsumer : IConsumeAsync<TMessage>
{
var consumer = (IConsumeAsync<TMessage>)GetConsumer<TConsumer>();
return consumer.Consume(message);
}
public virtual void ConsumeAdvanced<TMessage, TConsumer>(IMessage<TMessage> message, MessageReceivedInfo info)
where TMessage : class
where TConsumer : IConsumeAdvanced<TMessage>
{
var consumer = (IConsumeAdvanced<TMessage>)GetConsumer<TConsumer>();
consumer.Consume(message, info);
}
public virtual Task ConsumeAdvancedAsync<TMessage, TConsumer>(IMessage<TMessage> message, MessageReceivedInfo info)
where TMessage : class
where TConsumer : IConsumeAdvancedAsync<TMessage>
{
var consumer = (IConsumeAdvancedAsync<TMessage>)GetConsumer<TConsumer>();
return consumer.ConsumeAsync(message, info);
}
public virtual TResponse Respond<TRequest, TResponse, TConsumer>(TRequest request)
where TRequest : class
where TResponse : class
where TConsumer: IRespond<TRequest,TResponse>
{
var consumer = (IRespond<TRequest,TResponse>)GetConsumer<TConsumer>();
return consumer.Respond(request);
}
public virtual Task<TResponse> RespondAsync<TRequest, TResponse, TConsumer>(TRequest request)
where TRequest : class
where TResponse : class
where TConsumer : IRespondAsync<TRequest, TResponse>
{
var consumer = (IRespondAsync<TRequest, TResponse>)GetConsumer<TConsumer>();
return consumer.Respond(request);
}
}
}<file_sep>using System;
using System.Threading.Tasks;
namespace EasyNetQ.Wf.AutoConsumers
{
public interface IRespond<in TRequest, out TResponse>
where TRequest : class
where TResponse : class
{
TResponse Respond(TRequest request);
}
public interface IRespondAsync<in TRequest, TResponse>
where TRequest : class
where TResponse : class
{
Task<TResponse> Respond(TRequest request);
}
}<file_sep>using System;
using System.Activities;
using System.Activities.DurableInstancing;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.DurableInstancing;
using System.Xml.Linq;
namespace EasyNetQ.Wf
{
public interface IWorkflowApplicationHostInstanceStore : IDisposable
{
InstanceStore Store { get; }
void SetDefaultWorkflowInstanceOwner(XName workflowHostTypeName, IEnumerable<WorkflowIdentity> workflowIdentities);
bool TryRenewDefaultWorkflowInstanceOwner();
void ReleaseDefaultWorkflowInstanceOwner();
IEnumerable<InstancePersistenceEvent> WaitForEvents(TimeSpan timeout);
}
public class DefaultWorkflowApplicationHostInstanceStore : IWorkflowApplicationHostInstanceStore
{
private object _syncLock = new object();
private readonly InstanceStore _instanceStore;
private InstanceHandle _ownerInstanceHandle;
private TimeSpan _defaultTimeout = TimeSpan.FromSeconds(10);
private XName _workflowHostTypeName;
private IEnumerable<WorkflowIdentity> _workflowIdentities;
public InstanceStore Store { get { return _instanceStore; } }
public DefaultWorkflowApplicationHostInstanceStore(InstanceStore instanceStore)
{
if(instanceStore == null) throw new ArgumentNullException("instanceStore");
_instanceStore = instanceStore;
}
public virtual TimeSpan DefaultTimeout
{
get { return _defaultTimeout; }
}
public virtual InstanceView ExecuteCommand(InstancePersistenceCommand command, TimeSpan timeout)
{
TryRenewInstanceHandle(ref _ownerInstanceHandle);
return ExecuteCommandInternal(_ownerInstanceHandle, command, timeout);
}
public virtual void SetDefaultWorkflowInstanceOwner(XName workflowHostTypeName, IEnumerable<WorkflowIdentity> workflowIdentities)
{
if (Store.DefaultInstanceOwner == null || (_ownerInstanceHandle == null || _ownerInstanceHandle.IsValid == false))
{
lock (_syncLock)
{
if (Store.DefaultInstanceOwner == null ||
(_ownerInstanceHandle == null || _ownerInstanceHandle.IsValid == false))
{
_workflowHostTypeName = workflowHostTypeName;
_workflowIdentities = workflowIdentities;
TryRenewInstanceHandle(ref _ownerInstanceHandle);
InstancePersistenceCommand createOwnerCmd = null;
#if NET4
createOwnerCmd = new CreateWorkflowOwnerCommand();
((CreateWorkflowOwnerCommand)createOwnerCmd).InstanceOwnerMetadata.Add(WorkflowNamespaces.WorkflowHostTypePropertyName, new InstanceValue(workflowHostTypeName));
#else
if (workflowIdentities == null)
{
createOwnerCmd = new CreateWorkflowOwnerCommand();
((CreateWorkflowOwnerCommand) createOwnerCmd).InstanceOwnerMetadata.Add(WorkflowNamespaces.WorkflowHostTypePropertyName, new InstanceValue(workflowHostTypeName));
}
else
{
// support workflow versioning
createOwnerCmd = new CreateWorkflowOwnerWithIdentityCommand();
((CreateWorkflowOwnerWithIdentityCommand)createOwnerCmd).InstanceOwnerMetadata.Add(WorkflowNamespaces.WorkflowHostTypePropertyName, new InstanceValue(workflowHostTypeName));
((CreateWorkflowOwnerWithIdentityCommand)createOwnerCmd).InstanceOwnerMetadata.Add(WorkflowNamespaces.DefinitionIdentityFilterName, new InstanceValue(WorkflowIdentityFilter.Any));
((CreateWorkflowOwnerWithIdentityCommand)createOwnerCmd).InstanceOwnerMetadata.Add(WorkflowNamespaces.DefinitionIdentitiesName, new InstanceValue(workflowIdentities.ToList()));
}
#endif
Store.DefaultInstanceOwner = ExecuteCommand(createOwnerCmd, DefaultTimeout).InstanceOwner;
}
}
}
}
public virtual IEnumerable<InstancePersistenceEvent> WaitForEvents(TimeSpan timeout)
{
if (!TryRenewDefaultWorkflowInstanceOwner()) return null;
try
{
return Store.WaitForEvents(_ownerInstanceHandle, timeout);
}
catch (OperationCanceledException)
{
// instance handle most likely has been invalidated due to lost connection with MS SQL Server
}
catch (TimeoutException)
{
// no waiting instances within the timeout period
}
return null;
}
public virtual void ReleaseDefaultWorkflowInstanceOwner()
{
if (Store.DefaultInstanceOwner == null) return;
try
{
ExecuteCommand(new DeleteWorkflowOwnerCommand(), DefaultTimeout);
}
catch (Exception)
{
// instance handle could already be invalid
}
finally
{
Store.DefaultInstanceOwner = null;
_ownerInstanceHandle?.Free();
_ownerInstanceHandle = null;
}
}
public void Dispose()
{
ReleaseDefaultWorkflowInstanceOwner();
}
#region Helper methods
private InstanceView ExecuteCommandInternal(InstanceHandle handle, InstancePersistenceCommand command, TimeSpan timeout)
{
return Store.Execute(handle, command, timeout);
}
public bool TryRenewDefaultWorkflowInstanceOwner()
{
try
{
SetDefaultWorkflowInstanceOwner(_workflowHostTypeName, _workflowIdentities);
return true;
}
catch (InvalidOperationException)
{
ReleaseDefaultWorkflowInstanceOwner();
}
return false;
}
private void TryRenewInstanceHandle(ref InstanceHandle instanceHandle)
{
if (instanceHandle == null || !instanceHandle.IsValid)
{
// free the old instance handle
instanceHandle?.Free();
instanceHandle = Store.CreateInstanceHandle();
}
}
#endregion
}
}<file_sep>using System;
using System.Activities;
using System.Diagnostics;
using System.IO;
using System.Runtime.DurableInstancing;
using System.Threading;
using EasyNetQ;
using EasyNetQ.AutoSubscribe;
using EasyNetQ.Wf;
using EasyNetQ.Wf.AutoConsumers;
namespace ExampleTest
{
public class IWorkflowMessage { }
public class ExampleMessage
{
public string Name { get; set; }
}
public class ExampleMessageRequest
{
public string Name { get; set; }
}
public class ExampleMessageResponse
{
public Guid WorkflowId { get; set; }
}
public class ChatMessage
{
public string Message { get; set; }
}
public class ExampleConsumer :
IConsume<ExampleMessage>
{
public void Consume(ExampleMessage message)
{
throw new NotImplementedException();
}
}
public class AdvancedExampleConsumer :
IConsumeAdvanced<ExampleMessageRequest>
{
private readonly IBus _bus;
public AdvancedExampleConsumer(IBus bus)
{
_bus = bus;
}
public void Consume(IMessage<ExampleMessage> message, MessageReceivedInfo info)
{
Console.WriteLine("AdvancedExampleConsumer::Consume<ExampleMessage>");
}
public void Consume(IMessage<ExampleMessageRequest> messageContext, MessageReceivedInfo messageInfo)
{
Console.WriteLine("AdvancedExampleConsumer::Consume<ExampleMessage>");
// send back a message
//_bus.PublishEx(messageContext, new ExampleMessageResponse());
}
}
public class ExampleResponder :
IConsume<ChatMessage>,
IRespond<ExampleMessageRequest, ExampleMessageResponse>
{
public ExampleResponder(IEasyNetQLogger logger)
{
}
public ExampleMessageResponse Respond(ExampleMessageRequest request)
{
throw new NotImplementedException();
}
public void Consume(ChatMessage message)
{
throw new NotImplementedException();
}
}
}<file_sep>using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using EasyNetQ.Consumer;
using EasyNetQ.FluentConfiguration;
using EasyNetQ.Producer;
using EasyNetQ.Topology;
namespace EasyNetQ.Wf.AutoConsumers
{
public static class AdvancedBusConsumerExtensions
{
public static void RegisterConsumers(this IServiceRegister serviceRegister)
{
// TODO: use EasyNetQ methods for AutoSubscription
serviceRegister.Register<IConsumerMessageDispatcher, DefaultConsumerMessageDispatcher>();
}
#region Topic Based Attribute Routing
internal static string GetTopicForMessage(object message)
{
string topic = null;
TryGetTopicForMessageValue(message, out topic);
return topic;
}
private static bool TryGetTopicForMessageValue(object message, out string value)
{
if(message == null) throw new ArgumentNullException("message");
value = null;
var topicAttribute = message.GetType().GetCustomAttributes(typeof (OnTopicAttribute), false).Cast<OnTopicAttribute>().SingleOrDefault();
if (topicAttribute != null && !String.IsNullOrWhiteSpace(topicAttribute.Name))
{
value = topicAttribute.Name;
return true;
}
return false;
}
#endregion
#region Declare Exchange and Queue helper methods
internal static IExchange DeclareMessageExchange(this IBus bus, Type messageType)
{
var conventions = bus.Advanced.Container.Resolve<IConventions>();
var exchangeName = conventions.ExchangeNamingConvention(messageType);
var exchange = bus.Advanced.ExchangeDeclare(exchangeName, ExchangeType.Topic);
return exchange;
}
internal static IQueue DeclareMessageQueue(this IBus bus, Type messageType, string subscriptionId, Action<ISubscriptionConfiguration> configAction = null)
{
var conventions = bus.Advanced.Container.Resolve<IConventions>();
var connectionConfig = bus.Advanced.Container.Resolve<ConnectionConfiguration>();
var subscriptionConfig = new SubscriptionConfiguration(connectionConfig.PrefetchCount);
if (configAction != null)
{
configAction(subscriptionConfig);
}
var queueName = conventions.QueueNamingConvention(messageType, subscriptionId);
var queue = bus.Advanced.QueueDeclare(queueName, autoDelete: subscriptionConfig.AutoDelete, exclusive:subscriptionConfig.IsExclusive);
return queue;
}
internal static void BindMessageExchangeToQueue(this IBus bus, IExchange exchange, IQueue queue, Action<ISubscriptionConfiguration> configAction = null)
{
var connectionConfig = bus.Advanced.Container.Resolve<ConnectionConfiguration>();
var subscriptionConfig = new SubscriptionConfiguration(connectionConfig.PrefetchCount);
if (configAction != null)
{
configAction(subscriptionConfig);
}
foreach (var topic in subscriptionConfig.Topics.DefaultIfEmpty("#"))
{
bus.Advanced.Bind(exchange, queue, topic);
}
}
#endregion
public static IDisposable Subscribe<T>(this IBus bus, string subscriptionId, Action<IMessage<T>,MessageReceivedInfo> onMessage)
where T:class
{
return bus.Subscribe(subscriptionId, onMessage, x => { });
}
public static IDisposable Subscribe<T>(this IBus bus, string subscriptionId,
Action<IMessage<T>, MessageReceivedInfo> onMessage, Action<ISubscriptionConfiguration> configure)
where T : class
{
return bus.SubscribeAsync<T>(subscriptionId, (msg,info) =>
{
var tcs = new TaskCompletionSource<object>();
try
{
onMessage(msg, info);
tcs.SetResult(null);
}
catch (Exception exception)
{
tcs.SetException(exception);
}
return tcs.Task;
},
configure);
}
public static IDisposable SubscribeAsync<T>(this IBus bus, string subscriptionId, Func<IMessage<T>, MessageReceivedInfo, Task> onMessage)
where T : class
{
return bus.SubscribeAsync(subscriptionId, onMessage, x => { });
}
public static IDisposable SubscribeAsync<T>(this IBus bus, string subscriptionId, Func<IMessage<T>, MessageReceivedInfo, Task> onMessage, Action<ISubscriptionConfiguration> configAction=null)
where T : class
{
var connectionConfig = bus.Advanced.Container.Resolve<ConnectionConfiguration>();
var subscriptionConfig = new SubscriptionConfiguration(connectionConfig.PrefetchCount);
if (configAction != null)
{
configAction(subscriptionConfig);
}
var exchange = bus.DeclareMessageExchange(typeof(T));
var queue = bus.DeclareMessageQueue(typeof (T), subscriptionId, configAction);
bus.BindMessageExchangeToQueue(exchange, queue, configAction);
return bus.Advanced.Consume<T>(queue, onMessage, x => x.WithPriority(subscriptionConfig.Priority));
}
public static void SubscribeConsumer<TConsumer>(this IBus bus, string subscriptionId) where TConsumer : class
{
var messageDispatcher = bus.Advanced.Container.Resolve<IConsumerMessageDispatcher>();
// TODO: AutoSubscribeConsumer - subscribe using EasyNetQ.IConsume interface and EasyNetQ.IConsumeAsync
AutoSubscribeConsumerAdvanced<TConsumer>(bus, subscriptionId, messageDispatcher);
AutoSubscribeResponder<TConsumer>(bus, messageDispatcher, typeof (IRespond<,>), "Respond", "Respond",
typeof (Func<,>),
(requestType, responseType) => typeof (Func<,>).MakeGenericType(requestType, responseType));
AutoSubscribeResponder<TConsumer>(bus, messageDispatcher, typeof(IRespondAsync<,>), "RespondAsync", "RespondAsync",
typeof(Func<,>),
(requestType, responseType) => typeof(Func<,>).MakeGenericType(requestType, typeof(Task<>).MakeGenericType(responseType)));
}
private static void AutoSubscribeConsumerAdvanced<TConsumer>(IBus bus, string subscriptionId, IConsumerMessageDispatcher dispatcher) where TConsumer : class
{
var consumerType = typeof(TConsumer);
// IConsumeAdvanced
var consumeMessages =
consumerType.GetInterfaces()
.Where(x => x.IsInterface && x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IConsumeAdvanced<>))
.ToArray();
// IConsumeAdvancedAsync
var consumeAsyncMessages =
consumerType.GetInterfaces()
.Where(x => x.IsInterface && x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IConsumeAdvancedAsync<>))
.ToArray();
if (consumeMessages.Any() || consumeAsyncMessages.Any())
{
var conventions = bus.Advanced.Container.Resolve<IConventions>();
var publishExchangeDeclareStrategy = bus.Advanced.Container.Resolve<IPublishExchangeDeclareStrategy>();
var queue = bus.DeclareMessageQueue(typeof (TConsumer), subscriptionId, null);
var connectionConfig = bus.Advanced.Container.Resolve<ConnectionConfiguration>();
var subscriptionConfig = new SubscriptionConfiguration(connectionConfig.PrefetchCount);
bus.Advanced.Consume(queue, handlers =>
{
// IConsumeAdvanced
foreach (var consumeMessage in consumeMessages)
{
#if NET4
var genericTypeArgs = consumeMessage.GetGenericArguments().Where(t => !t.IsGenericParameter).ToArray();
var messageType = genericTypeArgs[0];
#else
var messageType = consumeMessage.GenericTypeArguments[0];
#endif
var exchange = bus.DeclareMessageExchange(messageType);
bus.BindMessageExchangeToQueue(exchange, queue, null);
var dispatchMethodInfo = dispatcher.GetType()
.GetMethod("ConsumeAdvanced", BindingFlags.Instance | BindingFlags.Public)
.MakeGenericMethod(messageType, typeof(TConsumer));
var actionMethodType = typeof(Action<,>).MakeGenericType(typeof(IMessage<>).MakeGenericType(messageType), typeof(MessageReceivedInfo));
var onMessageDelegate = Delegate.CreateDelegate(actionMethodType, dispatcher, dispatchMethodInfo);
// Add<T>(Action<IMessage<T>, MessageReceivedInfo> handler)
var addHandlerMethodInfo = typeof (IHandlerRegistration).GetMethods()
.First(x => x.Name == "Add" && x.IsGenericMethod && x.GetParameters().Count() > 0 &&
x.GetParameters()[0].ParameterType.GetGenericTypeDefinition() ==
typeof (Action<,>))
.MakeGenericMethod(messageType);
addHandlerMethodInfo.Invoke(handlers, new object[] {onMessageDelegate});
}
// IConsumeAdvancedAsync
foreach (var consumeMessage in consumeAsyncMessages)
{
#if NET4
var genericTypeArgs = consumeMessage.GetGenericArguments().Where(t => !t.IsGenericParameter).ToArray();
var messageType = genericTypeArgs[0];
#else
var messageType = consumeMessage.GenericTypeArguments[0];
#endif
var exchange = bus.DeclareMessageExchange(messageType);
bus.BindMessageExchangeToQueue(exchange, queue, null);
var dispatchMethodInfo = dispatcher.GetType()
.GetMethod("ConsumeAdvancedAsync", BindingFlags.Instance | BindingFlags.Public)
.MakeGenericMethod(messageType, typeof(TConsumer));
var actionMethodType = typeof (Func<,,>).MakeGenericType(typeof (IMessage<>).MakeGenericType(messageType),typeof (MessageReceivedInfo), typeof (Task));
var onMessageDelegate = Delegate.CreateDelegate(actionMethodType, dispatcher, dispatchMethodInfo);
// Add<T>(Func<IMessage<T>, MessageReceivedInfo, Task> handler)
var addHandlerMethodInfo = typeof (IHandlerRegistration).GetMethods()
.First(x => x.Name == "Add" && x.IsGenericMethod && x.GetParameters().Count() > 0 &&
x.GetParameters()[0].ParameterType.GetGenericTypeDefinition() ==
typeof (Func<,,>))
.MakeGenericMethod(messageType);
addHandlerMethodInfo.Invoke(handlers, new object[] { onMessageDelegate });
}
});
}
}
private static void AutoSubscribeResponder<TConsumer>(IBus bus, IConsumerMessageDispatcher dispatcher, Type responseMethodType, string dispatchMethod, string subscribeMethod, Type subscribeMethodType, Func<Type, Type, Type> responseActionType) where TConsumer : class
{
var responderType = typeof(TConsumer);
var responseMessages =
responderType.GetInterfaces()
.Where(x => x.IsInterface && x.IsGenericType && x.GetGenericTypeDefinition() == responseMethodType)
.ToArray();
if (responseMessages.Any())
{
foreach (var responseMessage in responseMessages)
{
#if NET4
var genericTypeArgs = responseMessage.GetGenericArguments().Where(t => !t.IsGenericParameter).ToArray();
var requestType = genericTypeArgs[0];
var responseType = genericTypeArgs[1];
#else
var requestType = responseMessage.GenericTypeArguments[0];
var responseType = responseMessage.GenericTypeArguments[1];
#endif
var genericBusSubscribeMethod = bus.GetType().GetMethods()
.Where(m => m.Name == subscribeMethod)
.Select(m => new {Method = m, Params = m.GetParameters()})
.Single(m => m.Params.Length == 1
&& m.Params[0].ParameterType.GetGenericTypeDefinition() == subscribeMethodType
).Method.MakeGenericMethod(requestType, responseType);
var dispatchMethodInfo = dispatcher.GetType()
.GetMethod(dispatchMethod, BindingFlags.Instance | BindingFlags.Public)
.MakeGenericMethod(requestType, responseType, typeof(TConsumer));
var actionMethodType = responseActionType(requestType, responseType);
var dispatchDelegate = Delegate.CreateDelegate(actionMethodType, dispatcher, dispatchMethodInfo);
genericBusSubscribeMethod.Invoke(bus, new object[] { dispatchDelegate });
}
}
}
}
}<file_sep>using System;
using System.Linq;
using System.Reflection;
namespace EasyNetQ.Wf.AutoConsumers
{
[Serializable]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class OnTopicAttribute : Attribute
{
public string Name { get; set; }
public OnTopicAttribute(string topic)
{
Name = topic;
}
}
}<file_sep>using System;
using System.Activities;
using System.Activities.DurableInstancing;
#if !NET4
using System.Activities.DynamicUpdate;
#endif
using System.Collections.Generic;
using System.Linq;
using System.Runtime.DurableInstancing;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using EasyNetQ.NonGeneric;
using EasyNetQ.Wf.AutoConsumers;
namespace EasyNetQ.Wf
{
public class DefaultWorkflowApplicationHost : IWorkflowApplicationHost, IWorkflowApplicationHostBehavior
{
private readonly IWorkflowApplicationHostInstanceStore _workflowInstanceStore;
private readonly IList<ISubscriptionResult> _subscriberRegistry = new List<ISubscriptionResult>();
private Activity _workflowDefinition;
private WorkflowIdentity _workflowDefinitionIdentity;
private IDictionary<WorkflowIdentity, Activity> _workflowVersionMap;
private string _argumentName;
private Type _argumentType;
private bool _isRunning = false;
private CancellationTokenSource _durableDelayInstanceCancellationTokenSource = null;
private Task _durableDelayInstanceTask = null;
private long _currentTaskCount = 0;
protected readonly IBus Bus;
protected readonly IEasyNetQLogger Log;
protected readonly IWorkflowApplicationHostPerformanceMonitor PerfMon;
protected string ArgumentName { get { return _argumentName; } }
protected Type ArgumentType { get { return _argumentType; } }
public DefaultWorkflowApplicationHost(IBus bus)
{
Bus = bus;
Log = bus.Advanced.Container.Resolve<IEasyNetQLogger>();
PerfMon = bus.Advanced.Container.Resolve<IWorkflowApplicationHostPerformanceMonitor>();
// create a single instance store per host
_workflowInstanceStore = bus.Advanced.Container.Resolve<IWorkflowApplicationHostInstanceStore>();
}
#region IWorkflowApplicationHost
public Activity WorkflowDefinition
{
get { return _workflowDefinition; }
}
public WorkflowIdentity WorkflowDefinitionIdentity
{
get { return _workflowDefinitionIdentity; }
}
public event EventHandler<RequestAdditionalTimeEventArgs> RequestAdditionalTime;
public IWorkflowApplicationHostInstanceStore WorkflowInstanceStore
{
get { return _workflowInstanceStore; }
}
public virtual void Initialize(IDictionary<WorkflowIdentity, Activity> workflowVersionMap)
{
if (_isRunning) throw new InvalidOperationException("Initialize cannot be called when WorkflowApplicationHost is running");
if (workflowVersionMap == null || !workflowVersionMap.Any()) throw new ArgumentNullException("workflowVersionMap");
_workflowVersionMap = workflowVersionMap;
if (workflowVersionMap.Count == 1 && workflowVersionMap.First().Key.Version == null)
{
// no versioning
_workflowDefinitionIdentity = null;
_workflowDefinition = workflowVersionMap.First().Value;
}
else
{
_workflowDefinitionIdentity = _workflowVersionMap.Keys.OrderByDescending(x => x.Version).First();
_workflowDefinition = _workflowVersionMap[_workflowDefinitionIdentity];
}
var argumentInfo = WorkflowBusExtensions.GetInArgumentsFromActivity(_workflowDefinition).Single();
_argumentName = argumentInfo.InArgumentName;
_argumentType = argumentInfo.InArgumentType;
WorkflowInstanceStore.SetDefaultWorkflowInstanceOwner(GetWorkflowHostTypeName(_workflowDefinition), (_workflowDefinitionIdentity != null ? _workflowVersionMap.Keys : null));
}
protected virtual string GetWorkflowName(Activity workflowDefinition)
{
return workflowDefinition.GetType().Name;
}
protected virtual void OnError(WorkflowApplication workflowApplication, Exception exception)
{
Log.ErrorWrite(String.Format("Workflow {0}-{1} error", workflowApplication.WorkflowDefinition.GetType().Name, workflowApplication.Id), exception);
}
public bool IsRunning
{
get { return _isRunning; }
}
public virtual void Start()
{
if (IsRunning)
return;
Log.InfoWrite("WorkflowApplicationHost {0} starting...", WorkflowDefinition.GetType().Name);
// setup a long running workflow host
Log.InfoWrite("Starting durable delay monitor task...");
_durableDelayInstanceCancellationTokenSource = new CancellationTokenSource();
_durableDelayInstanceTask = StartDurableDelayInstanceProcessing(_durableDelayInstanceCancellationTokenSource.Token, TimeSpan.FromSeconds(30));
Log.InfoWrite("WorkflowApplicationHost {0} started", WorkflowDefinition.GetType().Name);
_isRunning = true;
}
public virtual void Stop()
{
// stop the background workflow task
if (!IsRunning)
return;
Log.InfoWrite("WorkflowApplicationHost {0} stopping...", WorkflowDefinition.GetType().Name);
// signal the background task
Log.InfoWrite("Cancelling durable delay monitor task...");
OnRequestAdditionalTime(TimeSpan.FromSeconds(5));
_durableDelayInstanceCancellationTokenSource.Cancel();
// stop subscriptions to the host
foreach (var subscriptionResult in GetSubscriptions().ToArray())
{
// stop the consumers
Log.InfoWrite("Cancelling consumer subscription for exchange {0} on queue {1}", subscriptionResult.Exchange.Name, subscriptionResult.Queue.Name);
CancelSubscription(subscriptionResult);
}
int counter = 0;
// wait for the background task to complete
if (_durableDelayInstanceTask != null && (!_durableDelayInstanceTask.IsCanceled || !_durableDelayInstanceTask.IsCompleted))
{
Log.InfoWrite("Waiting for durable delay monitor task to complete...");
try
{
counter = 0;
do
{
// request additional time from Service Manager
OnRequestAdditionalTime(TimeSpan.FromSeconds(20));
if (_durableDelayInstanceTask.Wait(TimeSpan.FromSeconds(20)))
{
// task has completed, so break out
break;
}
// task is still running, continue waiting for the task to complete
counter++;
} while (counter < 4);
Log.ErrorWrite("Durable delay monitor task is not responding, forcing Dispose and continuing to shutdown");
_durableDelayInstanceTask.Dispose();
}
catch (ObjectDisposedException)
{
// Task was already disposed, so no problem
}
catch (TaskCanceledException)
{
// Task has been cancelled and is completed
Log.InfoWrite("Durable delay monitor task has been cancelled");
}
catch (Exception unexpectedException)
{
Log.ErrorWrite(unexpectedException);
}
}
else
{
Log.InfoWrite("Durable delay monitor task has ended");
}
counter = 0;
while (counter < 30 && Interlocked.Read(ref _currentTaskCount) > 0)
{
Log.InfoWrite("Waiting for {0} running workflows to complete...", Interlocked.Read(ref _currentTaskCount));
OnRequestAdditionalTime(TimeSpan.FromSeconds(5));
// waiting for running workflows to complete
Thread.Sleep(TimeSpan.FromSeconds(2));
}
if (Interlocked.Read(ref _currentTaskCount) > 0)
{
Log.ErrorWrite("Continuing to shutdown, {0} running workflows are still waiting to complete...", Interlocked.Read(ref _currentTaskCount));
}
else
{
Log.InfoWrite("All running workflows have completed");
}
_isRunning = false;
Log.InfoWrite("WorkflowApplicationHost {0} stopped", WorkflowDefinition.GetType().Name);
}
public virtual IEnumerable<ISubscriptionResult> GetSubscriptions()
{
return _subscriberRegistry.AsEnumerable();
}
public virtual void AddSubscription(ISubscriptionResult subscription)
{
_subscriberRegistry.Add(subscription);
}
public virtual void CancelSubscription(ISubscriptionResult subscription)
{
// remove from subscription list
_subscriberRegistry.Remove(subscription);
subscription.Dispose();
}
#endregion
#region Background Workflow Activation Monitoring
protected virtual bool TryLoadRunnableInstance(TimeSpan timeout, out WorkflowApplication workflowApplication)
{
workflowApplication = null;
try
{
#if NET4
workflowApplication = CreateWorkflowApplication(WorkflowDefinition, WorkflowDefinitionIdentity, null);
workflowApplication.LoadRunnableInstance(timeout);
return true;
#else
var runnableInstance = WorkflowApplication.GetRunnableInstance(WorkflowInstanceStore.Store, timeout);
if (runnableInstance != null)
{
if (_workflowVersionMap != null)
{
// SIDE-BY-SIDE Workflow versioning support - load the requested version of the workflow
workflowApplication = CreateWorkflowApplication(_workflowVersionMap[runnableInstance.DefinitionIdentity], runnableInstance.DefinitionIdentity, null);
}
else
{
// single-version support
workflowApplication = CreateWorkflowApplication(WorkflowDefinition, WorkflowDefinitionIdentity, null);
}
workflowApplication.Load(runnableInstance);
return true;
}
#endif
}
catch (TimeoutException)
{
workflowApplication = null;
}
catch (InstancePersistenceException)
{
workflowApplication = null;
}
catch (Exception ex)
{
workflowApplication = null;
Log.ErrorWrite(ex);
}
return false;
}
protected virtual bool HasRunnableInstance(TimeSpan timeout)
{
var events = WorkflowInstanceStore.WaitForEvents(timeout);
if (events != null)
{
foreach (var instancePersistenceEvent in events)
{
if (instancePersistenceEvent.Equals(HasRunnableWorkflowEvent.Value))
return true;
}
}
return false;
}
protected virtual Task StartDurableDelayInstanceProcessing(CancellationToken cancellationToken, TimeSpan timeout)
{
return Task.Factory.StartNew(() =>
{
restart:
Log.InfoWrite("Starting Durable Delay monitor");
try
{
while (!cancellationToken.IsCancellationRequested)
{
// wait for a runnable workflow instance
if (HasRunnableInstance(timeout))
{
// create a new workflow instance to hold the runnable instance
WorkflowApplication wfApp = null;
// load a Runnable Instance
if (TryLoadRunnableInstance(TimeSpan.FromSeconds(1), out wfApp))
{
Log.InfoWrite("Waking up Workflow {0}-{1} from Idle...", wfApp.WorkflowDefinition.GetType().Name, wfApp.Id);
// resume the instance asynchronously
ExecuteWorkflowInstanceAsync(wfApp);
}
}
}
}
catch (Exception unhandledException)
{
Log.ErrorWrite(unhandledException);
// if the service is still running, then restart the background workflow task
if (!cancellationToken.IsCancellationRequested) goto restart;
}
}, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
#endregion
#region IDisposable
private bool _disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
Stop();
if (!_disposed)
{
if (disposing)
{
foreach (var subscriptionResult in _subscriberRegistry)
{
subscriptionResult.Dispose();
}
_subscriberRegistry.Clear();
// dispose resources here
WorkflowInstanceStore.Dispose();
}
WorkflowBusExtensions.RemoveWorkflowApplicationHost((IWorkflowApplicationHost)this);
_disposed = true;
}
// dispose unmanaged resources here
}
#endregion
protected virtual void OnRequestAdditionalTime(TimeSpan timeout)
{
if (RequestAdditionalTime != null)
RequestAdditionalTime(this, new RequestAdditionalTimeEventArgs(timeout));
}
protected virtual XName GetWorkflowHostTypeName(Activity workflowDefinition)
{
return XName.Get(workflowDefinition.GetType().FullName, "http://tempuri.org/EasyNetQ-Wf");
}
public virtual string GetBookmarkNameFromMessageType(Type messageType)
{
if(messageType == null) throw new ArgumentNullException("messageType");
return messageType.FullName;
}
public virtual void AddWorkflowHostExtensions(WorkflowApplication workflowApplication)
{
workflowApplication.Extensions.Add((IWorkflowApplicationHostBehavior)this);
}
protected virtual WorkflowApplication CreateWorkflowApplication(Activity workflowDefinition, WorkflowIdentity workflowIdentity, IDictionary<string, object> args)
{
WorkflowApplication wfApp = null;
if (args != null)
{
#if !NET4
if(workflowIdentity != null)
wfApp = new WorkflowApplication(workflowDefinition, args, workflowIdentity);
else
wfApp = new WorkflowApplication(workflowDefinition, args);
#else
wfApp = new WorkflowApplication(workflowDefinition, args);
#endif
}
else
{
#if !NET4
if (workflowIdentity != null)
wfApp = new WorkflowApplication(workflowDefinition, workflowIdentity);
else
wfApp = new WorkflowApplication(workflowDefinition);
#else
wfApp = new WorkflowApplication(workflowDefinition);
#endif
}
// setup the Workflow Instance scope
var wfScope = new Dictionary<XName, object>() { { WorkflowNamespaces.WorkflowHostTypePropertyName, GetWorkflowHostTypeName(workflowDefinition) } };
wfApp.AddInitialInstanceValues(wfScope);
// add workflow extensions
AddWorkflowHostExtensions(wfApp);
// The following should stop causing InstanceOwnerException which can be caused by connection terminations or extremely long
// idle periods between workflow executions
// http://www.damirscorner.com/blog/posts/20140317-RefreshingInstanceStoreHandleInWorkflowFoundation.html
WorkflowInstanceStore.TryRenewDefaultWorkflowInstanceOwner();
// set the Workflow Application Instance Store
wfApp.InstanceStore = WorkflowInstanceStore.Store;
return wfApp;
}
protected virtual Task ExecuteWorkflowInstanceAsync(WorkflowApplication workflowApplication, object bookmarkResume = null, Guid? correlatingInstanceId=null)
{
DateTime startingTime = DateTime.UtcNow;
string workflowName = GetWorkflowName(workflowApplication.WorkflowDefinition);
Interlocked.Increment(ref _currentTaskCount);
var tcs = new System.Threading.Tasks.TaskCompletionSource<object>();
workflowApplication.PersistableIdle = (e) => PersistableIdleAction.Unload;
workflowApplication.Unloaded = (e) => tcs.TrySetResult(null);
workflowApplication.Aborted = (e) =>
{
var exception = new WorkflowHostException(
String.Format("Workflow {0}-{1} aborted", workflowApplication.WorkflowDefinition.GetType().Name, e.InstanceId),
e.Reason);
OnError(workflowApplication, exception);
tcs.TrySetException(exception);
};
workflowApplication.OnUnhandledException = (e) =>
{
var exception = new WorkflowHostException(
String.Format("Workflow {0}-{1} threw unhandled exception", workflowApplication.WorkflowDefinition.GetType().Name,
e.InstanceId), e.UnhandledException);
OnError(workflowApplication, exception);
tcs.TrySetException(exception);
return UnhandledExceptionAction.Abort;
};
workflowApplication.Completed = (e) =>
{
switch (e.CompletionState)
{
case ActivityInstanceState.Faulted:
// any exceptions which terminate the workflow will be here
var exception = new WorkflowHostException(
String.Format("Workflow {0}-{1} faulted", workflowApplication.WorkflowDefinition.GetType().Name,
e.InstanceId), e.TerminationException);
OnError(workflowApplication, exception);
tcs.TrySetException(exception);
break;
case ActivityInstanceState.Canceled:
Log.InfoWrite("Workflow {0}-{1} Canceled.", workflowApplication.WorkflowDefinition.GetType().FullName, e.InstanceId);
break;
default:
// Completed
Log.InfoWrite("Workflow {0}-{1} Completed.", workflowApplication.WorkflowDefinition.GetType().FullName, e.InstanceId);
break;
}
};
if (bookmarkResume != null)
{
PerfMon.WorkflowResumed(workflowName);
PerfMon.WorkflowRunning(workflowName);
// set the bookmark and resume the workflow
var bookmarkResult =
workflowApplication.ResumeBookmark(GetBookmarkNameFromMessageType(bookmarkResume.GetType()),
bookmarkResume);
}
else
{
// persist the workflow before we start to get an instance id
workflowApplication.Persist();
Guid workflowInstanceId = workflowApplication.Id;
// TODO: need to add record to persistance mapping the workflowInstanceId and its Workflow Definition
if (correlatingInstanceId.GetValueOrDefault(Guid.Empty) != Guid.Empty)
{
OnWorkflowInvokedWithCorrelation(workflowInstanceId, correlatingInstanceId.Value);
}
PerfMon.WorkflowStarted(workflowName);
PerfMon.WorkflowRunning(workflowName);
// run the workflow
workflowApplication.Run();
}
// decrement the request counter when the workflow has completed
tcs.Task.ContinueWith(task =>
{
Interlocked.Decrement(ref _currentTaskCount);
DateTime stopTime = DateTime.UtcNow;
PerfMon.WorkflowDuration(workflowName, stopTime.Subtract(startingTime));
if (task.IsFaulted)
{
PerfMon.WorkflowFaulted(workflowName);
}
else
{
PerfMon.WorkflowCompleted(workflowName);
}
}, TaskContinuationOptions.ExecuteSynchronously);
// return the workflow execution task
return tcs.Task;
}
public void OnDispatchMessage(object message)
{
if (message == null) throw new ArgumentNullException("message");
OnDispatchMessageAsync(message).Wait();
}
public void OnDispatchMessageAdvanced(IMessage message, MessageReceivedInfo info)
{
OnDispatchMessage(message.GetBody());
}
public Task OnDispatchMessageAdvancedAsync(IMessage message, MessageReceivedInfo info)
{
return OnDispatchMessageAsync(message.GetBody());
}
protected virtual void OnWorkflowInvokedWithCorrelation(Guid workflowInstanceId, Guid correlatingInstanceId) { }
public virtual Task OnDispatchMessageAsync(object message)
{
if (message == null) throw new ArgumentNullException("message");
string workflowName = GetWorkflowName(WorkflowDefinition);
PerfMon.MessageConsumed(workflowName);
WorkflowApplication wfApp = null;
object bookmark = null;
// Workflow Correlation
string correlationKey = CorrelateUsingAttribute.GetCorrelatesOnValue(message);
string[] correlationValues = null;
Guid correlatingWorkflowInstanceId = Guid.Empty;
string correlatingActivityId = null;
if (!String.IsNullOrWhiteSpace(correlationKey))
{
// find correlation id guid if we have found a correlation key
correlationValues = correlationKey.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
if (!Guid.TryParse(correlationValues[0], out correlatingWorkflowInstanceId))
{
throw new WorkflowHostException(String.Format("Correlation Id must be a Guid (or Guid string) on type {0}", message.GetType().FullName));
}
correlatingActivityId = correlationValues[1];
}
// Workflow Setup
if (message.GetType() == ArgumentType)
{
Log.InfoWrite("WorkflowApplicationHost::OnDispatchMessageAsync - Starting workflow instance {0} for message {1}", WorkflowDefinition.GetType().Name, message.GetType().Name);
// start a new instance
var workflowArgs = new Dictionary<string, object>() {{ArgumentName, message}};
wfApp = CreateWorkflowApplication(WorkflowDefinition, WorkflowDefinitionIdentity, workflowArgs);
}
else
{
bookmark = message;
// resume a persisted instance using the correlationId
Log.InfoWrite("WorkflowApplicationHost::OnDispatchMessageAsync - Resuming workflow {0} for message bookmark {1} instance id {2}", WorkflowDefinition.GetType().Name, message.GetType().Name, correlatingWorkflowInstanceId);
int persistanceLoadCounter = 0;
while (true)
{
try
{
#if NET4
wfApp = CreateWorkflowApplication(WorkflowDefinition, WorkflowDefinitionIdentity, null);
wfApp.Load(correlatingWorkflowInstanceId);
#else
var instance = WorkflowApplication.GetInstance(correlatingWorkflowInstanceId, WorkflowInstanceStore.Store);
if (WorkflowDefinitionIdentity != null)
{
// SIDE-BY-SIDE workflow versioning support
wfApp = CreateWorkflowApplication(_workflowVersionMap[instance.DefinitionIdentity], instance.DefinitionIdentity, null);
}
else
{
// single version support
wfApp = CreateWorkflowApplication(WorkflowDefinition, null, null);
}
wfApp.Load(instance);
#endif
Log.InfoWrite("Workflow[{0}-{1}] Loaded", wfApp.WorkflowDefinition.GetType().FullName, correlatingWorkflowInstanceId);
// successful load, break of of the retry loop
break;
}
catch (InstancePersistenceException persistenceException)
{
// exponential delay for a few seconds and try to load again
if (persistanceLoadCounter < 5)
{
persistanceLoadCounter++;
#if NET4
Thread.Sleep(TimeSpan.FromMilliseconds(250 * persistanceLoadCounter));
#else
Task.Delay(TimeSpan.FromMilliseconds(250 * persistanceLoadCounter)).Wait();
#endif
}
else
{
// too many retries loading this instance, could be bad, so throw the error to NACK the message
PerfMon.WorkflowFaulted(workflowName);
Log.ErrorWrite("Workflow[{0}-{1}] could not be loaded: {2}", WorkflowDefinition.GetType().FullName, correlatingWorkflowInstanceId, persistenceException.ToString());
throw;
}
}
catch (Exception ex)
{
PerfMon.WorkflowFaulted(workflowName);
Log.ErrorWrite("Workflow[{0}-{1}] could not be loaded: {2}", WorkflowDefinition.GetType().FullName, correlatingWorkflowInstanceId, ex.ToString());
throw;
}
}
}
// Workflow Execution
return ExecuteWorkflowInstanceAsync(wfApp, bookmark, (correlatingWorkflowInstanceId != Guid.Empty ? correlatingWorkflowInstanceId : (Guid?)null));
}
#region IWorkflowApplicationHostBehavior
public virtual T Resolve<T>() where T:class
{
return Bus.Advanced.Container.Resolve<T>();
}
public virtual void PublishMessage(object message, string topic = null)
{
if (message == null) throw new ArgumentNullException("message");
if (!String.IsNullOrWhiteSpace(topic))
{
Bus.PublishEx(message.GetType(), message, topic);
}
else
{
Bus.PublishEx(message.GetType(), message);
}
}
public virtual Task PublishMessageAsync(object message, string topic = null)
{
if (message == null) throw new ArgumentNullException("message");
if (!String.IsNullOrWhiteSpace(topic))
{
return Bus.PublishExAsync(message.GetType(), message, topic);
}
return Bus.PublishExAsync(message.GetType(), message);
}
public virtual void PublishMessageWithCorrelation(Guid workflowInstanceId, object message, string topic = null)
{
if (message == null) throw new ArgumentNullException("message");
string correlatesOnValue = null;
if (!CorrelateUsingAttribute.TryGetCorrelatesOnValue(message, out correlatesOnValue))
{
// we are the Parent, so we set Correlation to ourselves
CorrelateUsingAttribute.SetCorrelatesOnValue(message, workflowInstanceId, WorkflowDefinition.GetType().Name);
correlatesOnValue = CorrelateUsingAttribute.GetCorrelatesOnValue(message);
// if there is an explicit topic, then we use it, otherwise, inspect the message type for an OnTopic attribute
topic = topic ?? AdvancedBusConsumerExtensions.GetTopicForMessage(message);
}
else
{
// We are responding to a Parent, so we will route using their correlation and
// leave it on the message
topic = topic ?? (CorrelateUsingAttribute.GetCorrelatesOnValue(message) ?? AdvancedBusConsumerExtensions.GetTopicForMessage(message));
}
Log.InfoWrite("WorkflowApplicationHost::PublishMessageWithCorrelation - publishing message {0} with CorrelationKey {1}, on topic {2}",
message.GetType().Name, correlatesOnValue, topic);
// Publish the correlated message directly to the Bus
if (!String.IsNullOrWhiteSpace(topic))
Bus.Publish(message.GetType(), message, topic);
else
Bus.Publish(message.GetType(), message);
}
public virtual Task PublishMessageWithCorrelationAsync(Guid workflowInstanceId, object message, string topic = null)
{
if (message == null) throw new ArgumentNullException("message");
string correlatesOnValue = null;
if (!CorrelateUsingAttribute.TryGetCorrelatesOnValue(message, out correlatesOnValue))
{
// we are the Parent, so we set Correlation to ourselves
CorrelateUsingAttribute.SetCorrelatesOnValue(message, workflowInstanceId, WorkflowDefinition.GetType().Name);
correlatesOnValue = CorrelateUsingAttribute.GetCorrelatesOnValue(message);
// if there is an explicit topic, then we use it, otherwise, inspect the message type for an OnTopic attribute
topic = topic ?? AdvancedBusConsumerExtensions.GetTopicForMessage(message);
}
else
{
// We are responding to a Parent, so we will route using their correlation and
// leave it on the message
topic = topic ?? (CorrelateUsingAttribute.GetCorrelatesOnValue(message) ?? AdvancedBusConsumerExtensions.GetTopicForMessage(message));
}
Log.InfoWrite("WorkflowApplicationHost::PublishMessageWithCorrelationAsync - publishing message {0} with CorrelationKey {1}, on topic {2}",
message.GetType().Name, correlatesOnValue, topic);
// Publish the correlated message directly to the Bus
if (!String.IsNullOrWhiteSpace(topic))
return Bus.PublishAsync(message.GetType(), message, topic);
return Bus.PublishAsync(message.GetType(), message);
}
#endregion
}
}<file_sep>using System;
using System.Threading.Tasks;
namespace EasyNetQ.Wf
{
public interface IWorkflowApplicationHostBehavior
{
T Resolve<T>() where T : class;
string GetBookmarkNameFromMessageType(Type messageType);
Task PublishMessageWithCorrelationAsync(Guid workflowInstanceId, object message, string topic = null);
void PublishMessageWithCorrelation(Guid workflowInstanceId, object message, string topic = null);
void PublishMessage(object message, string topic = null);
Task PublishMessageAsync(object message, string topic = null);
}
}<file_sep>using System;
namespace EasyNetQ.Wf.Activities
{
internal interface IMessageActivity { }
internal interface IMessageReceiveActivity : IMessageActivity { }
internal interface IPublishMessageActivity : IMessageActivity { }
/*
public interface ISendMessageActivity : IMessageActivity { }
public interface IRespondMessageActivity : IMessageActivity { }
*/
}<file_sep>using System;
using Telerik.OpenAccess.Metadata;
using Telerik.OpenAccess.Metadata.Fluent;
namespace EasyNetQ.Wf.DurableInstancing.Data
{
public class DefinitionIdentity
{
public long SurrogateIdentityId { get; set; }
public Guid DefinitionIdentityHash { get; set; }
public Guid DefinitionIdentityAnyRevisionHash { get; set; }
public string Name { get; set; }
public string Package { get; set; }
public long? Build { get; set; }
public long? Major { get; set; }
public long? Minor { get; set; }
public long? Revision { get; set; }
public static MappingConfiguration GetMapping()
{
var mapping = new MappingConfiguration<DefinitionIdentity>();
mapping.MapType().ToTable("DefinitionIdentities");
mapping.HasProperty(p => p.SurrogateIdentityId).IsIdentity(KeyGenerator.Autoinc);
mapping.HasProperty(p => p.Name).WithInfiniteLength().IsUnicode();
mapping.HasProperty(p => p.Package).WithInfiniteLength().IsUnicode();
return mapping;
}
}
public class LockOwner
{
public Guid Id { get; set; }
public long SurrogateLockOwnerId { get; set; }
public DateTime LockExpiration { get; set; }
public Guid? WorkflowHostType { get; set; }
public string MachineName { get; set; }
public bool EnqueueCommand { get; set; }
public bool DeletesInstanceOnCompletion { get; set; }
public byte[] PrimitiveLockOwnerData { get; set; }
public byte[] ComplexLockOwnerData { get; set; }
public byte[] WriteOnlyPrimitiveLockOwnerData { get; set; }
public byte[] WriteOnlyComplexLockOwnerData { get; set; }
public short? EncodingOption { get; set; }
public short WorkflowIdentityFilter { get; set; }
public static MappingConfiguration GetMapping()
{
var mapping = new MappingConfiguration<LockOwner>();
mapping.MapType().ToTable("LockOwners");
mapping.HasProperty(p => p.SurrogateLockOwnerId).IsIdentity(KeyGenerator.Autoinc);
mapping.HasProperty(p => p.PrimitiveLockOwnerData).WithInfiniteLength().IsNullable();
mapping.HasProperty(p => p.ComplexLockOwnerData).WithInfiniteLength().IsNullable();
mapping.HasProperty(p => p.WriteOnlyPrimitiveLockOwnerData).WithInfiniteLength().IsNullable();
mapping.HasProperty(p => p.WriteOnlyComplexLockOwnerData).WithInfiniteLength().IsNullable();
return mapping;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EasyNetQ.Wf.DurableInstancing.Data;
namespace EasyNetQ.Wf.DurableInstancing
{
public class WorkflowInstanceCommands
{
private readonly IEasyNetQLogger Log;
private readonly IWorkflowDurableInstancingUnitOfWork DbContext;
public WorkflowInstanceCommands(IEasyNetQLogger logger, IWorkflowDurableInstancingUnitOfWork dataContext)
{
Log = logger;
DbContext = dataContext;
}
}
}
<file_sep>using System;
using System.Activities;
using System.ComponentModel;
namespace EasyNetQ.Wf.Activities
{
public sealed class BusPublish<TMessage> : CodeActivity, IPublishMessageActivity
where TMessage:class
{
[RequiredArgument]
public InArgument<TMessage> Message { get; set; }
[DefaultValue(null)]
public InArgument<string> Topic { get; set; }
protected override void Execute(CodeActivityContext context)
{
TMessage messageBody = this.Message.Get(context);
string topic = this.Topic.Get(context);
// publish using the WorkflowApplicationHost
var publishService = context.GetExtension<IWorkflowApplicationHostBehavior>();
publishService.PublishMessageWithCorrelation(context.WorkflowInstanceId, messageBody, topic);
}
}
}<file_sep>using System;
using System.Activities.Tracking;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace EasyNetQ.Wf.Tracking
{
public class LoggerTrackingParticipant : TrackingParticipantBase
{
private IEasyNetQLogger Log;
public LoggerTrackingParticipant(IEasyNetQLogger logger)
{
if(logger == null)
throw new ArgumentNullException("logger");
Log = logger;
}
protected override void OnWorkflowInstance(WorkflowInstanceRecord record, TimeSpan timeout)
{
Log.InfoWrite("Tracking::WorkflowInstance - Id:{0}, InstanceId:{1}, EventTime:{2}, Record#:{3}, Level:{4}, State:{5}", record.ActivityDefinitionId, record.InstanceId, record.EventTime, record.RecordNumber, record.Level, record.State);
}
protected override void OnWorkflowInstanceAborted(WorkflowInstanceAbortedRecord record, TimeSpan timeout)
{
Log.InfoWrite("Tracking::WorkflowInstanceAborted - Id:{0}, InstanceId:{1}, EventTime:{2}, Record#:{3}, Level:{4}, State:{5}, Reason:{6}", record.ActivityDefinitionId, record.InstanceId, record.EventTime, record.RecordNumber, record.Level, record.State, record.Reason);
}
protected override void OnWorkflowInstanceTerminated(WorkflowInstanceTerminatedRecord record, TimeSpan timeout)
{
Log.InfoWrite("Tracking::WorkflowInstanceTerminated - Id:{0}, InstanceId:{1}, EventTime:{2}, Record#:{3}, Level:{4}, State:{5}, Reason:{6}", record.ActivityDefinitionId, record.InstanceId, record.EventTime, record.RecordNumber, record.Level, record.State, record.Reason);
}
protected override void OnWorkflowInstanceSuspended(WorkflowInstanceSuspendedRecord record, TimeSpan timeout)
{
Log.InfoWrite("Tracking::WorkflowInstanceSuspended - Id:{0}, InstanceId:{1}, EventTime:{2}, Record#:{3}, Level:{4}, State:{5}, Reason:{6}", record.ActivityDefinitionId, record.InstanceId, record.EventTime, record.RecordNumber, record.Level, record.State, record.Reason);
}
protected override void OnFaultPropogation(FaultPropagationRecord record, TimeSpan timeout)
{
Log.InfoWrite("Tracking::FaultPropogation - Source:{0} Instance Id:{1}, EventTime:{2}, Record#:{3}, Level:{4}, Exception:{5}", record.FaultSource.Name, record.InstanceId, record.EventTime, record.RecordNumber, record.Level, record.Fault.ToString());
}
protected override void OnActivityState(ActivityStateRecord record, TimeSpan timeout)
{
StringBuilder arguments = new StringBuilder();
foreach (var key in record.Arguments.Keys)
{
arguments.AppendFormat("\"{0}\"={{{1}}}, ", key, record.Variables[key]);
}
StringBuilder variables = new StringBuilder();
foreach (var key in record.Variables.Keys)
{
variables.AppendFormat("\"{0}\"={{{1}}}, ", key, record.Variables[key]);
}
Log.InfoWrite("Tracking::ActivityState - InstanceId:{0}, Activity:{1}, EventTime:{2}, Record#:{3}, Level:{4}, State:{5}, Arguments: [{6}], Variables: [{7}]", record.InstanceId, record.Activity.Name, record.EventTime, record.RecordNumber, record.Level, record.State, arguments.ToString(), variables.ToString());
}
protected override void OnBookmarkResumption(BookmarkResumptionRecord record, TimeSpan timeout)
{
Log.InfoWrite("Tracking::BookmarkResumption - InstanceId:{0}, Bookmark Name:{1}, EventTime:{2}, Record#:{3}, Level:{4}, Payload Type:{5}", record.InstanceId, record.BookmarkName, record.EventTime, record.RecordNumber, record.Level, record.Payload.GetType().FullName);
}
protected override void OnCustomTracking(CustomTrackingRecord record, TimeSpan timeout)
{
StringBuilder data = new StringBuilder();
foreach (var key in record.Data.Keys)
{
data.AppendFormat("\"{0}\"={{{1}}}", key, record.Data[key]);
}
Log.InfoWrite("Tracking::CustomTracking - InstanceId:{0}, Name:{1}, EventTime:{2}, Record#:{3}, Level:{4}, Activity:{5}, Data:[{6}]", record.InstanceId, record.Name, record.EventTime, record.RecordNumber, record.Level, record.Activity.Name, data.ToString());
}
}
}
<file_sep>using System;
using Telerik.OpenAccess.Metadata;
using Telerik.OpenAccess.Metadata.Fluent;
namespace EasyNetQ.Wf.DurableInstancing.Data
{
public class Instance
{
public Guid Id { get; set; }
public long SurrogateInstanceId { get; set; }
public long? SurrogateLockOwnerId { get; set; }
public byte[] PrimitiveDataProperties { get; set; }
public byte[] ComplexDataProperties { get; set; }
public byte[] WriteOnlyPrimitiveDataProperties { get; set; }
public byte[] WriteOnlyComplexDataProperties { get; set; }
public byte[] MetadataProperties { get; set; }
public short? DataEncodingOption { get; set; }
public short? MetadataEncodingOption { get; set; }
public long Version { get; set; }
public DateTime? PendingTimer { get; set; }
public DateTime CreationTime { get; set; }
public DateTime? LastUpdated { get; set; }
public Guid WorkflowHostType { get; set; }
public long? ServiceDeploymentId { get; set; }
public string SuspensionExceptionName { get; set; }
public string SuspensionReason { get; set; }
public string BlockingBookmarks { get; set; }
public string LastMachineRunOn { get; set; }
public string ExecutionStatus { get; set; }
public bool? IsInitialized { get; set; }
public bool? IsSuspended { get; set; }
public bool? IsReadyToRun { get; set; }
public bool? IsCompleted { get; set; }
public long SurrogateIdentityId { get; set; }
public static MappingConfiguration GetMapping()
{
var mapping = new MappingConfiguration<Instance>();
mapping.MapType().ToTable("Instances");
mapping.HasProperty(p => p.SurrogateInstanceId).IsIdentity(KeyGenerator.Autoinc);
mapping.HasProperty(p => p.PrimitiveDataProperties).WithInfiniteLength().IsNullable();
mapping.HasProperty(p => p.ComplexDataProperties).WithInfiniteLength().IsNullable();
mapping.HasProperty(p => p.WriteOnlyPrimitiveDataProperties).WithInfiniteLength().IsNullable();
mapping.HasProperty(p => p.WriteOnlyComplexDataProperties).WithInfiniteLength().IsNullable();
mapping.HasProperty(p => p.MetadataProperties).WithInfiniteLength().IsNullable();
mapping.HasProperty(p => p.SuspensionExceptionName).WithVariableLength(450).IsNullable().IsUnicode();
mapping.HasProperty(p => p.SuspensionReason).WithInfiniteLength().IsUnicode().IsNullable();
mapping.HasProperty(p => p.BlockingBookmarks).WithInfiniteLength().IsUnicode().IsNullable();
mapping.HasProperty(p => p.LastMachineRunOn).WithVariableLength(450).IsUnicode().IsNullable();
return mapping;
}
}
}
<file_sep>using System;
using System.Activities.Tracking;
namespace EasyNetQ.Wf.Tracking
{
/// <summary>
/// Emit WF Tracking records to a Log
/// </summary>
public abstract class TrackingParticipantBase : TrackingParticipant
{
protected override void Track(TrackingRecord record, TimeSpan timeout)
{
var workflowInstanceAbortedRecord = record as WorkflowInstanceAbortedRecord;
if (workflowInstanceAbortedRecord != null)
{
OnWorkflowInstanceAborted(workflowInstanceAbortedRecord, timeout);
return;
}
var workflowInstanceUnhandledExceptionRecord = record as WorkflowInstanceUnhandledExceptionRecord;
if (workflowInstanceUnhandledExceptionRecord != null)
{
OnWorkflowInstanceUnhandledException(workflowInstanceUnhandledExceptionRecord, timeout);
return;
}
var workflowInstanceSuspendedRecord = record as WorkflowInstanceSuspendedRecord;
if (workflowInstanceSuspendedRecord != null)
{
OnWorkflowInstanceSuspended(workflowInstanceSuspendedRecord, timeout);
return;
}
var workflowInstanceTerminatedRecord = record as WorkflowInstanceTerminatedRecord;
if (workflowInstanceTerminatedRecord != null)
{
OnWorkflowInstanceTerminated(workflowInstanceTerminatedRecord, timeout);
return;
}
var workflowInstanceRecord = record as WorkflowInstanceRecord;
if (workflowInstanceRecord != null)
{
OnWorkflowInstance(workflowInstanceRecord, timeout);
return;
}
var activityStateRecord = record as ActivityStateRecord;
if (activityStateRecord != null)
{
OnActivityState(activityStateRecord, timeout);
return;
}
var activityScheduledRecord = record as ActivityScheduledRecord;
if (activityScheduledRecord != null)
{
OnActivityScheduled(activityScheduledRecord, timeout);
return;
}
var faultPropogationRecord = record as FaultPropagationRecord;
if (faultPropogationRecord != null)
{
OnFaultPropogation(faultPropogationRecord, timeout);
return;
}
var cancelRequestedRecord = record as CancelRequestedRecord;
if (cancelRequestedRecord != null)
{
OnCancelRequested(cancelRequestedRecord, timeout);
return;
}
var bookmarkResumptionRecord = record as BookmarkResumptionRecord;
if (bookmarkResumptionRecord != null)
{
OnBookmarkResumption(bookmarkResumptionRecord, timeout);
return;
}
var customTrackingRecord = record as CustomTrackingRecord;
if (customTrackingRecord != null)
{
OnCustomTracking(customTrackingRecord, timeout);
return;
}
}
protected virtual void OnCustomTracking(CustomTrackingRecord record, TimeSpan timeout) { }
protected virtual void OnBookmarkResumption(BookmarkResumptionRecord record, TimeSpan timeout) { }
protected virtual void OnCancelRequested(CancelRequestedRecord record, TimeSpan timeout) { }
protected virtual void OnFaultPropogation(FaultPropagationRecord record, TimeSpan timeout) { }
protected virtual void OnActivityScheduled(ActivityScheduledRecord record, TimeSpan timeout) { }
protected virtual void OnActivityState(ActivityStateRecord record, TimeSpan timeout) { }
protected virtual void OnWorkflowInstanceTerminated(WorkflowInstanceTerminatedRecord record, TimeSpan timeout) { }
protected virtual void OnWorkflowInstanceSuspended(WorkflowInstanceSuspendedRecord record, TimeSpan timeout) { }
protected virtual void OnWorkflowInstanceUnhandledException(WorkflowInstanceUnhandledExceptionRecord record, TimeSpan timeout) { }
protected virtual void OnWorkflowInstanceAborted(WorkflowInstanceAbortedRecord record, TimeSpan timeout) { }
protected virtual void OnWorkflowInstance(WorkflowInstanceRecord record, TimeSpan timeout) { }
}
}
|
a81fbd2f1883de39d7f42c400a3a90a0862ad6eb
|
[
"Markdown",
"C#"
] | 32
|
C#
|
jhuntsman/EasyNetQ.Wf
|
48f751a9d7b87d0e4561ae87d38b9fb092d79812
|
11dfbf18ea869e59829f9ecd038311f726f0168b
|
refs/heads/master
|
<file_sep>import {Color} from '../../index'
import test from './test'
export default Promise.all([
test(Color.fromString('hwb(0,0,0)').toString(), '#ff0000'),
test(Color.fromString('#e4f0f6' ).toString(Color.Space.HWB), 'hwb(200 0.89 0.04)'),
test(Color.fromString( ).toString(), '#00000000'),
test(Color.fromString('black' ).toString(), '#000000'),
test(Color.fromString('palegreen' ).toString(), '#98fb98'),
test((() => {
try {
return Color.fromString('blanco').toString()
} catch (e) {
return e.name
}
})(), 'ReferenceError'),
])
<file_sep>import {Color} from '../../index'
import test from './test'
export default Promise.all([
test(new Color(0.5,0,0).complement().toString(), '#008080'),
])
<file_sep>import {Color} from '../../index'
import test from './test'
export default Promise.all([
test((() => { let s = Color.randomName(); console.log(s.name()); return `${s.toString().slice(0,0)}` })(), ''),
test((() => { let s = Color.randomName(); console.log(s.name()); return `${s.toString().slice(0,0)}` })(), ''),
test((() => { let s = Color.randomName(); console.log(s.name()); return `${s.toString().slice(0,0)}` })(), ''),
])
<file_sep>import {Color} from '../../index'
import test from './test'
export default Promise.all([
test(new Color(0.5,0,0).invert().toString(), '#80ffff'),
])
<file_sep>// Note: this file exists only for typescript declaration.
// It is not meant to be compiled automatically.
// See `./index.js` for the manual output.
export { default as Color } from './src/class/Color.class'
<file_sep>import {Color} from '../../index'
import test from './test'
export default Promise.all([
test(new Color(255,0,0 ).rotate(120).toString(), '#00ff00'),
test(new Color(255,0,0, 0.5).rotate(120).toString(), '#00ff0080'),
])
<file_sep>import {Color} from '../../index'
import test from './test'
export default Promise.all([
test(new Color(0.25, 0.5, 1 ).toString(), '#4080ff'),
test(new Color(0.25, 0.5, 1 ).toString(Color.Space.HWB), 'hwb(220 0.25 0)'),
test(new Color(0.5 , 0.5, 0.5, 0.5).toString(Color.Space.HWB), 'hwb(0 0.5 0.5 / 0.5)'),
test(new Color( ).toString(Color.Space.HWB), 'hwb(0 0 1 / 0)'),
test(new Color(0.5 , 0.1, 0.9 ).toString(Color.Space.HSL), 'hsl(270 0.8 0.5)'),
])
<file_sep>const gulp = require('gulp')
const typedoc = require('gulp-typedoc')
const typescript = require('gulp-typescript')
// require('typedoc') // DO NOT REMOVE … peerDependency of `gulp-typedoc`
// require('typescript') // DO NOT REMOVE … peerDependency of `gulp-typescript`
const tsconfig = require('./tsconfig.json')
const typedocconfig = require('./config/typedoc.json')
gulp.task('dist', async function () {
return gulp.src('./src/class/*.class.ts')
.pipe(typescript(tsconfig.compilerOptions))
.pipe(gulp.dest('./dist/class/'))
})
gulp.task('test-out', async function () {
return gulp.src(['./test/src/{,*.}test.ts'])
.pipe(typescript(tsconfig.compilerOptions))
.pipe(gulp.dest('./test/out/'))
})
gulp.task('test-run', async function () {
await Promise.all([
require('./test/out/Color--fromString.test.js').default,
require('./test/out/Color--random.test.js').default,
require('./test/out/Color--randomName.test.js').default,
require('./test/out/Color-constructor.test.js').default,
require('./test/out/Color-toString.test.js').default,
require('./test/out/Color-invert.test.js').default,
require('./test/out/Color-rotate.test.js').default,
require('./test/out/Color-complement.test.js').default,
require('./test/out/Color-name.test.js').default,
])
console.info('All tests ran successfully!')
})
gulp.task('test', ['test-out', 'test-run'])
gulp.task('docs', async function () {
return gulp.src('./src/**/*.ts')
.pipe(typedoc(typedocconfig))
})
gulp.task('build', ['dist', 'test', 'docs'])
<file_sep>import {Color} from '../../index'
import test from './test'
export default Promise.all([
test((() => { let s = Color.random( ); console.log(s.toString()); return `${s.toString().slice(0,1)}` })(), '#'),
test((() => { let s = Color.random(true ); console.log(s.toString()); return `${s.toString().slice(0,1)}` })(), '#'),
test((() => { let s = Color.random(false); console.log(s.toString()); return `${s.toString().slice(0,1)}` })(), '#'),
])
<file_sep>import {Color} from '../../index'
import test from './test'
export default Promise.all([
test(new Color(0.5 , 0.5, 0.5, 0.5).rgb.join(), '0.5,0.5,0.5,0.5'),
test(new Color(0.25, 0.5, 1 ).rgb.join(), '0.25,0.5,1,1'),
test(new Color( ).rgb.join(), '0,0,0,0'),
])
<file_sep># extrajs-color
A css color in Javascript.
## DEPRECATED
This module is **deprecated**, and merged into [extrajs-types](https://github.com/chharvey/extrajs-types).
Version 4 is the last release of this package, and this repository is archived.
Any further development will be done in `extrajs-types`.
## Usage
install:
```bash
$ npm install extrajs-color
```
use:
```js
const Color = require('extrajs-color')
let red = new Color(255, 0, 0)
let green_fade = new Color(0, 255, 0, 0.5)
```
<file_sep>import * as xjs from 'extrajs'
const NAMES: { [index: string]: string } = require('../../src/color-names.json') // NB relative to dist
/**
* Enum for the types of string representations of colors.
*/
enum Space {
/** #rrggbb / #rrggbbaa / #rgb / #rgba */ HEX = 'hex',
/** rgb(r g b [/ a]) */ RGB = 'rgb',
/** hsv(h s v [/ a]) */ HSV = 'hsv',
/** hsl(h s l [/ a]) */ HSL = 'hsl',
/** hwb(h w b [/ a]) */ HWB = 'hwb',
/** cmyk(c m y k [/ a]) */ CMYK = 'cmyk',
}
/**
* A 24/32-bit color ("True Color") that can be displayed in a pixel, given three primary color channels
* and a possible transparency channel.
*/
export default class Color {
static readonly Space = Space
/**
* Calculate the alpha of two or more overlapping translucent colors.
*
* For two overlapping colors with respective alphas `a` and `b`, the compounded alpha
* of an even mix will be `1 - (1-a)*(1-b)`.
* For three, it would be `1 - (1-a)*(1-b)*(1-c)`.
* An alpha is a number within the interval [0,1], and represents the opacity
* of a translucent color. An alpha of 0 is completely transparent; an alpha
* of 1 is completely opaque.
* @param alphas an array of alphas
* @return the compounded alpha
*/
private static _compoundOpacity(alphas: number[]): number {
return 1 - alphas.map((a) => 1-a).reduce((a,b) => a*b)
}
/**
* Transform an sRGB channel value (gamma-corrected) to a linear value.
*
* Approximately, the square of the value: `(x) => x * x`.
* @see https://www.w3.org/Graphics/Color/sRGB.html
* @see https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation
* @param c_srgb an rgb component (0–1) of a color
* @returns the transformed linear value
*/
private static _sRGB_Linear(c_srgb: number): number {
return (c_srgb <= 0.03928) ? c_srgb / 12.92 : ((c_srgb + 0.055) / 1.055) ** 2.4
}
/**
* Return the inverse of {@link Color._sRGB_Linear}.
*
* Approximately, the square root of the value: `(x) => Math.sqrt(x)`.
* @see https://www.w3.org/Graphics/Color/sRGB.html
* @see https://en.wikipedia.org/wiki/SRGB#The_forward_transformation_(CIE_XYZ_to_sRGB)
* @param c_lin a perceived luminance (linear) of a color’s rgb component (0–1)
* @returns the transformed sRGB value
*/
private static _linear_sRGB(c_lin: number): number {
return (c_lin <= 0.00304) ? c_lin * 12.92 : 1.055 * c_lin ** (1 / 2.4) - 0.055
}
/**
* Return a new Color object, given red, green, and blue, in RGB-space, where
* each color channel is an integer 0–255.
* @param red the RGB-red channel of this color (an integer in 0–255)
* @param green the RGB-green channel of this color (an integer in 0–255)
* @param blue the RGB-blue channel of this color (an integer in 0–255)
* @param alpha the alpha channel of this color (a number 0–1)
* @returns a new Color object with rgba(red, green, blue, alpha)
*/
static fromRGB(red = 0, green = 0, blue = 0, alpha = 1): Color {
return new Color(red/255, green/255, blue/255, alpha)
}
/**
* Return a new Color object, given hue, saturation, and value in HSV-space.
*
* The HSV-hue must be between 0 and 360.
* The HSV-saturation must be between 0.0 and 1.0.
* The HSV-value must be between 0.0 and 1.0.
* The alpha must be between 0.0 and 1.0.
* @param hue the HSV-hue channel of this color (a number 0—360)
* @param sat the HSV-sat channel of this color (a number 0—1)
* @param val the HSV-val channel of this color (a number 0—1)
* @param alpha the alpha channel of this color (a number 0—1)
* @returns a new Color object with hsva(hue, sat, val, alpha)
*/
static fromHSV(hue = 0, sat = 0, val = 0, alpha = 1): Color {
hue = xjs.Math.mod(hue, 360)
let c: number = sat * val
let x: number = c * (1 - Math.abs(hue/60 % 2 - 1))
let m: number = val - c
let rgb: number[] = [c, x, 0]
if ( 0 <= hue && hue < 60) { rgb = [c, x, 0] }
else if ( 60 <= hue && hue < 120) { rgb = [x, c, 0] }
else if (120 <= hue && hue < 180) { rgb = [0, c, x] }
else if (180 <= hue && hue < 240) { rgb = [0, x, c] }
else if (240 <= hue && hue < 300) { rgb = [x, 0, c] }
else if (300 <= hue && hue < 360) { rgb = [c, 0, x] }
return new Color(...rgb.map((el) => el + m), alpha)
}
/**
* Return a new Color object, given hue, saturation, and luminosity in HSL-space.
*
* The HSL-hue must be between 0 and 360.
* The HSL-saturation must be between 0.0 and 1.0.
* The HSL-luminosity must be between 0.0 and 1.0.
* The alpha must be between 0.0 and 1.0.
* @see https://www.w3.org/TR/css-color-4/#hsl-to-rgb
* @param hue the HSL-hue channel of this color (a number 0—360)
* @param sat the HSL-sat channel of this color (a number 0—1)
* @param lum the HSL-lum channel of this color (a number 0—1)
* @param alpha the alpha channel of this color (a number 0—1)
* @returns a new Color object with hsla(hue, sat, lum, alpha)
*/
static fromHSL(hue = 0, sat = 0, lum = 0, alpha = 1): Color {
hue = xjs.Math.mod(hue, 360)
let c: number = sat * (1 - Math.abs(2*lum - 1))
let x: number = c * (1 - Math.abs(hue/60 % 2 - 1))
let m: number = lum - c/2
let rgb: number[] = [c, x, 0]
if ( 0 <= hue && hue < 60) { rgb = [c, x, 0] }
else if ( 60 <= hue && hue < 120) { rgb = [x, c, 0] }
else if (120 <= hue && hue < 180) { rgb = [0, c, x] }
else if (180 <= hue && hue < 240) { rgb = [0, x, c] }
else if (240 <= hue && hue < 300) { rgb = [x, 0, c] }
else if (300 <= hue && hue < 360) { rgb = [c, 0, x] }
return new Color(...rgb.map((el) => el + m), alpha)
}
/**
* Return a new Color object, given hue, white, and black in HWB-space.
*
* The HWB-hue must be between 0 and 360.
* The HWB-white must be between 0.0 and 1.0.
* The HWB-black must be between 0.0 and 1.0.
* The alpha must be between 0.0 and 1.0.
* @see https://www.w3.org/TR/css-color-4/#hwb-to-rgb
* @param hue the HWB-hue channel of this color (a number 0—360)
* @param white the HWB-white channel of this color (a number 0—1)
* @param black the HWB-black channel of this color (a number 0—1)
* @param alpha the alpha channel of this color (a number 0—1)
* @returns a new Color object with hwba(hue, white, black, alpha)
*/
static fromHWB(hue = 0, white = 0, black = 0, alpha = 1): Color {
return Color.fromHSV(hue, 1 - white / (1 - black), 1 - black, alpha)
// HWB -> RGB:
/*
var rgb = Color.fromHSL([hue, 1, 0.5]).rgb
for (var i = 0; i < 3; i++) {
rgb[i] *= (1 - white - black);
rgb[i] += white;
}
return new Color(...rgb)
*/
}
/**
* Return a new Color object, given cyan, magenta, yellow, and black in CMYK-space.
*
* The CMYK-cyan must be between 0.0 and 1.0.
* The CMYK-magenta must be between 0.0 and 1.0.
* The CMYK-yellow must be between 0.0 and 1.0.
* The CMYK-black must be between 0.0 and 1.0.
* The alpha must be between 0.0 and 1.0.
* @see https://www.w3.org/TR/css-color-4/#cmyk-rgb
* @param cyan the CMYK-cyan channel of this color (a number 0—1)
* @param magenta the CMYK-magenta channel of this color (a number 0—1)
* @param yellow the CMYK-yellow channel of this color (a number 0—1)
* @param black the CMYK-black channel of this color (a number 0—1)
* @param alpha the alpha channel of this color (a number 0—1)
* @returns a new Color object with cmyka(cyan, magenta, yellow, black, alpha)
*/
static fromCMYK(cyan = 0, magenta = 0, yellow = 0, black = 0, alpha = 1): Color {
return new Color(
1 - Math.min(cyan * (1 - black) + black, 1),
1 - Math.min(magenta * (1 - black) + black, 1),
1 - Math.min(yellow * (1 - black) + black, 1),
alpha
)
}
/**
* Return a new Color object, given a string.
*
* The string must have one of the following formats (spaces optional):
* - `#rrggbb`
* - `#rrggbbaa`
* - `#rgb`
* - `#rgba`
* - `rgb(r, g, b)` — DEPRECATED
* - `rgb(r, g, b, a)` — DEPRECATED
* - `rgba(r, g, b, a)` — DEPRECATED
* - `rgb(r g b)`
* - `rgb(r g b / a)`
* - `hsv(h, s, v)` — DEPRECATED
* - `hsv(h, s, v, a)` — DEPRECATED
* - `hsva(h, s, v, a)` — DEPRECATED
* - `hsv(h s v)`
* - `hsv(h s v / a)`
* - `hsl(h, s, l)` — DEPRECATED
* - `hsl(h, s, l, a)` — DEPRECATED
* - `hsla(h, s, l, a)` — DEPRECATED
* - `hsl(h s l)`
* - `hsl(h s l / a)`
* - `hwb(h, w, b)` — DEPRECATED
* - `hwb(h, w, b, a)` — DEPRECATED
* - `hwba(h, w, b, a)` — DEPRECATED
* - `hwb(h w b)`
* - `hwb(h w b / a)`
* - `cmyk(c, m, y, k)` — DEPRECATED
* - `cmyk(c, m, y, k, a)` — DEPRECATED
* - `cmyka(c, m, y, k, a)` — DEPRECATED
* - `cmyk(c m y k)`
* - `cmyk(c m y k / a)`
* - *any exact string match of a named color*
*
* Note that the comma-separated value syntax, while still supported, is deprecated.
* Authors should convert to the new space-separated value syntax, as specified in
* {@link https://drafts.csswg.org/css-color/|CSS Color Module Level 4, Editor’s Draft}.
* Deprecated syntax will become obsolete in an upcoming major version.
*
* @see {@link https://www.w3.org/TR/css-color-4/#named-colors|Named Colors | CSS Color Module Level 4}
* @param str a string of one of the forms described
* @returns a new Color object constructed from the given string
* @throws {RangeError} if the string given is not a valid format
* @throws {ReferenceError} if the color name given was not found
*/
static fromString(str = ''): Color {
if (str === '') return new Color()
if (str[0] === '#') {
if (![4,5,7,9].includes(str.length)) throw new RangeError(`Invalid string format: '${str}'.`)
if ([4,5].includes(str.length)) {
let [r, g, b, a]: string[] = [str[1], str[2], str[3], str[4] || '']
return Color.fromString(`#${r}${r}${g}${g}${b}${b}${a}${a}`)
}
let red : number = parseInt(str.slice(1,3), 16) / 255
let green: number = parseInt(str.slice(3,5), 16) / 255
let blue : number = parseInt(str.slice(5,7), 16) / 255
let alpha: number = (str.length === 9) ? parseInt(str.slice(7,9), 16)/255 : 1
try {
xjs.Number.assertType(red , 'non-negative')
xjs.Number.assertType(green, 'non-negative')
xjs.Number.assertType(blue , 'non-negative')
xjs.Number.assertType(alpha, 'non-negative')
} catch (e) {
throw new RangeError(`Invalid string format: '${str}'.`)
}
return new Color(red, green, blue, alpha)
}
if (!str.includes('(')) {
const returned: string|null = NAMES[str] || null
if (!returned) throw new ReferenceError(`No color found for the name given: '${str}'.`)
return Color.fromString(returned)
}
try {
return (() => {
const space : string = str.split('(')[0]
const cssarg: string = str.split('(')[1].slice(0, -1)
const channelstrings: string[] = (cssarg.includes(',')) ?
cssarg.split(',') : // legacy syntax — COMBAK{DEPRECATED}
cssarg.split('/')[0].split(' ').filter((s) => s !== '')
if (cssarg.includes('/')) {
channelstrings.push(cssarg.split('/')[1])
}
return xjs.Object.switch<Color>(space, {
rgb : (channels: number[]) => new Color (...channels.map((c) => c / 255)),
rgba : (channels: number[]) => new Color (...channels.map((c) => c / 255)), // COMBAK{DEPRECATED}
hsv : (channels: number[]) => Color.fromHSV (...channels),
hsva : (channels: number[]) => Color.fromHSV (...channels), // COMBAK{DEPRECATED}
hsl : (channels: number[]) => Color.fromHSL (...channels),
hsla : (channels: number[]) => Color.fromHSL (...channels), // COMBAK{DEPRECATED}
hwb : (channels: number[]) => Color.fromHWB (...channels),
hwba : (channels: number[]) => Color.fromHWB (...channels), // COMBAK{DEPRECATED}
cmyk : (channels: number[]) => Color.fromCMYK(...channels),
cmyka: (channels: number[]) => Color.fromCMYK(...channels), // COMBAK{DEPRECATED}
})(channelstrings.map((s) => +s))
})()
} catch (e) {
throw new RangeError(`Invalid string format: '${str}'.`)
}
}
/**
* Mix (average) a set of 2 or more colors. The average will be weighted evenly.
*
* If two colors `a` and `b` are given, calling this static method, `Color.mix([a, b])`,
* is equivalent to calling `a.mix(b)` without a weight.
* However, calling `Color.mix([a, b, c])` with 3 or more colors yields an even mix,
* and will *not* yield the same results as calling `a.mix(b).mix(c)`, which yields an uneven mix.
* Note that the order of the given colors does not change the result, that is,
* `Color.mix([a, b, c])` returns the same result as `Color.mix([c, b, a])`.
* @see Color.mix
* @param colors an array of Color objects, of length >=2
* @returns a mix of the given colors
*/
static mix(colors: Color[]): Color {
let red : number = xjs.Math.meanArithmetic(colors.map((c) => c.red ))
let green: number = xjs.Math.meanArithmetic(colors.map((c) => c.green))
let blue : number = xjs.Math.meanArithmetic(colors.map((c) => c.blue ))
let alpha: number = Color._compoundOpacity(colors.map((c) => c.alpha))
return new Color(red, green, blue, alpha)
}
/**
* Blur a set of 2 or more colors. The average will be weighted evenly.
*
* Behaves almost exactly the same as {@link Color.mix},
* except that this method uses a more visually accurate, slightly brighter, mix.
* @see Color.blur
* @param colors an array of Color objects, of length >=2
* @returns a blur of the given colors
*/
static blur(colors: Color[]): Color {
/**
* Calculate the compound value of two or more overlapping same-channel values.
* @private
* @param arr an array of same-channel values (red, green, or blue)
* @returns the compounded value
*/
function compoundChannel(arr: number[]): number {
return Color._linear_sRGB(xjs.Math.meanArithmetic(arr.map(Color._sRGB_Linear)))
}
let red : number = compoundChannel(colors.map((c) => c.red ))
let green: number = compoundChannel(colors.map((c) => c.green))
let blue : number = compoundChannel(colors.map((c) => c.blue ))
let alpha: number = Color._compoundOpacity(colors.map((c) => c.alpha))
return new Color(red, green, blue, alpha)
}
/**
* Generate a random color.
* @param alpha should the alpha channel also be randomized? (if false, default alpha value is 1)
* @returns a Color object with random values
*/
static random(alpha = true): Color {
return Color.fromString(`#${Math.random().toString(16).slice(2, (alpha) ? 10 : 8)}`)
}
/**
* Randomly select a Named Color.
* @returns one of the Named Colors, randomly chosen
*/
static randomName(): Color {
let named_colors: [string, string][] = Object.entries(NAMES)
return Color.fromString(named_colors[Math.floor(Math.random() * named_colors.length)][0])
}
/** The red channel of this color. A number in [0,1]. */
private readonly _RED: number
/** The green channel of this color. A number in [0,1]. */
private readonly _GREEN: number
/** The blue channel of this color. A number in [0,1]. */
private readonly _BLUE: number
/** The alpha channel of this color. A number in [0,1]. */
private readonly _ALPHA: number
private readonly _MAX: number
private readonly _MIN: number
private readonly _CHROMA: number
/**
*
* Construct a new Color object.
*
* Calling `new Color(r, g, b, a)` (4 arguments) specifies default behavior.
* Calling `new Color(r, g, b)` (3 arguments) will result in an opaque color (`#rrggbbFF`),
* where the alpha is 1 by default.
* Calling `new Color()` (no arguments) will result in transparent (`#00000000`).
* @param r the red channel of this color (a number 0—1)
* @param g the green channel of this color (a number 0—1)
* @param b the blue channel of this color (a number 0—1)
* @param a the alpha channel of this color (a number 0–1)
*/
constructor(r = 0, g = 0, b = 0, a = 1) {
if (arguments.length === 0) a = 0
this._RED = xjs.Math.clamp(0, r, 1)
this._GREEN = xjs.Math.clamp(0, g, 1)
this._BLUE = xjs.Math.clamp(0, b, 1)
this._ALPHA = xjs.Math.clamp(0, a, 1)
this._MAX = Math.max(this._RED, this._GREEN, this._BLUE)
this._MIN = Math.min(this._RED, this._GREEN, this._BLUE)
this._CHROMA = this._MAX - this._MIN
}
/**
* Return a string representation of this color.
*
* If the alpha of this color is 1, then the string returned will represent an opaque color,
* `hsv(h s v)`, `hsl(h s l)`, etc.
* Otherwise, the string returned will represent a translucent color,
* `hsv(h s v / a)`, `hsl(h s l / a)`, etc.
*
* The format of the numbers returned will be as follows. The default format is {@link Color.Space.HEX}.
* - all HEX values will be base 16 integers in [00,FF], two digits
* - HSV/HSL/HWB-hue values will be base 10 decimals in [0,360) rounded to the nearest 0.1
* - HSV/HSL-sat/val/lum, HWB-white/black, and CMYK-cyan/magenta/yellow/black values will be base 10 decimals in [0,1] rounded to the nearest 0.01
* - all RGB values will be base 10 integers in [0,255], one to three digits
* - all alpha values will be base 10 decimals in [0,1], rounded to the nearest 0.001
* @override
* @param space represents the space in which this color exists
* @returns a string representing this color
*/
toString(space = Color.Space.HEX): string {
const leadingZero = (n: number, r: number = 10) => `0${n.toString(r)}`.slice(-2)
if (space === Color.Space.HEX) {
return `#${this.rgb.slice(0,3).map((c) => leadingZero(Math.round(c * 255), 16)).join('')}${(this.alpha < 1) ? leadingZero(Math.round(this.alpha * 255), 16) : ''}`
}
const returned = xjs.Object.switch<number[]>(space, {
[Color.Space.RGB]: () => this.rgb.slice(0,3).map((c) => Math.round(c * 255)),
[Color.Space.HSV]: () => [
Math.round(this.hsvHue * 10) / 10,
Math.round(this.hsvSat * 100) / 100,
Math.round(this.hsvVal * 100) / 100,
],
[Color.Space.HSL]: () => [
Math.round(this.hslHue * 10) / 10,
Math.round(this.hslSat * 100) / 100,
Math.round(this.hslLum * 100) / 100,
],
[Color.Space.HWB]: () => [
Math.round(this.hwbHue * 10) / 10,
Math.round(this.hwbWhite * 100) / 100,
Math.round(this.hwbBlack * 100) / 100,
],
[Color.Space.CMYK]: () => [
Math.round(this.cmykCyan * 100) / 100,
Math.round(this.cmykMagenta * 100) / 100,
Math.round(this.cmykYellow * 100) / 100,
Math.round(this.cmykBlack * 100) / 100,
],
})()
return `${space}(${returned.join(' ')}${
(this.alpha < 1) ? ` / ${Math.round(this.alpha * 1000) / 1000}` : ''
})`
}
/**
* Get the red channel of this color.
*/
get red(): number { return this._RED }
/**
* Get the green channel of this color.
*/
get green(): number { return this._GREEN }
/**
* Get the blue channel of this color.
*/
get blue(): number { return this._BLUE }
/**
* Get the alpha (opacity) of this color.
*/
get alpha(): number { return this._ALPHA }
/**
* Get the hsv-hue of this color.
*
* The HSV-space hue (in degrees) of this color, or what "color" this color is.
* A number bound by [0, 360).
*/
get hsvHue(): number {
if (this._CHROMA === 0) return 0
let rgb_norm: [number, number, number] = [
this._RED,
this._GREEN,
this._BLUE,
]
return [
(r: number, g: number, b: number) => ((g - b) / this._CHROMA + 6) % 6 * 60,
(r: number, g: number, b: number) => ((b - r) / this._CHROMA + 2) * 60,
(r: number, g: number, b: number) => ((r - g) / this._CHROMA + 4) * 60,
][rgb_norm.indexOf(this._MAX)](...rgb_norm)
/*
* Exercise: prove:
* _HSV_HUE === Math.atan2(Math.sqrt(3) * (g - b), 2*r - g - b)
*/
}
/**
* Get the hsv-saturation of this color.
*
* The vividness of this color. A lower saturation means the color is closer to white,
* a higher saturation means the color is more true to its hue.
* A number bound by [0, 1].
*/
get hsvSat(): number {
return (this._CHROMA === 0) ? 0 : this._CHROMA / this.hsvVal
}
/**
* Get the hsv-value of this color.
*
* The brightness of this color. A lower value means the color is closer to black, a higher
* value means the color is more true to its hue.
* A number bound by [0, 1].
*/
get hsvVal(): number {
return this._MAX
}
/**
* Get the hsl-hue of this color.
*
* The Hue of this color. Identical to {@link Color.hsvHue}.
* A number bound by [0, 360).
*/
get hslHue(): number {
return this.hsvHue
}
/**
* Get the hsl-saturation of this color.
*
* The amount of "color" in the color. A lower saturation means the color is more grayer,
* a higher saturation means the color is more colorful.
* A number bound by [0, 1].
*/
get hslSat(): number {
return (this._CHROMA === 0) ? 0 : (this._CHROMA / ((this.hslLum <= 0.5) ? 2*this.hslLum : (2 - 2*this.hslLum)))
/*
* Exercise: prove:
* _HSL_SAT === _CHROMA / (1 - Math.abs(2*this.hslLum - 1))
* Proof:
* denom == (function (x) {
* if (x <= 0.5) return 2x
* else return 2 - 2x
* })(_HSL_LUM)
* Part A. Let x <= 0.5. Then 2x - 1 <= 0, and |2x - 1| == -(2x - 1).
* Then 1 - |2x - 1| == 1 + (2x - 1) = 2x. //
* Part B. Let 0.5 < x. Then 1 < 2x - 1, and |2x - 1| == 2x - 1.
* Then 1 - |2x - 1| == 1 - (2x - 1) = 2 - 2x. //
*/
}
/**
* Get the hsl-luminosity of this color.
*
* How "white" or "black" the color is. A lower luminosity means the color is closer to black,
* a higher luminosity means the color is closer to white.
* A number bound by [0, 1].
*/
get hslLum(): number {
return 0.5 * (this._MAX + this._MIN)
}
/**
* Get the hwb-hue of this color.
*
* The Hue of this color. Identical to {@link Color.hsvHue}.
* A number bound by [0, 360).
*/
get hwbHue(): number {
return this.hsvHue
}
/**
* Get the hwb-white of this color.
*
* The amount of White in this color. A higher white means the color is closer to #fff,
* a lower white means the color has a true hue (more colorful).
* A number bound by [0, 1].
*/
get hwbWhite(): number {
return this._MIN
}
/**
* Get the hwb-black of this color.
*
* The amount of Black in this color. A higher black means the color is closer to #000,
* a lower black means the color has a true hue (more colorful).
* A number bound by [0, 1].
*/
get hwbBlack(): number {
return 1 - this._MAX
}
/**
* Get the cmyk-cyan of this color.
*
* The amount of Cyan in this color, or a subtraction of the amount of Red in this color.
* A number bound by [0, 1].
*/
get cmykCyan(): number {
return (this.cmykBlack === 1) ? 0 : (1 - this.red - this.cmykBlack) / (1 - this.cmykBlack)
}
/**
* Get the cmyk-magenta of this color.
*
* The amount of Magenta in this color, or a subtraction of the amount of Green in this color.
* A number bound by [0, 1].
*/
get cmykMagenta(): number {
return (this.cmykBlack === 1) ? 0 : (1 - this.green - this.cmykBlack) / (1 - this.cmykBlack)
}
/**
* Get the cmyk-yellow of this color.
*
* The amount of Yellow in this color, or a subtraction of the amount of Blue in this color.
* A number bound by [0, 1].
*/
get cmykYellow(): number {
return (this.cmykBlack === 1) ? 0 : (1 - this.blue - this.cmykBlack) / (1 - this.cmykBlack)
}
/**
* Get the cmyk-black of this color.
*
* The amount of Black in this color in the CMYK color space.
* A number bound by [0, 1].
*/
get cmykBlack(): number {
return 1 - this._MAX
}
/**
* Get an array of RGBA channels.
*/
get rgb(): number[] { return [this.red, this.green, this.blue, this.alpha] }
/**
* Get an array of HSVA channels.
*/
get hsv(): number[] { return [this.hsvHue, this.hsvSat, this.hsvVal, this.alpha] }
/**
* Get an array of HSLA channels.
*/
get hsl(): number[] { return [this.hslHue, this.hslSat, this.hslLum, this.alpha] }
/**
* Get an array of HWBA channels.
*/
get hwb(): number[] { return [this.hwbHue, this.hwbWhite, this.hwbBlack, this.alpha] }
/**
* Get an array of CMYKA channels.
*/
get cmyk(): number[] { return [this.cmykCyan, this.cmykMagenta, this.cmykYellow, this.cmykBlack, this.alpha] }
/**
* Return the inversion of this color, preserving alpha.
*
* The inversion of a color is the difference between that color and white.
* @returns a new Color object that corresponds to this color’s inversion
*/
invert(): Color {
return new Color(
1 - this.red,
1 - this.green,
1 - this.blue,
this.alpha
)
}
/**
* Return a hue-rotation of this color, preserving alpha.
*
* a the number of degrees to rotate
* @returns a new Color object corresponding to this color rotated by `a` degrees
*/
rotate(a: number): Color {
return Color.fromHSV(((this.hsvHue + a) % 360), this.hsvSat, this.hsvVal, this.alpha)
}
/**
* Return the complement of this color.
*
* The complement of a color amounts to a hue rotation of 180 degrees.
* @returns a new Color object that corresponds to this color’s complement
*/
complement(): Color {
return this.rotate(180)
}
/**
* Return a more saturated (more colorful) version of this color by a percentage.
*
* This method calculates saturation in the HSL space.
* A parameter of 1.0 returns a color with full saturation, and 0.0 returns an identical color.
* A negative number will {@link Color.desaturate|desaturate} this color.
* Set `relative = true` to specify the amount as relative to the color’s current saturation.
*
* For example, if `$color` has an HSL-sat of 0.5, then calling `$color.saturate(0.5)` will return
* a new color with an HSL-sat of 1.0, because the argument 0.5 is simply added to the color’s saturation.
* However, calling `$color.saturate(0.5, true)` will return a new color with an HSL-sat of 0.75,
* because the argument 0.5, relative to the color’s current saturation of 0.5, results in
* an added saturation of 0.25.
*
* @param p must be between -1.0 and 1.0; the value by which to saturate this color
* @param relative should the saturation added be relative?
* @returns a new Color object that corresponds to this color saturated by `p`
*/
saturate(p: number, relative = false): Color {
let newsat: number = this.hslSat + (relative ? (this.hslSat * p) : p)
newsat = xjs.Math.clamp(0, newsat, 1)
return Color.fromHSL(this.hslHue, newsat, this.hslLum, this.alpha)
}
/**
* Return a less saturated version of this color by a percentage.
*
* A parameter of 1.0 returns a grayscale color, and 0.0 returns an identical color.
* @see Color.saturate
* @param p must be between -1.0 and 1.0; the value by which to desaturate this color
* @param relative should the saturation subtracted be relative?
* @returns a new Color object that corresponds to this color desaturated by `p`
*/
desaturate(p: number, relative = false): Color {
return this.saturate(-p, relative)
}
/**
* Return a lighter version of this color by a percentage.
*
* This method calculates with luminosity in the HSL space.
* A parameter of 1.0 returns white, and 0.0 returns an identical color.
* A negative parameter will {@link Color.darken|darken} this color.
* Set `relative = true` to specify the amount as relative to the color’s current luminosity.
*
* For example, if `$color` has an HSL-lum of 0.5, then calling `$color.lighten(0.5)` will return
* a new color with an HSL-lum of 1.0, because the argument 0.5 is simply added to the color’s luminosity.
* However, calling `$color.lighten(0.5, true)` will return a new color with an HSL-lum of 0.75,
* because the argument 0.5, relative to the color’s current luminosity of 0.5, results in
* an added luminosity of 0.25.
*
* @param p must be between -1.0 and 1.0; the amount by which to lighten this color
* @param relative should the luminosity added be relative?
* @returns a new Color object that corresponds to this color lightened by `p`
*/
lighten(p: number, relative = false): Color {
let newlum: number = this.hslLum + (relative ? (this.hslLum * p) : p)
newlum = xjs.Math.clamp(0, newlum, 1)
return Color.fromHSL(this.hslHue, this.hslSat, newlum, this.alpha)
}
/**
* Return a darker version of this color by a percentage.
*
* A parameter of 1.0 returns black, and 0.0 returns an identical color.
* @see Color.lighten
* @param p must be between -1.0 and 1.0; the amount by which to darken this color
* @param relative should the luminosity subtracted be relative?
* @returns a new Color object that corresponds to this color darkened by `p`
*/
darken(p: number, relative = false): Color {
return this.lighten(-p, relative)
}
/**
* Return a new color with the complemented alpha of this color.
*
* E.g. an alpha of 0.7, complemented, is 0.3 (the complement with 1.0).
* @returns a new Color object with the same color but complemented alpha
*/
negate(): Color {
return new Color(...this.rgb, 1 - this.alpha)
}
/**
* Return a less faded (larger alpha) version of this color.
*
* A parameter of 1.0 returns full opaqueness, and 0.0 returns an identical color.
* A negative parameter will {@link Color.fadeOut|fade out} this color.
* Set `relative = true` to specify the amount as relative to the color’s current opacity.
* @param p must be between -1.0 and 1.0; the amount by which to fade in this color
* @param relative should the alpha added be relative?
* @returns a new Color object that corresponds to this color faded in by `p`
*/
fadeIn(p: number, relative = false): Color {
let newalpha: number = this.alpha + (relative ? (this.alpha * p) : p)
newalpha = xjs.Math.clamp(0, newalpha, 1)
return new Color(...this.rgb, newalpha)
}
/**
* Return a more faded (smaller alpha) version of this color.
*
* A parameter of 1.0 returns transparent, and 0.0 returns an identical color.
* @see Color.fadeIn
* @param p must be between -1.0 and 1.0; the amount by which to fade out this color
* @param relative should the alpha subtracted be relative?
* @returns a new Color object that corresponds to this color faded out by `p`
*/
fadeOut(p: number, relative = false): Color {
return this.fadeIn(-p, relative)
}
/**
* Mix (average) another color with this color, with a given weight favoring that color.
*
* If `weight == 0.0`, return exactly this color.
* `weight == 1.0` return exactly the other color.
* `weight == 0.5` (default if omitted) return a perfectly even mix.
* In other words, `weight` is "how much of the other color you want."
* Note that `color1.mix(color2, weight)` returns the same result as `color2.mix(color1, 1-weight)`.
* @param color the second color
* @param weight between 0.0 and 1.0; the weight favoring the other color
* @returns a mix of the two given colors
*/
mix(color: Color, weight = 0.5): Color {
let red : number = xjs.Math.average(this.red , color.red , weight)
let green: number = xjs.Math.average(this.green, color.green, weight)
let blue : number = xjs.Math.average(this.blue , color.blue , weight)
let alpha: number = Color._compoundOpacity([this.alpha, color.alpha])
return new Color(red, green, blue, alpha)
}
/**
* Blur another color with this color, with a given weight favoring that color.
*
* Behaves almost exactly the same as {@link Color.mix},
* except that this method uses a more visually accurate, slightly brighter, mix.
* @see {@link https://www.youtube.com/watch?v=LKnqECcg6Gw|“Computer Color is Broken” by minutephysics}
* @param color the second color
* @param weight between 0.0 and 1.0; the weight favoring the other color
* @returns a blur of the two given colors
*/
blur(color: Color, weight = 0.5): Color {
/**
* Calculate the compound value of two overlapping same-channel values.
* @private
* @param c1 the first channel value (red, green, or blue)
* @param c2 the second channel value (corresponding to `c1`)
* @returns the compounded value
*/
function compoundChannel(c1: number, c2: number) {
return Color._linear_sRGB(xjs.Math.average(Color._sRGB_Linear(c1), Color._sRGB_Linear(c2), weight))
}
let red : number = compoundChannel(this.red , color.red )
let green: number = compoundChannel(this.green, color.green)
let blue : number = compoundChannel(this.blue , color.blue )
let alpha: number = Color._compoundOpacity([this.alpha, color.alpha])
return new Color(red, green, blue, alpha)
}
/**
* Compare this color with another color.
*
* Return `true` if they are the same color.
* Colors are the “same” iff they have exactly the same RGBA channels.
* Thus, “same” colors are “replaceable”.
* @param color a Color object
* @returns is the argument the “same” color as this color?
*/
equals(color: Color): boolean {
if (this === color) return true
if (this.alpha === 0 && color.alpha === 0) return true
return (
this.red === color.red
&& this.green === color.green
&& this.blue === color.blue
&& this.alpha === color.alpha
)
}
/**
* Return the *relative luminance* of this color.
*
* The relative luminance of a color is the perceived brightness of that color.
* Note that this is different from the actual luminosity of the color.
* For examle, lime (`#00ff00`) and blue (`#0000ff`) both have a luminosity of 0.5,
* even though lime is perceived to be much brighter than blue.
* In fact, the relative luminance of lime is 0.72 — about ten times that of blue’s, which is only 0.07.
*
* In this method, alpha is ignored, that is, the color is assumed to be opaque.
* @see https://www.w3.org/TR/WCAG21/#dfn-relative-luminance
* @see https://en.wikipedia.org/wiki/Relative_luminance#Relative_luminance_in_colorimetric_spaces
* @returns the relative luminance of this color, a number 0–1
*/
relativeLuminance(): number {
return 0.2126 * Color._sRGB_Linear(this.red)
+ 0.7152 * Color._sRGB_Linear(this.green)
+ 0.0722 * Color._sRGB_Linear(this.blue)
}
/**
* Return the *contrast ratio* between two colors.
* @see https://www.w3.org/TR/WCAG/#dfn-contrast-ratio
* @param color the second color to check
* @returns the contrast ratio of this color with the argument, a number 1–21
*/
contrastRatio(color: Color): number {
let rl_this: number = this.relativeLuminance()
let rl_color: number = color.relativeLuminance()
return (Math.max(rl_this, rl_color) + 0.05) / (Math.min(rl_this, rl_color) + 0.05)
}
/**
* Return a string name of this color, if one exists.
* @see {@link https://www.w3.org/TR/css-color-4/#named-colors|Named Colors | CSS Color Module Level 4}
* @returns the name of this color, else `null` if it does not have one
*/
name(): string|null {
let named_colors: [string, string][] = Object.entries(NAMES)
const returned: [string, string]|null = named_colors.find((c) => c[1].toLowerCase() === this.toString(Color.Space.HEX)) || null
return (returned) ? returned[0] : null
}
}
<file_sep>import {Color} from '../../index'
import test from './test'
export default Promise.all([
test(`${Color.fromString('#000000').name()}`, 'black'),
test(`${Color.fromString('#98FB98').name()}`, 'palegreen'),
test(`${Color.fromString('#fa8072').name()}`, 'salmon'),
test(`${Color.fromString('#c0ffee').name()}`, 'null'),
])
|
d8a309aacdd0ed5b0f167aa03178e8edea4f6d44
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 13
|
TypeScript
|
chharvey/extrajs-color
|
57c5c91bb30c2107d98bf5099d1b172de465fdc7
|
84c95ba764f03a31aaf330af604c28da69f84ee4
|
refs/heads/master
|
<repo_name>TheDeibo/CommandTracker<file_sep>/src/RTG/Tracker/CommandTracker.php
<?php
namespace RTG\Tracker;
use pocketmine\utils\Config;
use pocketmine\plugin\PluginBase;
use pocketmine\Server;
use pocketmine\Player;
use pocketmine\event\Listener;
use pocketmine\event\player\PlayerCommandPreprocessEvent;
class CommandTracker extends PluginBase implements Listener {
public function onEnable() {
$this->getServer()->getPluginManager()->registerEvents($this, $this);
$this->logs = new Config($this->getDataFolder() . "logs.txt");
}
public function onFilter(PlayerCommandPreprocessEvent $e) {
$msg = $e->getMessage();
$carray = explode(" ",trim($msg));
$m = $carray[0];
$p = $e->getPlayer();
$n = $p->getName();
$r = intval(time());
$time = date("m-d-Y H:i:s", $r);
if($p->isOp() or $p->hasPermission("system.track")) {
if($m === "/kick" or $m === "/ban" or $m === "/pardon") {
$this->logs->set($time, "Player: " . $n . " | Command: " . $msg);
$this->logs->save();
}
}
}
public function onDisable() {
}
}<file_sep>/README.md
# CommandTracker
A plugin which meets your need!
|
4f516804874cfcf64eb11c4bf95297f4a4e41a44
|
[
"Markdown",
"PHP"
] | 2
|
PHP
|
TheDeibo/CommandTracker
|
22a372597e824252abda4463650bbbe87d48dfec
|
a6f2bd02e29349e52a952c5d2abc3dd730ac82b9
|
refs/heads/master
|
<repo_name>sanmaopep/hackathon-blockchain-lottery-frontend<file_sep>/src/menu.ts
import cosmosState from './store/comos';
interface MenuItem {
text: string;
route: string;
/** Look up Icons: https://fontawesome.com/v4.7.0/icons/ */
icon: string;
}
const menuMap: MenuItem[] = [
{
route: '/lottery',
icon: 'fa fa-play-circle',
text: 'Lottery',
},
// {
// route: '/blockBrowser',
// icon: 'fa fa-folder-open-o',
// text: 'Block Browser',
// },
];
export default menuMap;
<file_sep>/src/utils/constants.ts
export const Mnemonic =
'mean merit that visit year twin cargo habit obscure organ deliver equip young miracle swarm frequent stuff picnic strike wasp stadium moral betray hand';
<file_sep>/src/store/lottery.ts
import { autorun, computed, observable, toJS } from 'mobx';
export interface Lottery {
id: string;
status: string;
description: string;
title: string;
people: number;
hashed?: boolean;
rounds?: number[];
currentRound?: number;
candidateNum?: number;
stopEnroll?: boolean;
}
export enum LotteryStatus {
NotStart,
Playing,
Finish,
}
class LotteryState {
@observable lotteries: Lottery[] = [];
@observable currLottery: Lottery | undefined;
@observable pplList: string[] = [];
@observable winner: string[][] | null = null;
@computed
get status(): LotteryStatus {
if (!this.currLottery) {
return LotteryStatus.NotStart;
}
if (!this.currLottery.stopEnroll) {
return LotteryStatus.NotStart;
}
if (this.winner !== null) {
return LotteryStatus.Finish;
} else {
return LotteryStatus.Playing;
}
}
@computed
get sortedPpl(): string[] {
let list = this.pplList.slice(0).reverse();
if (this.winner) {
let winnerList = this.winner.reduce((acm, curr) => {
return acm.concat(curr);
}, []);
let loserList = this.pplList.filter(ppl => {
return winnerList.indexOf(ppl) === -1;
});
list = winnerList.concat(loserList);
}
return list;
}
}
const lotteryState = new LotteryState();
export default lotteryState;
<file_sep>/README.md
# hackthon-blockchain-lottery-frontend
modify /src/store/cosmos -> CosmosState -> lcdUrl, chainId
modify /src/utils/constants -> Mnemonic
```
npm install
npm start
```
<file_sep>/src/utils/utils.ts
export function convertStringToBytes(str) {
if (typeof str !== 'string') {
throw new Error('str expects a string');
}
var myBuffer = [];
var buffer = Buffer.from(str, 'utf8');
for (var i = 0; i < buffer.length; i++) {
//@ts-ignore
myBuffer.push(buffer[i]);
}
return myBuffer;
}
export function sortObject(obj) {
if (obj === null) return null;
if (typeof obj !== 'object') return obj;
if (Array.isArray(obj)) return obj.map(sortObject);
const sortedKeys = Object.keys(obj).sort();
const result = {};
sortedKeys.forEach(key => {
result[key] = sortObject(obj[key]);
});
return result;
}
export function randomDeepColor() {
const r = Math.floor(123 - Math.random() * 123);
const g = Math.floor(123 - Math.random() * 123);
const b = Math.floor(123 - Math.random() * 123);
return 'rgba(' + r + ',' + g + ',' + b + ',0.8)';
}
export function getRankColor(num) {
return ['red', 'green', 'yellow'][num];
}
<file_sep>/src/store/comos.ts
import { convertStringToBytes, sortObject } from '@/utils/utils';
import { Mnemonic } from './../utils/constants';
import service from '@/utils/fetch';
import { toast } from 'react-toastify';
const cosmosjs = require('@cosmostation/cosmosjs');
interface Msg {
type: string;
[key: string]: any;
}
class CosmosState {
lcdUrl = 'http://192.168.137.171';
chainId = 'cosmoshub-lotterychain';
cosmos;
// info for current user
address;
ecpairPriv;
account_number;
sequence;
mnemonic;
constructor() {
this.cosmos = cosmosjs.network(this.lcdUrl, this.chainId);
this.setMnemonic(Mnemonic);
}
setMnemonic(mnemonic) {
this.mnemonic = mnemonic;
this.address = this.cosmos.getAddress(mnemonic);
this.ecpairPriv = this.cosmos.getECPairPriv(mnemonic);
}
async getAccount() {
const { result } = await service.get(this.lcdUrl + '/auth/accounts/' + this.address);
const { account_number, sequence } = result.value;
this.account_number = account_number;
this.sequence = sequence;
return result.value;
}
async broadcastMsgs(msgs: Msg[]) {
const { chainId } = this;
const { account_number, sequence } = await this.getAccount();
const msgJson = {
chain_id: chainId,
account_number,
sequence,
fee: {
amount: [],
gas: '200000',
},
msgs: msgs,
memo: '',
};
const stdSignMsg = {
json: msgJson,
bytes: convertStringToBytes(JSON.stringify(sortObject(msgJson))),
};
const signedTx = this.cosmos.sign(stdSignMsg, this.ecpairPriv);
const response = await this.cosmos.broadcast(signedTx);
if (response.code) {
const errMsg = JSON.parse(response.raw_log).message;
toast.error(errMsg);
throw { msg: errMsg };
}
return response;
}
}
const cosmosState = new CosmosState();
export default cosmosState;
<file_sep>/src/services/lottery.ts
import { Lottery } from './../store/lottery';
import cosmosState from '@/store/comos';
import { router } from 'umi';
import service from '@/utils/fetch';
import { toast } from 'react-toastify';
export async function createLottery(lottery: Lottery) {
const response = await cosmosState.broadcastMsgs([
{
type: 'lotteryservice/MsgCreateLottery',
value: {
...lottery,
hashed: lottery.hashed ? lottery.hashed : false,
rounds: lottery.rounds ? lottery.rounds.map(num => String(num)) : [],
owner: cosmosState.address,
},
},
]);
toast.success('Add Successfully!');
toast.success(JSON.stringify(response.raw_log));
router.replace('/lottery');
}
export async function getLotteries() {
const response = await service.get(cosmosState.lcdUrl + '/lotteryservice/lotteries');
if (!response) return;
return response.result;
}
export async function getLottery(id: string) {
const response = await service.get(cosmosState.lcdUrl + '/lotteryservice/lottery/' + id);
if (!response || !response.result) {
return [];
}
const Lottery = response.result.Lottery;
Lottery.currentRound = Number(Lottery.currentRound);
return Lottery;
}
export async function addPplToLottery(lotteryId: string, candidates: string[]) {
const response = await cosmosState.broadcastMsgs([
{
type: 'lotteryservice/MsgAddCandidates',
value: {
sender: cosmosState.address,
id: lotteryId,
candidates,
},
},
]);
toast.success('Add Successfully!');
toast.success(JSON.stringify(response.raw_log));
}
export async function getLotteryPpl(id: string) {
const response = await service.get(
cosmosState.lcdUrl + '/lotteryservice/lottery/' + id + '/candidates',
);
if (!response || !response.result) {
return [];
}
return response.result;
}
export async function getLotteryWinner(id: string) {
const response = await service.get(
cosmosState.lcdUrl + '/lotteryservice/lottery/' + id + '/winners',
);
if (!response || !response.result) {
return [];
}
return response.result;
}
export async function startLottery(lotteryId: string) {
await cosmosState.broadcastMsgs([
{
type: 'lotteryservice/MsgStartLottery',
value: {
sender: cosmosState.address,
id: lotteryId,
},
},
]);
toast.info('Start Playing!');
}
<file_sep>/src/utils/fetch.ts
import { toast } from 'react-toastify';
function parseJSON(response) {
return response.json();
}
function checkStatus(response: Response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
throw {
message: `${response.status} ${response.statusText}`,
};
}
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
function request(url, options = {}) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON)
.then(data => data)
.catch(err => {
toast.error(err.message);
});
}
const service = {
request: request,
get(url, data?) {
if (data) {
return request(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
} else {
return request(url);
}
},
post(url, data) {
return request(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
},
put(url, data) {
return request(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
},
delete(url, data) {
return request(url, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
},
};
export default service;
|
88c0eb6aa05df8c9341bc5919a2fc7f1907395f1
|
[
"Markdown",
"TypeScript"
] | 8
|
TypeScript
|
sanmaopep/hackathon-blockchain-lottery-frontend
|
cb92d2f9fe42ed1b94cbc7f8b90b5a5040ada8a0
|
cf4810e69bab9f7fbbf8ad49b1df3e2ffbed8b48
|
refs/heads/master
|
<repo_name>baaslaawe/Internet_radio_speaker_recognition<file_sep>/Offilne_speaker_recog_TIMIT.py
__author__ = '<NAME>'
"""
#######################################################################################################
If you use this project in scientific publication, we would appreciate citations to the following paper:
@article{WeychanAsrPi,
author = {<NAME> and <NAME> and <NAME>},
title = {Implementation aspects of speaker recognition using {Python} language and {Raspberry Pi} platform},
journal = {IEEE SPA: Signal Processing Algorithms, Architectures, Arrangements, and Applications Conference Proceedings},
year = {2015},
pages = {95--98},
confidential = {n}
}
#######################################################################################################
"""
# All TIMIT files should be placed in speakers directory.
# In this case the name of every file is like XXXyy.wav,
# where XXXX stands for person 'name' (like FADG from TIMIT files)
# and yy stands for number of utterrance (00 to 09)
# FADG00.wav, FADG01.wav, FADG02.wav
import glob
import os
import numpy as np
import MFCC
import scipy.io.wavfile as wav
from sklearn import mixture
import scipy.io as sio
def GMM_test(ii):
speakers_MFCC_dict = {}
speaker_GMM_dict = {}
files = glob.glob(os.getcwd()+'\\speakers\\*.wav')
gauss_num = 32
iterator = 1
num_iter = ii
if os.path.isfile('mfcc_'+str(gauss_num)+'.mat'):
speaker_GMM_dict = sio.loadmat('mfcc_'+str(gauss_num)+'.mat')
speaker_GMM_dict.pop('__header__')
speaker_GMM_dict.pop('__version__')
speaker_GMM_dict.pop('__globals__')
else:
for file in files:
#print(file)
if file[-6:-4] == '00': #file[len(file)-12:len(file)-9]
current_speaker = file[len(file)-10:len(file)-6]
print("############# Calculate MFCC and GMM for ", current_speaker, " , speaker no ", str(iterator))
#if iterator == 572:
# print("Tu bedzie error")
iterator += 1
merged_files = np.array([])
for i in range(0, 9):
current_file = wav.read(file[:-5]+str(i)+file[-4:])
merged_files = np.append(merged_files, current_file[1])
#print(type(merged_files))
speaker_MFCC = MFCC.extract(merged_files)
speaker_MFCC = speaker_MFCC[:, 1:]
speakers_MFCC_dict[current_speaker] = speaker_MFCC
g = mixture.GMM(n_components=gauss_num, n_iter=num_iter)
g.fit(speaker_MFCC)
speaker_model = np.array([g.means_, g.covars_, np.repeat(g.weights_[:, np.newaxis], 12, 1)])
speaker_GMM_dict[current_speaker] = speaker_model
sio.savemat('mfcc_'+str(gauss_num)+'.mat', speaker_GMM_dict, oned_as='row')
iterator = 1
good = 0
bad = 0
total = 0
for file in files:
if file[-6:-4] == '09':
g = mixture.GMM(n_components=gauss_num, n_iter=num_iter)
current_file = wav.read(file)
current_speaker = file[len(file)-10:len(file)-6]
#print(current_speaker, )
speaker_MFCC = MFCC.extract(current_file[1])
speaker_MFCC = speaker_MFCC[:, 1:]
log_prob = -10000
winner = 'nobody'
for key, values in speaker_GMM_dict.items():
try:
g.means_ = values[0, :, :]
g.covars_ = values[1, :, :]
g.weights_ = values[2, :, 1]
temp_prob = np.mean(g.score(speaker_MFCC))
if temp_prob > log_prob:
log_prob = temp_prob
winner = key
except TypeError:
print('error for ', key)
if current_speaker == winner:
good += 1
else:
bad += 1
total +=1
print(current_speaker, " speaker no ", str(iterator), " is similar to ", winner, " - log prob = ", str(log_prob))
print("good = ", str(good), ", bad = ", str(bad), ", total = ", str(total))
iterator += 1
print("GMM, n_iter = ", num_iter, ", Efficiency = ", str(good/total))
def VBGMM_test(cov_type, alpha_val):
#speakers_MFCC_dict = {}
#speaker_GMM_dict = {}
files = glob.glob(os.getcwd()+'\\speakers\\*.wav')
gauss_num = 32
iterator = 1
test_files = []
good = 0
bad = 0
total = 0
for file in files:
if file[-6:-4] == '09':
test_files.append(file)
for file in files:
#print(file)
if file[-6:-4] == '00': #file[len(file)-12:len(file)-9]
current_speaker = file[len(file)-10:len(file)-6]
#print("############# Calculate MFCC and VBGMM for ", current_speaker, " , speaker no ", str(iterator))
merged_files = np.array([])
for i in range(0, 9):
current_file = wav.read(file[:-5]+str(i)+file[-4:])
merged_files = np.append(merged_files, current_file[1])
#print(type(merged_files))
speaker_MFCC = MFCC.extract(merged_files)
speaker_MFCC = speaker_MFCC[:, 1:]
#speakers_MFCC_dict[current_speaker] = speaker_MFCC
g = mixture.VBGMM(n_components=gauss_num, n_iter=100, covariance_type=cov_type, alpha=alpha_val)
g.fit(speaker_MFCC)
#speaker_model = np.array([g.means_, g.precs_, np.repeat(g.weights_[:, np.newaxis], 12, 1)])
#speaker_GMM_dict[current_speaker] = speaker_model
log_prob = -10000
winner = 'nobody'
for test_file in test_files:
current_test_speaker = test_file[len(test_file)-10:len(test_file)-6]
current_test_file = wav.read(test_file)
test_speaker_MFCC = MFCC.extract(current_test_file[1])
test_speaker_MFCC = test_speaker_MFCC[:, 1:]
temp_prob = np.mean(g.score(test_speaker_MFCC))
if temp_prob > log_prob:
log_prob = temp_prob
winner = current_test_speaker
if winner == current_speaker:
good += 1
else:
bad += 1
total +=1
#print(current_speaker, " speaker no ", str(iterator), " is similar to ", winner, " - log prob = ", str(log_prob))
#print("good = ", str(good), ", bad = ", str(bad), ", total = ", str(total))
iterator += 1
print("VBGMM (covariance_type - ", cov_type, ", alpha - ", str(alpha_val), "), Efficiency = ", str(good/total))
#sio.savemat('mfcc_'+str(gauss_num)+'_VBGMM.mat', speaker_GMM_dict, oned_as='row')
def DPGMM_test(cov_type, alpha_val):
#speakers_MFCC_dict = {}
#speaker_GMM_dict = {}
files = glob.glob(os.getcwd()+'\\speakers\\*.wav')
gauss_num = 32
iterator = 1
test_files = []
good = 0
bad = 0
total = 0
for file in files:
if file[-6:-4] == '09':
test_files.append(file)
for file in files:
#print(file)
if file[-6:-4] == '00': #file[len(file)-12:len(file)-9]
current_speaker = file[len(file)-10:len(file)-6]
#print("############# Calculate MFCC and DPGMM for ", current_speaker, " , speaker no ", str(iterator))
#if iterator == 572:
# print("Tu bedzie error")
merged_files = np.array([])
for i in range(0, 9):
current_file = wav.read(file[:-5]+str(i)+file[-4:])
merged_files = np.append(merged_files, current_file[1])
#print(type(merged_files))
speaker_MFCC = MFCC.extract(merged_files)
speaker_MFCC = speaker_MFCC[:, 1:]
#speakers_MFCC_dict[current_speaker] = speaker_MFCC
g = mixture.DPGMM(n_components=gauss_num, n_iter=100, covariance_type=cov_type, alpha=alpha_val)
g.fit(speaker_MFCC)
#speaker_model = np.array([g.means_, g.precs_, np.repeat(g.weights_[:, np.newaxis], 12, 1)])
#speaker_GMM_dict[current_speaker] = speaker_model
log_prob = -10000
winner = 'nobody'
for test_file in test_files:
current_test_speaker = test_file[len(test_file)-10:len(test_file)-6]
current_test_file = wav.read(test_file)
test_speaker_MFCC = MFCC.extract(current_test_file[1])
test_speaker_MFCC = test_speaker_MFCC[:, 1:]
temp_prob = np.mean(g.score(test_speaker_MFCC))
if temp_prob > log_prob:
log_prob = temp_prob
winner = current_test_speaker
if winner == current_speaker:
good += 1
else:
bad += 1
total +=1
#print(current_speaker, " speaker no ", str(iterator), " is similar to ", winner, " - log prob = ", str(log_prob))
#print("good = ", str(good), ", bad = ", str(bad), ", total = ", str(total))
iterator += 1
print("DPGMM (covariance_type - ", cov_type, ", alpha - ", str(alpha_val), "), Efficiency = ", str(good/total))
#sio.savemat('mfcc_'+str(gauss_num)+'_VBGMM.mat', speaker_GMM_dict, oned_as='row')
if __name__ == "__main__":
GMM_test(10)
#alpha_num = [1, 10, 100]
#covariance_type = ["spherical", "tied", "diag", "full"]
#for i in alpha_num:
# for j in covariance_type:
# DPGMM_test(j, i)
# VBGMM_test(j, i)<file_sep>/Record_and_model.py
__author__ = '<NAME>'
"""
#######################################################################################################
If you use this project in scientific publication, we would appreciate citations to the following paper:
@article{WeychanAsrPi,
author = {<NAME> and <NAME> and <NAME>},
title = {Implementation aspects of speaker recognition using {Python} language and {Raspberry Pi} platform},
journal = {IEEE SPA: Signal Processing Algorithms, Architectures, Arrangements, and Applications Conference Proceedings},
year = {2015},
pages = {95--98},
confidential = {n}
}
#######################################################################################################
"""
import urllib
import ctypes
import binascii
import time
import pymedia.audio.acodec as acodec
import pymedia.muxer as muxer
import pymedia.audio.sound as sound
import numpy as np
import matplotlib.pyplot as plt
from sklearn import mixture
import scipy.io.wavfile as wav
import scipy.io as sio
import os
import MFCC
def read_radio_stream(url_):
an_array = np.array([])
r2 = urllib.urlopen(url_)
format_ = sound.AFMT_S16_LE
snd_out = sound.Output(44100, 2, format_)
dm = muxer.Demuxer('mp3')
dec = None
print(r2.info())
print('###################\n')
i = 0
while i < 1: # in the case of longer signals needed
start = time.time()
samples = r2.read(300000)
frames = dm.parse(samples)
if dec is None:
# Open decoder
dec = acodec.Decoder(dm.streams[0])
frames_list = decode_frames(frames, dec)
play_decoded_frames(frames_list, snd_out)
sound_np_array = ansic_to_numpy(frames_list)
sound_np_array = decimate(sound_np_array, 4)
an_array = np.append(an_array, np.transpose(sound_np_array))
end = time.time()
print end-start
i += 1
return an_array
def decode_frames(frames_, dec_):
frames_list_ = []
for fr in frames_:
r = dec_.decode(fr[1])
frames_list_.append(r.data)
return frames_list_
def play_decoded_frames(frames_, snd_out_):
for fr in frames_:
snd_out_.play(fr)
def decimate(np_array, factor):
np_array = np_array[0:(np_array.shape[0] / factor) * factor]
np_array = np_array.reshape(-1, factor)
np_array = np_array.reshape(-1, factor).mean(axis=1)
return np_array
def calc_rms(np_array):
return np.sqrt(sum(np_array ** 2))
def plot_audio_data(np_array):
plt.plot(np_array)
plt.show()
def ansic_to_numpy(frames_):
scale_fun = lambda x: x / 1.0 if x < 32768 else (x - 65536) / 1.0 # uint16 to int16
sound_np_array_ = np.array([])
for fr in frames_:
hex_values_str = fr.__str__()
hex_audio_mono = ''.join([hex_values_str[i:i + 2] for i in range(0, len(hex_values_str), 4)])
pcm_audio_uint16 = [int(binascii.b2a_hex(hex_audio_mono[i:i - 2:-1]), 16) for i in
range(3, len(hex_audio_mono), 2)] #little endian
pcm_audio = np.array([scale_fun(x) for x in pcm_audio_uint16])
sound_np_array_ = np.append(sound_np_array_, pcm_audio, axis=1)
r = dec_.decode(fr[1])
if r and r.data:
# raw_ansic_python_obj = ctypes.py_object(r.data)
# ACstr_raw_C_data = raw_ansic_python_obj.value
# hex_values_str = ACstr_raw_C_data.__str__()
hex_values_str = r.data.__str__()
# hex_audio_mono1 = hex_values_str[0:-1:2]
hex_audio_mono = ''.join([hex_values_str[i:i + 2] for i in range(0, len(hex_values_str), 4)])
pcm_audio_uint16 = [int(binascii.b2a_hex(hex_audio_mono[i:i - 2:-1]), 16) for i in
range(3, len(hex_audio_mono), 2)] # little endian
pcm_audio = np.array([scale_fun(x) for x in pcm_audio_uint16])
sound_np_array_ = np.append(sound_np_array_, pcm_audio, axis=1)
return sound_np_array_
def add_to_database(url_, person_name_):
gmm_models = {}
if os.path.isfile('mfcc.mat'):
gmm_models = sio.loadmat('mfcc.mat')
print "Recording and processing...\n\n"
full_sound_model = read_radio_stream(url_)
wav.write('People\\'+person_name_+'.wav', 11025, full_sound_model/32767.0)
print "Calculating MFCC and saving the model..."
mfcc_features = MFCC.extract(full_sound_model)
mfcc_features = mfcc_features[:, 1:]
g = mixture.GMM(n_components=128)
g.fit(mfcc_features)
model = np.array([g.means_, g.covars_, np.repeat(g.weights_[:, np.newaxis], 12, 1)]) # weights have to be repeated to properly save the np array
print len(g.means_)
gmm_models[person_name_] = model
sio.savemat('mfcc_32.mat', gmm_models, oned_as='row')
if __name__ == "__main__":
url = 'http://poznan5-4.radio.pionier.net.pl:8000/tuba10-1.mp3'
person_name = 'Person_2'
add_to_database(url, person_name)
<file_sep>/README.md
# Internet_radio_speaker_recognition
Python implementation of speaker recognition from Internet radio
<file_sep>/Internet_radio_speaker_windows.py
__author__ = '<NAME>'
"""
#######################################################################################################
If you use this project in scientific publication, we would appreciate citations to the following paper:
@article{WeychanAsrPi,
author = {<NAME> and <NAME> and <NAME>},
title = {Implementation aspects of speaker recognition using {Python} language and {Raspberry Pi} platform},
journal = {IEEE SPA: Signal Processing Algorithms, Architectures, Arrangements, and Applications Conference Proceedings},
year = {2015},
pages = {95--98},
confidential = {n}
}
#######################################################################################################
"""
import urllib
import wave
import string
import ctypes
import binascii
import time
import pymedia.audio.acodec as acodec
import pymedia.muxer as muxer
import pymedia.audio.sound as sound
import numpy as np
import matplotlib.pyplot as plt
from sklearn import mixture
import scipy.io as sio
import scipy.io.wavfile as wav
import MFCC
def read_radio_stream(url_):
database = sio.loadmat('mfcc_16_fft256_GMM.mat')
database.pop('__header__')
database.pop('__version__')
database.pop('__globals__')
r2 = urllib.urlopen(url_)
format_ = sound.AFMT_S16_LE
snd_out = sound.Output(44100, 2, format_)
dm = muxer.Demuxer('mp3')
dec = None
snd = None
print(r2.info())
print('###################\n')
while True:
samples = r2.read(15000)
frames = dm.parse(samples)
if dec is None:
dec = acodec.Decoder(dm.streams[0])
#start = time.clock()
frames_list = decode_frames(frames, dec)
#elapsed = (time.clock() - start)
#print "Decode - ", elapsed
#start = time.clock()
play_decoded_frames(frames_list, snd_out)
#elapsed = (time.clock() - start)
#print "Send to play play - ", elapsed
#start = time.clock()
sound_np_array = ansic_to_numpy(frames_list)
#elapsed = (time.clock() - start)
#print "To ndarray - ", elapsed
#start = time.clock()
sound_np_array = decimate(sound_np_array, 2)
#elapsed = (time.clock() - start)
#print "Decimate - ", elapsed
#start = time.clock()
mfcc_features = MFCC.extract(sound_np_array) #1.5s
mfcc_features = mfcc_features[:, 1:]
#elapsed = (time.clock() - start)
#print "MFCC - ", elapsed
#print mfcc_features.shape
g = mixture.GMM(n_components=16)
log_prob = -10000
winner = 'nobody'
for key, values in database.iteritems():
try:
#start = time.clock()
g.means_ = values[0, :, :]
g.covars_ = values[1, :, :]
g.weights_ = values[2, :, 1]
temp_prob = np.mean(g.score(mfcc_features))
if temp_prob > log_prob:
log_prob = temp_prob
winner = key
#elapsed = (time.clock() - start)
#print "Log-likelihood - ", elapsed
except TypeError:
print 'error for ', key
print winner, log_prob
print('\n###################')
def decode_frames(frames_, dec_):
frames_list_ = []
for fr in frames_:
r = dec_.decode(fr[1])
frames_list_.append(r.data)
return frames_list_
def play_decoded_frames(frames_, snd_out_):
for fr in frames_:
snd_out_.play(fr)
#snd_out_.play(frames_)
def ansic_to_numpy_old(frames_):
scale_fun = lambda x: x / 1.0 if x < 32768 else (x - 65536) / 1.0 # uint16 to int16
sound_np_array_ = np.array([])
for fr in frames_:
hex_values_str = fr.__str__()
hex_audio_mono = ''.join([hex_values_str[i:i + 2] for i in range(0, len(hex_values_str), 4)])
pcm_audio_uint16 = [int(binascii.b2a_hex(hex_audio_mono[i:i - 2:-1]), 16) for i in
range(3, len(hex_audio_mono), 2)] #little endian
pcm_audio = np.array([scale_fun(x) for x in pcm_audio_uint16])
sound_np_array_ = np.append(sound_np_array_, pcm_audio, axis=1)
return sound_np_array_
def ansic_to_numpy(frames_):
sound_np_array_ = np.array([])
for fr in frames_:
hex_values_str = fr.__str__()
pcm_audio = np.fromstring(hex_values_str, dtype='int16')
pcm_audio = pcm_audio[2::2]
sound_np_array_ = np.append(sound_np_array_, pcm_audio, axis=1)
return sound_np_array_
def decimate(np_array, factor):
np_array = np_array[0:(np_array.shape[0] / factor) * factor]
np_array = np_array.reshape(-1, factor)
np_array = np_array.reshape(-1, factor).mean(axis=1)
return np_array
def calc_rms(np_array):
return np.sqrt(sum(np_array ** 2))
def plot_audio_data(np_array):
plt.plot(np_array)
plt.show()
if __name__ == "__main__":
url = 'http://poznan5-4.radio.pionier.net.pl:8000/tuba10-1.mp3'
read_radio_stream(url)
|
5c8d1339158b5e0a393fca01deeb0240069c8df2
|
[
"Markdown",
"Python"
] | 4
|
Python
|
baaslaawe/Internet_radio_speaker_recognition
|
6bc140be25848da8b162c9efe011ddb71e44d61c
|
2f79efda0d48ce08718f0ddccdd60c6be8c34035
|
refs/heads/master
|
<repo_name>dujuncheng/buwang_wxxcx<file_sep>/src/utils/storage.js
const Storage = (key) => ({
set (v = '') {
wx.setStorageSync(key, v)
},
get () {
return wx.getStorageSync(key)
},
remove () {
wx.removeStorageSync(key)
}
})
module.exports = {
cookie: Storage('_x_session')
}
<file_sep>/src/utils/eventBus.js
export default class EventBus {
constructor() {
this._events = {};
}
on(ev, cb, ctx) {
if (arguments.length !== 3) {
throw new Error('EventBus Error: Must transfer three arguments, read doc for detail: http://git.beibei.com.cn/fe-wxmp/event-bus\n');
}
if (!ev) {
throw new Error(`EventBus Error: Need transfer a non-empty string for event name.`);
}
if (typeof cb !== 'function') {
throw new Error(`EventBus Error: The callback of '${ev}' must be a function.`);
}
if (!ctx) {
throw new Error(`EventBus Error: Need transfer page instance as context of '${ev}' callback.`);
}
this._events[ev] = this._events[ev] || [];
let events = this._events[ev];
// Avoid repeatedly collect dependencies
if (events.length) {
const noRepeat = events.every((item) => {
if (item.ctx !== ctx) {
return true;
}
if (item.cb !== cb) {
return true;
}
return false;
});
if (noRepeat) {
events.push({
cb,
ctx,
});
}
} else {
events.push({
cb,
ctx,
});
}
}
emit(ev, ...args) {
if (!ev) {
throw new Error(`EventBus Error: Need transfer a non-empty string for event name.`);
}
let events = this._events[ev];
if (!events || !events.length) {
console.warn(`EventBus Warn: No registered listener of event '${ev}'.`);
return;
}
events.forEach((item) => {
item.cb.call(item.ctx, ...args);
});
}
off(ev, cb) {
// if no arg, remove all listeners
if (!arguments.length) {
this._events = {};
return;
}
let events = this._events[ev];
// if only transfer ev, remove all listeners of this event
if (arguments.length === 1) {
delete this._events[ev];
return;
}
if (!events) {
console.warn(`EventBus Warn: No registered event '${ev}'.`);
return;
}
if (!events.length) {
console.warn(`EventBus Warn: No listener of the event '${ev}'.`);
return;
}
events.some((item, index) => {
if (item.cb === cb) {
events.splice(index, 1);
return true;
}
return false;
});
}
}
<file_sep>/src/config/const.js
let REVIEW_PAGE_SIZE = 10;
export {
REVIEW_PAGE_SIZE
}
<file_sep>/.eslintrc.js
module.exports = {
root: true,
env: {
node: true
},
rules: {
'no-multi-spaces': 0,
'no-console': 0,
'no-tabs': 0,
'no-mixed-spaces-and-tabs': 0,
'indent': 0,
'no-trailing-spaces': [2, { "skipBlankLines": true }],
},
'extends': [
'@megalo/standard'
]
}
<file_sep>/src/utils/ajax.js
const Storage = require('./storage.js')
const baseUrl = 'https://www.sharkbaby.club/notebook'
const ajax = (type, method, params) => {
return new Promise((resolve, reject) => {
wx.request({
method: type,
url: `${baseUrl}?method=${method}`,
data: params,
header: {
'Cookie': `_x_session=${Storage.cookie.get()}`
},
success (res) {
if (res.header && res.header['x_session']) {
Storage.cookie.set(res.header['x_session'])
}
if (res && res.data && !res.data.success && Number(res.data.err_code) === 2) {
wx.redirectTo({
url: '/pages/login-page/index'
})
}
if (res && res.data) {
resolve(res.data)
} else {
reject(res)
}
},
fail (e) {
reject(e)
}
})
})
}
module.exports = ajax
|
5f46912e7678341a7196c7299f5f781b9542b591
|
[
"JavaScript"
] | 5
|
JavaScript
|
dujuncheng/buwang_wxxcx
|
92b95f2f91c95ee9e142e82feabbfa5d246b6f70
|
16eb0333b8fd05c1b656b179b967391c9a13afd0
|
refs/heads/master
|
<repo_name>gideon-steinberg/circuits<file_sep>/lib/circuits/component/base.rb
require 'circuits/terminal/input'
require 'circuits/terminal/output'
module Circuits
# A component has a set of inputs an outputs. Every `tick` a componnent
# computes its outputs, but the componnent will wait for the `tock` before the
# componnent updates its own outputs
module Component
# Base class to extend
class Base
# Creates the Component with inputs and outputs
# @param opts [Hash] options to create the Component with
# @option opts [FixNum] :input_count The number of inputs
# @option opts [FixNum] :ouput_count The number of outputs
# @option opts [Hash] :port_mappings The port_mappings to use
def initialize(opts = {})
input_count = opts[:input_count] || default_input_count
output_count = opts[:output_count] || default_output_count
@inputs = input_count.times.collect { Circuits::Terminal::Input.new }
@outputs = output_count.times.collect { Circuits::Terminal::Output.new }
@port_mappings = opts[:port_mappings] || default_port_mappings
end
# the inputs of this component
attr_reader :inputs
# the outputs of this component
attr_reader :outputs
# For easy access to the ports
# @param [Symbol] method_name The name of the method
# @return [Input, Outpus] The corresponding port
def method_missing(method_name, *_, &__)
res = self[method_name]
super if res.nil?
res
end
# Sets all the outputs expose what was set in #tick
def tock
outputs.each(&:tock)
end
# So we can advertise what ports are available from {#method_missing}
# @param [Symbol] method_name The name of the method
# @return [Boolean] Wether or a method call will be responded to
def respond_to_missing?(method_name, _)
!self[method_name].nil? || super
end
# Gets the teminal assigned to the port
# @param port [Symbol] The symbol that represents the terminal
# @return [Input, Output] The terminal
def [](port)
port_mapping = port_mappings[port]
return nil if port_mapping.nil?
port_number = port_mapping[:number]
case port_mapping[:type]
when :input
inputs[port_number]
when :output
outputs[port_number]
end
end
private
attr_reader :port_mappings
def default_port_mappings
res = {}
(input_mappings + output_mappings).each do |mapping|
res.merge!(mapping)
end
res
end
def input_mappings
input_count = inputs.length
return [{ in: { type: :input, number: 0 } }] if input_count == 1
input_count.times.collect do |num|
{ num_to_port(num) => { type: :input, number: num } }
end
end
def output_mappings
output_count = outputs.length
return[{ out: { type: :output, number: 0 } }] if output_count == 1
output_count.times.collect do |num|
{ num_to_port(num + inputs.length) => { type: :output, number: num } }
end
end
def num_to_port(num)
(num + 'a'.ord).chr.to_sym
end
end
end
end
<file_sep>/spec/unit/circuits/component/sr_nor_spec.rb
require 'spec_helper'
require 'circuits/component/sr_nor'
describe Circuits::Component::SrNor do
describe '#tick' do
subject { Circuits::Component::SrNor.new }
context 'it has just been initialized' do
it 'is unset' do
expect(subject[:q].get).to eq false
expect(subject[:not_q].get).to eq true
end
it 'is stable' do
subject.tick
subject.tock
expect(subject[:q].get).to eq false
expect(subject[:not_q].get).to eq true
end
end
context 'is set' do
before do
subject[:r].set false
subject[:s].set true
subject.tick
subject.tock
subject[:s].set false
end
it 'is set' do
expect(subject[:q].get).to eq true
expect(subject[:not_q].get).to eq false
end
it 'is stable' do
subject.tick
subject.tock
expect(subject[:q].get).to eq true
expect(subject[:not_q].get).to eq false
end
it 'can be reset' do
subject[:r].set true
subject.tick
subject.tock
expect(subject[:q].get).to eq false
expect(subject[:not_q].get).to eq true
end
end
context 'is reset' do
before do
subject[:r].set true
subject[:s].set false
subject.tick
subject.tock
subject[:r].set false
end
it 'is reset' do
expect(subject[:q].get).to eq false
expect(subject[:not_q].get).to eq true
end
it 'is stable' do
subject.tick
subject.tock
expect(subject[:q].get).to eq false
expect(subject[:not_q].get).to eq true
end
it 'can be set' do
subject[:s].set true
subject.tick
subject.tock
expect(subject[:q].get).to eq true
expect(subject[:not_q].get).to eq false
end
end
end
end
<file_sep>/spec/unit/circuits/component/sr_nand_spec.rb
require 'spec_helper'
require 'circuits/component/sr_nand'
describe Circuits::Component::SrNand do
describe '#tick' do
subject { Circuits::Component::SrNand.new }
context 'it has just been initialized' do
it 'is unset' do
expect(subject[:q].get).to eq false
expect(subject[:not_q].get).to eq true
end
it 'is stable' do
subject.tick
subject.tock
expect(subject[:q].get).to eq false
expect(subject[:not_q].get).to eq true
end
end
context 'is set' do
before do
subject[:not_s].set false
subject[:not_r].set true
subject.tick
subject.tock
subject[:not_s].set true
end
it 'is set' do
expect(subject[:q].get).to eq true
expect(subject[:not_q].get).to eq false
end
it 'is stable' do
subject.tick
subject.tock
expect(subject[:q].get).to eq true
expect(subject[:not_q].get).to eq false
end
it 'can be reset' do
subject[:not_r].set false
subject.tick
subject.tock
expect(subject[:q].get).to eq false
expect(subject[:not_q].get).to eq true
end
end
context 'is reset' do
before do
subject[:not_s].set true
subject[:not_r].set false
subject.tick
subject.tock
subject[:not_r].set true
end
it 'is reset' do
expect(subject[:q].get).to eq false
expect(subject[:not_q].get).to eq true
end
it 'is stable' do
subject.tick
subject.tock
expect(subject[:q].get).to eq false
expect(subject[:not_q].get).to eq true
end
it 'can be set' do
subject[:not_s].set false
subject.tick
subject.tock
expect(subject[:q].get).to eq true
expect(subject[:not_q].get).to eq false
end
end
end
end
<file_sep>/lib/circuits/version.rb
# Circuits allows you to express logical circuits in code
module Circuits
# The version of the Circuits gem
VERSION = '0.10.0'
end
<file_sep>/spec/unit/circuits/component/base_spec.rb
require 'spec_helper'
require 'circuits/component/base'
# Mock component to include Circuits::Component::Base
class MockComponent1 < Circuits::Component::Base
def default_input_count
1
end
def default_output_count
1
end
end
# Mock component to include Circuits::Component::Base
class MockComponent2 < Circuits::Component::Base
def default_input_count
2
end
def default_output_count
2
end
end
describe Circuits::Component::Base do
describe '#[]' do
context 'one input and one output' do
subject { MockComponent1.new }
it 'has the input available as #in' do
expect(subject[:in]).to eq(subject.inputs[0])
end
it 'has the output available as #out' do
expect(subject[:out]).to eq(subject.outputs[0])
end
it 'has the input available as :in' do
expect(subject.in).to eq(subject.inputs[0])
end
it 'has the output available as :out' do
expect(subject.out).to eq(subject.outputs[0])
end
it 'gets nil when invalid' do
expect(subject[:a]).to eq(nil)
end
it 'responds to #in' do
expect(subject.respond_to? :in).to eq true
end
it 'responds to #out' do
expect(subject.respond_to? :out).to eq true
end
it 'does not respond to #a' do
expect(subject.respond_to? :a).to eq false
end
end
context 'two inputs and two outputs' do
subject { MockComponent2.new }
it 'has the inputs available as #a and #b' do
expect(subject.a).to eq(subject.inputs[0])
expect(subject.b).to eq(subject.inputs[1])
end
it 'has the outputs available as #c and #d' do
expect(subject.c).to eq(subject.outputs[0])
expect(subject.d).to eq(subject.outputs[1])
end
end
end
end
<file_sep>/spec/unit/circuits/component/and_spec.rb
require 'spec_helper'
require 'circuits/component/and'
describe Circuits::Component::And do
describe '#tick' do
context 'default input count' do
subject { Circuits::Component::And.new }
context 'false + false' do
it '= false' do
subject.a.set false
subject.b.set false
subject.tick
subject.tock
expect(subject.out.get).to eq false
end
end
context 'true + false' do
it '= false' do
subject.a.set true
subject.b.set false
subject.tick
subject.tock
expect(subject.out.get).to eq false
end
end
context 'false + true' do
it '= false' do
subject.a.set false
subject.b.set true
subject.tick
subject.tock
expect(subject.out.get).to eq false
end
end
context 'true + true' do
it '= true' do
subject.a.set true
subject.b.set true
subject.tick
subject.tock
expect(subject.out.get).to eq true
end
end
end
[3, 4, 8].each do |n|
context "with #{n} inputs" do
subject { Circuits::Component::And.new input_count: n }
before do
n.times { |x| subject.inputs[x].set inputs[x] }
end
context 'when all inputs are true' do
let(:inputs) { n.times.collect { true } }
it '= true' do
subject.tick
subject.tock
expect(subject.out.get).to eq true
end
end
context 'when all inputs are false' do
let(:inputs) { n.times.collect { false } }
it '= false' do
subject.tick
subject.tock
expect(subject.out.get).to eq false
end
end
context 'when any input is false' do
n.times do |x|
context "when input #{x} is false" do
let(:inputs) do
inputs = n.times.collect { true }
inputs[x] = false
inputs
end
it '= false' do
subject.tick
subject.tock
expect(subject.out.get).to eq false
end
end
end
end
end
end
end
end
<file_sep>/Rakefile
require 'bundler/gem_tasks'
require 'rspec/core/rake_task'
require 'rubocop/rake_task'
require 'reek/rake/task'
require 'yard'
RSpec::Core::RakeTask.new(:spec)
task default: :spec
RuboCop::RakeTask.new(:rubocop) do |task|
task.patterns = ['lib/**/*.rb']
# only show the files with failures
task.formatters = ['files']
end
Reek::Rake::Task.new
task lint: [:rubocop, :reek]
YARD::Rake::YardocTask.new(:yard) do |t|
t.stats_options = ['--list-undoc']
end
<file_sep>/lib/circuits/component/generic_state_circuit.rb
require 'circuits/component/base'
require 'circuits/component/and'
require 'circuits/component/or'
require 'circuits/component/d'
require 'circuits/component/not'
module Circuits
module Component
class GenericStateCircuit < Base
def initialize
super(port_mappings: { i: { type: :input, number: 0 },
out: { type: :output, number: 0 } })
@ands = []
@ors = []
@nots = []
@states = []
end
def set_number_of_ands number
@ands = []
number.times.each do |_|
@ands << And.new
end
end
def set_number_of_ors number
@ors = []
number.times.each do |_|
@ors << Or.new
end
end
def set_number_of_states number
@states = []
number.times.each do |_|
@states << D.new
end
end
def set_number_of_nots number
@nots = []
number.times.each do |_|
@nots << Not.new
end
end
def get_and number
@ands[number]
end
def get_or number
@ors[number]
end
def get_state number
@states[number]
end
def get_not number
@nots[number]
end
def tick
tick_internal
@states.each do |s|
s.clk.set true
end
tick_internal
@states.each do |s|
s.clk.set false
end
tick_internal
end
def tick_internal
number_of_inputs = 0
number_of_inputs += @ands.length
number_of_inputs += @ors.length
number_of_inputs += @nots.length
number_of_inputs.times.each do |_|
@ands.each(&:tick)
@ors.each(&:tick)
@nots.each(&:tick)
@states.each(&:tick)
@states.each(&:tock)
@ands.each(&:tock)
@ors.each(&:tock)
@nots.each(&:tock)
end
end
private
def default_input_count
1
end
def default_output_count
1
end
end
end
end<file_sep>/lib/circuits/component/d.rb
require 'circuits/component/base'
require 'circuits/component/sr_nand'
require 'circuits/component/and'
require 'circuits/component/nand'
module Circuits
module Component
# Positive edge triggered D-type flip flop
class D < Base
def initialize
super(port_mappings: { d: { type: :input, number: 0 },
clk: { type: :input, number: 1 },
q: { type: :output, number: 0 },
not_q: { type: :output, number: 1 } })
create_sub_components
link_sub_components
reset
end
# Computes the outputs based on the inputs and previous state
def tick
3.times.each do
sub_components.each(&:tick)
sub_components.each(&:tock)
end
end
private
attr_reader :and_gate, :sr_nand_clk, :sr_nand_d, :sr_nand_out,
:sub_components
def create_sub_components
@and_gate = Circuits::Component::And.new
@sr_nand_clk = Circuits::Component::SrNand.new
@sr_nand_d = Circuits::Component::SrNand.new
@sr_nand_out = Circuits::Component::SrNand.new
@sub_components = [@and_gate, @sr_nand_clk, @sr_nand_d, @sr_nand_out]
end
def default_input_count
2
end
def default_output_count
2
end
def link_and_gate
and_gate[:a].set sr_nand_clk[:not_q]
and_gate[:b].set self[:clk]
end
def link_outputs
self[:q].set sr_nand_out[:q]
self[:not_q].set sr_nand_out[:not_q]
end
def link_sr_nand_d
sr_nand_d[:not_s].set and_gate[:out]
sr_nand_d[:not_r].set self[:d]
end
def link_sr_nand_clk
sr_nand_clk[:not_s].set sr_nand_d[:not_q]
sr_nand_clk[:not_r].set self[:clk]
end
def link_sr_nand_out
sr_nand_out[:not_s].set sr_nand_clk[:not_q]
sr_nand_out[:not_r].set sr_nand_d[:q]
end
def link_sub_components
link_outputs
link_and_gate
link_sr_nand_d
link_sr_nand_clk
link_sr_nand_out
end
def reset
tick
tock
end
end
end
end
<file_sep>/spec/unit/circuits/component/d_spec.rb
require 'spec_helper'
require 'circuits/component/d'
describe Circuits::Component::D do
describe '#tick' do
subject { Circuits::Component::D.new }
context 'it has just been initialized' do
it 'is unset' do
expect(subject.q.get).to eq false
expect(subject.not_q.get).to eq true
end
it 'is stable' do
subject.tick
subject.tock
expect(subject.q.get).to eq false
expect(subject.not_q.get).to eq true
end
end
context 'has just been set' do
before do
subject.clk.set false
subject.tick
subject.tock
subject.d.set true
subject.clk.set true
subject.tick
subject.tock
subject.d.set false
subject.clk.set false
end
it 'is set' do
expect(subject.q.get).to eq true
expect(subject.not_q.get).to eq false
end
it 'is stable' do
subject.tick
subject.tock
expect(subject.q.get).to eq true
expect(subject.not_q.get).to eq false
end
it 'd high has no effect' do
subject.d.set true
subject.tick
subject.tock
expect(subject.q.get).to eq true
expect(subject.not_q.get).to eq false
end
it 'clock has to be positive edge' do
subject.d.set false
subject.clk.set true
subject.tick
subject.tock
expect(subject.q.get).to eq true
expect(subject.not_q.get).to eq false
end
it 'can be reset' do
subject.tick
subject.tock
subject.clk.set true
subject.tick
subject.tock
expect(subject.q.get).to eq false
expect(subject.not_q.get).to eq true
end
end
context 'has just been reset' do
before do
subject.clk.set false
subject.tick
subject.tock
subject.d.set false
subject.clk.set true
subject.tick
subject.tock
subject.clk.set false
end
it 'is reset' do
expect(subject.q.get).to eq false
expect(subject.not_q.get).to eq true
end
it 'is stable' do
subject.tick
subject.tock
expect(subject.q.get).to eq false
expect(subject.not_q.get).to eq true
end
it 'd high has no effect' do
subject.d.set true
subject.tick
subject.tock
expect(subject.q.get).to eq false
expect(subject.not_q.get).to eq true
end
it 'clock has to be positive edge' do
subject.d.set true
subject.clk.set true
subject.tick
subject.tock
expect(subject.q.get).to eq false
expect(subject.not_q.get).to eq true
end
it 'can be set' do
subject.tick
subject.tock
subject.d.set true
subject.clk.set true
subject.tick
subject.tock
expect(subject.q.get).to eq true
expect(subject.not_q.get).to eq false
end
end
end
end
<file_sep>/spec/unit/circuits/component/generic_state_circuit_spec.rb
require 'spec_helper'
require 'circuits/component/generic_state_circuit'
describe Circuits::Component::GenericStateCircuit do
before ':each' do
@state_circuit = Circuits::Component::GenericStateCircuit.new
@state_circuit.set_number_of_states 2
@state_circuit.set_number_of_ors 2
@state_circuit.set_number_of_ands 3
@state_circuit.set_number_of_nots 2
# a = !ab!i + a
@state_circuit.get_not(0).in.set @state_circuit.get_state(0).q
@state_circuit.get_not(1).in.set @state_circuit.i
@state_circuit.get_and(0).a.set @state_circuit.get_not(0).out
@state_circuit.get_and(0).b.set @state_circuit.get_state(1).q
@state_circuit.get_and(1).a.set @state_circuit.get_and(0).out
@state_circuit.get_and(1).b.set @state_circuit.get_not(1).out
@state_circuit.get_or(0).a.set @state_circuit.get_state(0).q
@state_circuit.get_or(0).b.set @state_circuit.get_and(1).out
@state_circuit.get_state(0).d.set @state_circuit.get_or(0).out
# b = i + b
@state_circuit.get_or(1).a.set @state_circuit.i
@state_circuit.get_or(1).b.set @state_circuit.get_state(1).q
@state_circuit.get_state(1).d.set @state_circuit.get_or(1).out
# out = ab
@state_circuit.get_and(2).a.set @state_circuit.get_state(0).q
@state_circuit.get_and(2).b.set @state_circuit.get_state(1).q
@state_circuit.out.set @state_circuit.get_and(2).out
def @state_circuit.do_cycle input
i.set input
tick
tock
end
end
describe 'one cycle' do
context 'when the input is false' do
it 'the output is false' do
@state_circuit.do_cycle false
expect(@state_circuit.out.get).to eq false
end
end
context 'when the input is true' do
it 'the output is false' do
@state_circuit.do_cycle true
expect(@state_circuit.out.get).to eq false
end
end
end
describe 'two cycles' do
context 'when the input is false, false' do
it 'the output is false' do
@state_circuit.do_cycle false
@state_circuit.do_cycle false
expect(@state_circuit.out.get).to eq false
end
end
context 'when the input is false, true' do
it 'the output is false' do
@state_circuit.do_cycle false
@state_circuit.do_cycle true
expect(@state_circuit.out.get).to eq false
end
end
context 'when the input is true, false' do
it 'the output is true' do
@state_circuit.do_cycle true
@state_circuit.do_cycle false
expect(@state_circuit.out.get).to eq true
end
end
context 'when the input is true, true' do
it 'the output is false' do
@state_circuit.do_cycle true
@state_circuit.do_cycle true
expect(@state_circuit.out.get).to eq false
end
end
end
describe 'three cycles' do
context 'when the input is false, false, false' do
it 'the output is false' do
@state_circuit.do_cycle false
@state_circuit.do_cycle false
@state_circuit.do_cycle false
expect(@state_circuit.out.get).to eq false
end
end
context 'when the input is false, false, true' do
it 'the output is false' do
@state_circuit.do_cycle false
@state_circuit.do_cycle false
@state_circuit.do_cycle true
expect(@state_circuit.out.get).to eq false
end
end
context 'when the input is false, true, false' do
it 'the output is true' do
@state_circuit.do_cycle false
@state_circuit.do_cycle true
@state_circuit.do_cycle false
expect(@state_circuit.out.get).to eq true
end
end
context 'when the input is false, true, true' do
it 'the output is false' do
@state_circuit.do_cycle false
@state_circuit.do_cycle true
@state_circuit.do_cycle true
expect(@state_circuit.out.get).to eq false
end
end
context 'when the input is true, false, false' do
it 'the output is true' do
@state_circuit.do_cycle true
@state_circuit.do_cycle false
@state_circuit.do_cycle false
expect(@state_circuit.out.get).to eq true
end
end
context 'when the input is true, false, true' do
it 'the output is true' do
@state_circuit.do_cycle true
@state_circuit.do_cycle false
@state_circuit.do_cycle true
expect(@state_circuit.out.get).to eq true
end
end
context 'when the input is true, true, false' do
it 'the output is true' do
@state_circuit.do_cycle true
@state_circuit.do_cycle true
@state_circuit.do_cycle false
expect(@state_circuit.out.get).to eq true
end
end
context 'when the input is true, true, true' do
it 'the output is false' do
@state_circuit.do_cycle true
@state_circuit.do_cycle true
@state_circuit.do_cycle true
expect(@state_circuit.out.get).to eq false
end
end
end
end
<file_sep>/spec/spec_helper.rb
require 'coveralls'
require 'simplecov'
SimpleCov.start
Coveralls.wear!
<file_sep>/spec/unit/circuits/terminal/input_spec.rb
require 'spec_helper'
require 'circuits/terminal/input'
describe Circuits::Terminal::Input do
describe '#get' do
context 'when given no state' do
subject { Circuits::Terminal::Input.new }
it 'is false' do
expect(subject.get).to eq(false)
end
end
end
describe '#set' do
let(:state) { double('state') }
context 'when given a state' do
subject { Circuits::Terminal::Input.new(state: state) }
it 'has that state' do
subject.set state
expect(subject.get).to eq(state)
end
end
context 'when given an input' do
let(:input) { Circuits::Terminal::Input.new(state: state) }
subject { Circuits::Terminal::Input.new }
it 'has the input state' do
subject.set input
expect(subject.get).to eq(state)
end
end
context 'when given an output' do
let(:output) { Circuits::Terminal::Output.new(state: state) }
subject { Circuits::Terminal::Input.new }
it 'has the output state' do
subject.set output
expect(subject.get).to eq(state)
end
end
end
end
<file_sep>/spec/unit/circuits/terminal/output_spec.rb
require 'spec_helper'
require 'circuits/terminal/output'
describe Circuits::Terminal::Output do
describe '#get' do
let(:state) { double('state') }
context 'when given no state' do
subject { Circuits::Terminal::Output.new }
it 'is false' do
expect(subject.get).to eq(false)
end
end
context 'when given a state' do
subject { Circuits::Terminal::Output.new(state: state) }
it 'has that state' do
expect(subject.get).to eq(state)
end
end
context 'when given an input' do
let(:input) { Circuits::Terminal::Input.new(state: state) }
subject { Circuits::Terminal::Output.new(terminal: input) }
it 'has the input state' do
expect(subject.get).to eq(state)
end
end
context 'when given an output' do
let(:output) { Circuits::Terminal::Output.new(state: state) }
subject { Circuits::Terminal::Output.new(terminal: output) }
it 'has the output state' do
expect(subject.get).to eq(state)
end
end
end
describe '#set' do
let(:state_1) { double('state_1') }
let(:state_2) { double('state_2') }
subject { Circuits::Terminal::Output.new(state: state_1) }
context 'when given a state' do
it 'gets does not get set immediately' do
subject.set state_2
expect(subject.get).to eq(state_1)
end
end
context 'when given an input' do
let(:input) { Circuits::Terminal::Input.new(state: state_2) }
it 'gets does not get set immediately' do
subject.set input
expect(subject.get).to eq(state_1)
end
end
context 'when given an output' do
let(:output) { Circuits::Terminal::Output.new(state: state_2) }
it 'gets does not get set immediately' do
subject.set output
expect(subject.get).to eq(state_1)
end
end
end
describe '#tock' do
let(:state_1) { double('state_1') }
let(:state_2) { double('state_2') }
subject { Circuits::Terminal::Output.new(state: state_1) }
context 'when given a state' do
it 'updates the state' do
subject.set state_2
subject.tock
expect(subject.get).to eq(state_2)
end
end
context 'when given an input' do
let(:input) { Circuits::Terminal::Input.new(state: state_2) }
it 'updates the state' do
subject.set input
subject.tock
expect(subject.get).to eq(state_2)
end
end
context 'when given an output' do
let(:output) { Circuits::Terminal::Output.new(state: state_2) }
it 'updates the state' do
subject.set output
subject.tock
expect(subject.get).to eq(state_2)
end
end
end
end
<file_sep>/lib/circuits/component/sr_nor.rb
require 'circuits/component/base'
require 'circuits/component/nor'
module Circuits
module Component
# SR NOR Latch
class SrNor < Base
def initialize
super(port_mappings: { r: { type: :input, number: 0 },
s: { type: :input, number: 1 },
q: { type: :output, number: 0 },
not_q: { type: :output, number: 1 } })
create_sub_components
link_sub_components
reset
end
# Computes the outputs based on the inputs and previous state
def tick
2.times.each do
sub_components.each(&:tick)
sub_components.each(&:tock)
end
end
private
attr_reader :nor_r, :nor_s, :sub_components
def create_sub_components
@nor_r = Nor.new
@nor_s = Nor.new
@sub_components = [@nor_r, @nor_s]
end
def default_input_count
2
end
def default_output_count
2
end
def link_nor_r
nor_r[:a].set self[:r]
nor_r[:b].set nor_s[:out]
end
def link_nor_s
nor_s[:a].set self[:s]
nor_s[:b].set nor_r[:out]
end
def link_outputs
self[:q].set nor_r[:out]
self[:not_q].set nor_s[:out]
end
def link_sub_components
link_nor_s
link_nor_r
link_outputs
end
def reset
self[:r].set true
tick
tock
self[:r].set false
end
end
end
end
<file_sep>/lib/circuits/component/nor.rb
require 'circuits/component/base'
module Circuits
module Component
# Logical NOR Operator
class Nor < Base
# Sets the output to be the result of a logical OR of the inputs
def tick
self[:out].set(!inputs.map(&:get).inject(:|))
end
private
def default_input_count
2
end
def default_output_count
1
end
end
end
end
<file_sep>/lib/circuits/component/sr_nand.rb
require 'circuits/component/base'
require 'circuits/component/nand'
module Circuits
module Component
# SR NAND Latch
class SrNand < Base
def initialize
super(port_mappings: { not_s: { type: :input, number: 0 },
not_r: { type: :input, number: 1 },
q: { type: :output, number: 0 },
not_q: { type: :output, number: 1 } })
create_sub_components
link_sub_components
reset
end
# Computes the outputs based on the inputs and previous state
def tick
2.times.each do
sub_components.each(&:tick)
sub_components.each(&:tock)
end
end
private
attr_reader :nand_s, :nand_r, :sub_components
def create_sub_components
@nand_s = Nand.new
@nand_r = Nand.new
@sub_components = [@nand_s, @nand_r]
end
def default_input_count
2
end
def default_output_count
2
end
def link_nand_r
nand_r[:a].set self[:not_r]
nand_r[:b].set nand_s[:out]
end
def link_nand_s
nand_s[:a].set self[:not_s]
nand_s[:b].set nand_r[:out]
end
def link_outputs
self[:q].set nand_s[:out]
self[:not_q].set nand_r[:out]
end
def link_sub_components
link_nand_s
link_nand_r
link_outputs
end
def reset
self[:not_s].set true
tick
tock
self[:not_r].set true
end
end
end
end
|
c04ade3b4e3e8300ebe09f4c4eee21a5536344bb
|
[
"Ruby"
] | 17
|
Ruby
|
gideon-steinberg/circuits
|
18eb28c2782ceec62c187c4e71f9b3364707689b
|
3c6498ea20696f11d8fce8f80b6d29c21fc27396
|
refs/heads/master
|
<file_sep><?php
$title = "Edit Hotel";
require_once 'header.php';
require_once 'footer.php';<file_sep><?php
$db = new PDO('mysql:host=172.31.22.43;dbname=Kristian_S1114120', 'Kristian_S1114120', 'Y0XDURR1fB');
?><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "UTF-8">
<title>Hotels App - <?php echo $title; ?></title>
</head>
<body>
<main>
<!--connect and get number of hotels-->
<?php
$numOfHotels = null;
require_once 'db.php';
$db = null;
?>
<a href="hotels.php">Hotels</a>
<p>Number Of Hotels: <?php echo $numOfHotels?></p>
<a href="api/hotels.php">API</a>
<file_sep><?php
$title = 'Update';
require_once 'footer.php';
|
0ef9226433268f74d2b4e732d6d8c14bc1c2c8e1
|
[
"PHP"
] | 4
|
PHP
|
KBCode23/phpYear1Final
|
c72a9deefdc89cc317adf1e45546432edcd32d7b
|
2e54fff831916d486225c98bfbfe3648ea792b94
|
refs/heads/master
|
<file_sep> // Initialize Firebase
var config = {
apiKey: "AIzaSyBiPEsbVeOpppIEYFUeZYlBXzNinARr09w",
authDomain: "cac2018-648ca.firebaseapp.com",
databaseURL: "https://cac2018-648ca.firebaseio.com",
projectId: "cac2018-648ca",
storageBucket: "cac2018-648ca.appspot.com",
messagingSenderId: "275374546726"
};
firebase.initializeApp(config);
let FIREBASE_DATABASE = firebase.database();
let FIREBASE_AUTH = firebase.auth();
let btnSignUp = document.getElementById("btnCreateAcc");
btnSignUp.addEventListener('click', e => {
let pws = document.querySelectorAll(".passwordForm");
if(pws[0].value != pws[1].value){
alert("passwords don't match");
}
else{
let firstName = document.getElementById("txtFirstName");
let lastName = document.getElementById("txtLastName");
let email = document.getElementById("emailForm").value;
let password = document.getElementById("password").value;
let userObj ={
firstName: firstName.value,
lastName: lastName.value
};
let promise = FIREBASE_AUTH.createUserWithEmailAndPassword(email, password).then(function(user){
FIREBASE_DATABASE.ref('users/' + user.uid).set(userObj).then(
function() {
console.log('User data successfully stored')
window.location = "../html/login.html";
}).catch(function(error) {
console.log(error);
});
});
}
});
<file_sep>"# ScheduleApp2018"
<file_sep> // Initialize Firebase
var config = {
apiKey: "AIzaSyBiPEsbVeOpppIEYFUeZYlBXzNinARr09w",
authDomain: "cac2018-648ca.firebaseapp.com",
databaseURL: "https://cac2018-648ca.firebaseio.com",
projectId: "cac2018-648ca",
storageBucket: "cac2018-648ca.appspot.com",
messagingSenderId: "275374546726"
};
firebase.initializeApp(config);
|
24c6954c819197a261970f16329ec53ed58a730c
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
Chubbypanda7134/ScheduleApp2018
|
49ac4ce28cbffaba45b878fdeb37dbf1f720237c
|
d01db6b547bd3162a6e865a753483630fee7a023
|
refs/heads/master
|
<repo_name>gavinmcgimpsey/tealeaf-pre-ruby<file_sep>/other-chaps/merge_exercise.rb
a = {one: "snickle", two: "snap", three: "whooney"}
b = {one: "snicker", three: "whinny", four: "start"}
# clean merge
with_corrections = a.merge(b)
puts a.values.to_s
puts with_corrections
puts "Do you want to accept the corrections? (y/n)"
response = gets.chomp
# destructive merge!
if response == "y"
a.merge!(b)
end
puts "Final version:"
puts a
<file_sep>/other-chaps/name.rb
puts 'What is your first name?'
firstname = gets.chomp
puts 'What is your last name?'
lastname = gets.chomp
name = firstname + ' ' + lastname
puts "Hello, #{name}!"
<file_sep>/workbook/intermediate/quiz2.rb
# Ex 1
munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => { "age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" }
}
males = munsters.select { |name, atts| atts["gender"] == "male" }
result = 0
males.each { |name, atts| result += atts["age"] }
puts result
# Ex 2
munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => { "age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" }
}
munsters.each do |name, atts|
puts "#{name} is a #{atts["age"]} year old #{atts["gender"]}."
end
# Ex 4
sentence = "<NAME> sat on a wall."
def reverser(str)
str.split(' ').reverse.join(' ')
end
puts reverser(sentence)
# Ex 5
answer = 42
def mess_with_it(some_number)
some_number += 8
end
new_answer = mess_with_it(answer)
puts "Prediction: 42"
p answer - 8
puts "After seeing that: how could I not notice that it never prints new_answer?"
<file_sep>/workbook/easy/quiz3.rb
# Ex 1
flintstones = %w(<NAME> Wilma Betty BamBam Pebbles)
p flintstones
# Ex 2
flintstones.push("Dino")
p flintstones
# Ex 3
flintstones = %w(<NAME> Wilma Betty BamBam Pebbles)
flintstones.push("Dino", "Hoppy")
p flintstones
# Ex 4
advice = "Few things in life are as important as house training your pet dinosaur."
p advice.slice!(0, advice.index("house"))
p advice
# Ex 5
statement = "The Flintstones Rock!"
p statement.split('t').length - 1
# Ex 6
title = "Flintstone Family Members"
p title.center(40)
<file_sep>/other-chaps/age.rb
puts "How old are you?"
age = gets.chomp.to_i
future = 10
4.times do
puts "In #{future} years you will be:\n#{age + future}"
future += 10
end
<file_sep>/other-chaps/anagrams.rb
# Given an array of strings, print arrays of each set of anagrams
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
'flow', 'neon']
letters = words.map { |word| word.chars.sort }
uniques = letters.uniq
word_sets = Hash.new
uniques.each do |lets|
# Set up storage for the corresponding words
if word_sets[lets] == nil
word_sets[lets] = []
end
# Until there are no more, get the index of the matching element in the
# letters variable, then add the corresponding value in the words variable
# to the storage in word_sets, then delete the element from letters and words
until letters.index(lets) == nil
current_index = letters.index(lets)
word_sets[lets] = word_sets[lets].push(words[current_index])
words.slice!(current_index)
letters.slice!(current_index)
end
end
results = word_sets.values
results.each {|anagrams| print anagrams}
<file_sep>/other-chaps/arrayplustwo.rb
# Didn't read carefully and mapped instead of iterating
array = [0, 1, 1, 2, 3, 5, 8]
arrayplustwo = array.map {|num| num + 2}
p array
p arrayplustwo
<file_sep>/workbook/easy/quiz2.rb
# Ex 1
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }
p ages.include?("Spot")
# Ex 2
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 }
p ages.values.reduce(:+)
# Ex 3
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }
ages.delete_if {|key, value| value >= 100}
p ages
# Ex 4
munsters_description = "The Munsters are creepy in a good way."
p munsters_description.capitalize
p munsters_description.swapcase
p munsters_description.downcase
p munsters_description.upcase
# Ex 5
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10 }
additional_ages = { "Marilyn" => 22, "Spot" => 237 }
p ages.merge(additional_ages)
# Ex 6
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 }
p ages.values.min
# Ex 7
advice = "Few things in life are as important as house training your pet dinosaur."
p advice.include?("Dino")
# Ex 8
flintstones = %w(<NAME> Wilma Betty BamBam Pebbles)
flintstones.each_with_index do |name, index|
if name.chars[0] == 'B' && name.chars[1] == 'e'
p index
break
end
end
# Ex 9
flintstones = %w(<NAME> Betty BamBam Pebbles)
flintstones.map! {|name| name[0..2]}
p flintstones
# Ex 10
flintstones = %w(<NAME> Betty BamBam Pebbles)
flintstones.map! {|name| name[0..2]}
p flintstones
<file_sep>/workbook/advanced/quiz1.rb
# Ex 1
puts "Error – greeting hasn't been defined."
# Ex 2
puts 'hi there'
# Ex 3
puts "A: one, two, and three"
puts "B: one, two, and three"
puts "C: two, three, and one"
# Ex 4
def new_uuid
uuid = ""
gen = Random.new
def get_rand_hex_char(gen)
gen.rand(15).to_s(16)
end
pattern = [8, 4, 4, 4, 12]
pattern.each do |num|
num.times do
uuid << get_rand_hex_char(gen)
end
uuid << '-'
end
uuid.chop
end
puts new_uuid
# Ex 5
def dot_separated_ip_address?(input_string)
dot_separated_words = input_string.split(".")
return false if dot_separated_words.length != 4
dot_separated_words.each { |word| return false if !is_a_number?(word) }
return true
end
<file_sep>/README.md
# tealeaf-pre-ruby
<file_sep>/workbook/easy/quiz1.rb
# Ex 1
puts "Exercise 1:"
puts "[1, 2, 2, 3]"
puts "uniq! would give us a lasting change."
puts
# Ex 2
puts "Exercise 2:"
puts "'!' is used for logical negation, or (sometimes) to indicate that a " +
"method mutates the caller. '?' is the ternary operator, or (sometimes) " +
"to indicate that a method returns a boolean."
puts "1. != is an operator that returns true when the comparators are not equal. "+
"Usually used in branching logic."
puts "2. Returns the opposite of the variable's truthiness."
puts "3. If the method exists, the ! says that the method mutates the caller."
puts "4. Syntax error."
puts "5. Ternary operator."
puts "6. According to Stack Overflow, this converts a truthy thing to a " +
"boolean true, and keeps 'false' and 'nil' as false."
puts
# Ex 3
advice = "Few things in life are as important as house training your pet dinosaur."
better_advice = advice.gsub(/important/,'urgent')
puts "Exercise 3:"
puts better_advice
puts
# Ex 4
puts "Exercise 4:"
puts "delete_at will delete '2' (at index 1) and return it."
puts "delete will delete '1' and return it."
puts
# Ex 5
puts "Exercise 5:"
puts (42 > 10 || 42 < 100) ? "42 is between 10 and 100" : "42 is not betwen 10 and 100"
puts
# Ex 6
famous_words = "and seven years ago..."
puts "Exercise 6:"
puts full_famous_words = "Four score " + famous_words
puts famous_words.prepend("Four score ")
puts
# Ex 7
puts "Exercise 7:"
p 42
puts
# Ex 8
flintstones = ["Fred", "Wilma"]
flintstones << ["Barney", "Betty"]
flintstones << ["BamBam", "Pebbles"]
puts "Exercise 8:"
p flintstones.flatten
puts
# Ex 9
flintstones = { "Fred" => 0, "Wilma" => 1, "Barney" => 2, "Betty" => 3, "BamBam" => 4, "Pebbles" => 5 }
puts "Exercise 9:"
p flintstones.assoc("Barney")
puts
# Ex 10
flintstones = ["Fred", "Barney", "Wilma", "Betty", "Pebbles", "BamBam"]
flints = {}
flintstones.each_with_index {|name, index| flints[name] = index}
puts "Exercise 10:"
p flints
<file_sep>/workbook/intermediate/quiz3.rb
# Ex 3
puts "my_string is pumpkinsrutabaga"
puts "my_array is ['pumpkins', 'rutabaga']"
# Wrong!
<file_sep>/workbook/intermediate/quiz1.rb
# Ex 1
10.times do |num|
result = ""
num.times {result << ' ' }
result << 'The Flintstones Rock!'
puts result
end
# Ex 2
statement = "The Flintstones Rock".split('')
results = Hash.new
letters = statement.uniq.sort
letters.reject! {|char| char =~ /\W|_/}
letters.each do |letter|
results[letter] = statement.count(letter)
end
p results
# Ex 3
puts "3: The result of (40 + 2) is an int, not a string."
puts " Add .to_s to the right paren or use the \#\{ \} construct"
puts " to evaluate the math within the string."
# Ex 4
puts "4: Q1: On subsequent lines: 1, 2, 3, 4 \# Wrong!"
puts " Q2: On subsequent lines: 1, 2"
# Ex 5
puts "5: Use a while loop, conditioned on dividend > 0."
puts " Bonus 1: To see if the number has an even dividend as a factor – if"
puts " so, the modulo operation will result in zero."
puts " Bonus 2: It will be returned by the function, since it is the last"
puts " value 'mentioned'."
# Ex 6
puts "6: The << operator pushes the element onto the array. If the element"
puts " is itself an array, it will become a sub-array. + concatenates,"
puts " so if the element is itself an array, its members will be added"
puts " individually to the buffer array."
puts " \# Didn't see the [ ] around the new_element in method 2!"
# Ex 7
puts "7: Finally looked at the answer."
# Ex 8
def titleize(str)
result = ""
words = str.split(' ')
words.each do |word|
result << word.capitalize << ' '
end
result
end
puts titleize("that has each word capitalized")
# Ex 9
munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => { "age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" },
"Marilyn" => { "age" => 23, "gender" => "female"}
}
munsters.each do |name, atts|
case atts["age"]
when 0..17
atts["age_group"] = "kid"
when 18..64
atts["age_group"] = "adult"
else
atts["age_group"] = "senior"
end
end
p munsters
|
9be2675c306775fa5f8d9d0abe890bbd1f646d8f
|
[
"Markdown",
"Ruby"
] | 13
|
Ruby
|
gavinmcgimpsey/tealeaf-pre-ruby
|
36f7b2b62d44408b7a7cfedc91ab573a8561d24e
|
535d7a6b7363c7d084c89a2de2ff428b64165375
|
refs/heads/master
|
<repo_name>nikhilbansal/happy-birthday-app<file_sep>/app/src/main/java/com/newlinecharacter/www/app/ListView.java
package com.newlinecharacter.www.app;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import com.newlinecharacter.www.app.adaptor.TabsPagerAdapter;
import com.newlinecharacter.www.app.tabs.GamesFragment;
public class ListView extends FragmentActivity implements
ActionBar.TabListener, GamesFragment.OnFragmentInteractionListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Photos", "Videos" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
if(mAdapter==null)
Log.i("tag", "NULL");
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onFragmentInteraction(Uri uri) {
}
public void play(View view)
{
// Intent intent = new Intent(MainActivity.this, ListView.class);
// startActivity(intent);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(view.getTag().toString())));
}
}
<file_sep>/app/src/main/java/com/newlinecharacter/www/app/FullScreenImage.java
package com.newlinecharacter.www.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import com.newlinecharacter.www.app.adaptor.PhotoImageAdapter;
/**
* Created by nikhil.bansal on 23/04/14.
*/
public class FullScreenImage extends Activity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_fullscreen_image);
Intent intent = getIntent();
int imageId = (Integer) intent.getExtras().get("id");
ImageView imageView = (ImageView)this.findViewById(R.id.imageView2);
//imageView.setLayoutParams( new ViewGroup.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT));
imageView.setImageResource(PhotoImageAdapter.mThumbIds[imageId]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
}
}<file_sep>/README.md
happy-birthday-app
==================
My first happy birthday android app completed in 10 hours.
Download the apk from http://www.newlinecharacter.com/app.apk
<file_sep>/app/src/main/java/com/newlinecharacter/www/app/adaptor/PhotoImageAdapter.java
package com.newlinecharacter.www.app.adaptor;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.newlinecharacter.www.app.R;
public class PhotoImageAdapter extends BaseAdapter {
private Context mContext;
public PhotoImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(400, 400));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
// imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
public static Integer[] mThumbIds = {
R.drawable.imb1, R.drawable.imb2,
R.drawable.imb3, R.drawable.imb4,
R.drawable.imb5, R.drawable.imb6,
R.drawable.imb7, R.drawable.imb8,
R.drawable.imb9, R.drawable.imb10,
R.drawable.imb11, R.drawable.imb12,
R.drawable.imb13, R.drawable.imb14,
R.drawable.imb15, R.drawable.imb16,
R.drawable.imb17, R.drawable.imb18,
R.drawable.imb19, R.drawable.imb20,
R.drawable.imb21, R.drawable.imb22,
};
// public Integer[] mThumbIds = {
//
// R.drawable.ima1,
//
// R.drawable.ima2,
//
// R.drawable.ima3,
//
// R.drawable.ima4,
//
// R.drawable.ima5,
//
// R.drawable.ima6,
//
// R.drawable.ima7,
//
// R.drawable.ima8,
//
// R.drawable.ima9,
//
// R.drawable.ima10,
//
// R.drawable.ima11,
//
// R.drawable.ima12,
//
// R.drawable.ima13,
//
// R.drawable.ima14,
//
// R.drawable.ima15,
//
// R.drawable.ima16,
//
// R.drawable.ima17,
//
// R.drawable.ima18,
//
// R.drawable.ima19,
//
// R.drawable.ima20,
//
// R.drawable.ima21,
//
// R.drawable.ima22
//
// };
}
//package com.example.www.app.adaptor;
//
//import android.content.Context;
//import android.graphics.Bitmap;
//import android.graphics.BitmapFactory;
//import android.os.AsyncTask;
//import android.os.StrictMode;
//import android.util.Log;
//import android.view.View;
//import android.view.ViewGroup;
//import android.widget.BaseAdapter;
//import android.widget.GridView;
//import android.widget.ImageView;
//
//import java.io.BufferedInputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.net.HttpURLConnection;
//import java.net.URL;
//import java.net.URLConnection;
//
///**
// * Created by nikhil.bansal on 23/04/14.
// */
//public class PhotoImageAdapter extends BaseAdapter {
// private Context mContext;
//
// public PhotoImageAdapter(Context c) {
// StrictMode.ThreadPolicy policy =
// new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
// mContext = c;
// }
//
// public int getCount() {
// return mThumbIds.length;
// }
//
// public Object getItem(int position) {
// return null;
// }
//
// public long getItemId(int position) {
// return 0;
// }
//
// ImageView imageView;
// public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) { // if it's not recycled, initialize some attributes
// imageView = new ImageView(mContext);
// imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
// imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageView.setPadding(8, 8, 8, 8);
// } else {
// imageView = (ImageView) convertView;
// }
//
// //imageView.setImageResource(mThumbIds[position]);
// //imageView.setImageBitmap(getImageBitmap("http://upload.wikimedia.org/wikipedia/commons/d/dd/Birthday_candles.jpg"));
// GetXMLTask task = new GetXMLTask();
// // Execute the task
// task.execute(new String[] { "" });
// return imageView;
// }
//
// private Integer[] mThumbIds = {1, 2, 3, 4, 5, 6
//// R.drawable.sample_2, R.drawable.sample_3,
//// R.drawable.sample_4, R.drawable.sample_5,
//// R.drawable.sample_6, R.drawable.sample_7,
//// R.drawable.sample_0, R.drawable.sample_1,
//// R.drawable.sample_2, R.drawable.sample_3,
//// R.drawable.sample_4, R.drawable.sample_5,
//// R.drawable.sample_6, R.drawable.sample_7,
//// R.drawable.sample_0, R.drawable.sample_1,
//// R.drawable.sample_2, R.drawable.sample_3,
//// R.drawable.sample_4, R.drawable.sample_5,
//// R.drawable.sample_6, R.drawable.sample_7
// };
//
//// private Bitmap getImageBitmap(String url) {
//// Bitmap bm = null;
//// try {
//// URL aURL = new URL(url);
//// URLConnection conn = aURL.openConnection();
//// try {
//// conn.connect();
//// } catch (IOException e) {
//// e.printStackTrace();
//// }
//// InputStream is = conn.getInputStream();
//// BufferedInputStream bis = new BufferedInputStream(is);
//// bm = BitmapFactory.decodeStream(bis);
//// bis.close();
//// is.close();
//// } catch (IOException e) {
//// Log.e("TAG", "Error getting bitmap", e);
//// }
//// return bm;
//// }
//
// private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
// @Override
// protected Bitmap doInBackground(String... urls) {
// Bitmap map = null;
// for (String url : urls) {
// map = getImageBitmap("http://upload.wikimedia.org/wikipedia/commons/d/dd/Birthday_candles.jpg");
// }
// return map;
// }
//
// // Sets the Bitmap returned by doInBackground
// @Override
// protected void onPostExecute(Bitmap result) {
//// view.setImageBitmap(result);
// imageView.setImageBitmap(getImageBitmap("http://upload.wikimedia.org/wikipedia/commons/d/dd/Birthday_candles.jpg"));
// }
//
// private Bitmap getImageBitmap(String url) {
// Bitmap bm = null;
// try {
// URL aURL = new URL(url);
// URLConnection conn = aURL.openConnection();
// try {
// conn.connect();
// } catch (IOException e) {
// e.printStackTrace();
// }
// InputStream is = conn.getInputStream();
// BufferedInputStream bis = new BufferedInputStream(is);
// bm = BitmapFactory.decodeStream(bis);
// bis.close();
// is.close();
// } catch (IOException e) {
// Log.e("TAG", "Error getting bitmap", e);
// }
// return bm;
// }
// }
//}
|
1ea89ec1a7c731fc35aee45d18f7fb44fba236ca
|
[
"Markdown",
"Java"
] | 4
|
Java
|
nikhilbansal/happy-birthday-app
|
a3c6792df2fa6854dfaf9b9fc0e68c9f952f9b94
|
2dd5847edd849bf3e6f85431c7fb7e28268a38da
|
refs/heads/master
|
<file_sep>from PIL import Image
from PIL import ImageEnhance
import math
# Completely different color
def diff_color( image ):
width,height=img.size
# Process every pixel
for x in range(width):
for y in range(height):
new_color = (0,100,100)
image.putpixel( (x,y), new_color)
return image
# Remove single color (red)
def remove_color( image, color ):
width,height=img.size
# Process every pixel
for x in range(width):
for y in range(height):
current_color = img.getpixel( (x,y) )
if color == "red":
new_color = (0,) + current_color[1:]
if color == "green":
new_color = current_color[:1] + (0,) + current_color[2:]
if color == "blue":
new_color = current_color[0:2] + (0,)
image.putpixel( (x,y), new_color)
return image
# Get color of specified pixel
def get_pixel( image, x, y ):
pix = image.load()
print pix[x,y]
return pix[x,y]
# Resize image
def resize( image, size1, size2 ):
new_img = image.resize((size1,size2))
return new_img
# Convert to grayscale (using 'grayscale' function on Wikipedia)
def rgb2gray(image):
width,height=img.size
# Process every pixel
for x in range(width):
for y in range(height):
current_color = img.getpixel( (x,y) )
scaling_function = (0.299, 0.587, 0.114)
new_color = int(sum([a*b for a,b in zip(current_color,scaling_function)]))
image.putpixel( (x,y), (new_color, new_color, new_color))
return image
def horse_vision(img, slices):
slices = 2
offset = 40
width, height = img.size
slice_size = int(width/slices)
# Left half
print int(slice_size) - offset
print 2*offset
print slice_size + offset
bbox = (0, 0, slice_size - offset, height)
slice_left = img.crop(bbox)
# Black box
slice_black = Image.new('RGB', (2*offset, height), (0,0,0))
# Right half
bbox = (slice_size + offset, 0, width, height)
slice_right = img.crop(bbox)
# New width and height
new_im = Image.new('RGB', (width, height))
x_offset = 0
for im in (slice_left, slice_black, slice_right):
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
return new_im
############################
# Start actual Python Script
############################
if __name__ == '__main__':
img = Image.open('spring.jpg')
# Function calls here
#img = diff_color(img)
#img = resize(img,100,100)
#img = rgb2gray(img)
#img = remove_color(img,"green")
#img = horse_vision(img,2)
#img = ImageEnhance.Sharpness(img).enhance(4)
# Displaying
img.show()
# Saving
#img.save('new_image','png')
<file_sep>from PIL import Image
from PIL import ImageFilter
COLORS = {"Snow": [255, 250, 250],
"Snow2": [238, 233, 233],
"Snow3": [205, 201, 201],
"Snow4": [139, 137, 137],
"GhostWhite": [248, 248, 255],
"WhiteSmoke": [245, 245, 245],
"Gainsboro": [220, 220, 220],
"FloralWhite": [255, 250, 240],
"OldLace": [253, 245, 230],
"Linen": [240, 240, 230],
"AntiqueWhite": [250, 235, 215],
"AntiqueWhite2": [238, 223, 204],
"AntiqueWhite3": [205, 192, 176],
"AntiqueWhite4": [139, 131, 120],
"PapayaWhip": [255, 239, 213],
"BlanchedAlmond": [255, 235, 205],
"Bisque": [255, 228, 196],
"Bisque2": [238, 213, 183],
"Bisque3": [205, 183, 158],
"Bisque4": [139, 125, 107],
"PeachPuff": [255, 218, 185],
"PeachPuff2": [238, 203, 173],
"PeachPuff3": [205, 175, 149],
"PeachPuff4": [139, 119, 101],
"NavajoWhite": [255, 222, 173],
"Moccasin": [255, 228, 181],
"Cornsilk": [255, 248, 220],
"Cornsilk2": [238, 232, 205],
"Cornsilk3": [205, 200, 177],
"Cornsilk4": [139, 136, 120],
"Ivory": [255, 255, 240],
"Ivory2": [238, 238, 224],
"Ivory3": [205, 205, 193],
"Ivory4": [139, 139, 131],
"LemonChiffon": [255, 250, 205],
"Seashell": [255, 245, 238],
"Seashell2": [238, 229, 222],
"Seashell3": [205, 197, 191],
"Seashell4": [139, 134, 130],
"Honeydew": [240, 255, 240],
"Honeydew2": [244, 238, 224],
"Honeydew3": [193, 205, 193],
"Honeydew4": [131, 139, 131],
"MintCream": [245, 255, 250],
"Azure": [240, 255, 255],
"AliceBlue": [240, 248, 255],
"Lavender": [230, 230, 250],
"LavenderBlush": [255, 240, 245],
"MistyRose": [255, 228, 225],
"White": [255, 255, 255],
"Black": [0, 0, 0],
"DarkSlateGray": [49, 79, 79],
"DimGray": [105, 105, 105],
"SlateGray": [112, 138, 144],
"LightSlateGray": [119, 136, 153],
"Gray": [190, 190, 190],
"LightGray": [211, 211, 211],
"MidnightBlue": [25, 25, 112],
"Navy": [0, 0, 128],
"CornflowerBlue": [100, 149, 237],
"DarkSlateBlue": [72, 61, 139],
"SlateBlue": [106, 90, 205],
"MediumSlateBlue": [123, 104, 238],
"LightSlateBlue": [132, 112, 255],
"MediumBlue": [0, 0, 205],
"RoyalBlue": [65, 105, 225],
"Blue": [0, 0, 255],
"DodgerBlue": [30, 144, 255],
"DeepSkyBlue": [0, 191, 255],
"SkyBlue": [135, 206, 250],
"LightSkyBlue": [135, 206, 250],
"SteelBlue": [70, 130, 180],
"LightSteelBlue": [176, 196, 222],
"LightBlue": [173, 216, 230],
"PowderBlue": [176, 224, 230],
"PaleTurquoise": [175, 238, 238],
"DarkTurquoise": [0, 206, 209],
"MediumTurquoise": [72, 209, 204],
"Turquoise": [64, 224, 208],
"Cyan": [0, 255, 255],
"LightCyan": [224, 255, 255],
"CadetBlue": [95, 158, 160],
"MediumAquamarine": [102, 205, 170],
"Aquamarine": [127, 255, 212],
"DarkGreen": [0, 100, 0],
"DarkOliveGreen": [85, 107, 47],
"DarkSeaGreen": [143, 188, 143],
"SeaGreen": [46, 139, 87],
"MediumSeaGreen": [60, 179, 113],
"LightSeaGreen": [32, 178, 170],
"PaleGreen": [152, 251, 152],
"SpringGreen": [0, 255, 127],
"LawnGreen": [124, 252, 0],
"Chartreuse": [127, 255, 0],
"MediumSpringGreen": [0, 250, 154],
"GreenYellow": [173, 255, 47],
"LimeGreen": [50, 205, 50],
"YellowGreen": [154, 205, 50],
"ForestGreen": [34, 139, 34],
"OliveDrab": [107, 142, 35],
"DarkKhaki": [189, 183, 107],
"Khaki": [240, 230, 140],
"PaleGoldenrod": [238, 232, 170],
"LightGoldenrodYellow": [250, 250, 210],
"LightYellow": [255, 255, 224],
"Yellow": [255, 255, 0],
"Gold": [255, 215, 0],
"LightGoldenrod": [238, 221, 130],
"Goldenrod": [218, 165, 32],
"DarkGoldenrod": [184, 134, 11],
"RosyBrown": [188, 143, 143],
"IndianRed": [205, 92, 92],
"SaddleBrown": [139, 69, 19],
"Sienna": [160, 82, 45],
"Peru": [205, 133, 63],
"Burlywood": [222, 184, 135],
"Beige": [245, 245, 220],
"Wheat": [245, 222, 179],
"SandyBrown": [244, 164, 96],
"Tan": [210, 180, 140],
"Chocolate": [210, 105, 30],
"Firebrick": [178, 34, 34],
"Brown": [165, 42, 42],
"DarkSalmon": [233, 150, 122],
"Salmon": [250, 128, 114],
"LightSalmon": [255, 160, 122],
"Orange": [255, 165, 0],
"DarkOrange": [255, 140, 0],
"Coral": [255, 127, 80],
"LightCoral": [240, 128, 128],
"Tomato": [255, 99, 71],
"OrangeRed": [255, 69, 0],
"Red": [255, 0, 0],
"Green": [0, 255, 0],
"HotPink": [255, 105, 180],
"DeepPink": [255, 20, 147],
"Pink": [255, 192, 203],
"LightPink": [255, 182, 193],
"PaleVioletRed": [219, 112, 147],
"Maroon": [176, 48, 96],
"MediumVioletRed": [199, 21, 133],
"VioletRed": [208, 32, 144],
"Violet": [238, 130, 238],
"Plum": [221, 160, 221],
"Orchid": [218, 112, 214],
"MediumOrchid": [186, 85, 211],
"DarkOrchid": [153, 50, 204],
"DarkViolet": [148, 0, 211],
"BlueViolet": [138, 43, 226],
"Purple": [160, 32, 240],
"MediumPurple": [147, 112, 219],
"Thistle": [216, 191, 216]}
# Completely different color
def diff_color(image):
width, height = img.size
# Process every pixel
for x in range(width):
for y in range(height):
new_color = (0, 100, 100)
image.putpixel((x, y), new_color)
return image
def get_pixel_luminance(rgb):
'''
Returns the luminance of a single pixel.
Pixel Luminance = 0.299 * R + 0.587 * G + 0.114 * B
**Parameters**
rgb: *list, int*
An RGB pixel.
**Returns**
luminance: *float*
The luminance of the specific pixel.
**References**
* http://stackoverflow.com/a/596243
'''
return 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]
def get_image_luminance(image):
'''
Loop through image and calculate a total luminance value for it.
Luminance is calculated as the total pixel luminance divided by the number
of pixels.
Pixel Luminance = 0.299 * R + 0.587 * G + 0.114 * B
**Parameters**
image: *image*
The PIL.Image image handle
**Returns**
luminance: *float*
The luminance of the entire image.
**References**
* http://stackoverflow.com/a/596243
'''
width, height = image.size
reds, greens, blues = 0, 0, 0
for x in range(width):
for y in range(height):
c = image.getpixel((x, y))
reds += c[0]
greens += c[1]
blues += c[2]
total_luminance = 0.299 * reds + 0.587 * greens + 0.114 * blues
return total_luminance / (width * height)
def scale_image_pixels(image, scale):
'''
A function to scale the pixels of an image by some float. Note, as pixels
are RGB and only integers, it will floor the scaled values.
**Parameters**
image: *image*
The PIL.Image image handle
scale: *list, float* or *float*
A value, or list of values if you want to do so element wise,
to scale the pixels by.
**Returns**
image: *image*
The PIL.Image image handle with scaled pixels
'''
if type(scale) == float:
scale = [scale, scale, scale]
width, height = image.size
for x in range(width):
for y in range(height):
current_colour = image.getpixel((x, y))
new_colour = tuple([int(c * s) for c, s in zip(current_colour, scale)])
new_colour = tuple([max(c, 0) for c in new_colour])
new_colour = tuple([min(c, 255) for c in new_colour])
image.putpixel((x, y), new_colour)
return image
def offset_image_pixels(image, offset):
'''
A function to offset the pixels of an image by some float. Note, as pixels
are RGB and only integers, it will floor the offset values.
**Parameters**
image: *image*
The PIL.Image image handle
offset: *list, int* or *int*
An offset. If given as a list it is done elementwise. Else, the
same offset impacts each pixel value equally.
**Returns**
image: *image*
The PIL.Image image handle with offset pixels
'''
if type(offset) == int:
offset = [offset, offset, offset]
width, height = image.size
for x in range(width):
for y in range(height):
current_colour = image.getpixel((x, y))
new_colour = tuple([int(c + o) for c, o in zip(current_colour, offset)])
new_colour = tuple([max(c, 0) for c in new_colour])
new_colour = tuple([min(c, 255) for c in new_colour])
image.putpixel((x, y), new_colour)
return image
def set_image_luminance(image, luminance):
'''
This function will scale the image brightness. It will find the
difference in total image luminance, and scale the current image
appropriately.
**Parameters**
image: *image*
The PIL.Image image handle
luminance: *float*
The luminance you want the image to have.
**Returns**
image: *image*
The PIL.Image image handle with the new luminance
'''
current_luminance = get_image_luminance(image)
# Recall, get_image_luminance is by pixel, so we just subtract and
# scale by pixel
scale = luminance / current_luminance
return scale_image_pixels(image, scale)
def edit_colour(image, operator="ADD", color="Red", scale=1.0, keep_luminance=True):
'''
This function gives the user full control over the colours of the image.
You can add or subtract different colors across the entire image. Further,
you can maintain the brightness of the scaled system.
**Parameters**
image: *image*
The PIL.Image image handle
operator: *str, optional*
Either an ADD or SUBTRACT operator.
color: *str, optional*
The colour you want to "play" with.
scale: *float, optional*
The scale of how much of color you want to add/remove.
keep_luminance: *bool, optional*
Maintain the brightness after processing the image.
**Returns**
image: *image*
The PIL.Image image handle with the edited colours
'''
if color not in COLORS:
raise Exception("You chose a bad color >:(")
if operator not in ["ADD", "SUBTRACT"]:
raise Exception("Opterator must be ADD or SUBTRACT")
# This is the total luminance of the image
luminance = get_image_luminance(image)
# This is the color we want to edit image by
sign = 1.0
if operator == "SUBTRACT":
sign = -1.0
edit_colour = [int(c * scale) * sign for c in COLORS[color]]
image = offset_image_pixels(image, edit_colour)
if keep_luminance:
# We want to maintain brightness, so let's do so
image = set_image_luminance(image, luminance)
return image
def color_blind(image, color1="Red", color2="Green"):
'''
This function will emulate being color1-color2 color blind. This works by
finding all instances of color1 and color2 in image, and changing it to a
sum of the two colors. A delta is given so that a range of colors is
acceptable.
**Parameters**
image: *image*
The PIL.Image image handle
color1: *str, optional*
A color to confuse with color2. Default it is Red
color2: *str, optional*
A color to confuse with color1. Default it is Green
**Returns**
image: *image*
The PIL.Image image handle with the edited colours
'''
luminance = get_image_luminance(image)
color1 = COLORS[color1]
color2 = COLORS[color2]
scale = [a + b for a, b in zip(color1, color2)]
total = float(sum(scale))
scale = [float(s / total) for s in scale]
width, height = image.size
for x in range(width):
for y in range(height):
color = image.getpixel((x, y))
c_blind = sum([c for c, s in zip(color, scale) if s != 0])
color = tuple([c if s == 0 else int(c_blind * s) for c, s in zip(color, scale)])
image.putpixel((x, y), color)
return set_image_luminance(image, luminance)
# Get color of specified pixel
def get_pixel(image, x, y):
pix = image.load()
print pix[x, y]
return pix[x, y]
# Resize image
def resize(image, size1, size2):
new_img = image.resize((size1, size2))
return new_img
# Convert to grayscale (using 'grayscale' function on Wikipedia)
def rgb2gray(image):
luminance = get_image_luminance(image)
width, height = img.size
# Process every pixel
for x in range(width):
for y in range(height):
current_color = img.getpixel((x, y))
avg = int(sum(current_color) / 3.0)
new_colour = (avg, avg, avg)
image.putpixel((x, y), new_colour)
return set_image_luminance(image, luminance)
def blur(image):
blurred_image = image.filter(ImageFilter.BLUR)
return blurred_image
def blur_alg(image, blur_range=2):
'''
This function lets the user blur their image to a specified degree.
**Parameters**
image: *image*
The PIL.Image image handle
blur_range: *int*
The amount of neighbours the function averages over when blurring
**Returns**
image: *image*
The PIL.Image image handle with the blurred colours
**References**
* http://gist.github.com/davechristian/917729
'''
'''
The blur algorithm
------------------
The algorithm works like this:
For every pixel in the image, add the red, green and blue values of it's
neighbouring pixels and divide each total red, green and blue value by
the total number of colours scanned. This then gives you the average pixel
colour for the pixel in the image being scanned.
The 20 x 3 dots below represented pixels, and the X represents the
pixel currently being checked.
..........
.....x....
..........
If the kernel size has been set to one then the pixel colour checks
would be done
like this ('o' represents a colour check):
....ooo...
....oxo...
....ooo...
'''
# Dimensions of the image
width, height = image.size
for x in range(height):
for y in range(width):
r, g, b, colour, count = 0, 0, 0, (0, 0, 0), 0
for blur_x in range(0 - blur_range, 0 + blur_range):
for blur_y in range(0 - blur_range, 0 + blur_range):
# Don't check outside screen edges
if (x + blur_x > 0 and x + blur_x < height and y + blur_y > 0 and y + blur_y < width):
colour = image.getpixel((y + blur_y, x + blur_x,))
# Sum of each colour within blur_range
r += colour[0]
g += colour[1]
b += colour[2]
count += 1
# Average of each colour
if (r > 0):
r = r / count
if (g > 0):
g = g / count
if (b > 0):
b = b / count
# Blur the image
blur = (r, g, b)
image.putpixel((y, x), blur)
return image
def horse_vision(img):
slices = 2
offset = 40
width, height = img.size
slice_size = int(width / slices)
# Left half
# print int(slice_size) - offset
# print 2 * offset
# print slice_size + offset
bbox = (0, 0, slice_size - offset, height)
slice_left = img.crop(bbox)
# Black box
slice_black = Image.new('RGB', (2 * offset, height), (0, 0, 0))
# Right half
bbox = (slice_size + offset, 0, width, height)
slice_right = img.crop(bbox)
# New width and height
new_im = Image.new('RGB', (width, height))
x_offset = 0
for im in (slice_left, slice_black, slice_right):
new_im.paste(im, (x_offset, 0))
x_offset += im.size[0]
return new_im
if __name__ == "__main__":
############################
# Start actual Python Script
############################
img = Image.open('spring.jpg')
img.show()
print get_image_luminance(img)
img = edit_colour(img, color="Purple", scale=1)
img.show()
print get_image_luminance(img)
img = rgb2gray(img)
print get_image_luminance(img)
img.show()
<file_sep>from PIL import Image
import ColourEdit as CE
img = Image.open('spring.jpg')
img.show()
img = CE.rg_color_blind(img, "Blue", "Purple", delta=50)
img.show()
# img = CE.horse_vision(img)
# img.show()
<file_sep>import pygame
import random
import math
size = 70 # boxes per side of grid (change number of boxes in the simulation)
pixels = 9 # pixels per side of box (change how big the boxes are)
genes = ['p']
dict = {'blue': 0.85, 'green': 0.5, 'red': 0.15, 'water': 0.99, 'leaf': 0.5, 'fire': 0.01}
randomness, cooperation, start, winner, health, mem = 0.01, 0.3, 0.5, 0.5, 10, 0.5
# User input questions
simulation = raw_input('Which simulation would you like to run? (options = normal/tumour/memorizer/pokemon): ')
if simulation == 'normal' or simulation == 'tumour':
randomness = input('What fraction of evolution would you like to be random? (ex. 0.02 = 2 percent are random): ')
cooperation = input('What fraction of cooperation would you like between cells? (ex. 0.0 = only fighting, 1.0 = only cooperation): ')
start = raw_input('What would you like to be the dominant gene at the beginning? (options = blue/green/red): ')
winner = raw_input('What would you like to be the dominant gene at the end? (options = blue/green/red): ')
elif simulation == 'pokemon':
while(True):
health = input('What is each Pokemons health? (10-100): ')
if health < 10 or health > 100:
print('Error! Health must be between 10 and 100')
continue
r_attack = input('What is fires attack power? (1-4): ')
g_attack = input('What is leafs attack power? (1-4): ')
b_attack = input('What is waters attack power? (1-4): ')
if r_attack < 1 or r_attack > 4 or g_attack < 1 or g_attack > 4 or b_attack < 1 or b_attack > 4:
print('Error! Attack power must be between 1 and 4')
continue
else:
break
else:
randomness = input('What fraction of evolution would you like to be random? (ex. 0.02 = 2 percent are random): ')
cooperation = input('What fraction of cooperation would you like between cells? (ex. 0.0 = only fighting, 1.0 = only cooperation): ')
start = raw_input('What would you like to be the dominant gene at the beginning? (options = blue/green/red): ')
mem = raw_input("What colour would you like to memorize its last move? (blue/green/red/all): ")
# Normal simulation of evolution of cells
def normal(x, y):
# returns your score
# x = your move, y = the opponent
# inputs are 'f' for Fight, 'c' for Cooperate
if x == 'f': # you Fight
if y == 'f': # they Fight
return -1
else: # they Cooperate
return 2
else: # you Cooperate
if y == 'f':
return -2
else:
return 1
# Simulation of cancerous cells invading healthy cells
def tumour(x, y):
# returns your score
# x = your move, y = the opponent
# inputs are 'f' for Fight, 'c' for Cooperate, 'canc' for Cancer, 'anti' for Antibodies
if x == 'f': # you Fight
if y == 'f': # they Fight
return -1
elif y == 'c': # they Cooperate
return 2
elif y == 'canc':
return -1
else:
return 1
elif x == 'c': # you Cooperate
if y == 'f':
return -2
elif y == 'c':
return 1
elif y == 'canc':
return -3
else:
return 1
elif x == 'canc':
if y == 'f':
return -1
elif y == 'c':
return 1
elif y == 'canc':
return 0
else:
return -3
else:
if y == 'f':
return -1
elif y == 'c':
return 0
elif y == 'canc':
return -2 # Antibody strength
elif y == 'anti_c':
return 1
else:
return -1
# SImulation of Pokemon-like battle between cells
def pokemon(x, y, your_type, opp_type):
if your_type == dict['fire']:
if opp_type == dict['fire']:
if x == 'f':
if y == 'f':
return -r_attack
else:
return r_attack
else:
if y == 'c':
return 1
else:
return -r_attack
elif opp_type == dict['leaf']:
if x == 'f':
if y == 'f':
return -0.5*g_attack
else:
return 1.5*r_attack
else:
if y == 'c':
return 0
else:
return -0.5*g_attack
else:
if x == 'f':
if y == 'f':
return -1.5*b_attack
else:
return 0.5*r_attack
else:
if y == 'c':
return 0
else:
return -1.5*b_attack
elif your_type == dict['leaf']:
if opp_type == dict['fire']:
if x == 'f':
if y == 'f':
return -1.5*r_attack
else:
return 0.5*g_attack
else:
if y == 'c':
return 0
else:
return -1.5*r_attack
elif opp_type == dict['leaf']:
if x == 'f':
if y == 'f':
return -g_attack
else:
return g_attack
else:
if y == 'c':
return 1
else:
return -g_attack
else:
if x == 'f':
if y == 'f':
return -0.5*b_attack
else:
return 1.5*g_attack
else:
if y == 'c':
return 0
else:
return -0.5*b_attack
else:
if opp_type == dict['fire']:
if x == 'f':
if y == 'f':
return -0.5*r_attack
else:
return 1.5*b_attack
else:
if y == 'c':
return 0
else:
return -0.5*r_attack
elif opp_type == dict['leaf']:
if x == 'f':
if y == 'f':
return -1.5*g_attack
else:
return 0.5*b_attack
else:
if y == 'c':
return 0
else:
return -1.5*g_attack
else:
if x == 'f':
if y == 'f':
return -b_attack
else:
return b_attack
else:
if y == 'c':
return 1
else:
return -b_attack
# If a cell dies, breed a new one based on the simulation chosen
def breed(self, a, b):
r = random.random()
if self.sim == 'tumour':
if (a == 0 and b == 1) or (a == 1 and b == 0):
if (r < 0.5):
return 0
else:
return 1
elif a == 0:
if (r < 0.49):
return max(a, b)
elif (r < (1.0 - self.rand)):
return min(a, b)
else:
return 1
else:
if (r < (0.9999 - 0.02 - self.rand) * (1.0/3.0)): # Strength - there is a 2% chance (0.02) that the cells will breed the dominant gene
return (a + b) / 2
elif (r < (0.9999 - 0.02 - self.rand) * (2.0/3.0)):
return max(a, b)
elif (r < (0.9999 - 0.02 - self.rand)):
return min(a, b)
elif (r < (0.9999 - self.rand)):
return dict[winner]
elif (r < 0.9999):
return random.random()
else:
return 0
elif self.sim == 'normal':
if (r < (1.0 - 0.02 - self.rand) * (1.0/3.0)):
return (a + b) / 2
elif (r < (1.0 - 0.02 - self.rand) * (2.0/3.0)):
return max(a, b)
elif (r < (1.0 - 0.02 - self.rand)):
return min(a, b)
elif (r < (1.0 - self.rand)):
return dict[winner]
else:
return random.random()
elif self.sim == 'memorizer':
if (r < (1.0 - self.rand) * (1.0/3.0)):
return (a + b) / 2
elif (r < (1.0 - self.rand) * (2.0/3.0)):
return max(a, b)
elif (r < (1.0 - self.rand)):
return min(a, b)
else:
return random.random()
else:
return a
class Agent:
# The cell chooses what it wants to do - 'f' or 'c', or 'canc' or 'anti_c' or 'anti_f' for tumour simulation
def choice(self, opp):
if self.sim == 'tumour':
if self.g['p'] == 0:
ch = 'canc'
elif self.g['p'] == 1:
r = random.random()
if(r < 0.5): # Ratio of cooperative antibodies to fighting antibodies
ch = 'anti_c'
else:
ch = 'anti_f'
elif random.random() < self.coop:
ch = 'c'
else:
ch = 'f'
elif self.sim == 'normal':
if random.random() < self.coop:
ch = 'c'
else:
ch = 'f'
elif self.sim == 'pokemon':
if random.random() < 0.5:
ch = 'c'
else:
ch = 'f'
# Memorizer Simulator
else:
if mem == 'red':
if 0 < self.g['p'] <= 0.33:
A = opp.uniqueId
# If first time for this opponent:
if(A not in self.prevOutcome):
self.prevOutcome[A] = random.choice([-2,-1,1,2])
self.prevChoice[A] = random.choice(['f','c'])
# Won last time
if self.prevOutcome[A] > 0:
if random.random() < self.g['p']:
ch = self.prevChoice[A]
else:
ch = flip(self.prevChoice[A])
# Lost last time
else:
if random.random() < self.g['p']:
ch = self.prevChoice[A]
else:
ch = flip(self.prevChoice[A])
self.prevChoice[A] = ch
else:
if random.random() < self.coop:
ch = 'c'
else:
ch = 'f'
elif mem == 'green':
if 0.33 < self.g['p'] <= 0.66:
A = opp.uniqueId
if(A not in self.prevOutcome):
self.prevOutcome[A] = random.choice([-2,-1,1,2])
self.prevChoice[A] = random.choice(['f','c'])
if self.prevOutcome[A] > 0:
if random.random() < self.g['p']:
ch = self.prevChoice[A]
else:
ch = flip(self.prevChoice[A])
else:
if random.random() < self.g['p']:
ch = self.prevChoice[A]
else:
ch = flip(self.prevChoice[A])
self.prevChoice[A] = ch
else:
if random.random() < self.coop:
ch = 'c'
else:
ch = 'f'
elif mem == 'blue':
if 0.66 < self.g['p'] < 1:
A = opp.uniqueId
if(A not in self.prevOutcome):
self.prevOutcome[A] = random.choice([-2,-1,1,2])
self.prevChoice[A] = random.choice(['f','c'])
if self.prevOutcome[A] > 0:
if random.random() < self.g['p']:
ch = self.prevChoice[A]
else:
ch = flip(self.prevChoice[A])
else:
if random.random() < self.g['p']:
ch = self.prevChoice[A]
else:
ch = flip(self.prevChoice[A])
self.prevChoice[A] = ch
else:
if random.random() < self.coop:
ch = 'c'
else:
ch = 'f'
else:
A = opp.uniqueId
if(A not in self.prevOutcome):
self.prevOutcome[A] = random.choice([-2,-1,1,2])
self.prevChoice[A] = random.choice(['f','c'])
if self.prevOutcome[A] > 0:
if random.random() < self.g['p']:
ch = self.prevChoice[A]
else:
ch = flip(self.prevChoice[A])
else:
if random.random() < self.g['p']:
ch = self.prevChoice[A]
else:
ch = flip(self.prevChoice[A])
self.prevChoice[A] = ch
return ch
# Select opponent
def opponent(self):
i = bound(self.i + random.choice([-1,0,1]))
j = bound(self.j + random.choice([-1,0,1]))
if i==self.i and j==self.j: # cannot fight self
return self.opponent() # try again
else:
return sim[i][j]
def battle(self, a):
ch = self.choice(a)
ach = a.choice(self)
if self.sim == 'tumour':
s = tumour(ch, ach)
self.score += s
sa = tumour(ach, ch)
a.score += sa
elif self.sim == 'normal' or self.sim == 'memorizer':
s = normal(ch, ach)
self.score += s
self.prevOutcome[a.uniqueId] = s
sa = normal(ach, ch)
a.score += sa
a.prevOutcome[self.uniqueId] = sa
else:
s = pokemon(ch, ach, self.g['p'], a.g['p'])
self.score += s
sa = pokemon(ach, ch, a.g['p'], self.g['p'])
a.score += sa
def update(self):
a = self.opponent()
self.battle(a)
if self.score <= 0:
if self.sim == 'pokemon':
self.score = health
else:
self.score = 10
self.prevChoice = {}
self.prevOutcome = {}
self.g['p'] = breed(self, a.g['p'], self.g['p'])
if self.g['p'] == 1:
self.score += 1
elif self.g['p'] == 0:
self.score -= 2
self.draw()
def __init__(self, i, j):
self.i = i
self.j = j
self.uniqueId = len(seq)
self.prevChoice = {}
self.prevOutcome = {}
self.g = {}
self.sim = simulation
self.rand = randomness
self.coop = cooperation
if self.sim != 'pokemon':
self.g['p'] = random.triangular(0, 1, dict[start])
self.score = 10
else:
self.g['p'] = random.choice([dict['fire'], dict['leaf'], dict['water']])
self.score = health
self.draw()
def draw(self):
x = base + self.i * pixels
y = base + self.j * pixels
boxes.append([shift(x,y,'p'), color(self.g['p'])])
def flip(ch):
if ch=='f':
return 'c'
else:
return 'f'
def bound(x):
return max(0, min(size-1, x))
def color(x):
z = pygame.Color(0,0,0,0)
if x == 0:
z.hsva = [0, 0, 0, 0]
elif x == 1:
z.hsva = [0, 0, 100, 0]
else:
z.hsva = [x*250, 95, 95, 0]
return z
def draw():
global boxes
rlist = []
for b in boxes:
R = pygame.Rect(b[0], (pixels, pixels))
pygame.draw.rect(screen, b[1], R, 0)
rlist.append(R)
boxes = []
pygame.display.update(rlist)
def shift(x, y, g):
if g=='p':
return (x,y)
# initialize graphics window:
pygame.init()
base = 20
nPix = int(base*2+math.ceil(pixels*size))
screen = pygame.display.set_mode([nPix, nPix])
pygame.display.set_caption("Agent-Based Evolution")
white = [255, 255, 255]
black = [0, 0, 0]
screen.fill(white)
pygame.display.flip()
font = pygame.font.Font(None, 25)
# initialize agents:
boxes = [] # only used in 'draw': tracks changed genes
seq = [] # one-dimensional list, permuted each turn
sim = [] # fixed two-dimensional grid for 'opponent' lookup
for i in range(0,size):
row = []
sim.append(row)
for j in range(0,size):
A = Agent(i, j)
row.append(A) # sim[i][j]
seq.append(A)
draw()
# main animation loop:
done = False
clock = pygame.time.Clock()
while done==False:
clock.tick(120) # max frames per second (speed up or slow down simulation)
time = pygame.time.get_ticks() / 1000.0
print(time)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
random.shuffle(seq)
for a in seq:
a.update()
draw()
pygame.quit()
# print summary statistics:
avg = {}
avg['p'] = 0
for a in seq:
avg['p'] += a.g['p']
N = len(seq)
print('p'+"="+str(round(100*avg['p']/N)/100))<file_sep>import turtle # Imports library that allows user to alter a turtle. A turtle is something that has a position and a direction, and can draw lines
from turtle import * # Imports functions from the turtle library that allow user to alter the turtle
from tkinter import * # Imports functions from the Tkinter library that allow user to create a Graphical User Interface (GUI)
from math import * # Imports functions from the math library that allows user to use math functions (ex. sine, cosine, square root)
# Global constant definitions
G = 6.67428e-11 # The gravitational constant G
AU = 149.6e9 # AU = Astronomical Unit = distance from earth to the sun = 149.6 million km, in meters.
SCALE = 75.0 / AU # Scale 1 AU to 30 pixels
# Class definitions: planet
class planet(Turtle): # This function defines the parameters for each planets
# Initialize planet name, location, velocity
vx = vy = 0.0
xloc = yloc = 0.0
# Compute the attraction between planet and other body
def attraction(self, other, date):
# Compute x, y, and total distances between planet and other body
rx = (other.xloc-self.xloc)
ry = (other.yloc-self.yloc)
r = sqrt(rx**2 + ry**2)
# Test if there is a collision between planets, handle the error!
if r < self.diameter and other.name != 'MarsRover':
raise ValueError("Collision between objects %r and %r"
% (self.name, other.name))
##############
# Add in function that handles the spacecraft landing case and returns fx, fy = 0,0
# Otherwise, update the gravitational force!
f = G * self.mass * other.mass / (r**2)
theta = atan2(ry, rx) # Find the angle between the hypotenuse and the adjacent side
fx = cos(theta) * f # Compute the x component of the force on the planet
fy = sin(theta) * f # Compute the y component of the force on the planet
return fx, fy # Return the x and y components of the force to the main loop
#########
# Add a testlanding function for the spacecraft! Return 1 if within diameter, 0 if not
# Include a test for spacecraft to mars distance
def loop(system): # This function calculates the orbit of each planet and displays it in a window
timestep = 1*24*3600 # One earth day
date = 0 # Starting date for the simulation - date increases for every iteration of the loop
#########
# Add date for thrust and velocity to add
for body in system: # Runs a loop for each planet
body.goto(body.xloc*SCALE, body.yloc*SCALE) # Puts the planet in its proper location on the display
body.pendown() # Puts down the pen - this means that a line will be draw to show the path of the orbit
while True: # Loop will run until user interrupts program (ctrl+c)
force = {} # Create a dictionary that holds the total forces on each planet
for body in system:
total_fx = total_fy = 0.0 # Initialize the x and y components on the planet as 0
# Update all forces exerted on the planets through gravity
for other in system:
if body is other: # Don't calculate the planet's attraction to itself
continue # Skip to the next planet
fx, fy = body.attraction(other, date) # Goes to the function called attraction (line 19)
total_fx += fx # Sums up the x components of the gravitational forces on the planet
total_fy += fy # Sums up the y components of the gravitational forces on the planet
force[body] = (total_fx, total_fy) # Assign the total force exerted on the planet to the dictionary, force
# Update velocities, test for landing
for body in system:
fx, fy = force[body] # Assign the components of the total force to the variables fx and fy
# Compute velocities from gravity
body.vx += fx / body.mass * timestep # Calculate the new x component of the velocity
body.vy += fy / body.mass * timestep # Calculate the new y component of the velocity
#######
# Add print statement to see the sizes of the velocities from each planet!
######
# If the body is earth, compute the angle theta to use to compute the new velocity angle for a Hohmann transfer
######
# Test if spacecraft has landed! use a test over all other bodies in system and call testLanding function if it's the spacecraft
# Set the onPlanet to be initialized to zero inside of the loop
######
# If landed, use planet velocity (other.vx, other.vy) instead
######
# Apply thrust on specified date: only to the spacecraft at the desired angle!
# Update locations of all bodies
for body in system:
body.xloc += body.vx * timestep # Calculate the new x component of the position
body.yloc += body.vy * timestep # Calculate the new y component of the position
body.goto(body.xloc*SCALE, body.yloc*SCALE) # Move everything!
date += 1 # After updating the positions and velocities of the planet, go to the next day
turtle.clear() # Restart the position of the turtle
turtle.penup() # Pick up the turtle to make sure it does not draw a line when you move it
turtle.hideturtle() # Hide the turtle when you move it
turtle.goto(300, 300) # Move turtle to the top right corner
turtle.write(str(date) + " Days",False, align="right", # Writes the number of days that have passed since the start of the simulation
font=("Arial", 18, "normal"))
def main(): # Sets up the positions, velocities, colours, and shapes of the planets on the display
# Planets start at average distance from sun, with mean speed
# Start in locations for January 26th
turtle.setup(800, 800) # Set the window size to 800 by 800 pixels
turtle.bgcolor("white") # Set up the window with a white background
"""
For each planet, the setup follows the same procedure:
planet = planet() Sets up the variables for the planet, goes to the function called planet (line 11)
planet.name = 'planet name' Names the planet
planet.mass = number Gives the planet a mass
planet.penup() Picks up the turtle so it does not draw a line when you move it
planet.color('colour') Gives the planet a colour (ex. yellow)
planet.shape('shape') Gives the planet a shape (ex. circle)
planet.xloc = number Gives the planet an x component position
planet.yloc = number Gives the planet a y component position
planet.vx = number Gives the planet an x component velocity
planet.vy = number Gives the planet a y component velocity
"""
sun = planet()
sun.name = 'Sun'
sun.mass = 1.98892 * 10**30
sun.penup()
sun.color('yellow')
sun.shape('circle')
sun.diameter = 1.3914 * 10**6
sun.shapesize(2.0,2.0,1)
"""sun.vx = 1000
sun.vy = 0"""
earth = planet()
earth.name = 'Earth'
earth.mass = 5.97 * 10**24
earth.penup()
earth.color('green')
earth.shape('circle')
earth.shapesize(0.6,0.6,1)
earth.diameter = 12742
earth.yloc = (1 * AU) * 0.80696031214
earth.xloc = (1 * AU) * -0.59060566762
earth.vy = 29.8 * 1000 * -0.59060566762
earth.vx = 29.8 * 1000 * -0.80696031214
"""moon = planet()
moon.name = 'Moon'
moon.mass = 734.9 * 10**20
moon.penup()
moon.color('black')
moon.shape('circle')
moon.shapesize(0.1,0.1,1)
moon.xloc = (1.453403112345339e-03 * AU) + (1 * AU) * -0.59060566762
moon.yloc = (1.982115197585754e-03 * AU) + (1 * AU) * 0.80696031214
moon.vx = (-4.929852973437543e-04 * AU)/(24*3600) + 29.8 * 1000 * -0.80696031214
moon.vy = (3.641097640628609E-04 * AU)/(24*3600) + 29.8 * 1000 * -0.59060566762"""
venus = planet()
venus.name = 'Venus'
venus.mass = 4.87 * 10**24
venus.penup()
venus.color('purple')
venus.shape('circle')
venus.diameter = 12104
venus.shapesize(0.6,0.6,1)
venus.yloc = (0.723 * AU)
venus.vx = -35.02 * 1000
mars = planet()
mars.name = 'Mars'
mars.mass = 6.3 * 10**24
mars.penup()
mars.color('red')
mars.shape('circle')
mars.shapesize(0.5,0.5,1)
#### If it's hard to land, increase diameter here!
mars.diameter = 6779
mars.xloc = (1.524 * AU) * 0.85391432258
mars.yloc = (1.524 * AU) * 0.52041361405
mars.vy = 24.1 * 1000 * 0.85391432258
mars.vx = 24.1 * 1000 * -0.52041361405
mercury = planet()
mercury.name = 'Mercury'
mercury.mass = 3.285 * 10**23
mercury.penup()
mercury.color('black')
mercury.shape('circle')
mercury.diameter = 4879
mercury.shapesize(0.3,0.3,1)
mercury.xloc = (0.39 * AU) * -0.74547599968
mercury.yloc = (0.39 * AU) * -0.66653247024
mercury.vy = 47.36 * 1000 * -0.74547599968
mercury.vx = 47.36 * 1000 * 0.66653247024
jupiter = planet()
jupiter.name = 'Jupiter'
jupiter.mass = 1.9 * 10**27
jupiter.penup()
jupiter.color('orange')
jupiter.shape('circle')
jupiter.diameter = 139822
jupiter.shapesize(1.2,1.2,1)
jupiter.xloc = (5.2 * AU) * -0.97480014384
jupiter.yloc = (5.2 * AU) * -0.22307998468
jupiter.vy = 13.06 * 1000 * -0.97480014384
jupiter.vx = 13.06 * 1000 * 0.22307998468
######
# Add space craft! Give it a name! Give it a mass (400-50,000kg)!
# Initialize it to earth's velocity and location
"""
alien = planet()
alien.name = 'Bob'
alien.mass = 3.4 * 10**27
alien.penup()
alien.color('pink')
alien.shape('turtle')
alien.shapesize(3.0,3.0,1)
alien.xloc = (5.8 * AU) * 0.97480014384
alien.yloc = (2.0 * AU)
alien.vx = -15000
"""
loop([sun, mercury, venus, earth, mars, jupiter, marsrover]) # Goes to the function called loop (line 37). Takes these planets and creates a solar system.
if __name__ == '__main__': # The code starts here
main() # Goes to the function called main (line 80)
|
2a144ea259ddc24c1b3d01baed04d97a617aa1ad
|
[
"Python"
] | 5
|
Python
|
lbacker/Coding-for-Students
|
c68680e672c1d13e9c316900f0d8ed5ce78fae3d
|
36de8056436efe4550ff97b3e9995f3ecc09cc10
|
refs/heads/master
|
<repo_name>gienekart/Simple-bug-saper<file_sep>/src/Game/Leaf.h
#pragma once
#include "Engine/Object.h"
class Leaf : public Object
{
public:
Leaf();
virtual ~Leaf();
};
<file_sep>/ide/CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(bugperProject)
set(CMAKE_BUILD_TYPE Debug CACHE STRING "Build type (Debug|Release|Test)")
set(top_DIR ${bugperProject_SOURCE_DIR}/..)
set(engine_src_DIR ${top_DIR}/src/Engine)
set(game_src_DIR ${top_DIR}/src/Game)
set(include_DIR ${top_DIR}/src)
set(BIN_DIR ${top_DIR}/bin)
set(LIB_DIR ${top_DIR}/lib)
include_directories(/usr/X11R6/include/)
link_directories(/usr/X11R6/lib)
link_directories(/usr/lib)
SET(EXTRA_LIBS GL X11 GLU glut png glee)
include_directories (${include_DIR})
include_directories (/usr/include)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${BIN_DIR}/${CMAKE_BUILD_TYPE})
set(HDRS_bugper
${game_src_DIR}/Leaf.h
${game_src_DIR}/button.h
${game_src_DIR}/button1.h
${game_src_DIR}/ladybug.h
${game_src_DIR}/Game.h
${game_src_DIR}/GameLogic.h
${game_src_DIR}/Pool.h
${game_src_DIR}/Mine.h
)
set(SRCS_bugper
${game_src_DIR}/main.cpp
${game_src_DIR}/Leaf.cpp
${game_src_DIR}/button.cpp
${game_src_DIR}/button1.cpp
${game_src_DIR}/ladybug.cpp
${game_src_DIR}/Game.cpp
${game_src_DIR}/GameLogic.cpp
${game_src_DIR}/Pool.cpp
${game_src_DIR}/Mine.cpp
)
set(HDRS_littleGLEngine
${engine_src_DIR}/GlEngine.h
${engine_src_DIR}/Object.h
${engine_src_DIR}/ObjectMgr.h
${engine_src_DIR}/load_png.h
${engine_src_DIR}/Resource.h
${engine_src_DIR}/Mesh.h
${engine_src_DIR}/Material.h
${engine_src_DIR}/Shader.h
${engine_src_DIR}/Texture.h
${engine_src_DIR}/ResourceMgr.h
${engine_src_DIR}/MeshMgr.h
${engine_src_DIR}/MaterialMgr.h
${engine_src_DIR}/ShaderMgr.h
${engine_src_DIR}/TextureMgr.h
${engine_src_DIR}/Timer.h
${engine_src_DIR}/GLHelpers.h
${engine_src_DIR}/InputHandler.h
${engine_src_DIR}/ExternLogic.h
${engine_src_DIR}/GLee.h
)
set(SRCS_littleGLEngine
${engine_src_DIR}/Object.cpp
${engine_src_DIR}/GlEngine.cpp
${engine_src_DIR}/ObjectMgr.cpp
${engine_src_DIR}/load_png.cpp
${engine_src_DIR}/Mesh.cpp
${engine_src_DIR}/Material.cpp
${engine_src_DIR}/Shader.cpp
${engine_src_DIR}/Texture.cpp
${engine_src_DIR}/ResourceMgr.cpp
${engine_src_DIR}/MeshMgr.cpp
${engine_src_DIR}/MaterialMgr.cpp
${engine_src_DIR}/ShaderMgr.cpp
${engine_src_DIR}/TextureMgr.cpp
${engine_src_DIR}/Timer.cpp
${engine_src_DIR}/GLHelpers.cpp
${engine_src_DIR}/InputHandler.cpp
)
add_library(littleGLEngine ${HDRS_littleGLEngine} ${SRCS_littleGLEngine})
target_link_libraries(littleGLEngine ${EXTRA_LIBS})
add_executable(bugper ${HDRS_bugper} ${SRCS_bugper})
target_link_libraries(bugper ${EXTRA_LIBS} littleGLEngine)
<file_sep>/src/Engine/GlEngine.h
#pragma once
#include <stdio.h>
#include "Engine/GLHelpers.h"
class ExternLogic;
class GlEngine
{
public:
static GlEngine* getEngine();
~GlEngine();
void init(int argc, char **argv);
void run();
void setCamera(float posX, float posY, float posZ,
float targetX, float targetY, float targetZ);
void setExternLogic(ExternLogic* logicToCall);
void setShowMode(GLuint glModeCode);
static bool canWork();
enum GLMode
{
FaceMode,
EdgeMode
};
private:
GlEngine();
static GlEngine* engine;
static void redraw();
void initLights();
static void iddle();
void initBasicMaterial();
static void RenderingScene();
static void SelectingScene();
static void CaclulateSelection(int hits);
ExternLogic* logicToCall;
int windowHandle;
static const int height = 600;
static const int width = 800;
};
<file_sep>/src/Game/Game.h
#pragma once
#include "Engine/ExternLogic.h"
#include "Engine/InputHandler.h"
#include "Game/GameLogic.h"
class Game : public ExternLogic
{
public:
Game();
~Game();
virtual void frameCall(float deltaTime);
private:
struct position3D
{
float x;
float y;
float z;
} cameraLookingFrom, cameraLookingAt;
void changeCameraHorisontal(float deltaTime);
void changeCameraVertical(float deltaTime, bool goingUp);
void changeBasicPoint(float deltatime, char stright, char side);
void updateCameraSets();
void displayAsWireframe(bool active);
float lookingAngle;
InputHandler* input;
GameLogic* logic;
static const float VerticalSpeed;
static const float BasicPointSpeed;
static const float MinHeight;
static const float MaxHeight;
static const float MinRadius;
static const float MaxRadius;
};<file_sep>/src/Game/button.cpp
#include "Game/button.h"
#include "Engine/MeshMgr.h"
Button::Button()
{
this->mesh = (Mesh*)MeshMgr::getMgr()->getResource("button");
this->setScale(0.2);
}
Button::~Button()
{
}
<file_sep>/src/Engine/GLHelpers.h
#pragma once
#include "GLee.h"
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include "Engine/load_png.h"
class glHelp
{
public:
static GLuint MakePngTexture(const char *filename);
static GLuint MakeShader(GLuint shaderType, const char* shaderCode);
static GLuint MakeShaderProgram(GLuint fragmentNo=0, GLuint vertexNo=0);
};
<file_sep>/src/Engine/ShaderMgr.h
#pragma once
#include "Engine/ResourceMgr.h"
class ShaderMgr: public ResourceMgr
{
public:
static ShaderMgr* getMgr();
private:
virtual Resource* createResource(const std::string& name);
Resource* createShaderPart(const std::string& name, GLuint type);
static ShaderMgr* mgr;
};
<file_sep>/src/Game/button1.cpp
#include <math.h>
#include <iostream>
#include <string>
#include "Game/button1.h"
#include "Engine/MaterialMgr.h"
const float InfoButton::changeSpeed = 0.7;
InfoButton::InfoButton(const char* howMany)
{
std::string ending = howMany;
std::string material = "button";
material += ending;
this->material = (Material*)MaterialMgr::getMgr()->getResource(material.c_str());
}
InfoButton::~InfoButton()
{
}
void InfoButton::Update(float detlatime)
{
this->angle += detlatime * changeSpeed;
}<file_sep>/src/Engine/InputHandler.cpp
#include "Engine/InputHandler.h"
#include <GL/glut.h>
InputHandler* InputHandler::handler = NULL;
const char InputHandler::ESC = 27;
InputHandler* InputHandler::getInputHandler()
{
if (InputHandler::handler == NULL)
{
InputHandler::handler = new InputHandler();
}
return InputHandler::handler;
}
InputHandler::InputHandler():pressedKeys(256), pressedSpecialKeys(256),
pressedInMouse(MouseEnumSize), lastPressedKeys(256), lastPressedSpecialKeys(256),
lastPressedInMouse(MouseEnumSize)
{
for(int i=0; i<256; i++ )
{
pressedKeys[i] = false;
pressedSpecialKeys[i] = false;
lastPressedKeys[i] = false;
lastPressedSpecialKeys[i] = false;
}
for(int i=0; i<MouseEnumSize; i++ )
{
pressedInMouse[i] = false;
lastPressedInMouse[i] = false;
}
}
InputHandler::~InputHandler()
{
}
void InputHandler::frameUpdate()
{
this->lastPressedKeys = this->pressedKeys;
this->lastPressedSpecialKeys = this->pressedSpecialKeys;
this->lastPressedInMouse = this->pressedInMouse;
}
void InputHandler::keyPressed(unsigned char key, int x, int y)
{
InputHandler::handler->pressedKeys[key] = true;
}
void InputHandler::keyUp(unsigned char key, int x, int y)
{
InputHandler::handler->pressedKeys[key] = false;
}
void InputHandler::keySpecialPressed(int key, int x, int y)
{
InputHandler::handler->pressedSpecialKeys[key] = true;
}
void InputHandler::keySpecialUp(int key, int x, int y)
{
InputHandler::handler->pressedSpecialKeys[key] = false;
}
void InputHandler::MouseButton(int button, int state, int x, int y)
{
// Respond to mouse button presses.
// If button1 pressed, mark this state so we know in motion function.
InputHandler* myhandler = InputHandler::handler;
if (button == GLUT_LEFT_BUTTON)
{
myhandler->pressedInMouse[MouseLeftButton] =
(state == GLUT_DOWN) ? true : false;
}
else if (button == GLUT_RIGHT_BUTTON)
{
myhandler->pressedInMouse[MouseRightButton] =
(state == GLUT_DOWN) ? true : false;
}
else if (button == GLUT_MIDDLE_BUTTON)
{
myhandler->pressedInMouse[MouseMiddleButton] =
(state == GLUT_DOWN) ? true : false;
}
myhandler->RecalcMouseMove(x, y);
}
void InputHandler::MouseMotion(int x, int y)
{
// If button1 pressed, zoom in/out if mouse is moved up/down.
InputHandler* myhandler = InputHandler::handler;
myhandler->RecalcMouseMove(x, y);
}
bool InputHandler::isPressedKey(unsigned char keyCode)
{
return (this->pressedKeys[keyCode] && this->lastPressedKeys[keyCode]);
}
bool InputHandler::isPressedSpecial(int keyIndex)
{
return (this->pressedSpecialKeys[keyIndex] && this->lastPressedSpecialKeys[keyIndex]);
}
bool InputHandler::isMousePressed(MouseKey key)
{
return (this->pressedInMouse[key] && this->lastPressedInMouse[key]);
}
bool InputHandler::isUpKey(unsigned char keyCode)
{
return (!this->pressedKeys[keyCode] && this->lastPressedKeys[keyCode]);
}
bool InputHandler::isUpSpecial(int keyIndex)
{
return (!this->pressedSpecialKeys[keyIndex] && this->lastPressedSpecialKeys[keyIndex]);
}
bool InputHandler::isMouseUp(MouseKey key)
{
return (!this->pressedInMouse[key] && this->lastPressedInMouse[key]);
}
bool InputHandler::isDownKey(unsigned char keyCode)
{
return (this->pressedKeys[keyCode] && !this->lastPressedKeys[keyCode]);
}
bool InputHandler::isDownSpecial(int keyIndex)
{
return (this->pressedSpecialKeys[keyIndex] && !this->lastPressedSpecialKeys[keyIndex]);
}
bool InputHandler::isMouseDown(MouseKey key)
{
return (this->pressedInMouse[key] && !this->lastPressedInMouse[key]);
}
Mouse2D InputHandler::getLastMouseMotion()
{
return this->lastMove;
}
Mouse2D InputHandler::getLastMousePosition()
{
return this->lastPosition;
}
void InputHandler::RecalcMouseMove(Mouse2D newPosition)
{
this->lastMove.x = newPosition.x - this->lastPosition.x;
this->lastMove.y = newPosition.y - this->lastPosition.y;
this->lastPosition = newPosition;
}
void InputHandler::RecalcMouseMove(int newX, int newY)
{
this->lastMove.x = newX - this->lastPosition.x;
this->lastMove.y = newY - this->lastPosition.y;
this->lastPosition.x = newX;
this->lastPosition.y = newY;
}<file_sep>/src/Engine/Object.h
#pragma once
class Mesh;
class Material;
class Object {
public:
struct position
{
float x;
float y;
float z;
};
Object();
Object(float x, float y, float z);
Object(Object::position pos);
virtual ~Object();
void setPosition(float x, float y, float z);
Object::position getPosition();
void setScale(float scale);
float getScale();
void unselect();
void select();
virtual void Update(float detlatime);
virtual void Render();
protected:
Mesh* mesh;
Material* material;
float scale;
float angle;
float selection;
float colorMix;
Object::position pos;
private:
void registerObject();
};
<file_sep>/src/Engine/load_png.h
#pragma once
char * load_png(const char *name, int *width, int *height);
<file_sep>/src/Engine/Mesh.cpp
#include "Engine/Mesh.h"
Mesh::Mesh(std::string name, const Mesh::meshData* data) :
Resource(name),
vertexPosition(data->vertexPosition),
textureCoords(data->textureCoords),
vertexNormals(data->vertexNormals),
vertexIndexes(data->vertexIndexes)
{
}
Mesh::~Mesh()
{
}
void Mesh::Render()
{
//enable object properietes
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
//filling data
glNormalPointer(GL_FLOAT, 0, &(this->vertexNormals[0]));
glVertexPointer(3, GL_FLOAT, 0, &(this->vertexPosition[0]));
glTexCoordPointer(2, GL_FLOAT, 0, &(this->textureCoords[0]));
//rendering
glDrawElements(GL_TRIANGLES, this->vertexIndexes.size(), GL_UNSIGNED_SHORT,
&(this->vertexIndexes[0]));
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY); // disable vertex arrays
glDisableClientState(GL_NORMAL_ARRAY);
}
<file_sep>/src/Game/ladybug.cpp
#include "Engine/GlEngine.h"
#include "Game/ladybug.h"
#include "Engine/MeshMgr.h"
#include "Engine/MaterialMgr.h"
#include "Game/GameLogic.h"
#include "Engine/ObjectMgr.h"
const float LadyBug::colorAnimationLenght = 1;
const float LadyBug::flyAnimationLenght = 3;
const float LadyBug::flyAnimationHeight = 30;
const float LadyBug::informationDelay = 0.03;
LadyBug::LadyBug(GameLogic* logicToInform, int col, int row):logicToInform(logicToInform),
col(col),row(row),informedAboutFly(false), isFlying(false), state(notClicked)
{
this->mesh = (Mesh*)MeshMgr::getMgr()->getResource("ladybug");
this->material = (Material*)MaterialMgr::getMgr()->getResource("ladybug");
this->setScale(0.4);
this->angleVelocity = (this->logicToInform->getRandom() - 0.5) * 2;
ObjectMgr::getMgr()->addUsable(this);
}
LadyBug::~LadyBug()
{
}
void LadyBug::Click()
{
if (this->isFlying == true)
return;
if(this->state == notClicked)
{
this->state = ClikkedOnce;
this->animationTime = 0;
}
else if(this->state == ClikkedOnce)
{
this->state = ClickedTwice;
this->animationTime = 0;
this->isFlying = true;
}
}
void LadyBug::Update(float deltaTime)
{
this->angle += this->angleVelocity * deltaTime;
if(this->state == notClicked)
{
return;
}
if(this->state == ClikkedOnce)
{
this->animationTime += deltaTime;
this->colorMix = this->animationTime / colorAnimationLenght;
return;
}
if(this->state == ClickedTwice)
{
this->animationTime += deltaTime;
float animationPercent = this->animationTime / flyAnimationHeight;
this->pos.y = animationPercent * flyAnimationHeight;
if (this->informedAboutFly == false && animationPercent > informationDelay)
{
this->informedAboutFly = true;
this->logicToInform->StartedBug(this->col, this->row);
}
}
}
void LadyBug::NeightbourCall()
{
if (this->isFlying == true)
return;
this->state = ClickedTwice;
this->animationTime = 0;
this->isFlying = true;
}
<file_sep>/src/Engine/Timer.h
#pragma once
#include <time.h>
class Timer
{
public:
static Timer * getTimer();
~Timer();
clock_t getTime();
float getTimeFromLastUpdate();
void updateTime();
private:
Timer();
clock_t currentTime;
float timeDuration;
static Timer* timer;
};<file_sep>/src/Engine/GlEngine.cpp
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Engine/GlEngine.h"
#include "Engine/Timer.h"
#include "Engine/InputHandler.h"
#include "Engine/ObjectMgr.h"
#include "Engine/ExternLogic.h"
#define SELECT_BUFF_SIZE 4096 //should be more than enough
GlEngine* GlEngine::engine = NULL;
GLuint selectBuf[SELECT_BUFF_SIZE];
GlEngine* GlEngine::getEngine()
{
if (GlEngine::engine == NULL)
{
GlEngine::engine = new GlEngine();
}
return GlEngine::engine;
}
GlEngine::GlEngine()
{
//Initialize all critical singletons
InputHandler::getInputHandler();
}
GlEngine::~GlEngine()
{
}
bool GlEngine::canWork()
{
const char* version = (char*)gluGetString(GLU_VERSION);
return atof(version) >= 1.3;
}
void GlEngine::run()
{
glutMainLoop(); /* Start GLUT event-processing loop */
return;
}
void GlEngine::setExternLogic(ExternLogic* logicToCall)
{
this->logicToCall = logicToCall;
}
void GlEngine::setShowMode(GLuint glModeCode)
{
glPolygonMode(GL_FRONT_AND_BACK, glModeCode);
}
void GlEngine::redraw()
{
float daltaTime = ObjectMgr::getMgr()->update();
GlEngine::engine->logicToCall->frameCall(daltaTime);
InputHandler::getInputHandler()->frameUpdate();
SelectingScene();
RenderingScene();
if(InputHandler::getInputHandler()->isPressedKey(InputHandler::ESC)) //if pressed ESC key
{
exit(0);
}
}
void GlEngine::RenderingScene()
{
// clear buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glPushMatrix();
ObjectMgr::getMgr()->redraw(false);
glPopMatrix();
glFinish();
glutSwapBuffers();
}
void GlEngine::SelectingScene()
{
Mouse2D position = InputHandler::getInputHandler()->getLastMousePosition();
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
glSelectBuffer (SELECT_BUFF_SIZE, selectBuf);
glRenderMode (GL_SELECT);
//Preppering to selection
glPushMatrix();
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // Reset The Projection Matrix
gluPickMatrix(position.x, viewport[3] - position.y, 2, 2, viewport);
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
glInitNames();
glPushName(0);
//"Rendering" goes here
ObjectMgr::getMgr()->redraw(true);
glPopMatrix();
glFinish();
int hits = glRenderMode(GL_RENDER);
GlEngine::CaclulateSelection(hits);
// Returning default settigns
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // Reset The Projection Matrix
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); // Calculate The Aspect Ratio Of The Window
glMatrixMode(GL_MODELVIEW);
}
void GlEngine::CaclulateSelection(int hits)
{
if (hits <= 0)
return;
int n = selectBuf[3];
GLuint minz = selectBuf[1];
for (int i = 1; i < hits; i++)
{
if (selectBuf[i * 4 + 1] < minz)
{
n = selectBuf[i * 4 + 3];
minz = selectBuf[i * 4 + 1];
}
}
ObjectMgr::getMgr()->selectObiectNumber(n);
}
void GlEngine::iddle()
{
redraw();
}
void GlEngine::setCamera(float posX, float posY, float posZ, float targetX, float targetY, float targetZ)
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(posX, posY, posZ, targetX, targetY, targetZ, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)
}
void GlEngine::initLights()
{
//Light0 is an general ambient for all scene
//Light1 is a point light which will give us directional light
// set up general ambient light
GLfloat lightKa[] = {.3f, .3f, .3f, 1.0f}; // ambient light
glLightfv(GL_LIGHT0, GL_AMBIENT, lightKa);
// set up point light colors (diffuse, specular)
GLfloat lightKd[] = {.65f, .65f, .65f, 1.0f}; // diffuse light
GLfloat lightKs[] = {1, 1, 1, 1}; // specular light
glLightfv(GL_LIGHT1, GL_DIFFUSE, lightKd);
glLightfv(GL_LIGHT1, GL_SPECULAR, lightKs);
// position the light
float lightPos[4] = {10, 3, 0, 1}; // positional light
glLightfv(GL_LIGHT1, GL_POSITION, lightPos);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1); // MUST enable each light source after configuration
}
void GlEngine::init(int argc, char **argv)
{
//window creation
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(width, height);
this->windowHandle = glutCreateWindow(argv[0]);
// register GLUT callback functions
glutDisplayFunc(&(GlEngine::redraw));
glutKeyboardFunc(&(InputHandler::keyPressed));
glutKeyboardUpFunc(&(InputHandler::keyUp));
glutSpecialFunc(&(InputHandler::keySpecialUp));
glutSpecialUpFunc(&(InputHandler::keySpecialPressed));
glutMouseFunc(&(InputHandler::MouseButton));
glutMotionFunc(&(InputHandler::MouseMotion));
glutPassiveMotionFunc(&(InputHandler::MouseMotion));
glutIdleFunc(&(GlEngine::iddle));
// enable /disable features
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glShadeModel(GL_SMOOTH);
glClearColor(0, 0, 0, 1); // background color
glClearDepth(1.0f); // 0 is near, 1 is far
glDepthFunc(GL_LEQUAL);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // Reset The Projection Matrix
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); // Calculate The Aspect Ratio Of The Window
glMatrixMode(GL_MODELVIEW);
this->initLights();
this->initBasicMaterial();
}
void GlEngine::initBasicMaterial()
{
GLfloat material_Ka[] = {1.f, 1.f, 1.f, 1.0f};
GLfloat material_Kd[] = {1.f, 1.f, 1.f, 1.0f};
GLfloat material_Ks[] = {1.f, 1.f, 1.f, 1.0f};
GLfloat material_Ke[] = {1.f, 1.f, 1.f, 1.0f};
GLfloat material_Se = 20.0f;
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, material_Ka);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_Kd);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_Ks);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_Ke);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, material_Se);
}<file_sep>/src/Engine/ObjectMgr.cpp
#include "Engine/Object.h"
#include "Engine/ObjectMgr.h"
#include "Engine/Timer.h"
#include <GL/gl.h>
using namespace std;
ObjectMgr* ObjectMgr::mgr = NULL;
ObjectMgr* ObjectMgr::getMgr()
{
if (ObjectMgr::mgr == NULL)
{
ObjectMgr::mgr = new ObjectMgr();
}
return ObjectMgr::mgr;
}
ObjectMgr::ObjectMgr()
{
//for propper timer initialisation
//at the beginning of game
Timer::getTimer();
}
ObjectMgr::~ObjectMgr()
{
}
void ObjectMgr::add(Object* objectToAdd)
{
this->loadedObjects.push_back(objectToAdd);
}
void ObjectMgr::addUsable(Object* objectToAdd)
{
this->usableObjects.push_back(objectToAdd);
}
void ObjectMgr::remove(Object* objectToRemove)
{
this->loadedObjects.remove(objectToRemove);
}
float ObjectMgr::update()
{
Timer::getTimer()->updateTime();
float deltaTime = Timer::getTimer()->getTimeFromLastUpdate();
list<Object*>::iterator current;
current = this->loadedObjects.begin();
list<Object*>::iterator end;
end = this->loadedObjects.end();
for(;current != end; current++)
{
(*current)->unselect();
(*current)->Update(deltaTime);
}
return deltaTime;
}
void ObjectMgr::redraw(bool isHitMode)
{
int index = 1;
std::list<Object*>* list;
// Changing list of models to rendering
// depending on mode
if(isHitMode == false)
{
list = &(this->loadedObjects);
}
else
{
list = &(this->usableObjects);
};
std::list<Object*>::iterator current;
current = list->begin();
std::list<Object*>::iterator end;
end = list->end();
for(;current != end; current++)
{
if(isHitMode == true)
{
glLoadName(index);
index++;
}
(*current)->Render();
}
}
void ObjectMgr::selectObiectNumber(int number)
{
std::list<Object*>::iterator current = this->usableObjects.begin();
std::list<Object*>::iterator end = this->usableObjects.end();
int counter = 0;
for(current; current != end; current++)
{
counter++;
if(counter == number)
{
(*current)->select();
this->selected = (*current);
return;
}
}
this->selected = NULL;
}
Object* ObjectMgr::getSelectedObject()
{
return this->selected;
}<file_sep>/src/Game/button1.h
//#pragma once
#include "Game/button.h"
#pragma once
class InfoButton: public Button
{
public:
InfoButton(const char* howMany);
virtual ~InfoButton();
virtual void Update(float detlatime);
private:
static const float changeSpeed;
};
<file_sep>/src/Engine/Mesh.h
#pragma once
#include "Engine/Resource.h"
#include <vector>
#include <GL/gl.h>
class Mesh: public Resource
{
public:
struct meshData
{
std::vector<GLfloat> vertexPosition;
std::vector<GLfloat> textureCoords;
std::vector<GLfloat> vertexNormals;
std::vector<GLushort> vertexIndexes;
};
Mesh(std::string name, const Mesh::meshData* data);
virtual ~Mesh();
virtual void Render();
private:
std::vector<GLfloat> vertexPosition;
std::vector<GLfloat> textureCoords;
std::vector<GLfloat> vertexNormals;
std::vector<GLushort> vertexIndexes;
};
<file_sep>/src/Engine/MaterialMgr.cpp
#include "Engine/MaterialMgr.h"
#include "Engine/Material.h"
#include "Engine/ShaderMgr.h"
#include "Engine/TextureMgr.h"
#include <fstream>
std::string color0("color0");
std::string color1("color1");
std::string normal("normal");
std::string shader("shader");
MaterialMgr* MaterialMgr::mgr = NULL;
MaterialMgr* MaterialMgr::getMgr()
{
if (MaterialMgr::mgr == NULL)
{
MaterialMgr::mgr = new MaterialMgr();
}
// It's for objects with no second texture.
TextureMgr::getMgr()->getResource("black");
return MaterialMgr::mgr;
}
Resource* MaterialMgr::createResource(const std::string& name)
{
//opening file with material data
std::string fileExtenction(".mat");
std::string fileName = name + fileExtenction;
std::ifstream data(fileName.c_str());
Material::materialData materialData;
materialData.color = NULL;
materialData.color2 = NULL;
materialData.normal = NULL;
materialData.shader = NULL;
while (data.good())
{
//filling
std::string slot;
std::string value;
data>>slot>>value;
// Check with type of shader program is defined and read it's source.
if(slot == color0)
{
materialData.color = (Texture*)TextureMgr::getMgr()->getResource(value);
}
else if (slot == color1)
{
materialData.color2 = (Texture*)TextureMgr::getMgr()->getResource(value);
}
else if (slot == shader)
{
materialData.shader = (Shader*)ShaderMgr::getMgr()->getResource(value);
}
}
Material* material = new Material(name, &materialData);
return material;
}
<file_sep>/src/Game/button.h
#include "Engine/Object.h"
#pragma once
class Button: public Object
{
public:
Button();
virtual ~Button();
};
<file_sep>/src/Engine/Shader.h
#pragma once
#include "Engine/Resource.h"
#include <GL/gl.h>
class Shader: public Resource
{
public:
struct shaderData
{
GLuint fragmentShader;
GLuint vertexShader;
};
//Constructor for Shader program
Shader(std::string name, Shader::shaderData* data);
//Constructor for fragment/vertex shader
Shader(std::string name, GLuint type, const char * code);
virtual ~Shader();
const GLuint getShaderNumber();
virtual void Render();
private:
GLuint shaderProgramNumber;
};
<file_sep>/src/Engine/ObjectMgr.h
#pragma once
#include <list>
class Object;
class ObjectMgr
{
public:
ObjectMgr();
~ObjectMgr();
static ObjectMgr* getMgr();
void add(Object* objectToAdd);
void addUsable(Object* objectToAdd);
void remove(Object* objectToRemove);
float update();
void redraw(bool isHitMode);
void selectObiectNumber(int number);
Object* getSelectedObject();
private:
std::list<Object*> loadedObjects;
std::list<Object*> usableObjects;
Object* selected;
static ObjectMgr* mgr;
};
<file_sep>/src/Engine/GLHelpers.cpp
#include "Engine/GLHelpers.h"
GLuint glHelp::MakePngTexture(const char *filename)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
int w, h;
GLubyte *pixels = (GLubyte *)load_png(filename, &w, &h);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
free(pixels);
return tex;
}
GLuint glHelp::MakeShaderProgram(GLuint fragmentNo, GLuint vertexNo)
{
GLuint program_object; // a handler to the GLSL program used to update
program_object = glCreateProgram(); // creating a program object
if (fragmentNo != 0)
{
glAttachShader(program_object, fragmentNo);
}
if (vertexNo != 0)
{
glAttachShader(program_object, vertexNo);
}
// Link the shaders into a complete GLSL program.
glLinkProgram(program_object);
//printProgramInfoLog(program_object); // verifies if all this is ok so far
// some extra code for checking if all this initialization is ok
GLint prog_link_success;
glGetObjectParameterivARB(program_object, GL_OBJECT_LINK_STATUS_ARB, &prog_link_success);
if (!prog_link_success) {
//fprintf(stderr, "The shaders could not be linked\n");
exit(1);
}
return program_object;
}
GLuint glHelp::MakeShader(GLuint shaderType, const char* shaderCode)
{
GLuint shaderHandler;
shaderHandler = glCreateShader(shaderType); // creating a fragment shader object
if (shaderHandler != 0)
{
glShaderSource(shaderHandler, 1, &shaderCode, NULL); // assigning the fragment source
//printProgramInfoLog(program_object); // verifies if all this is ok so far
// compiling and attaching the fragment shader onto program
glCompileShader(shaderHandler);
}
return shaderHandler;
}
<file_sep>/src/Engine/InputHandler.h
#pragma once
#include <vector>
struct Mouse2D
{
int x;
int y;
};
class InputHandler
{
public:
static const char ESC;
enum MouseKey
{
MouseLeftButton,
MouseRightButton,
MouseMiddleButton,
MouseEnumSize //it must be always last
};
static InputHandler* getInputHandler();
~InputHandler();
static void keyUp(unsigned char key, int x, int y);
static void keyPressed(unsigned char key, int x, int y);
static void keySpecialUp(int key, int x, int y);
static void keySpecialPressed(int key, int x, int y);
static void MouseButton(int button, int state, int x, int y);
static void MouseMotion(int x, int y);
void frameUpdate();
bool isPressedKey(unsigned char keyCode);
bool isPressedSpecial(int keyIndex);
bool isMousePressed(MouseKey key);
bool isDownKey(unsigned char keyCode);
bool isDownSpecial(int keyIndex);
bool isMouseDown(MouseKey key);
bool isUpKey(unsigned char keyCode);
bool isUpSpecial(int keyIndex);
bool isMouseUp(MouseKey key);
Mouse2D getLastMousePosition();
Mouse2D getLastMouseMotion();
private:
InputHandler();
static InputHandler* handler;
void RecalcMouseMove(Mouse2D newPosition);
void RecalcMouseMove(int newX, int newY);
std::vector<bool> pressedKeys;
std::vector<bool> pressedSpecialKeys;
std::vector<bool> pressedInMouse;
std::vector<bool> lastPressedKeys;
std::vector<bool> lastPressedSpecialKeys;
std::vector<bool> lastPressedInMouse;
Mouse2D lastPosition;
Mouse2D lastMove;
};<file_sep>/src/Game/Mine.h
#pragma once
#include "Game/button1.h"
class Mine : public Button
{
public:
Mine();
virtual ~Mine();
};<file_sep>/src/Game/Game.cpp
#include <math.h>
#include "Game/Game.h"
#include "Engine/GlEngine.h"
const float Game::VerticalSpeed = 3.5;
const float Game::BasicPointSpeed = 4;
const float Game::MaxHeight = 20;
const float Game::MinHeight = 3;
const float Game::MinRadius = 0.6;
const float Game::MaxRadius = 40;
Game::Game():input(InputHandler::getInputHandler())
{
this->cameraLookingAt.x = 0;
this->cameraLookingAt.y = 0;
this->cameraLookingAt.z = 0;
this->cameraLookingFrom.x = 0;
this->cameraLookingFrom.y = 10;
this->cameraLookingFrom.z = 10;
this->lookingAngle = 0;
this->updateCameraSets();
this->logic = new GameLogic();
this->logic->BuildPool(5, 3);
}
Game::~Game()
{
}
void Game::frameCall(float deltaTime)
{
if(this->input->isMousePressed(InputHandler::MouseRightButton))
{
this->changeCameraHorisontal(deltaTime);
}
// Camera height
if(this->input->isPressedKey('q') == true)
{
this->changeCameraVertical(deltaTime, true);
}
if(this->input->isPressedKey('z'))
{
this->changeCameraVertical(deltaTime, false);
}
// Base point move
if(this->input->isPressedKey('w'))
{
this->changeBasicPoint(deltaTime, 1, 0);
}
if(this->input->isPressedKey('s'))
{
this->changeBasicPoint(deltaTime, -1, 0);
}
if(this->input->isPressedKey('a'))
{
this->changeBasicPoint(deltaTime, 0, 1);
}
if(this->input->isPressedKey('d'))
{
this->changeBasicPoint(deltaTime, 0, -1);
}
//Display change
this->displayAsWireframe(this->input->isPressedKey('x'));
// For managing click on ladyBug
if(this->input->isMouseUp(InputHandler::MouseLeftButton))
{
this->logic->ClickLadyBug();
}
}
void Game::changeCameraHorisontal(float deltaTime)
{
Mouse2D move = this->input->getLastMouseMotion();
//Data preparation
float radius = sqrt(pow(this->cameraLookingFrom.x, 2) + pow(this->cameraLookingFrom.z, 2));
float angle = atan2(this->cameraLookingFrom.x, this->cameraLookingFrom.z);
if (move.y > 300)
{
move.y = 300;
}
else if (move.y < -300)
{
move.y = -300;
}
//section for move
angle += float(move.x) / 20 *deltaTime;
radius *= float(move.y) / 10 *deltaTime + 1;
if (radius < Game::MinRadius)
{
radius = Game::MinRadius;
}
else if (radius > Game::MaxRadius)
{
radius = Game::MaxRadius;
}
this->cameraLookingFrom.x = radius * sin(angle);
this->cameraLookingFrom.z = radius * cos(angle);
this->updateCameraSets();
this->lookingAngle = angle;
}
void Game::updateCameraSets()
{
position3D cameraPosition;
cameraPosition.x = this->cameraLookingAt.x + this->cameraLookingFrom.x;
cameraPosition.y = this->cameraLookingAt.y + this->cameraLookingFrom.y;
cameraPosition.z = this->cameraLookingAt.z + this->cameraLookingFrom.z;
GlEngine* engine = GlEngine::getEngine();
engine->setCamera(cameraPosition.x, cameraPosition.y, cameraPosition.z,
this->cameraLookingAt.x, this->cameraLookingAt.y, this->cameraLookingAt.z);
}
void Game::changeCameraVertical(float deltaTime, bool goingUp)
{
float changePosition = Game::VerticalSpeed * deltaTime;
if (goingUp == true)
{
this->cameraLookingFrom.y += changePosition;
if (this->cameraLookingFrom.y > Game::MaxHeight)
{
this->cameraLookingFrom.y = Game::MaxHeight;
}
}
else
{
this->cameraLookingFrom.y -= changePosition;
if (this->cameraLookingFrom.y < Game::MinHeight)
{
this->cameraLookingFrom.y = Game::MinHeight;
}
}
this->updateCameraSets();
}
void Game::changeBasicPoint(float deltatime, char stright, char side)
{
//Data preparation
float strightDir = stright * cos(this->lookingAngle) - side * sin(this->lookingAngle);
float sideDir = stright * sin(this->lookingAngle) + side * cos(this->lookingAngle);
this->cameraLookingAt.x += -sideDir * Game::BasicPointSpeed * deltatime;
this->cameraLookingAt.z += -strightDir * Game::BasicPointSpeed * deltatime;
if (this->cameraLookingAt.x < - Game::MaxRadius)
{
this->cameraLookingAt.x = - Game::MaxRadius;
}
if (this->cameraLookingAt.x > Game::MaxRadius)
{
this->cameraLookingAt.x = Game::MaxRadius;
}
if (this->cameraLookingAt.z < - Game::MaxRadius)
{
this->cameraLookingAt.z = - Game::MaxRadius;
}
if (this->cameraLookingAt.z > Game::MaxRadius)
{
this->cameraLookingAt.z = Game::MaxRadius;
}
this->updateCameraSets();
}
void Game::displayAsWireframe(bool active)
{
GlEngine* engine = GlEngine::getEngine();
if (active == true)
{
engine->setShowMode(GL_LINE);
}
else
{
engine->setShowMode(GL_FILL);
}
}<file_sep>/src/Engine/Shader.cpp
#include "Engine/GlEngine.h"
#include "Engine/Shader.h"
Shader::Shader(std::string name, Shader::shaderData* data):Resource(name)
{
this->shaderProgramNumber = glHelp::MakeShaderProgram(data->fragmentShader,
data->vertexShader);
}
Shader::Shader(std::string name, GLuint type, const char * code):Resource(name)
{
this->shaderProgramNumber = glHelp::MakeShader(type, code);
}
Shader::~Shader()
{
}
const GLuint Shader::getShaderNumber()
{
return this->shaderProgramNumber;
}
void Shader::Render()
{
glUseProgram(this->shaderProgramNumber);
}
<file_sep>/src/Game/ladybug.h
#pragma once
#include "Engine/Object.h"
class GameLogic;
class LadyBug : public Object
{
public:
LadyBug(GameLogic* logicToInform, int col, int row);
~LadyBug();
void Click();
void NeightbourCall();
virtual void Update(float deltaTime);
private:
enum ClickedMeaning
{
notClicked,
ClikkedOnce, //should change colour
ClickedTwice, //should fly
};
GameLogic* logicToInform;
ClickedMeaning state;
float animationTime;
bool informedAboutFly;
bool isFlying;
int col;
int row;
float angleVelocity;
static const float colorAnimationLenght;
static const float flyAnimationLenght;
static const float flyAnimationHeight;
static const float informationDelay;
};<file_sep>/src/Engine/MeshMgr.cpp
#include <fstream>
#include <sstream>
#include "Engine/MeshMgr.h"
#include "Engine/Mesh.h"
#include "rapidxml/rapidxml.hpp"
MeshMgr* MeshMgr::mgr = NULL;
MeshMgr* MeshMgr::getMgr()
{
if (MeshMgr::mgr == NULL)
{
MeshMgr::mgr = new MeshMgr();
}
return MeshMgr::mgr;
}
Resource* MeshMgr::createResource(const std::string& name)
{
//prepering data structure
Mesh::meshData meshData;
int vertexNumber;
//opening file with mesh data
std::string fileExtenction(".mesh");
std::string fileName = name + fileExtenction;
std::ifstream data(fileName.c_str());
//read file to string used as char*
std::string meshDataPure;
std::stringstream buffer;
buffer << data.rdbuf();
meshDataPure = buffer.str();
data.close();
meshDataPure.append("\0");
//Parse to XML tree
char* meshDataPureChar = &meshDataPure[0];
rapidxml::xml_document<> doc;
doc.parse<0>(meshDataPureChar);
rapidxml::xml_node<>* root = doc.first_node();
//Finding needed vertex connected buffers size
rapidxml::xml_node<>* vertexRoot = root->first_node("sharedgeometry");
vertexNumber = atoi(vertexRoot->first_attribute("vertexcount")->value());
meshData.vertexPosition.reserve(vertexNumber*3+1);
meshData.vertexNormals.reserve(vertexNumber*3+1);
meshData.textureCoords.reserve(vertexNumber*2+1);
//Filling vertex buffers
vertexRoot = vertexRoot->first_node(); //bacause XML has such strange construction.
rapidxml::xml_node<>* vertex = vertexRoot->first_node();
//for each vertex
while (vertex != NULL)
{
rapidxml::xml_node<>* position = vertex->first_node("position");
float value = atof(position->first_attribute("x")->value());
meshData.vertexPosition.push_back(value);
value = atof(position->first_attribute("y")->value());
meshData.vertexPosition.push_back(value);
value = atof(position->first_attribute("z")->value());
meshData.vertexPosition.push_back(value);
rapidxml::xml_node<>* normal = vertex->first_node("normal");
value = atof(normal->first_attribute("x")->value());
meshData.vertexNormals.push_back(value);
value = atof(normal->first_attribute("y")->value());
meshData.vertexNormals.push_back(value);
value = atof(normal->first_attribute("z")->value());
meshData.vertexNormals.push_back(value);
rapidxml::xml_node<>* texcoord = vertex->first_node("texcoord");
value = atof(texcoord->first_attribute("u")->value());
meshData.textureCoords.push_back(value);
value = atof(texcoord->first_attribute("v")->value());
meshData.textureCoords.push_back(value);
vertex = vertex->next_sibling();
} //Filling vertex information complite
//Finding needed face connected buffers size
rapidxml::xml_node<>* faceRoot = root->first_node("submeshes")->first_node("submesh")->
first_node("faces");
int faces = atoi(faceRoot->first_attribute("count")->value());
meshData.vertexIndexes.reserve(faces*3+1);
rapidxml::xml_node<>* face = faceRoot->first_node();
//Filling buffer
while(face != NULL)
{
float value = atoi(face->first_attribute("v1")->value());
meshData.vertexIndexes.push_back(value);
value = atoi(face->first_attribute("v2")->value());
meshData.vertexIndexes.push_back(value);
value = atoi(face->first_attribute("v3")->value());
meshData.vertexIndexes.push_back(value);
face = face->next_sibling();
}
Mesh* mesh = new Mesh(name, &meshData);
return mesh;
}
<file_sep>/src/Engine/MaterialMgr.h
#pragma once
#include "Engine/ResourceMgr.h"
class MaterialMgr: public ResourceMgr
{
public:
static MaterialMgr* getMgr();
private:
virtual Resource* createResource(const std::string& name);
static MaterialMgr* mgr;
};
<file_sep>/src/Engine/TextureMgr.h
#pragma once
#include "Engine/ResourceMgr.h"
class TextureMgr: public ResourceMgr
{
public:
static TextureMgr* getMgr();
private:
virtual Resource* createResource(const std::string& name);
static TextureMgr* mgr;
};
<file_sep>/src/Engine/ResourceMgr.cpp
#include "Engine/ResourceMgr.h"
ResourceMgr::ResourceMgr()
{
}
ResourceMgr::~ResourceMgr()
{
}
void ResourceMgr::add(Resource* toAdd)
{
this->objects[toAdd->getName()] = toAdd;
}
Resource* ResourceMgr::getResource(const std::string& name)
{
Resource* res = this->objects[name];
if(res == NULL)
{
res = this->createResource(name);
this->add(res);
}
return res;
}
<file_sep>/src/Engine/ShaderMgr.cpp
#include <fstream>
#include <sstream>
#include "Engine/Shader.h"
#include "Engine/ShaderMgr.h"
std::string fragment("fragment");
std::string vertex("vertex");
ShaderMgr* ShaderMgr::mgr = NULL;
ShaderMgr* ShaderMgr::getMgr()
{
if (ShaderMgr::mgr == NULL)
{
ShaderMgr::mgr = new ShaderMgr();
}
return ShaderMgr::mgr;
}
Resource* ShaderMgr::createResource(const std::string& name)
{
//opening file with shader data
std::string fileExtenction(".shad");
std::string fileName = name + fileExtenction;
std::ifstream data(fileName.c_str());
//creation of structure
Shader::shaderData shaderData;
shaderData.fragmentShader = 0;
shaderData.vertexShader = 0;
while (data.good())
{
//filling
std::string type;
std::string code;
data>>type>>code;
// Check with type of shader program is defined and read it's source.
if(type == fragment)
{
Shader* fragment = (Shader*)this->createShaderPart(code, GL_FRAGMENT_SHADER_ARB);
shaderData.fragmentShader = fragment->getShaderNumber();
}
else if (type == vertex)
{
Shader* vertex = (Shader*)this->createShaderPart(code, GL_VERTEX_SHADER_ARB);
shaderData.vertexShader = vertex->getShaderNumber();
}
}
data.close();
Shader* shader = new Shader(name, &shaderData);
return shader;
}
Resource* ShaderMgr::createShaderPart(const std::string& name, GLuint type)
{
std::string ShaderCode;
std::ifstream source(name.c_str());
std::stringstream buffer;
buffer << source.rdbuf();
ShaderCode = buffer.str();
source.close();
Resource* shaderPart = new Shader(name, type, ShaderCode.c_str());
this->add(shaderPart);
return shaderPart;
}
<file_sep>/src/Game/Pool.cpp
#include "Game/Pool.h"
#include "Game/ladybug.h"
#include "Game/button.h"
#include "Game/Mine.h"
const float Pool::BugSize = 1;
const int Pool::MineCode = -1;
int neightbours[][2] = {{-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}};
inline int Pool::coord(int col, int row)
{
return row * this->size + col;
}
inline int Pool::findCol(int pos)
{
return pos % this->size;
}
inline int Pool::findRow(int pos)
{
return pos / this->size;
}
Pool::Pool(int size, GameLogic* parent):size(size), poolInfo(size*size, 0),
parent(parent)
{
this->leaf = new Leaf();
this->leaf->setPosition(0.f, -0.05f, 0.f);
this->leaf->setScale(size+3);
}
Pool::~Pool()
{
}
void Pool::fillWithBugs()
{
for(int col = 0; col < this->size; col++)
for(int row = 0; row < this->size; row++)
{
LadyBug* bug = new LadyBug(this->parent, col, row);
this->putObject(col, row, bug);
}
}
LadyBug* Pool::getLadyBug(int col, int row)
{
if((0 <= col) && (col < this->size) && (0 <= row) && (row < this->size))
{
return this->bugs[coord(col, row)];
}
else
{
return NULL;
}
}
Button* Pool::getObject(int col, int row)
{
return this->objects[coord(col, row)];
}
void Pool::putInfoButton(int col, int row, int howManyMines)
{
Button* infoButton;
switch(howManyMines)
{
case 1:
infoButton = new InfoButton("1");
break;
case 2:
infoButton = new InfoButton("2");
break;
case 3:
infoButton = new InfoButton("3");
break;
case 4:
infoButton = new InfoButton("4");
break;
case 5:
infoButton = new InfoButton("5");
break;
case 6:
infoButton = new InfoButton("6");
break;
case 7:
infoButton = new InfoButton("7");
break;
case 8:
infoButton = new InfoButton("8");
break;
}
this->putObject(col, row, infoButton);
}
void Pool::putMine(int col, int row)
{
Mine* mine = new Mine();
this->putObject(col, row, mine);
this->poolInfo[coord(col, row)] = -1;
}
void Pool::putObject(int col, int row, Button* object)
{
this->objects[coord(col, row)] = object;
this->recalcCoords(col, row, 0, object);
}
void Pool::putObject(int col, int row, LadyBug* object)
{
this->bugs[coord(col, row)] = object;
this->recalcCoords(col, row, 0.f, object);
}
void Pool::updateInfoButtons()
{
this->recalcPoolInfo();
for(int pos=0; pos < this->poolInfo.size(); pos++)
{
if(this->poolInfo[pos] > 0) //if has some trubelsome neightbours
{
int col = findCol(pos);
int row = findRow(pos);
this->putInfoButton(col, row, this->poolInfo[pos]);
}
}
}
void Pool::recalcCoords(int col, int row, float height, Object* object)
{
float dist = (float)(this->size) * Pool::BugSize;
float halfdist = dist / 2.0;
float resolution = Pool::BugSize;
float colPos = -halfdist + col * resolution;
float rowPos = -halfdist + row * resolution;
object->setPosition(colPos, height, row);
}
void Pool::recalcPoolInfo()
{
for(int pos = 0; pos <size*size; pos++)
{
if(this->poolInfo[pos] == Pool::MineCode)
{
int col = findCol(pos);
int row = findRow(pos);
this->increaseNeightbourRisk(col, row);
}
}
}
void Pool::increaseNeightbourRisk(int col, int row)
{
for(int i = 0; i < 8; i++)
{
int newCol = col + neightbours[i][0];
int newRow = row + neightbours[i][1];
// if neightbour is in pool
if((0 <= newCol) && (newCol < this->size) &&
(0 <= newRow) && (newRow < this->size))
{
if(this->poolInfo[coord(newCol, newRow)] != Pool::MineCode)
{
this->poolInfo[coord(newCol, newRow)]++;
}
}
}
}
int Pool::getCellValue(int col, int row)
{
return this->poolInfo[coord(col, row)];
}<file_sep>/src/Engine/load_png.cpp
#include <stdlib.h>
#include <assert.h>
#include <stdint.h>
#include "png.h"
#include "Engine/load_png.h"
#define PNG_SIG_BYTES 8
//#define uint8_t char
char * load_png(const char *name, int *width, int *height)
{
FILE *png_file = fopen(name, "rb");
assert(png_file);
uint8_t header[PNG_SIG_BYTES];
fread(header, 1, PNG_SIG_BYTES, png_file);
assert(!png_sig_cmp(header, 0, PNG_SIG_BYTES));
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
assert(png_ptr);
png_infop info_ptr = png_create_info_struct(png_ptr);
assert(info_ptr);
png_infop end_info = png_create_info_struct(png_ptr);
assert(end_info);
assert(!setjmp(png_jmpbuf(png_ptr)));
png_init_io(png_ptr, png_file);
png_set_sig_bytes(png_ptr, PNG_SIG_BYTES);
png_read_info(png_ptr, info_ptr);
*width = png_get_image_width(png_ptr, info_ptr);
*height = png_get_image_height(png_ptr, info_ptr);
png_uint_32 bit_depth, color_type;
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
color_type = png_get_color_type(png_ptr, info_ptr);
if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
png_set_gray_1_2_4_to_8(png_ptr);
if (bit_depth == 16)
png_set_strip_16(png_ptr);
if(color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
else if(color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
png_set_gray_to_rgb(png_ptr);
}
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
png_set_tRNS_to_alpha(png_ptr);
else
png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
png_read_update_info(png_ptr, info_ptr);
png_uint_32 rowbytes = png_get_rowbytes(png_ptr, info_ptr);
png_uint_32 numbytes = rowbytes*(*height);
png_byte* pixels = (png_byte*)malloc(numbytes);
png_byte** row_ptrs = (png_byte**)malloc((*height) * sizeof(png_byte*));
int i;
for (i=0; i<(*height); i++)
row_ptrs[i] = pixels + ((*height) - 1 - i)*rowbytes;
png_read_image(png_ptr, row_ptrs);
free(row_ptrs);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(png_file);
return (char *)pixels;
}
<file_sep>/src/Engine/Resource.h
#pragma once
#include <string>
class Resource
{
public:
Resource(std::string name):name(name){};
virtual ~Resource(){};
const std::string getName(){return name;};
virtual void Render()=0;
private:
std::string name;
};
<file_sep>/src/Engine/ExternLogic.h
#pragma once
class ExternLogic
{
public:
virtual void frameCall(float deltaTime) = 0;
};<file_sep>/src/Engine/Texture.cpp
#include "Engine/Texture.h"
Texture::Texture(std::string name, GLuint textureNumber):Resource(name),
textureNumber(textureNumber)
{
}
Texture::~Texture()
{
}
void Texture::Render()
{
glBindTexture(GL_TEXTURE_2D, this->textureNumber);
}
<file_sep>/src/Engine/Material.h
#include "Engine/Resource.h"
#include <GL/gl.h>
#ifndef MATERIAL_H
#define MATERIAL_H
class Texture;
class Shader;
class Material: public Resource
{
public:
struct materialData
{
Shader* shader;
Texture* color;
Texture* color2;
Texture* normal;
};
Material(std::string name, Material::materialData* data);
virtual ~Material();
GLuint getShaderHandler();
virtual void Render();
private:
Material::materialData data;
};
#endif
<file_sep>/src/Game/Leaf.cpp
#include "Game/Leaf.h"
#include "Engine/MeshMgr.h"
#include "Engine/MaterialMgr.h"
Leaf::Leaf()
{
this->mesh = (Mesh*)MeshMgr::getMgr()->getResource("leaf");
this->material = (Material*)MaterialMgr::getMgr()->getResource("leaf");
}
Leaf::~Leaf()
{
}
<file_sep>/src/Engine/TextureMgr.cpp
#include "Engine/GLHelpers.h"
#include "Engine/TextureMgr.h"
#include "Engine/Texture.h"
TextureMgr* TextureMgr::mgr = NULL;
TextureMgr* TextureMgr::getMgr()
{
if (TextureMgr::mgr == NULL)
{
TextureMgr::mgr = new TextureMgr();
}
return TextureMgr::mgr;
}
Resource* TextureMgr::createResource(const std::string& name)
{
//opening file with mesh data
std::string fileExtenction(".png");
std::string fileName = name + fileExtenction;
GLuint textureNumber = glHelp::MakePngTexture(fileName.c_str());
Texture* texture = new Texture(name, textureNumber);
return texture;
}
<file_sep>/src/Engine/Timer.cpp
#include "Engine/Timer.h"
Timer* Timer::timer = NULL;
Timer* Timer::getTimer()
{
if (Timer::timer == NULL)
{
Timer::timer = new Timer();
}
return Timer::timer;
}
Timer::Timer()
{
this->currentTime = clock();
this->timeDuration = 0;
}
Timer::~Timer()
{
}
void Timer::updateTime()
{
clock_t newTime = clock();
this->timeDuration = float(newTime - this->currentTime)/CLOCKS_PER_SEC;
this->currentTime = newTime;
}
float Timer::getTimeFromLastUpdate()
{
return this->timeDuration;
}
clock_t Timer::getTime()
{
return clock();
}
<file_sep>/src/Engine/ResourceMgr.h
#pragma once
#include "Engine/Resource.h"
#include <map>
class ResourceMgr
{
public:
ResourceMgr();
~ResourceMgr();
Resource* getResource(const std::string& name);
void add(Resource* toAdd);
protected:
virtual Resource* createResource(const std::string& name)=0;
std::map<std::string, Resource*> objects;
};
<file_sep>/src/Game/Mine.cpp
#include "Game/Mine.h"
#include "Engine/MaterialMgr.h"
Mine::Mine()
{
this->material = (Material*)MaterialMgr::getMgr()->getResource("mine");
}
Mine::~Mine()
{
}<file_sep>/src/Game/Pool.h
#pragma once
#include <map>
#include <vector>
#include "Game/ladybug.h"
#include "Game/button.h"
#include "Game/Leaf.h"
struct bugCoordinates
{
short col;
short row;
};
class GameLogic;
class Pool
{
public:
Pool(int size, GameLogic* parent);
~Pool();
void fillWithBugs();
void putMine(int col, int row);
void updateInfoButtons();
LadyBug* getLadyBug(int col, int row);
Button* getObject(int col, int row);
int getCellValue(int col, int row);
static const int MineCode;
private:
void putInfoButton(int col, int row, int howManyMines);
void putObject(int col, int row, Button* object);
void putObject(int col, int row, LadyBug* object);
void recalcCoords(int col, int row, float height, Object* object);
void recalcPoolInfo();
void increaseNeightbourRisk(int col, int row);
int coord(int col, int row);
int findCol(int pos);
int findRow(int pos);
GameLogic* parent;
int size;
std::map<int, LadyBug*> bugs;
std::map<int, Button*> objects;
std::vector<short> poolInfo;
Leaf* leaf;
static const float BugSize;
};<file_sep>/src/Game/GameLogic.h
#pragma once
class Pool;
class GameLogic
{
public:
GameLogic();
~GameLogic();
void BuildPool(int size, int mines);
void StartedBug(int col, int row);
void ClickLadyBug();
float getRandom();
private:
int checkPoolValue(int col, int row);
int endGame(bool isWinning);
Pool* pool;
int bugs;
int mines;
};<file_sep>/src/Game/main.cpp
#include "Engine/GlEngine.h"
#include "Game/Game.h"
#include <iostream>
int main( int argc, char* args[] )
{
GlEngine* engine = GlEngine::getEngine();
if(GlEngine::canWork() == false)
{
std::cout<<"You have too low version of OGL."<<std::endl;
return 1;
}
engine->init(argc, args);
Game* game = new Game();
engine->setExternLogic(game);
engine->run();
return 0;
}
<file_sep>/src/Engine/Material.cpp
#include "Engine/GLHelpers.h"
#include "Engine/Material.h"
#include "Engine/Texture.h"
#include "Engine/Shader.h"
Material::Material(std::string name, Material::materialData* data) : Resource(name), data(*data)
{
}
Material::~Material()
{
}
GLuint Material::getShaderHandler()
{
return this->data.shader->getShaderNumber();
}
void Material::Render()
{
//load shader
this->data.shader->Render();
GLuint shaderNumber = getShaderHandler();
//load textures to propper slots
if(this->data.color != NULL)
{
GLint texture = glGetUniformLocationARB(shaderNumber, "texture0");
glActiveTextureARB(GL_TEXTURE0_ARB);
this->data.color->Render();
glUniform1iARB(texture, 0);
}
if(this->data.color2 != NULL)
{
GLuint texture = glGetUniformLocationARB(shaderNumber, "texture1");
glActiveTextureARB(GL_TEXTURE1_ARB);
this->data.color2->Render();
glUniform1iARB(texture, 1);
}
if(this->data.normal != NULL)
{
//GLuint texture = glGetUniformLocationARB(shaderNumber, "texture0");
this->data.normal->Render();
//glUniform1iARB(texture, 2);
}
}
<file_sep>/src/Engine/MeshMgr.h
#pragma once
#include "Engine/ResourceMgr.h"
class MeshMgr: public ResourceMgr
{
public:
static MeshMgr* getMgr();
private:
virtual Resource* createResource(const std::string& name);
static MeshMgr* mgr;
};
<file_sep>/README.txt
This is my first project using pure OpenGL.
In that project I have to make simple clone of "saper".
However the most important part is to use pixel and
vertex shaders for some simple special effects.
version 0.0
- something what is compillable.
version 0.1
- one fragment shader is working with one simple model with no lights
version 0.2
- added working vertex shader with scale and one axis rotation.
- changed file format to more complicated but supported by Blender
so now making models is preaty easy.
- fixed bugs with many textures shown by one fragment shader (basic fail).
- minor changes in almost all resources groups, especially with shaders
so now one fragment/vertex shader can be shared by many shader programs.
version RC1
- selection of models work
- all game logic work
- checking if current OpenGL is 1.3 or higher work
- cleaning all code from trashes from developing done
<file_sep>/src/Engine/Object.cpp
#include "Engine/GLHelpers.h"
#include "Engine/Object.h"
#include "Engine/ObjectMgr.h"
#include "Engine/Mesh.h"
#include "Engine/Material.h"
Object::Object() : mesh(NULL), material(NULL), scale(1), angle(0), selection(0),
colorMix(0)
{
this->pos.x = 0;
this->pos.y = 0;
this->pos.z = 0;
registerObject();
}
Object::Object(float x, float y, float z) : mesh(NULL), material(NULL), scale(1),
angle(0), selection(0), colorMix(0)
{
this->pos.x = x;
this->pos.y = y;
this->pos.z = z;
registerObject();
}
Object::Object(Object::position pos) : mesh(NULL), material(NULL), pos(pos), scale(1),
angle(0), selection(0), colorMix(0)
{
registerObject();
}
Object::~Object()
{
}
void Object::setPosition(float x, float y, float z)
{
this->pos.x = x;
this->pos.y = y;
this->pos.z = z;
}
void Object::setScale(float scale)
{
this->scale = scale;
}
float Object::getScale()
{
return this->scale;
}
void Object::Update(float detlatime)
{
}
void Object::Render()
{
//setting position
glPushMatrix();
glTranslatef(this->pos.x, this->pos.y, this->pos.z);
//setting up material
this->material->Render();
//Setting object scale
GLuint shader = this->material->getShaderHandler();
GLint scaleLocation = glGetUniformLocationARB(shader, "objectScale");
glUniform1fARB(scaleLocation, this->scale);
GLint angleLocation = glGetUniformLocationARB(shader, "objectAngle");
glUniform1fARB(angleLocation, this->angle);
GLint selectionLocation = glGetUniformLocationARB(shader, "objectSelection");
glUniform1fARB(selectionLocation, this->selection);
GLint textureMixLocation = glGetUniformLocationARB(shader, "textureMix");
glUniform1fARB(textureMixLocation, this->colorMix);
//render geometry with current material sets
this->mesh->Render();
//remove changes
glPopMatrix();
glFlush();
}
void Object::registerObject()
{
ObjectMgr::getMgr()->add(this);
}
void Object::unselect()
{
this->selection = 0.0;
}
void Object::select()
{
this->selection = 1.0;
}<file_sep>/src/Game/GameLogic.cpp
#include <time.h>
#include <stdlib.h>
#include <iostream>
#include "Game/GameLogic.h"
#include "Game/Pool.h"
#include "Engine/ObjectMgr.h"
int myneightbours[][2] = {{-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}};
GameLogic::GameLogic():pool(NULL)
{
srand((unsigned)time( NULL ));
}
GameLogic::~GameLogic()
{
}
void GameLogic::BuildPool(int size, int mines)
{
this->mines = mines;
// Building pool
this->pool = new Pool(size, this);
// Filling with mines
while (mines > 0)
{
//TODO propper random, but for tests now is good
int col = (int)(this->getRandom()*size);
int row = (int)(this->getRandom()*size);
if(this->pool->getObject(col, row) == NULL)
{
mines--;
this->pool->putMine(col, row);
}
}
// Putting number objects
this->pool->updateInfoButtons();
//filling with bugs
this->pool->fillWithBugs();
this->bugs = size*size; // On pool we hawe that many bugs
}
void GameLogic::ClickLadyBug()
{
LadyBug* bug = (LadyBug*)ObjectMgr::getMgr()->getSelectedObject();
if(bug != NULL)
{
bug->Click();
}
}
void GameLogic::StartedBug(int col, int row)
{
Button* object = this->pool->getObject(col, row);
if(object == NULL) // If not standing on any number
{
for(int i=0; i < 8; i++)
{
int newCol = col + myneightbours[i][0];
int newRow = row + myneightbours[i][1];
LadyBug* bug = this->pool->getLadyBug(newCol, newRow);
if(bug != NULL)
{
bug->NeightbourCall();
}
}
}
if (this->pool->getCellValue(col, row) == Pool::MineCode)
{
std::cout<<"You lost the game!!\n";
std::cout <<"And who is the bugmaster? Who? WHO!!!"<<std::endl;
}
this->bugs--;
if(this->bugs == this->mines)
{
std::cout<<"NNOOOOOOOooooooo.......\n";
std::cout<<"Ok, you won this time."<<std::endl;
}
}
float GameLogic::getRandom()
{
int randed = rand() % 32767;
float floatRand = (float)randed;
return floatRand/32767.0f;
}<file_sep>/src/Engine/Texture.h
#pragma once
#include "Engine/Resource.h"
#include <GL/gl.h>
class Texture: public Resource
{
public:
Texture(std::string name, GLuint textureNumber);
~Texture();
virtual void Render();
private:
GLuint textureNumber;
GLenum lastChosenTextureNumber;
};
|
3ba43599a0aa935cc3959f50a909703d79e96e8f
|
[
"Text",
"C",
"CMake",
"C++"
] | 53
|
C++
|
gienekart/Simple-bug-saper
|
30ac12786c11490fd8675b32b1adc7d79124bb00
|
5af9ee168bcbb1de5634e78e025f286cc0a32495
|
refs/heads/main
|
<repo_name>lazarus2019/facebook-template<file_sep>/README.md
# facebook-template
Make A Website Like Facebook Using HTML And CSS | Social Media Website Design
<file_sep>/app.js
const settingsMenu = document.querySelector(".settings-menu");
const userPhoto = document.querySelector(".user-photo");
const darkBtn = document.querySelector("#dark-btn");
const adsContainer = document.querySelector(".ads-container");
function settingMenuToggle() {
settingsMenu.classList.toggle("settings-menu-height");
}
// window.addEventListener("click", function(){
// // // if(event.target != settingsMenu && settingsMenu.classList.contains("settings-menu-height")){
// // // settingsMenu.classList.remove("settings-menu-height");
// // // }
// // if(event.target != settingsMenu && settingsMenu.classList.contains("settings-menu-height")){
// // console.log("outside")
// // }
// console.log(event.target)
// });
// Change dark mode on/off
darkBtn.addEventListener('click', () => {
darkBtn.classList.toggle("dark-btn-on");
document.body.classList.toggle("dark-theme");
// Saving theme mode setting
if (localStorage.getItem("theme") == "light") {
localStorage.setItem("theme", "dark");
} else {
localStorage.setItem("theme", "light");
}
})
if (localStorage.getItem("theme") == "light") {
darkBtn.classList.remove("dark-btn-on");
document.body.classList.remove("dark-theme");
}
else if (localStorage.getItem("theme") == "dark") {
darkBtn.classList.add("dark-btn-on");
document.body.classList.add("dark-theme");
} else {
localStorage.setItem("theme", "light");
}
let box = document.getElementById('box'),
btn = document.querySelector('button');
btn.addEventListener('click', function () {
if (box.classList.contains('hidden')) {
box.classList.remove('hidden');
setTimeout(function () {
box.classList.remove('visuallyhidden');
}, 20);
} else {
box.classList.add('visuallyhidden');
box.addEventListener('transitionend', function (e) {
box.classList.add('hidden');
}, {
capture: false,
once: true,
passive: false
});
}
}, false);
|
ae08b3eb8170a9b4d217ce4848df07ea3d75a903
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
lazarus2019/facebook-template
|
e94dc2898c8a0258a00886bc2747a5d3549ba6e2
|
7d4fb46458d7a986a4faa7c06fadf46d382324c7
|
refs/heads/master
|
<file_sep>// var i2 = ['广州广州,快上车', '功夫熊猫:你的姿势不对', '好舍友', '后面妹纸:别拍,等我带上口罩', '可以,画面很美',
// '厉害,请收下我的膝盖', '美美哒', '美女一枚', '你又翻墙出外面玩了?', '生日快乐',
// '生日快乐2', '树爷爷:你好重,快下来', '一对好姐妹', '中间那排,第三位同学请起来回答问题'
// ];
// var i3 = ['大海,绽放自由', '党的宗旨是一切为人民服务(所以我的外卖是不是可以交给你了?)', '钢琴老师好', '好惬意', '黄胖子! ! !',
// '耶~', '举起手来', '来,看镜头', '美女,时隔一年,你又来了', '你应该面朝大海,来,在拍一次',
// '傻乎乎', '哇,哪里?好想去', '哇哦,好好玩的样子', '我们来玩足球吧', '嘻嘻,久别重逢',
// '耶,可爱的笑脸', '衣服和场合很搭调nice', '这是谁?认出有奖'
// ];
function randomBackground() {
var couleurFond;
var numFond = Math.floor((Math.random() * 10) + 1);
switch (numFond) {
case 1:
couleurFond = "#16a085";
break;
case 2:
couleurFond = "#27ae60";
break;
case 3:
couleurFond = "#2980b9";
break;
case 4:
couleurFond = "#8e44ad";
break;
case 5:
couleurFond = "#2c3e50";
break;
case 6:
couleurFond = "#f39c12";
break;
case 7:
couleurFond = "#d35400";
break;
case 8:
couleurFond = "#c0392b";
break;
case 9:
couleurFond = "#bdc3c7";
break;
case 10:
couleurFond = "#7f8c8d";
break;
}
return couleurFond;
}
function changeCouleur() {
var tabNum = [];
while (tabNum.length < 4) {
var numSlime = Math.floor((Math.random() * 10) + 1);
if (tabNum.indexOf(numSlime) == -1) {
tabNum.push(numSlime);
}
}
for (var i = 0; i < 4; i++) {
var couleurSlime;
var corpsSlime = document.getElementsByClassName("corps");
switch (tabNum[i]) {
case 1:
couleurSlime = "#1abc9c";
break;
case 2:
couleurSlime = "#2ecc71";
break;
case 3:
couleurSlime = "#3498db";
break;
case 4:
couleurSlime = "#9b59b6";
break;
case 5:
couleurSlime = "#34495e";
break;
case 6:
couleurSlime = "#f1c40f";
break;
case 7:
couleurSlime = "#e67e22";
break;
case 8:
couleurSlime = "#e74c3c";
break;
case 9:
couleurSlime = "#ecf0f1";
break;
case 10:
couleurSlime = "#95a5a6";
break;
}
corpsSlime[i].style.fill = couleurSlime;
}
}
var Vector = function (x, y) {
this.x = x || 0;
this.y = y || 0;
};
Vector.prototype = {
add: function (v) {
this.x += v.x;
this.y += v.y;
return this;
},
length: function () {
return Math.sqrt(this.x * this.x + this.y * this.y);
},
rotate: function (theta) {
var x = this.x;
var y = this.y;
this.x = Math.cos(theta) * this.x - Math.sin(theta) * this.y;
this.y = Math.sin(theta) * this.x + Math.cos(theta) * this.y;
return this;
},
mult: function (f) {
this.x *= f;
this.y *= f;
return this;
}
};
var Leaf = function (p, r, c, ctx) {
this.p = p || null;
this.r = r || 0;
this.c = c || 'rgba(255,255,255,1.0)';
this.ctx = ctx;
}
Leaf.prototype = {
render: function () {
var that = this;
var ctx = this.ctx;
var f = Branch.random(1, 2)
for (var i = 0; i < 5; i++) {
(function (r) {
setTimeout(function () {
ctx.beginPath();
ctx.fillStyle = that.color;
ctx.moveTo(that.p.x, that.p.y);
ctx.arc(that.p.x, that.p.y, r, 0, Branch.circle, true);
ctx.fill();
}, r * 60);
})(i);
}
}
}
var Branch = function (p, v, r, c, t) {
this.p = p || null;
this.v = v || null;
this.r = r || 0;
this.length = 0;
this.generation = 1;
this.tree = t || null;
this.color = c || 'rgba(255,255,255,1.0)';
this.register();
};
Branch.prototype = {
register: function () {
this.tree.addBranch(this);
},
draw: function () {
var ctx = this.tree.ctx;
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.moveTo(this.p.x, this.p.y);
ctx.arc(this.p.x, this.p.y, this.r, 0, Branch.circle, true);
ctx.fill();
},
modify: function () {
var angle = 0.2 - (0.2 / this.generation);
this.p.add(this.v);
this.length += this.v.length();
this.r *= 0.99;
this.v.rotate(Branch.random(-angle, angle)); //.mult(0.996);
if (this.r < 0.8 || this.generation > 10) {
this.tree.removeBranch(this);
var l = new Leaf(this.p, 10, this.color, this.tree.ctx);
l.render();
}
},
grow: function () {
this.draw();
this.modify();
this.fork();
},
fork: function () {
var p = this.length - Branch.random(90, 180); // + (this.generation * 10);
if (p > 0) {
var n = Math.round(Branch.random(1, 5));
this.tree.stat.fork += n - 1;
for (var i = 0; i < n; i++) {
Branch.clone(this);
}
this.tree.removeBranch(this);
}
}
};
Branch.circle = 2 * Math.PI;
Branch.random = function (min, max) {
return Math.random() * (max - min) + min;
};
Branch.clone = function (b) {
var r = new Branch(new Vector(b.p.x, b.p.y), new Vector(b.v.x, b.v.y), b.r, b.color, b.tree);
r.generation = b.generation + 1;
return r;
};
Branch.rgba = function (r, g, b, a) {
return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
};
Branch.randomrgba = function (min, max, a) {
return Branch.rgba(Math.round(Branch.random(min, max)), Math.round(Branch.random(min, max)), Math.round(Branch.random(
min, max)), a);
};
var Tree = function () {
var branches = [];
var timer;
this.stat = {
fork: 0,
length: 0
};
this.addBranch = function (b) {
branches.push(b);
};
this.removeBranch = function (b) {
for (var i = 0; i < branches.length; i++) {
if (branches[i] === b) {
branches.splice(i, 1);
return;
}
}
};
this.render = function (fn) {
var that = this;
timer = setInterval(function () {
fn.apply(that, arguments);
if (branches.length > 0) {
for (var i = 0; i < branches.length; i++) {
branches[i].grow();
}
} else {
clearInterval(timer);
}
}, 1000 / 30);
};
this.init = function (ctx) {
this.ctx = ctx;
};
this.abort = function () {
branches = [];
this.stat = {
fork: 0,
length: 0
}
};
};
var Fireworks = function () {
var self = this;
var rand = function (rMi, rMa) {
return ~~((Math.random() * (rMa - rMi + 1)) + rMi);
}
var hitTest = function (x1, y1, w1, h1, x2, y2, w2, h2) {
return !(x1 + w1 < x2 || x2 + w2 < x1 || y1 + h1 < y2 || y2 + h2 < y1);
};
window.requestAnimFrame = function () {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window
.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function (a) {
window.setTimeout(a, 1E3 / 60)
}
}();
self.init = function () {
self.canvas = document.createElement('canvas');
$(self.canvas).addClass('fireworks');
self.canvas.width = self.cw = $(window).innerWidth();
self.canvas.height = self.ch = $(window).innerHeight();
self.particles = [];
self.partCount = 150;
self.fireworks = [];
self.mx = self.cw / 2;
self.my = self.ch / 2;
self.currentHue = 30;
self.partSpeed = 5;
self.partSpeedVariance = 10;
self.partWind = 50;
self.partFriction = 5;
self.partGravity = 1;
self.hueMin = 0;
self.hueMax = 360;
self.fworkSpeed = 4;
self.fworkAccel = 10;
self.hueVariance = 30;
self.flickerDensity = 25;
self.showShockwave = true;
self.showTarget = false;
self.clearAlpha = 25;
$(document.body).append(self.canvas);
self.ctx = self.canvas.getContext('2d');
self.ctx.lineCap = 'round';
self.ctx.lineJoin = 'round';
self.lineWidth = 1;
self.bindEvents();
self.canvasLoop();
self.canvas.onselectstart = function () {
return false;
};
};
self.createParticles = function (x, y, hue) {
var countdown = self.partCount;
while (countdown--) {
var newParticle = {
x: x,
y: y,
coordLast: [{
x: x,
y: y
},
{
x: x,
y: y
},
{
x: x,
y: y
}
],
angle: rand(0, 360),
speed: rand(((self.partSpeed - self.partSpeedVariance) <= 0) ? 1 : self
.partSpeed - self.partSpeedVariance, (self.partSpeed + self.partSpeedVariance)
),
friction: 1 - self.partFriction / 100,
gravity: self.partGravity / 2,
hue: rand(hue - self.hueVariance, hue + self.hueVariance),
brightness: rand(50, 80),
alpha: rand(40, 100) / 100,
decay: rand(10, 50) / 1000,
wind: (rand(0, self.partWind) - (self.partWind / 2)) / 25,
lineWidth: self.lineWidth
};
self.particles.push(newParticle);
}
};
self.updateParticles = function () {
var i = self.particles.length;
while (i--) {
var p = self.particles[i];
var radians = p.angle * Math.PI / 180;
var vx = Math.cos(radians) * p.speed;
var vy = Math.sin(radians) * p.speed;
p.speed *= p.friction;
p.coordLast[2].x = p.coordLast[1].x;
p.coordLast[2].y = p.coordLast[1].y;
p.coordLast[1].x = p.coordLast[0].x;
p.coordLast[1].y = p.coordLast[0].y;
p.coordLast[0].x = p.x;
p.coordLast[0].y = p.y;
p.x += vx;
p.y += vy;
p.y += p.gravity;
p.angle += p.wind;
p.alpha -= p.decay;
if (!hitTest(0, 0, self.cw, self.ch, p.x - p.radius, p.y - p.radius, p.radius *
2, p.radius * 2) || p.alpha < .05) {
self.particles.splice(i, 1);
}
};
};
self.drawParticles = function () {
var i = self.particles.length;
while (i--) {
var p = self.particles[i];
var coordRand = (rand(1, 3) - 1);
self.ctx.beginPath();
self.ctx.moveTo(Math.round(p.coordLast[coordRand].x), Math.round(p.coordLast[
coordRand].y));
self.ctx.lineTo(Math.round(p.x), Math.round(p.y));
self.ctx.closePath();
self.ctx.strokeStyle = 'hsla(' + p.hue + ', 100%, ' + p.brightness + '%, ' + p.alpha +
')';
self.ctx.stroke();
if (self.flickerDensity > 0) {
var inverseDensity = 50 - self.flickerDensity;
if (rand(0, inverseDensity) === inverseDensity) {
self.ctx.beginPath();
self.ctx.arc(Math.round(p.x), Math.round(p.y), rand(p.lineWidth, p.lineWidth +
3) / 2, 0, Math.PI * 2, false)
self.ctx.closePath();
var randAlpha = rand(50, 100) / 100;
self.ctx.fillStyle = 'hsla(' + p.hue + ', 100%, ' + p.brightness +
'%, ' + randAlpha + ')';
self.ctx.fill();
}
}
};
};
self.createFireworks = function (startX, startY, targetX, targetY) {
var newFirework = {
x: startX,
y: startY,
startX: startX,
startY: startY,
hitX: false,
hitY: false,
coordLast: [{
x: startX,
y: startY
},
{
x: startX,
y: startY
},
{
x: startX,
y: startY
}
],
targetX: targetX,
targetY: targetY,
speed: self.fworkSpeed,
angle: Math.atan2(targetY - startY, targetX - startX),
shockwaveAngle: Math.atan2(targetY - startY, targetX - startX) + (90 * (
Math.PI / 180)),
acceleration: self.fworkAccel / 100,
hue: self.currentHue,
brightness: rand(50, 80),
alpha: rand(50, 100) / 100,
lineWidth: self.lineWidth
};
self.fireworks.push(newFirework);
};
self.updateFireworks = function () {
var i = self.fireworks.length;
while (i--) {
var f = self.fireworks[i];
self.ctx.lineWidth = f.lineWidth;
vx = Math.cos(f.angle) * f.speed,
vy = Math.sin(f.angle) * f.speed;
f.speed *= 1 + f.acceleration;
f.coordLast[2].x = f.coordLast[1].x;
f.coordLast[2].y = f.coordLast[1].y;
f.coordLast[1].x = f.coordLast[0].x;
f.coordLast[1].y = f.coordLast[0].y;
f.coordLast[0].x = f.x;
f.coordLast[0].y = f.y;
if (f.startX >= f.targetX) {
if (f.x + vx <= f.targetX) {
f.x = f.targetX;
f.hitX = true;
} else {
f.x += vx;
}
} else {
if (f.x + vx >= f.targetX) {
f.x = f.targetX;
f.hitX = true;
} else {
f.x += vx;
}
}
if (f.startY >= f.targetY) {
if (f.y + vy <= f.targetY) {
f.y = f.targetY;
f.hitY = true;
} else {
f.y += vy;
}
} else {
if (f.y + vy >= f.targetY) {
f.y = f.targetY;
f.hitY = true;
} else {
f.y += vy;
}
}
if (f.hitX && f.hitY) {
self.createParticles(f.targetX, f.targetY, f.hue);
self.fireworks.splice(i, 1);
}
};
};
self.drawFireworks = function () {
var i = self.fireworks.length;
self.ctx.globalCompositeOperation = 'lighter';
while (i--) {
var f = self.fireworks[i];
self.ctx.lineWidth = f.lineWidth;
var coordRand = (rand(1, 3) - 1);
self.ctx.beginPath();
self.ctx.moveTo(Math.round(f.coordLast[coordRand].x), Math.round(f.coordLast[
coordRand].y));
self.ctx.lineTo(Math.round(f.x), Math.round(f.y));
self.ctx.closePath();
self.ctx.strokeStyle = 'hsla(' + f.hue + ', 100%, ' + f.brightness + '%, ' + f.alpha +
')';
self.ctx.stroke();
if (self.showTarget) {
self.ctx.save();
self.ctx.beginPath();
self.ctx.arc(Math.round(f.targetX), Math.round(f.targetY), rand(1, 8), 0,
Math.PI * 2, false)
self.ctx.closePath();
self.ctx.lineWidth = 1;
self.ctx.stroke();
self.ctx.restore();
}
if (self.showShockwave) {
self.ctx.save();
self.ctx.translate(Math.round(f.x), Math.round(f.y));
self.ctx.rotate(f.shockwaveAngle);
self.ctx.beginPath();
self.ctx.arc(0, 0, 1 * (f.speed / 5), 0, Math.PI, true);
self.ctx.strokeStyle = 'hsla(' + f.hue + ', 100%, ' + f.brightness + '%, ' +
rand(25, 60) / 100 + ')';
self.ctx.lineWidth = f.lineWidth;
self.ctx.stroke();
self.ctx.restore();
}
};
};
self.bindEvents = function () {
$(window).on('resize', function () {
clearTimeout(self.timeout);
self.timeout = setTimeout(function () {
self.canvas.width = self.cw = $(window).innerWidth();
self.canvas.height = self.ch = $(window).innerHeight();
self.ctx.lineCap = 'round';
self.ctx.lineJoin = 'round';
}, 100);
});
$(self.canvas).on('mousedown', function (e) {
self.mx = e.pageX - self.canvas.offsetLeft;
self.my = e.pageY - self.canvas.offsetTop;
self.currentHue = rand(self.hueMin, self.hueMax);
self.createFireworks(self.cw / 2, self.ch, self.mx, self.my);
$(self.canvas).on('mousemove.fireworks', function (e) {
self.mx = e.pageX - self.canvas.offsetLeft;
self.my = e.pageY - self.canvas.offsetTop;
self.currentHue = rand(self.hueMin, self.hueMax);
self.createFireworks(self.cw / 2, self.ch, self.mx, self.my);
});
});
$(self.canvas).on('mouseup', function (e) {
$(self.canvas).off('mousemove.fireworks');
});
}
self.clear = function () {
self.particles = [];
self.fireworks = [];
self.ctx.clearRect(0, 0, self.cw, self.ch);
};
self.canvasLoop = function () {
requestAnimFrame(self.canvasLoop, self.canvas);
self.ctx.globalCompositeOperation = 'destination-out';
self.ctx.fillStyle = 'rgba(0,0,0,' + self.clearAlpha / 100 + ')';
self.ctx.fillRect(0, 0, self.cw, self.ch);
self.updateFireworks();
self.updateParticles();
self.drawFireworks();
self.drawParticles();
};
self.init();
}
// 展示图片
function showImg() {
if (imgName.length > 0) {
var name = imgName.shift();
$(".show-content img").eq(0).attr('src', './img/1/' + name + '.png');
$(".show-content span").eq(0).text(name);
$(".show-content").addClass('show-animation');
setTimeout(function () {
$(".show-content").removeClass('show-animation');
}, 5000);
setTimeout(function () {
showImg()
}, 5500);
} else {
//放烟花
showFireworks();
// 伸展背景
console.log(fillStyle);
stretchBackground();
}
}
// 放烟花
function showFireworks() {
var fworks = new Fireworks();
for (var i = 0; i < 50; ++i) {
var mx = Branch.random(0, window.innerWidth);
var my = Branch.random(0, 200);
fworks.createFireworks(fworks.cw / 2, fworks.ch, mx, my);
}
setInterval(function () {
var count = Branch.random(0, 8);
for (var i = 0; i < count; ++i) {
var mx = Branch.random(0, window.innerWidth);
var my = Branch.random(0, 200);
fworks.createFireworks(fworks.cw / 2, fworks.ch, mx, my);
}
}, 1000)
}
function drawBackground(scale) {
ctx.fillStyle = fillStyle;
ctx.beginPath();
ctx.moveTo(0, canvas.height);
ctx.lineTo(400 * scale, canvas.height - 130 * scale);
ctx.lineTo(canvas.width - 450 * scale, canvas.height - 130 * scale);
ctx.lineTo(canvas.width, canvas.height);
ctx.lineTo(0, canvas.height)
ctx.closePath();
ctx.fill();
}
function drawTree() {
ctx.globalCompositeOperation = "lighter";
var center_x = canvas.width / 2;
var stretch_factor = 600 / canvas.height;
var y_speed = 2 / stretch_factor;
var t = new Tree();
t.init(ctx);
for (var i = 0; i < 3; i++) {
new Branch(new Vector(center_x, canvas.height - 200), new Vector(Math.random(0.5, 0.5), -y_speed), 20 / stretch_factor,
Branch.randomrgba(0, 255, 0.2), t);
}
t.render(function () {
console.log(this.stat.fork)
});
setTimeout(function () {
$('.wrap').css({
opacity: 1
})
}, 8000);
}
function stretchBackground() {
var scale = 1;
var stop = setInterval(function () {
scale += 0.005;
drawBackground(scale);
if (scale >= 1.40) {
clearInterval(stop);
drawTree();
}
}, 80);
}
function getEcharts() {
// Step:3 为模块加载器配置echarts的路径,从当前页面链接到echarts.js,定义所需图表路径
require.config({
paths: {
echarts: './js'
}
});
// Step:4 动态加载echarts然后在回调函数中开始使用,注意保持按需加载结构定义图表路径
require(
[
'echarts',
'echarts/chart/map'
],
function (ec) {
// --- 地图 ---
var myChart2 = ec.init(document.getElementById('mainMap'));
myChart2.setOption({
dataRange: {
min: 0,
max: 100,
show: false,
color: ['#ff3333', 'orange', 'yellow', 'lime', 'aqua'],
textStyle: {
color: '#fff',
}
},
animationDuration: 25000,
series: [{
name: '全国',
type: 'map',
roam: false,
hoverable: false,
mapType: 'china',
itemStyle: {
normal: {
borderColor: 'rgba(100,149,237,1)',
borderWidth: 0.5,
areaStyle: {
color: '#1b1b1b'
}
}
},
data: [],
markLine: {
smooth: true,
symbol: ['none', 'circle'],
symbolSize: 1,
itemStyle: {
normal: {
color: '#fff',
borderWidth: 1,
borderColor: 'rgba(30,144,255,0.5)'
}
},
data: [],
},
geoCoord: {
'上海': [121.4648, 31.2891],
'东莞': [113.8953, 22.901],
'东营': [118.7073, 37.5513],
'中山': [113.4229, 22.478],
'临汾': [111.4783, 36.1615],
'临沂': [118.3118, 35.2936],
'丹东': [124.541, 40.4242],
'丽水': [119.5642, 28.1854],
'乌鲁木齐': [87.9236, 43.5883],
'佛山': [112.8955, 23.1097],
'保定': [115.0488, 39.0948],
'兰州': [103.5901, 36.3043],
'包头': [110.3467, 41.4899],
'北京': [116.4551, 40.2539],
'北海': [109.314, 21.6211],
'南京': [118.8062, 31.9208],
'南宁': [108.479, 23.1152],
'南昌': [116.0046, 28.6633],
'南通': [121.1023, 32.1625],
'厦门': [118.1689, 24.6478],
'台州': [121.1353, 28.6688],
'合肥': [117.29, 32.0581],
'呼和浩特': [111.4124, 40.4901],
'咸阳': [108.4131, 34.8706],
'哈尔滨': [127.9688, 45.368],
'唐山': [118.4766, 39.6826],
'嘉兴': [120.9155, 30.6354],
'大同': [113.7854, 39.8035],
'大连': [122.2229, 39.4409],
'天津': [117.4219, 39.4189],
'太原': [112.3352, 37.9413],
'威海': [121.9482, 37.1393],
'宁波': [121.5967, 29.6466],
'宝鸡': [107.1826, 34.3433],
'宿迁': [118.5535, 33.7775],
'常州': [119.4543, 31.5582],
'广州': [113.5107, 23.2196],
'廊坊': [116.521, 39.0509],
'延安': [109.1052, 36.4252],
'张家口': [115.1477, 40.8527],
'徐州': [117.5208, 34.3268],
'德州': [116.6858, 37.2107],
'惠州': [114.6204, 23.1647],
'成都': [103.9526, 30.7617],
'扬州': [119.4653, 32.8162],
'承德': [117.5757, 41.4075],
'拉萨': [91.1865, 30.1465],
'无锡': [120.3442, 31.5527],
'日照': [119.2786, 35.5023],
'昆明': [102.9199, 25.4663],
'杭州': [119.5313, 29.8773],
'枣庄': [117.323, 34.8926],
'柳州': [109.3799, 24.9774],
'株洲': [113.5327, 27.0319],
'武汉': [114.3896, 30.6628],
'汕头': [117.1692, 23.3405],
'江门': [112.6318, 22.1484],
'沈阳': [123.1238, 42.1216],
'沧州': [116.8286, 38.2104],
'河源': [114.917, 23.9722],
'泉州': [118.3228, 25.1147],
'泰安': [117.0264, 36.0516],
'泰州': [120.0586, 32.5525],
'济南': [117.1582, 36.8701],
'济宁': [116.8286, 35.3375],
'海口': [110.3893, 19.8516],
'淄博': [118.0371, 36.6064],
'淮安': [118.927, 33.4039],
'深圳': [114.5435, 22.5439],
'清远': [112.9175, 24.3292],
'温州': [120.498, 27.8119],
'渭南': [109.7864, 35.0299],
'湖州': [119.8608, 30.7782],
'湘潭': [112.5439, 27.7075],
'滨州': [117.8174, 37.4963],
'潍坊': [119.0918, 36.524],
'烟台': [120.7397, 37.5128],
'玉溪': [101.9312, 23.8898],
'珠海': [113.7305, 22.1155],
'盐城': [120.2234, 33.5577],
'盘锦': [121.9482, 41.0449],
'石家庄': [114.4995, 38.1006],
'福州': [119.4543, 25.9222],
'秦皇岛': [119.2126, 40.0232],
'绍兴': [120.564, 29.7565],
'聊城': [115.9167, 36.4032],
'肇庆': [112.1265, 23.5822],
'舟山': [122.2559, 30.2234],
'苏州': [120.6519, 31.3989],
'莱芜': [117.6526, 36.2714],
'菏泽': [115.6201, 35.2057],
'营口': [122.4316, 40.4297],
'葫芦岛': [120.1575, 40.578],
'衡水': [115.8838, 37.7161],
'衢州': [118.6853, 28.8666],
'西宁': [101.4038, 36.8207],
'西安': [109.1162, 34.2004],
'贵阳': [106.6992, 26.7682],
'连云港': [119.1248, 34.552],
'邢台': [114.8071, 37.2821],
'邯郸': [114.4775, 36.535],
'郑州': [113.4668, 34.6234],
'鄂尔多斯': [108.9734, 39.2487],
'重庆': [107.7539, 30.1904],
'金华': [120.0037, 29.1028],
'铜川': [109.0393, 35.1947],
'银川': [106.3586, 38.1775],
'镇江': [119.4763, 31.9702],
'长春': [125.8154, 44.2584],
'长沙': [113.0823, 28.2568],
'长治': [112.8625, 36.4746],
'阳泉': [113.4778, 38.0951],
'青岛': [120.4651, 36.3373],
'韶关': [113.7964, 24.7028]
},
markPoint: {
symbol: 'emptyCircle',
symbolSize: function (v) {
return 10 + v / 10
},
effect: {
show: true,
shadowBlur: 0
},
itemStyle: {
normal: {
label: {
show: false
}
},
emphasis: {
label: {
position: 'top'
}
}
},
data: [{
name: '乌鲁木齐',
value: 100
}, {
name: '淄博',
value: 95
},
{
name: '广州',
value: 90
},
{
name: '大连',
value: 80
},
{
name: '南宁',
value: 70
},
{
name: '南昌',
value: 60
},
{
name: '拉萨',
value: 50
},
{
name: '长春',
value: 40
},
{
name: '包头',
value: 30
},
{
name: '铜川',
value: 20
},
{
name: '常州',
value: 10
}
]
}
},
{
name: '北京 Top10',
type: 'map',
mapType: 'china',
data: [],
markLine: {
smooth: true,
effect: {
show: true,
scaleSize: 1,
period: 30,
color: '#fff',
shadowBlur: 10
},
itemStyle: {
normal: {
label: {
show: false
},
borderWidth: 1,
lineStyle: {
type: 'solid',
shadowBlur: 10
}
}
},
data: [
[{
name: '乌鲁木齐'
}, {
name: '广州',
value: 100
}],
[{
name: '淄博'
}, {
name: '广州',
value: 95
}],
[{
name: '大连'
}, {
name: '广州',
value: 80
}],
[{
name: '南宁'
}, {
name: '广州',
value: 70
}],
[{
name: '南昌'
}, {
name: '广州',
value: 60
}],
[{
name: '拉萨'
}, {
name: '广州',
value: 50
}],
[{
name: '长春'
}, {
name: '广州',
value: 40
}],
[{
name: '包头'
}, {
name: '广州',
value: 30
}],
[{
name: '铜川'
}, {
name: '广州',
value: 20
}],
[{
name: '常州'
}, {
name: '广州',
value: 10
}]
]
},
markPoint: {
symbol: 'emptyCircle',
symbolSize: function (v) {
return 0.1
},
effect: {
show: false,
shadowBlur: 0
},
itemStyle: {
normal: {
label: {
show: true,
position: 'top',
textStyle: {
fontSize: 14
}
}
},
emphasis: {
label: {
show: false
}
}
},
data: [{
name: '乌鲁木齐',
value: 100
}, {
name: '淄博',
value: 95
},
{
name: '广州',
value: 90
},
{
name: '大连',
value: 80
},
{
name: '南宁',
value: 70
},
{
name: '南昌',
value: 60
},
{
name: '拉萨',
value: 50
},
{
name: '长春',
value: 40
},
{
name: '包头',
value: 30
},
{
name: '铜川',
value: 20
},
{
name: '常州',
value: 10
}
]
}
}
]
});
});
}
var canvas;
var ctx;
var fillStyle = randomBackground();
/**
* 地图展示模块
*/
function mapInit() {
getEcharts();
setTimeout(function () {
$('#mapBlock').addClass('mapRotate')
$('body').addClass('changeBackground').css({
background: 'url("./img/bg2.jpg") no-repeat',
backgroundSize: 'cover'
});
setTimeout(function () {
$('#mapBlock').remove();
$('.content').css({
display: 'block'
});
var $window = $(window);
canvas = $('#canvas')[0];
canvas.width = $window.width();
canvas.height = $window.height();
ctx = canvas.getContext("2d");
drawBackground(1);
showImg();
changeCouleur();
}, 2000)
}, 10000)
}
|
794c2336e4f86ddbc91f89b1b58272185a3e979b
|
[
"JavaScript"
] | 1
|
JavaScript
|
winixt/bac-joker.github.io
|
e3d0c626bce845fcb51d1a3de6081a8d34708e36
|
8207ea58a98b51e0045c0c00d9888d21dedfdfcc
|
refs/heads/master
|
<file_sep>//Pong
;(function(){
var pong = document.getElementById('pong');
if(pong && pong.getContext('2d')){
var c = pong.getContext('2d');
//Configuration
c.fillStyle = c.strokeStyle = '#FFF';
c.textAlign ='center';
c.textBaseline = 'middle';
var cfg = {
borderWidth : 5,
widthLines : 10,
padHeight : 80,
ballVelocity : 3,
padMaxVelocity : 5,
padAcel : 0.4,
padRes : 0.21,
middle : pong.width/2,
btnFont : 18,
btnHeight : 40,
humanVsPC : true,
fontSize : function(n){
c.font = n + 'px sans-serif'
},
dificult : 0.3,
ia_y : pong.height/2
},
limit = {
top : cfg.borderWidth + cfg.widthLines,
bottom : pong.height - cfg.borderWidth - 2*cfg.widthLines,
left : cfg.borderWidth + cfg.widthLines,
right : pong.width - cfg.borderWidth - 2*cfg.widthLines
},
//Screens
currentScreen = 'start', //start,config,game,pause,end
//Sprites
lineTop = {
x : cfg.borderWidth + cfg.widthLines,
y : cfg.borderWidth,
w : pong.width - 2*(cfg.widthLines+cfg.borderWidth),
h : cfg.widthLines
},
lineBottom = {
x : cfg.borderWidth + cfg.widthLines,
y : pong.height - cfg.borderWidth - cfg.widthLines,
w : pong.width - 2*(cfg.widthLines+cfg.borderWidth),
h : cfg.widthLines
},
lineMiddle = {
x : cfg.middle - 2,
yInit : 2*cfg.borderWidth+cfg.widthLines,
y : 2*cfg.borderWidth+cfg.widthLines,
w : 4,
h : cfg.widthLines,
limitY : pong.height - 2*cfg.borderWidth-cfg.widthLines
},
padA = {
score : 0,
scoreX : cfg.middle -40,
x : cfg.borderWidth,
y : (pong.height - cfg.padHeight)/2,
w : cfg.widthLines,
h : cfg.padHeight,
dir : 0,
vel : 0
},
padB = {
score : 0,
scoreX : cfg.middle +40,
x : pong.width - cfg.borderWidth - cfg.widthLines,
y : (pong.height - cfg.padHeight)/2,
w : cfg.widthLines,
h : cfg.padHeight,
dir : 0,
vel : 0
},
ball = {
x : padA.x+ padA.w + 5,
y : (pong.height - cfg.padHeight)/2,
w : cfg.widthLines,
h : cfg.widthLines,
dirX : 1,
dirY : -1,
dir : 0,
vel : 0
},
bckMov = {
lTop : lineTop,
lBottom : lineBottom,
lLeft : {
x : cfg.borderWidth,
y : cfg.borderWidth,
w : cfg.widthLines,
h : pong.height - 2*cfg.borderWidth
},
lRight : {
x : limit.right + cfg.widthLines,
y : cfg.borderWidth,
w : cfg.widthLines,
h : pong.height - 2*cfg.borderWidth
},
ball : {
x: cfg.middle,
y: pong.height/2,
w : cfg.widthLines,
h : cfg.widthLines,
dirX : 1,
dirY : -1
},
color : '#555',
draw : function(){
if(currentScreen != 'game'){
if(this.ball.x <= limit.left || this.ball.x >= limit.right) this.ball.dirX *= -1;
if(this.ball.y <= limit.top || this.ball.y >= limit.bottom) this.ball.dirY *= -1;
this.ball.x += cfg.ballVelocity*this.ball.dirX;
this.ball.y += cfg.ballVelocity*this.ball.dirY;
c.save();
c.fillStyle = this.color;
drawLine(this.lTop);
drawLine(this.lBottom);
drawLine(this.lLeft);
drawLine(this.lRight);
drawLine(this.ball);
c.restore();
}
}
}
//Buttons
btnPlay = {
x : cfg.middle - 60,
y : 340,
w : 120,
h : cfg.btnHeight,
text : 'play'
},
btnNewGame = {
x : cfg.middle - 60,
y : 250,
w : 120,
h : cfg.btnHeight,
text : 'new game'
},
btnContinue = {
x : cfg.middle - 60,
y : 310,
w : 120,
h : cfg.btnHeight,
text : 'continue'
},
radiobuttonHvPC = {
x : cfg.middle - 70,
y : 180,
w : 140,
h : cfg.btnHeight,
text : 'human vs. pc'
},
radiobuttonHvH = {
x : cfg.middle - 70,
y : 220,
w : 140,
h : cfg.btnHeight,
text : 'human vs. human'
},
//Actions
ia = function(){
if(cfg.humanVsPC){
if(ball.dirX == -1 && ball.x < (pong.width*cfg.dificult)){
cfg.ia_y = ball.y;
var dirY = ball.dirY;
for(var x = ball.x;x > limit.left;x -= cfg.ballVelocity){
if(cfg.ia_y <= limit.top || cfg.ia_y >= limit.bottom){
dirY *= -1;
}
cfg.ia_y += cfg.ballVelocity*dirY;
}
};
var difY = cfg.ia_y - (padA.y + cfg.padHeight/2),
absDifY = Math.abs(difY);
if(absDifY > (cfg.padHeight/2)){
padA.dir = difY/absDifY;
}else{
padA.dir = 0;
}
};
},
start = function(){
currentScreen = 'config';
},
play = function(){
padA.score = padB.score = 0;
currentScreen = 'game';
padA.y = padB.y = (pong.height - cfg.padHeight)/2;
ball.y = (pong.height - cfg.widthLines)/2;
},
padMoving = function(pad){
if(Math.abs(pad.vel)<=cfg.padMaxVelocity){
pad.vel += pad.dir*cfg.padAcel;
}
if(pad.vel<0){pad.vel += cfg.padRes};
if(pad.vel>0){pad.vel -= cfg.padRes};
pad.y += pad.vel;
if(pad.y < cfg.borderWidth) pad.y = cfg.borderWidth;
if(pad.y > (limit.bottom+2*cfg.widthLines-cfg.padHeight)) pad.y = limit.bottom+2*cfg.widthLines-cfg.padHeight;
},
moving = function(){
if(ball.x <= limit.left){
ball.dirX *= -1;
if(padA.dir!=0)ball.dirY *= (padA.dir*ball.dirY);
if(ball.y <= padA.y || ball.y >= (padA.y+cfg.padHeight)){
ball.x = cfg.middle;
padB.score++;
}
}
if(ball.x >= limit.right){
ball.dirX *= -1;
if(padB.dir!=0)ball.dirY *= (padB.dir*ball.dirY);
if(ball.y <= padB.y || ball.y >= (padB.y+cfg.padHeight)){
ball.x = cfg.middle;
padA.score++;
}
}
if(ball.y <= limit.top || ball.y >= limit.bottom){
ball.dirY *= -1;
}
ball.x += cfg.ballVelocity*ball.dirX;
ball.y += cfg.ballVelocity*ball.dirY;
ia();
//Pads
padMoving(padA);
padMoving(padB);
},
//Draw functions
drawLine = function(obj){
c.beginPath();
c.moveTo(obj.x,obj.y);
c.lineTo(obj.x+obj.w,obj.y);
c.lineTo(obj.x+obj.w,obj.y+obj.h);
c.lineTo(obj.x,obj.y+obj.h);
c.fill();
c.closePath();
},
drawButton = function(obj){
c.beginPath();
c.moveTo(obj.x,obj.y);
c.lineTo(obj.x+obj.w,obj.y);
c.lineTo(obj.x+obj.w,obj.y+obj.h);
c.lineTo(obj.x,obj.y+obj.h);
c.lineTo(obj.x,obj.y);
c.stroke();
c.closePath();
cfg.fontSize(cfg.btnFont);
c.fillText (obj.text, obj.x+obj.w/2, obj.y + obj.h/2);
},
drawRadio = function(obj,select){
c.save();
c.textAlign = 'left';
c.beginPath();
c.arc(obj.x, obj.y+cfg.btnHeight/2, 10, 0, 2*Math.PI, false);
c.stroke();
c.closePath();
if(select){
c.beginPath();
c.arc(obj.x, obj.y+cfg.btnHeight/2, 6, 0, 2*Math.PI, false);
c.fill();
c.closePath();
}
cfg.fontSize(cfg.btnFont);
c.fillText (obj.text, obj.x+20, obj.y + obj.h/2);
c.restore();
},
drawStage = function(){
//Clear all
c.clearRect(0,0,pong.width,pong.height);
bckMov.draw();
//Screens
switch(currentScreen){
case 'start':
cfg.fontSize(70);
c.fillText ('Pong', cfg.middle, 150);
c.save();
c.fillStyle = '#999';
cfg.fontSize(12);
c.fillText ('A simple HTML5 canvas app based in the ancient Pong game.', cfg.middle, 230);
c.fillText ('Copyright 2012 <NAME>.', cfg.middle, 450);
c.restore();
drawButton(btnNewGame);
break;
case 'config':
cfg.fontSize(50);
c.fillText ('New Game', cfg.middle, 130);
drawRadio(radiobuttonHvPC,cfg.humanVsPC);
drawRadio(radiobuttonHvH,!cfg.humanVsPC);
c.save();
c.fillStyle = '#999';
cfg.fontSize(12);
c.fillText ('- To pause the game, press SPACEBAR key.', cfg.middle, 280);
c.fillText ('- Press UP and DOWN key arrows to move the Left Pad up and down.', cfg.middle, 295);
if(!cfg.humanVsPC){
c.fillText ('- Press Q and A key to move the Right Pad up and down.', cfg.middle, 310);
}
c.restore();
drawButton(btnPlay);
break;
case 'game':
drawLine(lineTop);
drawLine(lineBottom);
//Scores
cfg.fontSize(50);
c.fillText (padA.score, padA.scoreX, 80);
c.fillText (padB.score, padB.scoreX, 80);
//Middle line
for(lineMiddle.y = lineMiddle.yInit;lineMiddle.y<=lineMiddle.limitY;lineMiddle.y+=(2*cfg.widthLines)){
drawLine(lineMiddle);
}
moving();
//Pads
drawLine(padA);
drawLine(padB);
//Ball
drawLine(ball);
if(padA.score >= 7 || padB.score >= 7){
currentScreen = 'end';
}
break;
case 'pause':
cfg.fontSize(50);
c.fillText ('Pause', cfg.middle, 130);
drawButton(btnContinue);
drawButton(btnNewGame);
break;
case 'end':
cfg.fontSize(50);
c.fillText ('Game Over', cfg.middle, 130);
var messToYou = 'You win ';
if(padA.score > padB.score && cfg.humanVsPC){
messToYou = 'You lose ';
}
cfg.fontSize(30);
c.fillText (messToYou+padA.score+' - '+padB.score, cfg.middle, 200);
drawButton(btnNewGame);
break;
};
},
drawTimer = setInterval(function(){
drawStage();
},20),
//Events
on = function(elem,eventType, eventHandler) {
if (elem.addEventListener) {
elem.addEventListener(eventType, eventHandler,false);
} else if (elem.attachEvent) {
eventType = "on" + eventType;
elem.attachEvent(eventType, eventHandler);
} else {
elem["on" + eventType] = eventHandler;
}
},
accButton = function(ev,obj,callback){
var mouseX = ev.clientX-pong.offsetLeft,
mouseY = ev.clientY-pong.offsetTop;
if(mouseX > obj.x && mouseX < obj.x+obj.w && mouseY > obj.y && mouseY < obj.y+obj.h){
callback();
};
};
on(pong,'click',function(ev){
//Screens
switch(currentScreen){
case 'start':
accButton(ev,btnNewGame,start);
break;
case 'config':
accButton(ev,radiobuttonHvPC,function(){
cfg.humanVsPC = true;
});
accButton(ev,radiobuttonHvH,function(){
cfg.humanVsPC = false;
});
accButton(ev,btnPlay,play);
break;
case 'game':
//
break;
case 'pause':
accButton(ev,btnNewGame,start);
accButton(ev,btnContinue,function(){
currentScreen = 'game';
});
break;
case 'end':
accButton(ev,btnNewGame,start);
break;
};
});
on(document,'keydown',function(ev){
ev = ev ? ev : window.event;
var key = ev.charCode ? ev.charCode : ev.keyCode;
log(key)
//Screens
switch(currentScreen){
case 'start':
//
break;
case 'config':
//
break;
case 'game':
switch(key){
case 38:
//arriba
padB.dir = -1;
break;
case 40:
//abajo
padB.dir = 1;
break;
case 81:
//arriba
if(!cfg.humanVsPC) padA.dir = -1;
break;
case 65:
//abajo
if(!cfg.humanVsPC) padA.dir = 1;
break;
case 32:
currentScreen = 'pause';
break;
};
break;
case 'pause':
//
break;
case 'end':
//
break;
};
});
on(document,'keyup',function(ev){
ev = ev ? ev : window.event;
var key = ev.charCode ? ev.charCode : ev.keyCode;
//Screens
switch(currentScreen){
case 'start':
//
break;
case 'config':
//
break;
case 'game':
switch(key){
case 38:
//arriba
padB.dir = 0;
break;
case 40:
//abajo
padB.dir = 0;
break;
case 81:
//arriba
if(!cfg.humanVsPC) padA.dir = 0;
break;
case 65:
//abajo
if(!cfg.humanVsPC) padA.dir = 0;
break;
};
break;
case 'pause':
//
break;
case 'end':
//
break;
};
});
}
})();
|
858f7a2f7519841ebaf82434e2545b19b883cfe8
|
[
"JavaScript"
] | 1
|
JavaScript
|
pablocazorla/Pong
|
f05e6c27dd26ae42f58d1d793b55f24a43f4fccb
|
1f983d6b9f51f750c463a8952c97d10b0d8526fb
|
refs/heads/master
|
<file_sep># Balsa-Boilerplate
<file_sep>// Import modules
// ---
import { src, dest, watch, parallel, series } from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import browserSync from 'browser-sync';
import del from 'del';
// Gulp variables
// ---
const $ = gulpLoadPlugins();
const bs = browserSync.create();
// Source and destination location
// ---
const dirs = {
src : './src',
dest: './dist'
};
// Sources location
// ---
const srcFiles = {
sass: `${dirs.src}/sass/**/*.sass`,
pug : `${dirs.src}/pug/**/*.pug`,
js : `${dirs.src}/js/**/*.js`
};
// PugJS options
// ---
const pugOpts = {
pretty: ' '
};
// SASS Task
// ---
export const buildSass = () =>
src([ srcFiles.sass, '!**/vendor/**' ])
.pipe($.sourcemaps.init())
.pipe($.sass.sync().on('error', $.sass.logError))
.pipe($.sourcemaps.write('.'))
.pipe(dest(`${dirs.dest}/css`))
.pipe($.filter('**/*.css'))
.pipe(bs.stream());
// PugJS Task
// ---
export const buildPug = () =>
src([ srcFiles.pug, '!**/(_)*.pug' ])
.pipe($.pug(pugOpts))
.pipe(dest(dirs.dest));
// JS Task
// ---
export const buildJs = () =>
src([ srcFiles.js, '!**/vendor/**', '!**/(_)*.js' ])
.pipe($.sourcemaps.init())
.pipe($.include())
.pipe($.sourcemaps.write('.'))
.pipe(dest(`${dirs.dest}/js`))
.pipe($.filter('**/*.js'))
.pipe(bs.stream());
// Serve and Watch Task
// ---
export const ServeAndWatch = () => {
bs.init({ server: dirs.dest });
watch(srcFiles.sass, buildSass);
watch(srcFiles.pug, buildPug);
watch(srcFiles.js, buildJs);
watch(`${dirs.dest}/*.html`).on('change', bs.reload);
};
// Clean Task
// ---
export const clean = () =>
del([ dirs.dest ]);
// Serve Task
// ---
export const serve = series(clean, parallel(buildPug, buildSass, buildJs), ServeAndWatch);
// Default Task
// ---
export default serve;
|
6b34987bf71cde1653c786189fe7941767556974
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Balsakup/Balsa-Boilerplate
|
2e6bcb15ec26553fd616826a85bef5abb6d577fa
|
b499017d0c24e35ca179f47498568b9824805e9d
|
refs/heads/master
|
<file_sep>
public class CalculateArea {
private static double rectangleAreaInMainMethod;
public static void main(String[] args)
{
double circleAreaInMainMethod = CalculateCircleArea(10);
System.out.println("Area of the circle is " + circleAreaInMainMethod);
double rectangleAreaInMainMethod = AreaRect (8,3);
System.out.println("Area of the rectangle is " + rectangleAreaInMainMethod);
}
// TODO Auto-generated method stub
public static double CalculateCircleArea(int radius)
{
//This method calculates the area of a circle
//Input: integer radius value
//Output: double area
double area = 3.14 * radius * radius;
return area;
}
public static double AreaRect(int width, int length){
double area= length * width;
return area;
}
}
|
80f1796d75fa06925495384b89832af57801ecda
|
[
"Java"
] | 1
|
Java
|
nationmurray59/YearUp
|
0de2407c4b35d774f290e15251cc35e64695c9f7
|
9c7c02da81d63ca909d52b7fbe39dee3caa1f8d6
|
refs/heads/master
|
<repo_name>b4ldr/puppet-jbtest<file_sep>/spec/spec_helper.rb
# frozen_string_literal: true
require 'puppetlabs_spec_helper/module_spec_helper'
# vim: syntax=ruby
<file_sep>/spec/classes/test_spec.rb
# frozen_string_literal: true
require 'spec_helper'
describe 'jbtest' do
# let(:params) { { host: '192.0.2.2', } }
let(:facts) { {} }
Puppet::Util::Log.level = :debug
Puppet::Util::Log.newdestination(:console)
context "on #test" do
describe 'check default config' do
it { is_expected.to compile.with_all_deps }
end
end
end
<file_sep>/Gemfile
source ENV['GEM_SOURCE'] || "https://rubygems.org"
group :test do
gem 'puppetlabs_spec_helper', '~> 2.2.0', :require => false
gem 'rspec-puppet', '~> 2.5', :require => false
end
if facterversion = ENV['FACTER_GEM_VERSION']
gem 'facter', facterversion.to_s, :require => false, :groups => [:test]
else
gem 'facter', :require => false, :groups => [:test]
end
ENV['PUPPET_VERSION'].nil? ? puppetversion = '~> 4.0' : puppetversion = ENV['PUPPET_VERSION'].to_s
gem 'puppet', puppetversion, :require => false, :groups => [:test]
# vim: syntax=ruby
<file_sep>/Rakefile
require 'puppetlabs_spec_helper/rake_tasks'
# vim: syntax=ruby
|
b690b597812d495bb1fb406ffeb86d1af3f51aff
|
[
"Ruby"
] | 4
|
Ruby
|
b4ldr/puppet-jbtest
|
e0bb1beba49b421fe99664ec1efaa7a1a2a1c623
|
8f1d2066054243be252f5bc32dc224340efe0bec
|
refs/heads/master
|
<repo_name>dptorri/explain_me_react_redux<file_sep>/src/store/index.js
import { createStore, combineReducers } from "redux"
import * as ducks from "./reducers"
const reducers = combineReducers(ducks)
const store = createStore(reducers)
export default store;<file_sep>/src/store/reducers/session.js
// Actions: what we can do to our statue
const LOGIN = "session/LOGIN"
const LOGOUT = "session/LOGOUT"
const DEFAULT_STATE = { isLoggedIn: false }
// Reducer
const sessionReducer = (state = DEFAULT_STATE, action = {}) => {
switch(action.type) {
case LOGIN:
return {
...state,
isLoggedIn: true
}
case LOGOUT:
return {
...state,
isLoggedIn: false
}
}
return state
}
export default sessionReducer;
// Action creators
export const loginUser = () => {
return { type: LOGIN }
}
export const logoutUser = () => {
return { type: LOGOUT }
}
<file_sep>/src/components/Root/LoginStatus/index.js
import LoginStatus from './LoginStatus'
export default LoginStatus
|
548eeeb08196079069826f07db9514b3a52fc56f
|
[
"JavaScript"
] | 3
|
JavaScript
|
dptorri/explain_me_react_redux
|
464b322fd1746c3e9cb96c04c6e6cb5f715965ef
|
34775533398ae256235e6d37ee55a459a5a47a76
|
refs/heads/master
|
<file_sep>import requests
import json
import os
from platforms.utils import replace_values
from errors import NetworkRequestFailed
class TelegramPlatform:
def __init__(self, event_data, api_token, chat_id):
self.event_data = event_data
self.api_token = api_token
self.chat_id = chat_id
self.load_message()
def load_message(self):
"""
Load the JSON Webhook template for Discord and prepend the fields
:return:
"""
message_raw = open('message-texts/message-telegram.txt').read()
message_raw = self.replace_values(message_raw, self.event_data)
self.sendMessage(message_raw)
def sendMessage(self, message_text):
"""
Send a Message to the Discord Webhook
:return:
"""
headers = {
'Content-Type': 'application/json',
}
url = f"https://api.telegram.org/bot{self.api_token}/sendMessage"
data = {
text: message_text,
chat_id: self.chat_id
}
response = requests.post(url, data=json.dumps(data), headers=headers)
if response.status_code == 200:
logging.info('Discord Channel has succesfully been notified!')
else:
logging.critical('The Network Request failed!')
raise NetworkRequestFailed(f"Network Request Failed. Error: {response.text}")
<file_sep># scheduler-bot
Notify different Messaging platforms about .ical events :)
<file_sep>def replace_values(message_raw, event_data):
return message_raw.replace('[EVENT TITLE]', event_data['subject']) \
.replace('[DESCRIPTION]', event_data['description']) \
.replace('[LOCATION]', event_data['location'])
<file_sep>import fire
from datetime import date
from apscheduler.schedulers.blocking import BlockingScheduler
from icalendar import Calendar, Event
import recurring_ical_events
from platforms.notifier import Notifier
from datetime import datetime, timedelta
import os
import logging
from errors import NetworkRequestFailed, MissingResource
#logging.basicConfig(filename='schedule_bot.log', level=logging.DEBUG)
class SchedulerBot:
def __init__(self, platform_data, minutes_before_event):
self.platform_data = platform_data
self.minutes_before_event = minutes_before_event
def parse_events(self, cal_resource):
"""
:param ical_resource:
:return:
"""
events = []
calendar = Calendar.from_ical(cal_resource)
logging.info('Found the following events!')
start_date = (2020,1,1)
end_date = (2021,1,1)
for event in recurring_ical_events.of(calendar).between(start_date, end_date):
if event.name == "VEVENT":
event_data = {
"subject": event["summary"].to_ical().decode('utf-8'),
"description": event["description"].to_ical().decode('utf-8'),
"start_date": event["dtstart"].dt,
"location": event["location"].to_ical().decode('utf-8')
}
logging.info(event_data)
#print(event_data)
events.append(event_data)
self.schedule_events(events)
def schedule_events(self, events):
jobs = []
notification_platform = Notifier(self.platform_data)
# Start the scheduler
scheduler = BlockingScheduler()
print('working')
for event in events:
job_date = event["start_date"] - timedelta(minutes=self.minutes_before_event)
job = scheduler.add_job(notification_platform.notify, 'date', run_date=job_date, args=[event])
jobs.append(job)
scheduler.start()
def startBot(platform="discord", calType="file", calResource = None, minutes_before_event=5,
discord_webhook_url=None, telegram_api_token = None, telegram_chat_id = None):
"""
Start the bot
:param platform: Current Option Discord
:param calType: Local File or Online. file / network
:param calResource: Link to the said file
:param minutes_before_event: How many minutes before an event should the bot notify. Default 5
:param discord_webhook_url: The Webhook where the bot should post
:param telegram_api_token: The API Token for the bot
:param telegram_chat_id: The Chat ID where the messages should be sent
"""
# Lower Text for easily parsing data
platform = platform.lower()
calType = calType.lower()
# Check if there's a resource we can parse
if calResource is None:
raise MissingResource("URL or File was empty!")
if platform == "discord":
if discord_webhook_url is None:
raise MissingAuthData("A Webhook URL for Discord was not found! Exiting.")
platform_data = {"platform": "discord", "webhook_url": discord_webhook_url}
elif platform == "telegram":
if telegram_api_token is None:
raise MissingAuthData("A Token for Telegram was not found! Exiting.")
if telegram_chat_id is None:
raise MissingAuthData("A Chat ID for Telegram was not found! Exiting.")
platform_data = {"platform": "telegram", "api_token": telegram_api_token, "chat_id": telegram_chat_id}
if calType == 'file':
logging.info('Opening Calendar file from File...')
file_content = open(calResource, 'rb')
elif calType == 'network':
logging.info('Opening Calendar file from Network...')
import requests
try:
cal = requests.get(calResource)
if cal.status_code != 200:
raise NetworkRequestFailed(f"Network request failed!")
file_content = cal.text
except:
raise NetworkRequestFailed(f"Network request failed!")
bot = SchedulerBot(platform_data, minutes_before_event)
bot.parse_events(file_content)
if __name__ == '__main__':
fire.Fire(startBot)<file_sep>#from discord import DiscordPlatform
from platforms.notifier import Notifier
from platforms.discord import DiscordPlatform
from platforms.utils import replace_values<file_sep>class NetworkRequestFailed(Exception):
"""
Executed when the network request fails
"""
pass
class MissingResource(Exception):
"""
Executed when the Resource was empty
"""
pass
class InvalidOption(Exception):
"""
Executed when the user provides an invalid option
"""
pass
class MissingAuthData(Exception):
"""
Executed when the user doesn't provide a webhook url for discord or API token for Telegram
"""
pass<file_sep>fire
apscheduler
requests
icalendar
recurring-ical-events<file_sep>import requests
import json
import os
import logging
from errors import NetworkRequestFailed
from platforms.utils import replace_values
class DiscordPlatform:
def __init__(self, event_data, webhook_url):
self.event_data = event_data
self.webhook_url = webhook_url
self.load_message()
def load_message(self):
"""
Load the JSON Webhook template for Discord and prepend the fields
:return:
"""
message_raw = open('message-texts/message-discord.json').read()
message_raw = replace_values(message_raw, self.event_data)
message_json = json.loads(message_raw)
self.sendMessage(message_json)
def sendMessage(self, message_json):
"""
Send a Message to the Discord Weebhook
:return:
"""
headers = {
'Content-Type': 'application/json',
}
webhook_url = self.webhook_url
response = requests.post(webhook_url, data=json.dumps(message_json), headers=headers)
if response.status_code == 200:
logging.info('Discord Channel has succesfully been notified!')
else:
logging.critical('The Network Request failed!')
raise NetworkRequestFailed(f"Network Request Failed. Error: {response.text}")
<file_sep>class Notifier:
def __init__(self, platform_data):
self.platform_data = platform_data
def notify(self, event_data):
if self.platform_data["platform"] == "discord":
from platforms.discord import DiscordPlatform
webhook_url = self.platform_data["webhook_url"]
DiscordPlatform(event_data, webhook_url)
if self.platform_data["platform"] == "telegram":
from platforms.telegram import TelegramPlatform
api_token = self.platform_data["api_token"]
chat_id = self.platform_data["chat_id"]
TelegramPlatform(event_data, api_token, chat_id)
|
e858c3696830e1eba289f2bb226701a91688a85f
|
[
"Markdown",
"Python",
"Text"
] | 9
|
Python
|
MatejMecka/scheduler-bot
|
64f5ca3ca4504f038bd5910cb0e2b94465668bff
|
7451e0b61c30507db1822dccd3eb11b69677d8e7
|
refs/heads/master
|
<repo_name>Eugenics/Kata<file_sep>/README.md
# Kata from CodeWars
<file_sep>/Classes/Kata.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace KataApp.Classes
{
class Kata
{
public static IEnumerable<T> UniqueInOrder<T>(IEnumerable<T> iterable)
{
List<T> retList = new List<T>();
List<T> inpList = iterable.ToList();
if (inpList.Count > 0)
{
int j = 0;
retList.Add(inpList[0]);
for (int i = 1; i < inpList.Count; i++)
{
object a1 = inpList[i];
object a2 = retList[j];
if (!a2.Equals(a1))
{
retList.Add(inpList[i]);
j++;
}
}
return retList;
}
else
return inpList;
}
public static double[] Tribonacci(double[] signature, int n)
{
// hackonacci me
// if n==0, then return an array of length 1, containing only a 0
if (n == 0)
return new double[1] { 0 };
else
{
double[] tribonacciArray = new double[n];
if (n <= 3)
for (int i = 0; i < n; i++)
{
tribonacciArray[i] = signature[i];
}
else
{
for (int i = 0; i < signature.Length; i++)
{
tribonacciArray[i] = signature[i];
}
for (int i = 3; i < tribonacciArray.Length; i++)
{
tribonacciArray[i] = tribonacciArray[i - 1] + tribonacciArray[i - 2] + tribonacciArray[i - 3];
}
}
return tribonacciArray;
}
}
public static int FindShort(string s)
{
/*List<string> sList = new List<string>();
foreach(string word in s.Split(' '))
{
sList.Add(word);
}
int minSize = sList[0].Length;
for (int i = 0; i < sList.Count; i++)
{
if (sList[i].Length < minSize)
minSize = sList[i].Length;
}
return minSize;*/
return s.Split(' ').Min(x => x.Length);
}
public static String Accum(string s)
{
string retString = "";
for (int i = 0; i < s.Length; i++)
{
for (int j = 0; j <= i; j++)
{
if (j == 0)
retString = retString + s[i].ToString().ToUpper();
else
retString = retString + s[i].ToString().ToLower();
}
if (i < s.Length - 1)
retString = retString + '-';
}
return retString;
}
public static long FindNextSquare(long num)
{
double numSQRT = Math.Sqrt(num);
if (numSQRT - Math.Floor(numSQRT) > 0.0)
return -1;
else
return (long)Math.Pow(numSQRT + 1.0, 2.0);
//return Sqrt(num) % 1 == 0 ? (long)Pow(Sqrt(num) + 1, 2) : -1;
}
public static string MakeComplement(string dna)
{
char[] dnaCHR = dna.ToCharArray();
for (int i = 0; i < dna.Length; i++)
{
if (dna[i] == 'A') dnaCHR[i] = 'T';
else
if (dna[i] == 'T') dnaCHR[i] = 'A';
else
if (dna[i] == 'C') dnaCHR[i] = 'G';
else
if (dna[i] == 'G') dnaCHR[i] = 'C';
}
string retStr = new String(dnaCHR);
return retStr;
//return String.Join("",
// from ch in dna
// select "AGCT"["TCGA".IndexOf(ch)]
// );
// private static Dictionary<char, char> _complements =
// new Dictionary<char, char>(){
// {'A','T'},
// {'T','A'},
// {'C','G'},
// {'G','C'},
// };
//public static string MakeComplement(string dna)
//{
// return dna.Aggregate("", (sum, acid) => sum + _complements[acid]);
//}
}
public static string CreatePhoneNumber(int[] numbers)
{
//int i = 0;
//string telNum = "(";
//foreach(int num in numbers)
//{
// telNum = telNum + num.ToString();
// switch(i)
// {
// case 2:
// telNum = telNum + ") ";
// break;
// case 5:
// telNum = telNum + "-";
// break;
// }
// i++;
//}
//return telNum;
return long.Parse(string.Concat(numbers)).ToString("(000) 000-0000");
}
public static int GetNumber(string str)
{
int maxSeq = 0;
int i = 0;
while (str.Length - i >= 5)
{
if (int.Parse(str.Substring(i, 5)) > maxSeq) maxSeq = int.Parse(str.Substring(i, 5));
i++;
}
return maxSeq;
}
public static int DigitalRoot(long n)
{
while (n > 9)
{
long tmp = 0;
char[] nChr = n.ToString().ToCharArray();
for (int i = 0; i < nChr.Length; i++)
{
tmp = tmp + (long)Char.GetNumericValue(nChr[i]);
}
n = tmp;
}
return (int)n;
}
public static int Persistence(long n)
{
int perCnt = 0;
while (n > 9)
{
long tmp = 1;
char[] nChr = n.ToString().ToCharArray();
for (int i = 0; i < nChr.Length; i++)
{
tmp = tmp * (long)Char.GetNumericValue(nChr[i]);
}
n = tmp;
perCnt++;
}
return perCnt;
}
public static string Encrypt(string text, int n)
{
if (text == null || n <= 0)
{
return text;
}
for (int i = 0; i < n; i++)
{
string str1 = "";
string str2 = "";
for (int j = 1; j < text.Length; j = j + 2)
{
str1 = str1 + text[j];
}
for (int j = 0; j < text.Length; j = j + 2)
{
str2 = str2 + text[j];
}
text = String.Concat(str1, str2);
}
return text;
}
public static string Decrypt(string encryptedText, int n)
{
if (encryptedText == null || n <= 0)
{
return encryptedText;
}
for (int i = 0; i < n; i++)
{
int str1Len = (int)Math.Floor((double)encryptedText.Length / 2.0);
string str1 = encryptedText.Substring(0, str1Len);
string str2 = encryptedText.Substring(str1Len, encryptedText.Length - str1Len);
encryptedText = "";
for (int j = 0; j < str1Len; j++)
{
encryptedText = encryptedText + str2[j] + str1[j];
if (j == str1Len - 1 && str1Len < str2.Length) // Add last symbol
{
encryptedText = encryptedText + str2[j + 1];
}
}
}
return encryptedText;
}
public static bool ValidParentheses(string input)
{
int leftCnt = 0;
int rightCnt = 0;
//foreach (Match m in Regex.Matches(input, "("))
//{
// leftCnt++;
//}
//if(input.Length - leftCnt != leftCnt)
// return false;
int i = 0;
while (i < input.Length)
{
int foundCnt = 0;
while (i < input.Length && input[i] != ')')
{
if (input[i] == '(')
{
leftCnt++;
foundCnt++;
}
i++;
}
if (leftCnt == 0 && i < input.Length) return false;
if (i < input.Length && input[i] == ')' && foundCnt == 0) return false;
foundCnt = 0;
while (i < input.Length && input[i] != '(')
{
if (input[i] == ')')
{
rightCnt++;
foundCnt++;
}
i++;
}
if (i < input.Length && input[i] == '(' && foundCnt == 0) return false;
}
if (leftCnt == rightCnt) return true;
else return false;
}
public static void GetLenght()
{
int[,] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int s = a.Length;
Console.WriteLine(s);
}
}
public class Johnann
{
public List<long> John(long n)
{
List<long> johnResult = new List<long> { };
List<long> annResult = new List<long> { };
johnResult.Add(0);
annResult.Add(1);
int tJohn = 0;
int tAnn = 0;
for (int i = 1; i < n; i++)
{
tJohn = (int)johnResult[i - 1]; // Johns katas in previous day
tAnn = (int)annResult[i - 1]; // Anns katas in previous day
johnResult.Add(i - annResult[tJohn]);
annResult.Add(i - johnResult[tAnn]);
}
return johnResult;
}
public List<long> Ann(long n)
{
List<long> johnResult = new List<long> { };
List<long> annResult = new List<long> { };
johnResult.Add(0);
annResult.Add(1);
int tJohn = 0;
int tAnn = 0;
for (int i = 1; i < n; i++)
{
tJohn = (int)johnResult[i - 1]; // Johns katas in previous day
tAnn = (int)annResult[i - 1]; // Anns katas in previous day
johnResult.Add(i - annResult[tJohn]);
annResult.Add(i - johnResult[tAnn]);
}
return annResult;
}
public long SumJohn(long n)
{
long result = John(n).Sum();
return result;
}
public long SumAnn(long n)
{
long result = Ann(n).Sum();
return result;
}
}
public class RangeExtraction
{
public string Extract(int[] args)
{
//solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
// returns "-6,-3-1,3-5,7-11,14,15,17-20"
List<string> retString = new List<string> { };
List<int> linkString = new List<int> { };
for (int i = 0; i < args.Length; i++)
{
if (i + 2 >= args.Length)
{
retString.Add(args[i].ToString());
continue;
}
if (args[i] + 2 != args[i + 2])
{
retString.Add(args[i].ToString());
}
else
{
linkString.Add(args[i]);
i++;
while (args[i] - linkString.Last() == 1 && i < args.Length)
{
linkString.Add(args[i]);
i++;
if (i >= args.Length) break;
}
retString.Add(linkString.First() + "-" + linkString.Last());
linkString.Clear();
i--;
}
}
return string.Join(",", retString); //TODO
}
}
public class ClockWiseSnail
{
public string Snail()
{
int[][] array = new int[1][];
array[0] = new int[0];
/*{
new int[0]
//new int[] { 5, 6, 7 },
//new int[] { 9, 10, 11 }
//new int[] { 13, 14, 15, 16 }
};*/
if (array == null || array.Length == 0 || array[0].Length == 0) return string.Join(",", new int[0]);
List<int> snailRoad = new List<int> { };
for (int i = 0; i < (array.Length % 2 > 0 ? array.Length / 2 + 1 : array.Length / 2); i++)
{
int squareLen = array.Length - (i * 2);
int[][] square = new int[squareLen][];
for (int j = 0; j < squareLen; j++)
{
square[j] = new int[squareLen];
for (int k = 0; k < squareLen; k++)
{
square[j][k] = array[j + i][k + i];
}
}
int tempSnailRoadLen = (int)Math.Pow(squareLen, 2) - (int)Math.Pow(squareLen - 2, 2) <= 0 ?
(int)Math.Pow(squareLen, 2) : (int)Math.Pow(squareLen, 2) - (int)Math.Pow(squareLen - 2, 2);
// Temporary snail road for this square (array whith count of snail steps)
int[] tempSnailRoad = new int[tempSnailRoadLen];
// Temp index
int tempIndex = 0;
// First row (going rigth)
for (int k = 0; k < squareLen; k++)
{
tempSnailRoad[tempIndex] = square[0][k];
tempIndex++;
}
// Middle row - last element (going down)
for (int j = 1; j < squareLen - 1; j++)
{
tempSnailRoad[tempIndex] = square[j].Last();
tempIndex++;
}
// Last row and not first row (going left)
if (squareLen > 1)
{
for (int k = squareLen - 1; k >= 0; k--)
{
tempSnailRoad[tempIndex] = square[squareLen - 1][k];
tempIndex++;
}
}
// Middle row - firs element (going up)
for (int j = squareLen - 2; j >= 1; j--)
{
tempSnailRoad[tempIndex] = square[j].First();
tempIndex++;
}
snailRoad.AddRange(tempSnailRoad);
}
return string.Join(",",snailRoad.ToArray());
}
}
}
|
f3cfae5e399963a226381acbb178506d0e268c53
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
Eugenics/Kata
|
e5736a94489f12ce172de7482c8b9168a0bd8791
|
3097e8c4623be3aff684d86aed42321a5bcbaa15
|
refs/heads/master
|
<file_sep>var mysql = require("mysql");
var inquirer = require("inquirer");
var table = require("console.table");
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "<PASSWORD>",
database: "bamazon_db"
});
connection.connect(function (error) {
if (error) throw error;
console.log("connected as id " + connection.threadId + "\n"); showProducts();
});
function purchase (product, quantity, price){
connection.query("UPDATE products SET stock_quantity = stock_quantity - ? where item_id = ?", [quantity, product.item_id], function(err, res) {
console.log("Your total cost is $" + quantity * price)
console.log("You just purchased ", product.product_name)
showProducts()
})
}
function showProducts() {
connection.query("SELECT * FROM products", function (error, res) {
if (error) throw error;
console.table(res);
promptCustomer(res);
})
}
function promptCustomer(item) {
// console.log(item)
inquirer.prompt([
{
type: "input",
name: "buy",
message: "What is the ID of the product you would like to buy? (Or type Quit to exit)",
},
])
.then(function (answer) {
console.log(answer)
if (answer.buy.toLowerCase() === "quit") {
console.log("Come back again soon!")
process.exit(0)
}
var price = item [answer.buy].price;
var holdId = parseInt(answer.buy);
var product = checkDb(holdId, item);
if (product) {
console.log("Thank you")
inquirer.prompt([
{
type: "input",
name: "amount",
message: "How many of this product would you like to purchase?",
}])
.then(function (data) {
// quantity > product.stock_quantity? console.log("Not enough in stock!") ?showProducts():null: console.log("test")
var quantity = data.amount;
if (quantity > product.stock_quantity) {
console.log("Not enough in stock!")
showProducts()
}
else {
purchase(product, quantity, price)
}
})
}
else {
console.log("item not in stock")
}
})
function checkDb(holdId, item) {
for (let index = 0; index < item.length; index++) {
if (item[index].item_id === holdId) {
return item[index]
}
}
return null;
}
//need to add price and inventory and I just cant figure it out I will go to class to see or meet again with my tutor
}<file_sep>DROP DATABASE IF EXISTS bamazon_db;
CREATE DATABASE bamazon_db;
-- Uses bamazon db
USE bamazon_db;
-- Creation of my products table --
CREATE TABLE products (
item_id INT auto_increment NOT NULL,
product_name VARCHAR(30) NOT NULL,
department_name VARCHAR(30) NOT NULL,
price DECIMAL(10,3) NOT NULL,
stock_quantity INT(10) NOT NULL,
PRIMARY KEY (item_id)
);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Shovel", "Gardening", "50", "5");
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Seed Packet", "Gardening", "3", "100");
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Hoe", "Gardening", "15", "9");
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Gloves", "Gardening", "7", "1");
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Potting Soil", "Gardening", "10", "0");
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Pots", "Gardening", "15", "18");
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Bulbs", "Gardening", "8", "25");
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Fertilizer", "Gardening", "10", "4");
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Rake", "Gardening", "17", "5");
|
982264d1adcd0540099f7c8061d27e3048c25be6
|
[
"JavaScript",
"SQL"
] | 2
|
JavaScript
|
avalonmtg/Bamazon
|
8dcc24911a19964ec68516338c62f3f4b4e43ecc
|
6714b545b1617d46262c28122161038e8a77448d
|
refs/heads/master
|
<file_sep># vue boilerplate
This is a simple boilerplate to use for building web-apps with vue.
It includes vuex and vue-router.
## License
vue boilerplate is released under the MIT License. See [LICENSE][1] file for details.
[1]: https://github.com/seebaermichi/vue-boilerplate/blob/master/LICENSE
<file_sep>'use strict'
import './home.sass'
import template from './home.pug'
import Vue from 'vue'
export default Vue.component('Home', {
template,
computed: {
title() {
return this.$store.state.data.title
}
}
})
<file_sep>const ExtractTextPlugin = require('extract-text-webpack-plugin')
const ExtendedDefinePlugin = require('extended-define-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const merge = require('deepmerge')
const webpack = require('webpack')
const extractSass = new ExtractTextPlugin({
filename: '[name].css'
})
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
const config = merge.all([
{},
require(path.join(__dirname, 'config', 'default')),
require(path.join(__dirname, 'config', process.env.NODE_ENV))
])
module.exports = {
entry: {
app: './src/index.js',
vendor: [
'vue',
'vue-router',
'vuex'
]
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
},
devtool: 'source-maps',
module: {
rules: [
{
test: /\.sass$/,
use: extractSass.extract({
use: [
{
loader: 'css-loader'
}, {
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
]
})
},
{
test: /\.(jpe?g|png|gif|svg|mp3)$/,
use: 'file-loader?name=[path][name].[hash].[ext]'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
babelrc: true
}
},
{
loader: 'eslint-loader',
options: {
failOnError: false,
failOnWarning: false
}
}
]
},
{
test: /\.pug$/,
exclude: /node_modules/,
use: ['html-loader', 'pug-html-loader']
},
]
},
plugins: [
extractSass,
new ExtendedDefinePlugin({
GLOBAL_CONFIG: config
}),
new HtmlWebpackPlugin({
template: './index.pug'
}),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js' })
],
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
}
}
}
<file_sep>'use strict'
import './index.sass'
import template from './index.pug'
import Vue from 'vue'
import router from './router'
import store from './store'
new Vue({
el: '#app',
template,
router,
store
})
|
5c248ce36a6be33166f5a38b52b11709e2fc1777
|
[
"Markdown",
"JavaScript"
] | 4
|
Markdown
|
seebaermichi/vue-boilerplate
|
918961744a4127026273cf26b72f1cb5f150f6d7
|
6411b33dd1ac58449fe4aee7039ceff959d1988e
|
refs/heads/master
|
<repo_name>takoikatakotako/atcoder<file_sep>/abc120_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc120_b() {
int A, B, K;
cin >> A >> B >> K;
int counter = 0;
for (int i = 100; i <= 100; --i) {
if (A % i == 0 && B % i == 0) {
++counter;
if (counter == K) {
cout << i << endl;
return 0;
}
}
}
}
<file_sep>/abc141_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
using ll = long long;
int main() {
string S;
cin >> S;
bool flug = true;
// 奇数
for (int i = 0; i < S.size(); i += 2) {
if (S[i] == 'R' || S[i] == 'U' || S[i] == 'D') {
} else {
flug = false;
}
}
// 偶数
for (int i = 1; i < S.size(); i += 2) {
if (S[i] == 'L' || S[i] == 'U' || S[i] == 'D') {
} else {
flug = false;
}
}
if (flug) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
<file_sep>/abc115_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc115_b() {
int N;
cin >> N;
vector<int> p(N);
for (int i = 0; i < N; ++i) {
cin >> p[i];
}
int max = *max_element(p.begin(), p.end());
int sum = accumulate(p.begin(), p.end(), 0);
cout << sum - max / 2 << endl;
}<file_sep>/abc107_b.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
using namespace std;
int abc107_b() {
int H, W;
cin >> H >> W;
vector< vector<string> > map(H, vector<string>(W));
for (int i = 0; i < H; ++i) {
string S;
cin >> S;
for (int j = 0; j < W; ++j) {
map[i][j] = S[j];
}
}
// row が全部 . の場合は消す
for (int i = 0; i < H; ++i) {
bool isFind = false;
for (int j = 0; j < W; ++j) {
if (map[i][j] == "#") {
isFind = true;
}
}
if (isFind) {
continue;
}
// delete row
map.erase(map.begin() + i);
--H;
--i;
}
// column が全部 . の場合は消す
for (int i = 0; i < W; ++i) {
bool isFind = false;
for (int j = 0; j < H; ++j) {
if (map[j][i] == "#") {
isFind = true;
}
}
if (isFind) {
continue;
}
// delete column
for (int j = 0; j < H; ++j) {
map[j].erase(map[j].begin() + i);
}
--W;
--i;
}
for (int i = 0; i < H; ++i) {
for (int j = 0; j < W; ++j) {
cout << map[i][j];
}
cout << endl;
}
return 0;
}<file_sep>/abc101_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
using namespace std;
int abc101_a() {
string S;
cin >> S;
int num = 0;
for (int i = 0; i < S.size(); ++i) {
string sss = S.substr(i, 1);
if (sss == "+") {
++num;
} else {
--num;
}
}
cout << num << endl;
return 0;
}<file_sep>/abc132_c.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc132_c() {
lli N;
cin >> N;
vector<lli> d(N);
for (lli i = 0; i < N; ++i) {
cin >> d[i];
}
sort(d.begin(), d.end());
lli center = N / 2;
lli abc = d[center - 1];
lli arc = d[center];
cout << arc - abc << endl;
return 0;
}
<file_sep>/abc117_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc117_b() {
int N;
cin >> N;
vector<int> l(N);
for (int i = 0; i < N; ++i) {
cin >> l[i];
}
int max = *max_element(l.begin(), l.end());
int sum = accumulate(l.begin(), l.end(), 0);
if (max < sum - max) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}<file_sep>/abc146_a.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
#include <map>
using namespace std;
using lli = long long int;
using ll = long long;
int main() {
string S;
cin >> S;
map<string, int> mp; // 文字列 → 整数 の連想配列
mp["SUN"] = 7;
mp["MON"] = 6;
mp["TUE"] = 5;
mp["WED"] = 4;
mp["THU"] = 3;
mp["FRI"] = 2;
mp["SAT"] = 1;
cout << mp[S] << endl;
}
<file_sep>/abc127_c.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc127_c() {
lli N, M;
cin >> N >> M;
vector<lli> L(M);
vector<lli> R(M);
for (int i = 0; i < M; ++i) {
cin >> L[i];
cin >> R[i];
}
lli lMax = *max_element(L.begin(), L.end());
lli rMin = *min_element(R.begin(), R.end());
if (lMax <= rMin) {
cout << rMin - lMax + 1 << endl;
} else {
cout << 0 << endl;
}
}<file_sep>/abc121_c.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
using ll = long long;
struct Shop {
lli price;
lli amount;
bool operator<(const Shop &another) const {
return price < another.price;
};
} ;
int abc121_c() {
lli N, M;
cin >> N >> M;
vector<Shop> shops(N);
for (int i = 0; i < N; ++i) {
lli price;
cin >> price;
lli amount;
cin >> amount;
Shop shop;
shop.price = price;
shop.amount = amount;
shops[i] = shop;
}
sort(shops.begin(), shops.end());
int i = 0;
lli answer = 0;
do {
Shop shop = shops[i];
lli price = shop.price;
lli amount = shop.amount;
bool flag = false;
for (int j = 0; j < amount; ++j) {
answer += price;
--M;
if (M == 0) {
break;
}
}
++i;
} while (M > 0);
cout << answer << endl;
return 0;
}
<file_sep>/abc098_c.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int abc098_c() {
int N;
cin >> N;
string S;
cin >> S;
vector<int> counterWtoE(N);
vector<int> counterEtoW(N);
counterWtoE[0] = 0;
counterEtoW[0] = 0;
for (int i = 0; i < N - 1; ++i) {
counterWtoE[i + 1] = counterWtoE[i];
if (S.substr(i, 1) == "W") {
++counterWtoE[i + 1];
}
}
reverse(S.begin(), S.end());
for (int i = 0; i < N - 1; ++i) {
counterEtoW[i + 1] = counterEtoW[i];
if (S.substr(i, 1) == "E") {
++counterEtoW[i + 1];
}
}
reverse(counterEtoW.begin(), counterEtoW.end());
int min = N;
for (int i = 0; i < N; ++i) {
int num = counterWtoE[i] + counterEtoW[i];
if (min > num) {
min = num;
}
}
cout << min << endl;
}
<file_sep>/abc116_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc116_b() {
int s;
cin >> s;
vector<int> a;
a.push_back(s);
for (int i = 0; i <= 1000000; ++i) {
int num = a[i];
if (num % 2 == 0) {
int n = num / 2;
auto result = find(a.begin(), a.end(), n);
if (result == a.end()) {
// not found
a.push_back(n);
} else {
cout << i + 2 << endl;
return 0;
}
} else {
int n = 3 * num + 1;
auto result = find(a.begin(), a.end(), n);
if (result == a.end()) {
// not found
a.push_back(n);
} else {
cout << i + 2 << endl;
return 0;
}
}
}
return 0;
}<file_sep>/aoj_ALDS1_1_A.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_1_A&lang=jp
// 挿入ソート
static void printArray(vector<int> vector) {
int size = vector.size();
for (int i = 0; i < size; ++i) {
if (i == size - 1) {
cout << vector[i] << endl;
} else {
cout << vector[i] << " ";
}
}
}
int aoj_ALDS1_1_A() {
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
printArray(A);
for (int i = 1; i < N; ++i) {
int v = A[i];
int j = i - 1;
while (j >= 0 && A[j] > v) {
A[j+1] = A[j];
j--;
}
A[j+1] = v;
printArray(A);
}
return 0;
}
<file_sep>/abc123_b.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int main() {
vector<int> numbers(5);
for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}
int min = 9;
bool changed = false;
for (int i = 0; i < numbers.size(); ++i) {
int number = numbers[i];
number = number % 10;
if (number != 0 && min >= number) {
min = number;
changed = true;
}
}
if (!changed) {
int sum = 0;
for (int i = 0; i < numbers.size(); ++i) {
sum += numbers[i];
}
cout<< sum << endl;
return 0;
}
int sum = 0;
for (int i = 0; i < numbers.size(); ++i) {
int number = numbers[i];
if (number % 10 == 0) {
sum += number;
} else {
sum += (number / 10 + 1) * 10;
}
}
cout << sum - 10 + min << endl;
}<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(competitive_programming)
set(CMAKE_CXX_STANDARD 14)
add_executable(competitive_programming main.cpp)<file_sep>/abc060_b.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int abc060_b() {
int A, B, C;
cin >> A >> B >> C;
for (int i = 0; i < B; ++i) {
if ((A * i) % B == C) {
cout << "YES";
return 0;
}
}
cout << "NO";
}
<file_sep>/abc065_b.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int abc065_b() {
int N;
cin >> N;
vector<int> A(N + 1);
for (int i = 1; i < N + 1; ++i) {
cin >> A[i];
}
bool flag = true;
int i = 1;
int counter = 0;
while (flag) {
if(i == 0){
flag = false;
counter = -1;
break;
}
if (i == 2) {
flag = false;
// 最初で数えてしまっているので、一回減らす
--counter;
}
int temp = A[i];
A[i] = 0;
i = temp;
++counter;
}
cout << counter << endl;
}
<file_sep>/abc118_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc118_a() {
int A, B;
cin >> A;
cin >> B;
if (B % A == 0) {
cout << A + B << endl;
} else {
cout << B - A << endl;
}
}<file_sep>/tenka1_2019_c.cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int tenka1_2019_c() {
int N;
string S;
cin >> N >> S;
vector<int> counterSharpToDot(N);
vector<int> counterDotToSharp(N);
counterSharpToDot[0] = 0;
counterDotToSharp[0] = 0;
for (int i = 0; i < N - 1; ++i) {
counterSharpToDot[i + 1] = counterSharpToDot[i];
if (S.substr(i, 1) == "#") {
++counterSharpToDot[i + 1];
}
}
reverse(S.begin(), S.end());
for (int i = 0; i < N - 1; ++i) {
counterDotToSharp[i + 1] = counterDotToSharp[i];
if (S.substr(i, 1) == ".") {
++counterDotToSharp[i + 1];
}
}
reverse(counterDotToSharp.begin(), counterDotToSharp.end());
int min = N;
for (int i = 0; i < N; ++i) {
int num = counterDotToSharp[i] + counterSharpToDot[i];
if (min > num) {
min = num;
}
}
cout << min << endl;
return 0;
}
<file_sep>/abc100_a.cpp
#include <iostream>
#include<math.h>
using namespace std;
int abc100_a() {
int A, B;
cin >> A >> B;
int amari = 16 - A - B;
int sa = abs(A - B);
if (sa > amari) {
cout << ":(" << endl;
} else {
cout << "Yay!" << endl;
}
return 0;
}
<file_sep>/abc129_c.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
#define rep(i, n) for (int i = 0; i < n; ++i)
int abc129_c() {
int n, m;
cin >> n >> m;
vector<int> broken(n+1);
rep(i,m) {
int a;
cin >> a;
broken[a] = 1;
}
vector<int> dp(n+2);
const int mod = 1000000007;
dp[n] = 1;
for (int i = n-1; i >= 0; i--) {
if (broken[i]) {
dp[i] = 0;
continue;
}
dp[i] = (dp[i+1] + dp[i+2]) % mod;
}
cout << dp[0] << endl;
return 0;
}
<file_sep>/abc086_c.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int abc086_c() {
int N;
cin >> N;
vector<int> tList(N + 1);
vector<int> xList(N + 1);
vector<int> yList(N + 1);
tList[0] = 0;
xList[0] = 0;
yList[0] = 0;
for (int i = 1; i <= N; ++i) {
cin >> tList[i];
cin >> xList[i];
cin >> yList[i];
}
bool flg = true;
for (int i = 1; i <= N; ++i) {
int time = tList[i] - tList[i - 1];
int x = xList[i] - xList[i - 1];
int y = yList[i] - yList[i - 1];
// 移動が無理な場合
if (x + y > time) {
flg = false;
break;
}
// 偶奇が合わない場合
if (abs(x + y) % 2 != time % 2) {
flg = false;
break;
}
}
if (flg) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
<file_sep>/abc112_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc112_b() {
double N, T;
cin >> N >> T;
vector<int > costs;
for (int i = 0; i < N; ++i) {
int c, t;
cin >> c >> t;
if (t <= T) {
costs.push_back(c);
}
}
if (costs.size() == 0) {
cout << "TLE" << endl;
return 0;
}
int min = *std::min_element(costs.begin(), costs.end());
cout << min << endl;
}<file_sep>/abc127_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc127_b() {
int r, D, x2000;
cin >> r >> D >> x2000;
int x = x2000;
for (int i = 0; i < 10; ++i) {
int xi = r * x - D;
cout << xi << endl;
x = xi;
}
}<file_sep>/abc110_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc110_b() {
lli N, M, X, Y;
cin >> N >> M >> X >> Y;
vector<lli> x(N);
for (int i = 0; i < N; ++i) {
cin >> x[i];
}
vector<lli> y(M);
for (int i = 0; i < M; ++i) {
cin >> y[i];
}
lli xMax = *max_element(x.begin(), x.end());
lli yMin = *min_element(y.begin(), y.end());
if (X < Y && xMax < yMin && xMax < Y && yMin > X+1) {
cout << "No War" << endl;
} else {
cout << "War" << endl;
}
}<file_sep>/abc135_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
using ll = long long;
int main() {
int N;
cin >> N;
vector<int> p(N);
int counter = 0;
for (int i = 1; i <= N; ++i) {
int num;
cin >> num;
if (i != num) {
++counter;
}
}
if (counter > 2) {
cout << "NO" << endl;
} else {
cout << "YES" << endl;
}
return 0;
}
<file_sep>/abc108_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc108_b() {
lli x1, y1, x2, y2, x3, y3, x4, y4;
cin >> x1 >> y1 >> x2 >> y2;
lli x = x2 - x1;
lli y = y2 - y1;
x3 = x2 - y;
y3 = y2 + x;
x4 = x1 - y;
y4 = y1 + x;
cout << x3 << " " << y3 << " " << x4 << " " << y4 << endl;
}<file_sep>/abc103_b.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc103_b() {
int N;
cin >> N;
string S, T;
cin >> S >> T;
long length = S.size();
for (int i = 0; i < length; ++i) {
// 一個ずらす
string first = S.substr(0, 1);
string last = S.substr(length - 1, 1);
S = S.substr(1, length - 1) + first;
if (S == T) {
cout << "Yes" << endl;
return 0;
}
}
cout << "No" << endl;
return 0;
}<file_sep>/abc145_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
#include <map>
using namespace std;
using lli = long long int;
using ll = long long;
int main() {
int N;
string S;
cin >> N >> S;
if (N % 2 == 1) {
cout << "No" << endl;
return 0;
}
string leftS = S.substr(0, N / 2);
string rightS = S.substr(N / 2, N - 1);
if (leftS == rightS) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
<file_sep>/abc124_a.cpp
#include <iostream>
#include<math.h>
using namespace std;
int abc124_a() {
int A, B;
cin >> A >> B;
if (A == B) {
cout << 2 * A;
} else if (A > B) {
cout << 2 * A - 1;
} else {
cout << 2 * B - 1;
}
}
<file_sep>/abc132_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc132_b() {
long n;
cin >> n;
vector<long> p(n);
for (long i = 0; i < n; ++i) {
cin >> p[i];
}
int counter = 0;
for (long i = 1; i < n - 1; ++i) {
vector<long> check(3);
check[0] = p[i - 1];
check[1] = p[i];
check[2] = p[i + 1];
sort(check.begin(), check.end());
if (check[1] == p[i]) {
++counter;
}
}
cout << counter << endl;
return 0;
}
<file_sep>/abc122_c.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
using ll = long long;
int abc122_c() {
lli N, Q;
cin >> N >> Q;
string S;
cin >> S;
vector<lli> l(Q);
vector<lli> r(Q);
for (int i = 0; i < Q; ++i) {
cin >> l[i] >> r[i];
}
// 累積和を計算
vector<lli> count(N);
lli counter = 0;
count[0] = 0;
for (int i = 1; i < N; ++i) {
if (S[i] == 'C' && S[i - 1] == 'A') {
++counter;
}
count[i] = counter;
}
for (int i = 0; i < Q; ++i) {
lli numL = l[i] - 1;
lli numR = r[i] - 1;
lli answer = count[numR] - count[numL];
cout << answer << endl;
}
return 0;
}
<file_sep>/abc124_d.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 渡された文字をひっくりかえす
string reverse(string str) {
// 一旦 0 をXに
replace(str.begin(), str.end(), '0', 'X');
replace(str.begin(), str.end(), '1', '0');
replace(str.begin(), str.end(), 'X', '1');
return str;
}
int abc124_d() {
int N, K;
cin >> N >> K;
string S;
cin >> S;
string newS = S;
for (int i = 0; i < N; ++i) {
for (int j = 3; j < N; ++j) {
// 上限を超えてしまった場合
if (i + j >= N) {
break;
}
newS = "3";
}
}
}
<file_sep>/abc106_b.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
using namespace std;
int abc106_b() {
int N;
cin >> N;
int numCounter = 0;
for (int i = 1; i <= N; ++i) {
int counter = 0;
for (int j = 1; j <=i; j+=2) {
if (i % j == 0) {
++counter;
}
}
if (counter == 8) {
++numCounter;
}
}
cout << numCounter << endl;
}<file_sep>/abc119_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc119_b() {
int N;
cin >> N;
vector<double> x(N);
vector<string> u(N);
for (int i = 0; i < N; ++i) {
cin >> x[i];
cin >> u[i];
}
double sum = 0;
for (int i = 0; i < N; ++i) {
if (u[i] == "BTC") {
sum += 380000.0 * x[i];
} else {
sum += x[i];
}
}
cout << sum << endl;
}<file_sep>/aoj_ALDS1_3_A.cpp
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_A&lang=jp
// スタック
vector<string> split20190516(const string &s, char delimiter) {
vector<string> elements;
stringstream ss(s);
string item;
while (getline(ss, item, delimiter)) {
if (!item.empty()) {
elements.push_back(item);
}
}
return elements;
}
class Stack {
private:
int top;
vector<int> array;
public:
void initialize() {
top = -1;
array = {};
}
bool isEmpty() {
return array.size() == 0;
}
void push(int number) {
array.push_back(number);
++top;
}
int pop() {
int number = array[top];
array.pop_back();
--top;
return number;
}
};
int aoj_ALDS1_3_A() {
string s;
getline(cin, s);
vector<string> array = split20190516(s, ' ');
Stack stack;
stack.initialize();
for (int i = 0; i < array.size(); ++i) {
string str = array[i];
if (str == "+") {
int number1 = stack.pop();
int number2 = stack.pop();
stack.push(number2 + number1);
} else if (str == "-") {
int number1 = stack.pop();
int number2 = stack.pop();
stack.push(number2 - number1);
} else if (str == "*") {
int number1 = stack.pop();
int number2 = stack.pop();
stack.push(number2 * number1);
} else {
int number;
number = atoi(str.c_str());
stack.push(number);
}
}
cout << stack.pop() << endl;
return 0;
}
<file_sep>/abc119_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
#include <sstream>
using namespace std;
vector<string> split20190517(const string &s, char delimiter) {
vector<string> elements;
stringstream ss(s);
string item;
while (getline(ss, item, delimiter)) {
if (!item.empty()) {
elements.push_back(item);
}
}
return elements;
}
int stringToInt20190517(string str) {
int number = atoi(str.c_str());
return number;
}
int abc119_a() {
string s;
cin >> s;
vector<string> strArray = split20190517(s, '/');
int year = stringToInt20190517(strArray[0]);
int month = stringToInt20190517(strArray[1]);
int day = stringToInt20190517(strArray[2]);
if (year <= 2019 && month <= 4 && day <= 30) {
cout << "Heisei" << endl;
} else {
cout << "TBD" << endl;
}
}<file_sep>/abc125_c.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
lli gcd(lli x, lli y) {
if (y == 0) return x;
return gcd(y, x % y);
}
lli max(lli a, lli b) {
return (a > b) ? a : b;
}
int abc125_c() {
lli N;
cin >> N;
vector<lli> A(N);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
vector<lli> L(N + 1);
vector<lli> R(N + 1);
for (int i = 0; i < N; i++) {
if (i != 0) {
L[i + 1] = gcd(L[i], A[i - 1]);
}
R[N - 1 - i] = gcd(R[N - i], A[N - 1 - i]);
}
lli ans = 0;
for (int i = 0; i < N; i++) {
ans = max(ans, gcd(L[i + 1], R[i + 1]));
}
cout << ans << endl;
}
<file_sep>/aoj_ALDS1_2_A.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_2_A
// バブルソート
static void printArray(vector<int> vector) {
int size = vector.size();
for (int i = 0; i < size; ++i) {
if (i == size - 1) {
cout << vector[i] << endl;
} else {
cout << vector[i] << " ";
}
}
}
int aoj_ALDS1_2_A() {
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
// 逆の隣接要素が存在する
bool flag = true;
int counter = 0;
while (flag) {
flag = false;
for (int j = N - 1; j > 0; --j) {
if(A[j] < A[j-1]) {
swap(A[j], A[j - 1]);
flag = true;
++counter;
}
}
}
printArray(A);
cout << counter << endl;
return 0;
}
<file_sep>/abc109_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc109_b() {
lli N;
cin >> N;
vector<string> history(N);
bool flag = true;
for (int i = 0; i < N; ++i) {
string w;
cin >> w;
if (i == 0) {
history[0] = w;
continue;
}
string beforeLast = history[i - 1];
beforeLast = beforeLast.substr(beforeLast.size() - 1, 1);
string first = w.substr(0, 1);
if (beforeLast != first) {
flag = false;
break;
}
auto result = find(history.begin(), history.end(), w);
if (result != history.end()) {
// found
flag = false;
break;
}
history[i] = w;
}
if (flag) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}<file_sep>/abc111_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc111_a() {
string n;
cin >> n;
for (int i = 0; i < n.size(); ++i) {
string str = n.substr(i, 1);
if (str == "9") {
cout << "1";
} else {
cout << "9";
}
}
cout << endl;
}<file_sep>/abc120_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
#include <sstream>
using namespace std;
int abc120_a() {
int A, B, C;
cin >> A >> B >> C;
if (B > A * C) {
cout << C << endl;
} else {
cout << B/ A << endl;
}
}<file_sep>/0_utils.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <sstream>
using namespace std;
// マップ系の問題のパース
void mapProblems() {
int H, W;
cin >> H >> W;
vector <vector<string>> map(H, vector<string>(W));
for (int i = 0; i < H; ++i) {
string S;
cin >> S;
for (int j = 0; j < W; ++j) {
map[i][j] = S[j];
}
}
}
// 文字列を int に変換
int stringToInt(string str) {
int number = atoi(str.c_str());
return number;
}
// 文字列を分割して vector に入れる
vector<string> split(const string &s, char delimiter) {
vector<string> elements;
stringstream ss(s);
string item;
while (getline(ss, item, delimiter)) {
if (!item.empty()) {
elements.push_back(item);
}
}
return elements;
}
// ベクターの最小値を取得する
// unsigned long minElementIndex = min_element(temps.begin(),temps.end()) - temps.begin();
// GCD を求める
lli gcd(lli x, lli y) {
if(y == 0) return x;
return gcd(y, x%y);
}
// long long int で大きい方を取得する
lli max(lli a, lli b) {
return (a > b) ? a : b;
}
// 文字列中の文字数をカウント
long charCounter(string sentence, char character) {
return count(sentence.cbegin(), sentence.cend(), character);
}
// 独自 struct のソート
<file_sep>/abc118_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc118_b() {
int N, M;
cin >> N >> M;
vector<int> A(M + 1);
for (int i = 0; i < M + 1; ++i) {
A[i] = 0;
}
for (int i = 0; i < N; ++i) {
int K;
cin >> K;
for (int j = 0; j < K; ++j) {
int food;
cin >> food;
++A[food];
}
}
int counter = 0;
for (int i = 0; i < M + 1; ++i) {
if (A[i] == N) {
++counter;
}
}
cout << counter << endl;
}<file_sep>/abc110_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc110_a() {
int A, B, C;
cin >> A >> B >> C;
int resultA = A * 10 + B + C;
int resultB = A + B * 10 + C;
int resultC= A + B + C * 10;
vector<int> answer(3);
answer.push_back(resultA);
answer.push_back(resultB);
answer.push_back(resultC);
int max = *max_element(answer.begin(), answer.end());
cout << max << endl;
}<file_sep>/abc124_c.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int abc124_c() {
string S;
cin >> S;
int N = S.size();
// 最初が0のやつと比べる
// 01010101
//
int zeroOneCounter = 0;
for (int i = 0; i < N; ++i) {
if (atoi(S.substr(i, 1).c_str()) != (i % 2)) {
++zeroOneCounter;
}
}
int oneZeroCounter = 0;
for (int i = 0; i < N; ++i) {
if (atoi(S.substr(i, 1).c_str()) == (i % 2)) {
++oneZeroCounter;
}
}
if (zeroOneCounter > oneZeroCounter) {
cout << oneZeroCounter;
} else {
cout << zeroOneCounter;
}
}
<file_sep>/abc049_c.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int abc049_c() {
string S;
cin >> S;
reverse(S.begin(), S.end());
string eraser = "eraser";
string erase = "erase";
string dreamer = "dreamer";
string dream = "dream";
reverse(eraser.begin(), eraser.end());
reverse(erase.begin(), erase.end());
reverse(dreamer.begin(), dreamer.end());
reverse(dream.begin(), dream.end());
do {
int flg = false;
if (S.substr(0, eraser.size()) == eraser) {
flg = true;
S = S.substr(eraser.size(), S.size() - eraser.size());
}
if (S.substr(0, erase.size()) == erase) {
flg = true;
S = S.substr(erase.size(), S.size() - erase.size());
}
if (S.substr(0, dreamer.size()) == dreamer) {
flg = true;
S = S.substr(dreamer.size(), S.size() - dreamer.size());
}
if (S.substr(0, dream.size()) == dream) {
flg = true;
S = S.substr(dream.size(), S.size() - dream.size());
}
// 全部見つからないとbreak
if (flg != 0) continue;
break;
} while (true);
if (S == "") {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
<file_sep>/abc128_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
struct Shop {
int id;
string city;
int price;
bool operator<(const Shop &another) const {
// return city < another.city;
if (city != another.city) {
return city < another.city;
} else {
return price > another.price;
}
};
} ;
int abc128_b() {
int N;
cin >> N;
vector<Shop> array(N);
for (int i = 0; i < N; ++i) {
int id = i + 1;
string s;
int p;
cin >> s >> p;
Shop shop;
shop.id = id;
shop.city = s;
shop.price = p;
array[i] = shop;
}
sort(array.begin(), array.end());
for (int i = 0; i < N; ++i) {
cout << array[i].id << endl;
}
return 0;
}<file_sep>/tenka1_2019_a.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int tenka1_2019_a() {
int A, B, C;
cin >> A >> B >> C;
// C が一番大さい
if (A < C && B < C) {
cout << "No" << endl;
return 0;
}
// C が一番小さい
if (C < A && C < B) {
cout << "No" << endl;
return 0;
}
cout << "Yes" << endl;
return 0;
}
<file_sep>/aoj_ALDS1_2_C.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_2_C&lang=jp
// 安定ソート
static void printArray(vector<string> vector) {
int size = vector.size();
for (int i = 0; i < size; ++i) {
if (i == size - 1) {
cout << vector[i] << endl;
} else {
cout << vector[i] << " ";
}
}
}
static string isStable(vector<string> in, vector<string> out) {
int N = in.size();
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
for (int a = 0; a < N; ++a) {
for (int b = a + 1; b < N; ++b) {
if (in[i].substr(1, 1) == in[j].substr(1, 1) && in[i] == out[b] && in[j] == out[a]) {
return "Not stable";
}
}
}
}
}
return "Stable";
}
int aoj_ALDS1_2_C() {
int N;
cin >> N;
vector<string> cards(N);
for (int i = 0; i < N; ++i) {
cin >> cards[i];
}
vector<string> bubbleCards(N);
bubbleCards = cards;
vector<string> selectionCards(N);
selectionCards = cards;
// Bubble Sort
for (int i = 0; i < N; ++i) {
for (int j = N - 1; j > i; --j) {
if (bubbleCards[j].substr(1, 1) < bubbleCards[j - 1].substr(1, 1)) {
swap(bubbleCards[j], bubbleCards[j - 1]);
}
}
}
// printArray(bubbleCards);
// cout << isStable(cards, bubbleCards) << endl;
// Selection Sort
for (int i = 0; i < N; ++i) {
int minj = i;
for (int j = i; j < N; ++j) {
if (selectionCards[j].substr(1, 1) < selectionCards[minj].substr(1, 1)) {
minj = j;
}
}
swap(selectionCards[i], selectionCards[minj]);
}
printArray(bubbleCards);
cout << isStable(cards, bubbleCards) << endl;
printArray(selectionCards);
cout << isStable(cards, selectionCards) << endl;
return 0;
}
<file_sep>/abc146_c.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
#include <map>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long int;
using ll = long long;
ll getDigit(ll num) {
return to_string(num).length();
}
ll getPrice(ll A, ll B, ll N) {
return A * N + B * getDigit(N);
}
int main() {
ll a, b, x;
cin >> a >> b >> x;
ll l = 0, r = 1000000001;
while (r - l > 1) {
ll c = (l + r) / 2;
if (getPrice(a, b, c) <= x) {
l = c;
} else {
r = c;
}
}
cout << l << endl;
return 0;
}
<file_sep>/aoj_ALDS1_1_D.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int aoj_ALDS1_1_D() {
int N;
cin >> N;
vector<int> R(N);
for (int i = 0; i < N; ++i) {
cin >> R[i];
}
int maxBenefit = R[1] - R[0];
int minNum = R[0];
for (int i = 1; i < N; ++i) {
if (R[i-1] < minNum) {
minNum = R[i-1];
}
int benefit = R[i] - minNum;
if (benefit > maxBenefit) {
maxBenefit = benefit;
}
}
cout << maxBenefit << endl;
}
<file_sep>/abc102_c.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc102_c() {
int N;
cin >> N;
vector<long long> A(N);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
vector<long long> B(N);
for (int i = 0; i < N; ++i) {
B[i] = A[i] - (i + 1);
}
sort(B.begin(), B.end());
long long centerIndex = B.size() / 2;
long long b = B[centerIndex];
long long num = 0;
for (int i = 0; i < N; ++i) {
num += abs(B[i] - b);
}
cout << num << endl;
return 0;
}<file_sep>/abc141_a.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
using ll = long long;
int main() {
string S;
cin >> S;
if (S == "Sunny") {
cout << "Cloudy" << endl;
} else if (S == "Cloudy") {
cout << "Rainy" << endl;
} else if (S == "Rainy") {
cout << "Sunny" << endl;
}
return 0;
}
<file_sep>/abc100_b.cpp
#include <iostream>
#include<math.h>
using namespace std;
int abc100_b() {
long long D, N;
cin >> D >> N;
// 100 だけ特別
if (N == 100) {
cout << (N + 1) * (int) pow(100, D) << endl;
return 0;
}
cout << N * (int) pow(100, D) << endl;
return 0;
}
<file_sep>/abc102_b.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc102_b() {
int N;
cin >> N;
vector<long long> A(N);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
long long min = *std::min_element(A.begin(), A.end());
long long max = *std::max_element(A.begin(), A.end());
cout << max - min << endl;
}<file_sep>/abc142_a.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
using ll = long long;
int main() {
int N;
cin >> N;
if (N % 2 == 0) {
cout << 0.5 << endl;
return 0;
}
int harf = N / 2;
cout << double((harf + 1.0) / N) << endl;
return 0;
}
<file_sep>/abc113_b.cpp
//
// Created by <NAME> on 2019-05-23.
//
<file_sep>/wip_aoj_ALDS1_2_B.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_2_B
// 選択ソート
static void printArray(vector<int> vector) {
int size = vector.size();
for (int i = 0; i < size; ++i) {
if (i == size - 1) {
cout << vector[i] << endl;
} else {
cout << vector[i] << " ";
}
}
}
int aoj_ALDS1_2_() {
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
printArray(A);
// cout << counter << endl;
return 0;
}<file_sep>/abc103_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc103_a() {
vector<int> A(3);
for (int i = 0; i < 3; ++i) {
cin >> A[i];
}
sort(A.begin(), A.end(), greater<>());
int num = 0;
for (int i = 1; i < 3; ++i) {
num += abs(A[i - 1] - A[i]);
}
cout << num << endl;
return 0;
}<file_sep>/abc124_b.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int abc124_b() {
int N;
cin >> N;
vector<int> H(N + 1);
H[0] = 0;
for (int i = 1; i <= N; ++i) {
cin >> H[i];
}
int counter = 0;
for (int i = 1; i <= N; ++i) {
bool topFlg = true;
for (int j = 0; j < i; ++j) {
if (H[j] > H[i]) {
topFlg = false;
break;
}
}
if (topFlg) {
++counter;
}
}
cout << counter;
}
<file_sep>/abc111_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc111_b() {
double N;
cin >> N;
if (N <= 111) {
cout << "111" << endl;
} else if (N <= 222) {
cout << "222" << endl;
} else if (N <= 333) {
cout << "333" << endl;
} else if (N <= 444) {
cout << "444" << endl;
} else if (N <= 555) {
cout << "555" << endl;
} else if (N <= 666) {
cout << "666" << endl;
} else if (N <= 777) {
cout << "777" << endl;
} else if (N <= 888) {
cout << "888" << endl;
} else if (N <= 999) {
cout << "999" << endl;
}
}<file_sep>/abc132_a.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
long charCounter(string sentence, char character) {
return count(sentence.cbegin(), sentence.cend(), character);
}
int abc132_a() {
string S;
cin >> S;
if ((charCounter(S, S[0]) == 2) && (charCounter(S, S[1]) == 2) &&
(charCounter(S, S[2]) == 2) && (charCounter(S, S[3]) == 2)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
<file_sep>/exawizards2019_c.cpp
//#include <iostream>
//#include <string>
//#include <vector>
//
//
//using namespace std;
//
//int main() {
//
// int N, Q;
// string s;
// cin >> N >> Q >> s;
//
// vector<string> t(Q);
// vector<string> d(Q);
//
// for (int i = 0; i < Q; ++i) {
// string t_str;
// string d_str;
//
// cin >> t_str;
// cin >> d_str;
//
// t[i] = t_str;
// d[i] = d_str;
// }
//
// vector<int> golem(N);
// for (int i = 0; i < N; ++i) {
// golem[i] = 1;
// }
//
// for (int i = 0; i < Q; ++i) {
//
// // 対象のマップは何か
// string targetMap = t[i];
// string command = d[i];
//
//
// for (int j = 0; j < N; ++j) {
//
// if (targetMap == s.substr(j , 1)) {
// if (command == "L") {
// if (j == 0) {
// // 一番左の時
// golem[0] = 0;
// } else {
// // 一番左以外
// golem[j - 1] = golem[j - 1] + golem[j];
// golem[j] = 0;
// }
// } else if (command == "R") {
// if (j == N - 1) {
// // 一番右の時
// golem[N - 1] = 0;
// } else {
// // 一番右以外
// golem[j + 1] = golem[j + 1] + golem[j];
// golem[j] = 0;
// }
// }
//
// }
// }
// }
//
//
// long count = 0;
// for (int i = 0; i < N; ++i) {
// count = count + golem[i];
// }
//
// cout << count << endl;
//
//}
//
<file_sep>/abc135_a.cpp
//
// Created by <NAME> on 2019-08-30.
//
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
using ll = long long;
int abc135_a() {
lli A, B;
cin >> A >> B;
lli k = (A + B) / 2;
if (abs(A - k) == abs(B - k)) {
cout << k << endl;
} else {
cout << "IMPOSSIBLE" << endl;
}
return 0;
}
<file_sep>/abc108_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
using namespace std;
int abc108_a() {
int K;
cin >> K;
if (K % 2 == 0) {
int hanbun = K / 2;
cout << hanbun * hanbun << endl;
} else {
int hanbun = K / 2;
cout << hanbun * (hanbun + 1) << endl;
};
}<file_sep>/aoj_ALDS1_2_B.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_2_B&lang=jp
// 選択ソート
static void printArray(vector<int> vector) {
int size = vector.size();
for (int i = 0; i < size; ++i) {
if (i == size - 1) {
cout << vector[i] << endl;
} else {
cout << vector[i] << " ";
}
}
}
int aoj_ALDS1_2_B() {
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
int counter = 0;
for (int i = 0; i < N; ++i) {
int minj = i;
for (int j = i; j < N; ++j) {
if (A[j] < A[minj]) {
minj = j;
}
}
if(i != minj) {
swap(A[i], A[minj]);
++counter;
}
}
printArray(A);
cout << counter << endl;
return 0;
}
<file_sep>/abc087_c.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int abc087_c() {
int N;
cin >> N;
vector<vector<int> > map(2, vector<int>(N));
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < N; ++j) {
cin >> map[i][j];
}
}
// 左からの和
vector<int> topSum(N);
topSum[0] = map[0][0];
for (int i = 1; i < N; ++i) {
topSum[i] = topSum[i - 1] + map[0][i];
}
// 右からの和
vector<int> bottomSum(N);
bottomSum[N - 1] = map[1][N - 1];
for (int i = N - 2; i >= 0; --i) {
bottomSum[i] = bottomSum[i + 1] + map[1][i];
}
// 最大値を検索する
int max = 0;
for (int i = 0; i < N; ++i) {
int num = topSum[i] + bottomSum[i];
if (num > max) {
max = num;
}
}
cout << max << endl;
}
<file_sep>/abc122_b.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc122_b() {
string S;
cin >> S;
int max = 0;
int counter = 0;
for (int i = 0; i < S.size(); ++i) {
string str = S.substr(i, 1);
if (str == "A" || str == "T" || str == "C" || str == "G") {
++counter;
} else {
counter = 0;
}
if (counter > max) {
max = counter;
}
}
cout << max << endl;
}<file_sep>/abc142_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
using ll = long long;
int main() {
lli N, K;
cin >> N >> K;
vector<int> h(N);
for (int i = 0; i < N; ++i) {
cin >> h[i];
}
lli counter = 0;
for (int i = 0; i < N; ++i) {
if (h[i] >= K) {
++counter;
}
}
cout << counter << endl;
return 0;
}
<file_sep>/abc130_d.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc130_d() {
lli N, K;
cin >> N >> K;
vector<lli> a(N);
for (int i = 0; i < N; ++i) {
cin >> a[i];
}
lli answer = 0;
lli sum = 0;
int r = 0;
for (int l = 0; l < N; ++l) {
while (sum < K) {
if (r == N) {
break;
}
else {
sum += a[r];
r++;
}
}
if (sum < K) {
break;
}
answer += N - r + 1;
sum -= a[l];
}
cout << answer << endl;
return 0;
}
<file_sep>/abc130_c.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc130_c() {
double W, H, x, y;
cin >> W >> H >> x >> y;
double S = W * H / 2;
int count = (x == W / 2 && y == H / 2) ? 1 : 0;
cout << S << " " << count << endl;
}<file_sep>/abc131_d.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
struct Task {
lli A;
lli B;
bool operator<(const Task &another) const {
return B < another.B;
};
};
int abc131_d() {
int N;
cin >> N;
vector<Task> tasks(N);
for (int i = 0; i < N; ++i) {
lli a, b;
cin >> a >> b;
Task task;
task.A = a;
task.B = b;
tasks[i] = task;
}
sort(tasks.begin(), tasks.end());
lli time = 0;
for (int i = 0; i < N; ++i) {
Task task = tasks[i];
time += task.A;
if (time <= task.B) {
continue;
} else {
cout << "No" << endl;
return 0;
}
}
cout << "Yes" << endl;
return 0;
}
<file_sep>/abc143_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
using ll = long long;
int main() {
int N;
cin >> N;
vector<int> d(N);
for (int i = 0; i < N; ++i) {
cin >> d[i];
}
lli answer = 0;
for (lli i = 0; i < N; ++i) {
for (lli j = 0; j < N; ++j) {
answer += d[i] * d[j];
}
answer -= d[i] * d[i];
}
cout << answer / 2 << endl;
return 0;
}
<file_sep>/abc133_d.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc133_d() {
lli N;
cin >> N;
vector<lli> A(N);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
vector<lli> X(N);
X[0] = 0;
for (int i = 0; i < N; ++i) {
X[0] += A[i];
if (i % 2 != 0) {
X[0] -= 2 * A[i];
}
}
for (int i = 1; i < N; ++i) {
X[i] = 2 * A[i - 1] - X[i - 1];
}
for (int i = 0; i < N; ++i) {
cout << X[i] << " ";
}
cout << endl;
return 0;
}
<file_sep>/abc116_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc116_a() {
vector<int> R(3);
cin >> R[0] >> R[1] >> R[2];
sort(R.begin(), R.end());
cout << R[0] * R[1] / 2 << endl;
}<file_sep>/abc128_c.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
string binary(lli bina){
lli ans = 0;
for (lli i = 0; bina>0 ; i++)
{
ans = ans+(bina%2)*pow(10,i);
bina = bina/2;
}
return to_string(ans);
}
int abc128_c() {
int N, M;
cin >> N >> M;
vector<int> kVec;
vector<vector<int >> sVec;
vector<int> pVec;
for (int i = 0; i < M; ++i) {
int k;
cin >> k;
kVec.push_back(k);
vector<int > sVecRow;
for (int j = 0; j < k; ++j) {
int s;
cin >> s;
sVecRow.push_back(s);
}
sVec.push_back(sVecRow);
}
for (int i = 0; i < M; ++i) {
int p;
cin >> p;
pVec.push_back(p);
}
// スイッチの状態に合わせて回す
int result = 0;
lli count = (lli)pow(2.0, N);
for (lli i = 0; i < count; ++i) {
string nishin = binary(i);
lli length = (lli)nishin.length();
for (int j = 0; j < N - length; ++j) {
nishin = "0" + nishin;
}
vector<bool> swVec;
length = (lli)nishin.length();
for (lli j = 0; j < length; ++j) {
string are = nishin.substr(length - j - 1, 1);
if (are == "1") {
swVec.push_back(true);
} else {
swVec.push_back(false);
}
}
bool isLight = true;
for (lli j = 0; j <M ; ++j) {
int k = kVec[j];
vector<int> vecvec = sVec[j];
int counter = 0;
for (int l = 0; l < k; ++l) {
int index = vecvec[l];
bool isOn = swVec[index - 1];
if (isOn) {
++counter;
}
}
int p = pVec[j];
if (counter % 2 == p) {
// ついた
} else {
isLight = false;
break;
}
}
if (isLight) {
++result;
}
}
cout << result << endl;
return 0;
}<file_sep>/abc104_b.cpp
#include <iostream>
#include <math.h>
#include <vector>
#include <numeric>
using namespace std;
string replaceOtherStr(string &replacedStr, string from, string to) {
const unsigned int pos = replacedStr.find(from);
const int len = from.length();
if (pos == string::npos || from.empty()) {
return replacedStr;
}
return replacedStr.replace(pos, len, to);
}
int abc104_b() {
string S;
cin >> S;
// 先頭が大文字のA
if (S.substr(0, 1) != "A") {
cout << "WA" << endl;
return 0;
}
// 先頭から3文字と末尾から2文字の間にCが一個
int counter = 0;
for (int i = 2; i < S.size() - 1; ++i) {
if (S.substr(i, 1) == "C") {
++counter;
}
}
if (counter != 1) {
cout << "WA" << endl;
return 0;
}
// 全部小文字であることを判定
// 大文字を小文字に置換
S = replaceOtherStr(S, "A", "a");
S = replaceOtherStr(S, "C", "c");
for (int i = 0; i < S.size(); ++i) {
char c = S[i];
if (isupper(c)) {
cout << "WA" << endl;
return 0;
}
}
cout << "AC" << endl;
return 0;
}<file_sep>/abc113_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc113_a() {
int X, Y;
cin >> X >> Y;
cout << X + Y / 2 << endl;
}<file_sep>/wip_abc104_c.cpp
#include <iostream>
#include <math.h>
#include <vector>
#include <numeric>
using namespace std;
int wip_abc104_c() {
int D, G;
cin >> D >> G;
vector<int> P(D);
vector<int> C(D);
for (int i = 0; i < D; ++i) {
cin >> P[i];
cin >> C[i];
}
return 0;
}<file_sep>/abc105_b.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
using namespace std;
int abc105_b() {
int N;
cin >> N;
for (int i = 0; i < 100 / 7; ++i) {
for (int j = 0; j < 100 / 4; ++j) {
if (4 * i + 7 * j == N) {
cout << "Yes" << endl;
return 0;
}
}
}
cout << "No" << endl;
}<file_sep>/abc140_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
#include <map>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using lli = long long int;
using ll = long long;
int main() {
lli N;
cin >> N;
vector<lli> A(N);
vector<lli> B(N);
vector<lli> C(N-1);
for (lli i = 0; i < N; ++i) {
cin >> A[i];
}
for (lli i = 0; i < N; ++i) {
cin >> B[i];
}
for (lli i = 0; i < N - 1; ++i) {
cin >> C[i];
}
lli result = 0;
for (lli i = 0; i < N; ++i) {
lli index = A[i];
result += B[index - 1];
if (i != N - 1 && A[i] + 1 == A[i + 1]) {
result += C[index - 1];
}
}
cout << result << endl;
}
<file_sep>/abc100_c.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
using namespace std;
int abc100_c() {
int N;
cin >> N;
vector<int> a(N);
for (int i = 0; i < N; ++i) {
cin >> a[i];
}
vector<int> counter(N);
for (int i = 0; i < N; ++i) {
int num = a[i];
int count = 0;
do {
if (num % 2 != 0) {
break;
}
num = num / 2;
++count;
} while (true);
counter[i] = count;
}
cout << accumulate(counter.begin(), counter.end(), 0) << endl;
return 0;
}
<file_sep>/abc117_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int abc117_a() {
double T, X;
cin >> T;
cin >> X;
cout << T/ X << endl;
}<file_sep>/wip_abc101_c .cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
using namespace std;
// 参考 https://misteer.hatenablog.com/entry/ARC099#C---Minimization-%E6%9C%80%E5%B0%8F%E5%8C%96
//int main() {
//
// // わからんー
// int N, K;
// cin >> N >> K;
// int ans = (N - 2) / (K - 1) + 1;
// cout << ans << endl;
// return 0;
//}<file_sep>/abc055_b.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int num = 1000000007;
int abc055_b() {
int N;
cin >> N;
long long power = 1;
for (int i = 1; i <= N; ++i) {
power = power * i;
power = power % num;
}
cout << power;
}
<file_sep>/abc046_b.cpp
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
int abc046_b() {
int N, K;
cin >> N >> K;
long long answer;
answer = K * pow(K - 1, N - 1);
cout << answer;
}
<file_sep>/abc107_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
using namespace std;
int abc107_a() {
int N, i;
cin >> N >> i;
cout << N - i + 1 << endl;
}<file_sep>/abc122_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
#include <sstream>
using namespace std;
int abc122_a() {
string b;
cin >> b;
if (b == "A") {
cout << "T" << endl;
} else if (b == "T") {
cout << "A" << endl;
} else if (b == "C") {
cout << "G" << endl;
} else if (b == "G") {
cout << "C" << endl;
}
}<file_sep>/abc123_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
#include <algorithm>
#include <sstream>
using namespace std;
int abc123_a() {
int a, b, c, d, e, k;
cin >> a >> b >> c >> d >> e >> k;
bool flag = true;
if (abs(a - b) > k) {
flag = false;
}
if (abs(a - c) > k) {
flag = false;
}
if (abs(a - d) > k) {
flag = false;
}
if (abs(a - e) > k) {
flag = false;
}
if (abs(b - c) > k) {
flag = false;
}
if (abs(b - d) > k) {
flag = false;
}
if (abs(b - e) > k) {
flag = false;
}
if (abs(c - d) > k) {
flag = false;
}
if (abs(c - e) > k) {
flag = false;
}
if (abs(d - e) > k) {
flag = false;
}
if (flag) {
cout << "Yay!" << endl;
} else {
cout << ":(" << endl;
}
}<file_sep>/abc114_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
using namespace std;
using lli = long long int;
int abc114_b() {
string S;
cin >> S;
vector<int> nums;
for (int i = 0; i < S.size() - 2; ++i) {
string str = S.substr(i, 3);
int num = atoi(str.c_str());
nums.push_back(abs(753 - num));
}
int min = *std::min_element(nums.begin(), nums.end());
cout << min << endl;
}<file_sep>/aoj_ALDS1_3_B.cpp
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_B&lang=jp
// キュー
struct Process {
string name;
int time;
};
class Queue {
private:
int MAX;
int head;
int tail;
Process Q[100];
public:
void initialize(int size) {
head = tail = 0;
MAX = size;
}
bool isEmpty() {
return head == tail;
}
bool isFull() {
return head == (tail + 1) % MAX;
}
void enqueue(Process x) {
if (isFull()) {
throw ("オーバーフロー");
}
Q[tail] = x;
if (tail + 1 == MAX) {
tail = 0;
} else {
++tail;
}
}
Process dequeue() {
if (isEmpty()) {
throw ("アンダーフロー");
}
Process x = Q[head];
if (head + 1 == MAX) {
head = 0;
} else {
++head;
}
return x;
}
};
int wip_aoj_ALDS1_3_B() {
int n, q;
cin >> n >> q;
vector<Process> processList;
for (int i = 0; i < n; ++i) {
string name;
cin >> name;
int time;
cin >> time;
processList.push_back({name, time});
}
Queue queue;
queue.initialize((int) processList.size());
for (Process process : processList) {
queue.enqueue(process);
}
do {
int quantum = n;
do {
Process process = queue.dequeue();
if (process.time > quantum) {
queue.enqueue({process.name, process.time - quantum});
} else {
quantum -= process.time;
cout << process.name << ' ' << process.time << endl;
}
} while (quantum != 0);
} while (!queue.isEmpty());
return 0;
}
<file_sep>/abc102_a.cpp
#include <iostream>
#include<math.h>
#include <vector>
#include <numeric>
using namespace std;
int abc102_a() {
int N;
cin >> N;
if (N % 2 == 0) {
cout << N << endl;
} else {
cout << N * 2 << endl;
}
}<file_sep>/abc146_b.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>
#include <map>
using namespace std;
using lli = long long int;
using ll = long long;
int main() {
int N;
string S;
cin >> N >> S;
for(int i = 0 ; i < S.length() ; i++) {
int x = S[i] - 'A';
x = (x + N) % 26;
S[i] = x + 'A';
}
cout << S << endl;
}
|
f8f9eea9e866c9f0c67832380e4c7abd1108f640
|
[
"CMake",
"C++"
] | 94
|
C++
|
takoikatakotako/atcoder
|
2dc80f365f9f26b9488dc79ca9d857b7e285dffe
|
a3c7f2ad151645542a901208cf77272015fa3156
|
refs/heads/master
|
<repo_name>femichel/Demo-1<file_sep>/demo.py
def sum(a, b):
return (a+b)
print(sum(5,2))
def div(a, b):
return (a/b)
print(div(8,4))
|
dc10696568c21e9c5ce8934b27fdb4d690120856
|
[
"Python"
] | 1
|
Python
|
femichel/Demo-1
|
709a9013a859d5a73c2dac87eb00ef2f8e81596d
|
47fb2d44d4246cac11f605cfe92df7608334a9a7
|
refs/heads/master
|
<file_sep>package com.example.ThymeleafProject.service;
import com.example.ThymeleafProject.LekarzController;
import com.example.ThymeleafProject.TestController;
import com.example.ThymeleafProject.model.SkierowanieDoLekarza;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class LekarzService {
private Map<Integer, SkierowanieDoLekarza> skierowanieDoLekarzaMap = new HashMap<>();
public SkierowanieDoLekarza createSkierowanieDoLekarza(String lekarz, String pacjent, Date termin) {
int iD = new Random().nextInt();
SkierowanieDoLekarza skierowanieDoLekarza = new SkierowanieDoLekarza(iD, lekarz, pacjent, termin);
skierowanieDoLekarzaMap.put(iD, skierowanieDoLekarza);
return skierowanieDoLekarza;
}
public void deleteSkierowanieDoLekarza(int iD) {
skierowanieDoLekarzaMap.remove(iD);
}
public Collection<SkierowanieDoLekarza> listSkierowaniaDoLekarza() {
return skierowanieDoLekarzaMap.values();
}
public SkierowanieDoLekarza getSkierowanieDoLekarza(int iD) {
if (skierowanieDoLekarzaMap.get(iD) == null) {
throw new LekarzController.NotFoundException();
}
return skierowanieDoLekarzaMap.get(iD);
}
public SkierowanieDoLekarza updateSkierowanie (SkierowanieDoLekarza skierowanieDoLekarza) {
SkierowanieDoLekarza existing = getSkierowanieDoLekarza(skierowanieDoLekarza.getiD());
existing.setLekarz(skierowanieDoLekarza.getLekarz());
existing.setPacjent(skierowanieDoLekarza.getPacjent());
existing.setTermin(skierowanieDoLekarza.getTermin());
skierowanieDoLekarzaMap.put(existing.getiD(),existing);
return existing;
}
}
<file_sep>rootProject.name = 'ThymeleafProject'
|
e6cf575c6de21dd0c6e28b4b9dcfd7102445baec
|
[
"Java",
"Gradle"
] | 2
|
Java
|
vexai/ThymeleafProject
|
83816b51a76783a038731439b9a80e418eac2111
|
5b915df69b4c3b743bbfdf598ee8293ca479f877
|
refs/heads/master
|
<file_sep><?php
// your app consumer key
define( 'CONSUMER_KEY', 'ZFd8OJPABFEg9fDw6FPbvtLXY');
// your app consumer secret
define( 'CONSUMER_SECRET', '<KEY>');
// your app callback url
define( 'OAUTH_CALLBACK', 'http://localhost/Saran/login_fb_twitter/index.php' );
<file_sep><?php
// using sessions to store token info
session_start();
// require config and twitter helper
require 'config.php';
require 'twitter-login-php/autoload.php';
// use our twitter helper
use Abraham\TwitterOAuth\TwitterOAuth;
if ( isset( $_SESSION['twitter_access_token'] ) && $_SESSION['twitter_access_token'] ) { // we have an access token
$isLoggedIn = true;
} elseif ( isset( $_GET['oauth_verifier'] ) && isset( $_GET['oauth_token'] ) && isset( $_SESSION['oauth_token'] ) && $_GET['oauth_token'] == $_SESSION['oauth_token'] ) { // coming from twitter callback url
// setup connection to twitter with request token
$connection = new TwitterOAuth( CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret'] );
// get an access token
$access_token = $connection->oauth( "oauth/access_token", array( "oauth_verifier" => $_GET['oauth_verifier'] ) );
// save access token to the session
$_SESSION['twitter_access_token'] = $access_token;
// user is logged in
$isLoggedIn = true;
} else { // not authorized with our app, show login button
// connect to twitter with our app creds
$connection = new TwitterOAuth( CONSUMER_KEY, CONSUMER_SECRET );
// get a request token from twitter
$request_token = $connection->oauth( 'oauth/request_token', array( 'oauth_callback' => OAUTH_CALLBACK ) );
// save twitter token info to the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// user is logged in
$isLoggedIn = false;
}
if ( $isLoggedIn ) { // logged in
// get token info from session
$oauthToken = $_SESSION['twitter_access_token']['oauth_token'];
$oauthTokenSecret = $_SESSION['twitter_access_token']['oauth_token_secret'];
// setup connection
$connection = new TwitterOAuth( CONSUMER_KEY, CONSUMER_SECRET, $oauthToken, $oauthTokenSecret );
// user twitter connection to get user info
$user = $connection->get( "account/verify_credentials", ['include_email' => 'true'] );
if ( property_exists( $user, 'errors' ) ) { // errors, clear session so user has to re-authorize with our app
$_SESSION = array();
header( 'Refresh:0' );
} else { // display user info in browser
?>
<img src="<?php echo $user->profile_image_url; ?>" />
<br />
<b>User:</b> <?php echo $user->name; ?>
<br />
<b>Location:</b> <?php echo $user->location; ?>
<br />
<b>Twitter Handle:</b> <?php echo $user->screen_name; ?>
<br />
<b>Description:</b> <?php echo $user->description; ?>
<br />
<b>User Created:</b> <?php echo $user->created_at; ?>
<br />
<hr />
<br />
<a href="logout.php">Logout</a>
<?php
}
} else {
$url = $connection->url( 'oauth/authorize', array( 'oauth_token' => $request_token['oauth_token'] ) );
?>
<!DOCTYPE html >
<html lang="en" itemscope itemtype="http://schema.org/Article">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LOGIN</title>
<script src="https://apis.google.com/js/client:platform.js?onload=renderButton" async defer></script>
<meta name="google-signin-client_id" content="390553438912-upsil31oeko7edibicf9uoos1rkissvg.apps.googleusercontent.com">
<link href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
// Render Google Sign-in button
function renderButton() {
gapi.signin2.render('gSignIn', {
'scope': 'profile email',
'display':'none',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSuccess,
'onfailure': onFailure
});
}
// Sign-in success callback
function onSuccess(googleUser) {
// Get the Google profile data (basic)
//var profile = googleUser.getBasicProfile();
// Retrieve the Google account data
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get({
'userId': 'me'
});
request.execute(function (resp) {
// Display the user details
var profileHTML = '<h3>Welcome '+resp.given_name+'! <a href="javascript:void(0);" onclick="signOut();">Sign out</a></h3>';
profileHTML += '<img src="'+resp.picture+'"/><p><b>Google ID: </b>'+resp.id+'</p><p><b>Name: </b>'+resp.name+'</p><p><b>Email: </b>'+resp.email+'</p><p><b>Gender: </b>'+resp.gender+'</p><p><b>Locale: </b>'+resp.locale+'</p><p><b>Google Profile:</b> <a target="_blank" href="'+resp.link+'">click to view profile</a></p>';
document.getElementsByClassName("userContent")[0].innerHTML = profileHTML;
document.getElementById("gSignIn").style.display = "none";
document.getElementsByClassName("userContent")[0].style.display = "block";
});
});
}
// Sign-in failure callback
function onFailure(error) {
alert(error);
}
// Sign out the user
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
document.getElementsByClassName("userContent")[0].innerHTML = '';
document.getElementsByClassName("userContent")[0].style.display = "none";
document.getElementById("gSignIn").style.display = "block";
});
auth2.disconnect();
}
</script>
<style type="text/css">
.continer{padding: 20px;}
.userContent{
padding: 10px 20px;
margin: auto;
width: 350px;
background-color: #f7f7f7;
box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),
0 2px 10px 0 rgba(0, 0, 0, 0.12);
}
.userContent h3{font-size: 17px;}
.userContent p{font-size: 15px;}
.userContent img{max-width: 100%;margin-bottom: 5px;}
.login-form {
width: 340px;
margin: 30px auto;
}
.login-form form {
margin-bottom: 15px;
background: #f7f7f7;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
padding: 30px;
}
.login-form h2 {
margin: 0 0 15px;
}
.login-form .hint-text {
color: #777;
padding-bottom: 15px;
text-align: center;
}
.form-control, .btn {
min-height: 38px;
border-radius: 2px;
}
.login-btn {
font-size: 15px;
font-weight: bold;
}
.or-seperator {
margin: 20px 0 10px;
text-align: center;
border-top: 1px solid #ccc;
}
.or-seperator i {
padding: 0 10px;
background: #f7f7f7;
position: relative;
top: -11px;
z-index: 1;
}
.social-btn .btn {
margin: 10px 0;
font-size: 15px;
text-align: left;
line-height: 24px;
}
.social-btn .btn i {
float: left;
margin: 4px 15px 0 5px;
min-width: 15px;
}
.input-group-addon .fa{
font-size: 18px;
}
</style>
</head>
<body style="background-color:black">
<div class="login-form">
<form method="post">
<h2 class="text-center">Sign in</h2>
<div class="text-center social-btn">
<a href="javascript:void(0);" onclick="fbLogin()" id="fbLink" class="btn btn-primary btn-block"><i class="fa fa-facebook"></i> Sign in with <b>Facebook</b></a>
<a href="<?php echo $url; ?>" class="btn btn-info btn-block"><i class="fa fa-twitter"></i> Sign in with <b>Twitter</b></a>
<div id="gSignIn"></div>
</div>
<div class="or-seperator"><i>or</i></div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input type="email" class="form-control" name="email" placeholder="Email" required="required">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock"></i></span>
<input type="password" class="form-control" name="password" placeholder="<PASSWORD>" required="required">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-block login-btn">Sign in</button>
</div>
<div class="clearfix">
<label class="pull-left checkbox-inline"><input type="checkbox"> Remember me</label>
<a href="#" class="pull-right text-success">Forgot Password?</a>
</div>
</form>
<div class="hint-text small">Don't have an account? <a href="#" class="text-success">Register Now!</a></div>
</div>
<div class="userContent" style="display: none;"></div>
<div id="status"></div>
<div id="userData"></div>
</body>
<script>
window.fbAsyncInit = function() {
// FB JavaScript SDK configuration and setup
FB.init({
appId : '2282546262028402', // FB App ID
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v2.8' // use graph api version 2.8
});
// Check whether the user already logged in
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//display user data
getFbUserData();
}
});
};
// Load the JavaScript SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Facebook login with JavaScript SDK
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
} else {
document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
}
}, {scope: 'email'});
}
// Fetch the user profile data from facebook
function getFbUserData(){
FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture'},
function (response) {
document.getElementById('fbLink').setAttribute("onclick","fbLogout()");
document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
document.getElementById('userData').innerHTML = '<p><b>FB ID:</b> '+response.id+'</p><p><b>Name:</b> '+response.first_name+' '+response.last_name+'</p><p><b>Email:</b> '+response.email+'</p><p><b>Gender:</b> '+response.gender+'</p><p><b>Locale:</b> '+response.locale+'</p><p><b>Picture:</b> <img src="'+response.picture.data.url+'"/></p><p><b>FB Profile:</b> <a target="_blank" href="'+response.link+'">click to view profile</a></p>';
});
}
// Logout from facebook
function fbLogout() {
FB.logout(function() {
document.getElementById('fbLink').setAttribute("onclick","fbLogin()");
document.getElementById('fbLink').innerHTML = 'sign in with Facebook';
document.getElementById('userData').innerHTML = '';
document.getElementById('status').innerHTML = 'You have successfully logout from Facebook.';
});
}
</script>
</html>
<?php
}?>
|
419810033c8c9916e92e657102834be72bbfcbdd
|
[
"PHP"
] | 2
|
PHP
|
Arunodhaya/SocialLogin
|
9b5b714bb149c0e367b1db7f76a68c3ac4d5a1dc
|
2b0a04b14756b596df2dce6904b86479dd6832d5
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
namespace poco
{
class HandleInput
{
public static void main()
{
checkModifiers();
if (specialKeys() == true) return;
if (arrowKeys() == true) return;
if (Program.control != true && Program.alt != true)
{
if (Program.cursorx >= Program.width)
{
ConsoleFuncs.writeAt(Program.key.ToString(), 0, Program.cursory+1);
Program.cursorx = 1;
Program.cursory++;
Program.globalCursorX++;
} else
{
ConsoleFuncs.writeAt(Program.key.ToString(), Program.cursorx, Program.cursory);
Program.cursorx++;
Program.globalCursorX++;
}
if(Program.key.ToString() != "~")
{
Program.currentFileData += Program.key.ToString();
} else
{
Program.currentFileData += "!~";
}
} else if (Program.control == true)
{
if(Program.cki.Key == ConsoleKey.S)
{
//Console.WriteLine("save");
Files.saveFile(Program.currentPath);
}
}
}
/*
only spaghetti below here
and above here
*/
private static void checkModifiers()
{
if ((Program.cki.Modifiers & ConsoleModifiers.Alt) != 0)
{
Program.alt = true;
}
else
{
Program.alt = false;
}
if ((Program.cki.Modifiers & ConsoleModifiers.Shift) != 0)
{
Program.shift = true;
}
else
{
Program.shift = false;
}
if ((Program.cki.Modifiers & ConsoleModifiers.Control) != 0)
{
Program.control = true;
}
else
{
Program.control = false;
}
}
private static bool specialKeys()
{
if (Program.keyInfo.Key == ConsoleKey.Backspace && Program.cursorx != 0)
{
try
{
ConsoleFuncs.writeAt(" ", Program.cursorx - 1, Program.cursory);
Program.cursorx -= 1;
Program.globalCursorX -= 1;
Console.SetCursorPosition(Program.cursorx, Program.cursory);
string[] lines = Program.currentFileData.Split("~\n");
char[] chars = lines[Program.globalCursorY].ToCharArray();
// have to do this because just setting it to an empty string doesnt work
var foos = new List<char>(chars);
foos.RemoveAt((int)(Program.globalCursorX));
chars = foos.ToArray();
var concatChars = string.Join("", chars);
lines[Program.globalCursorY] = concatChars;
Program.currentFileData = string.Join("~\n", lines);
return true;
} catch {
Program.cursorx -= 1;
Program.globalCursorX -= 1;
return true;
}
}
else if (Program.keyInfo.Key == ConsoleKey.Backspace && Program.globalCursorX == 0 && Program.globalCursorY != 0)
{
/*try
{
ConsoleFuncs.writeAt(" ", Program.cursorx, Program.cursory + 1);
Program.cursory -= 1;
Program.globalCursorY -= 1;
return true;
} catch { return true; }*/
return true;
} else if (Program.keyInfo.Key == ConsoleKey.Backspace && Program.globalCursorX == 0 && Program.globalCursorY == 0)
{
return true;
}
else if (Program.keyInfo.Key == ConsoleKey.Enter)
{
ConsoleFuncs.writeAt("\n", Program.cursorx, Program.cursory);
Program.cursorx = 0;
Program.globalCursorX = 0;
Program.cursory += 1;
Program.globalCursorY += 1;
Program.currentFileData += "~\n";
return true;
}
return false;
}
private static bool arrowKeys()
{
if (Program.keyInfo.Key == ConsoleKey.LeftArrow)
{
if (Program.cursorx == 0) { }
else
{
Console.SetCursorPosition(Program.cursorx - 1, Program.cursory);
Program.cursorx--;
Program.globalCursorX--;
}
return true;
}
else if (Program.keyInfo.Key == ConsoleKey.DownArrow)
{
if (Program.globalCursorY + 1 >= Program.height - 3) return true;
if (Program.globalCursorY == Program.height - 1) { }
else
{
string[] lines = Program.currentFileData.Split("~\n");
Console.SetCursorPosition(Program.cursorx, Program.cursory + 1);
Program.cursory++;
Program.globalCursorY++;
var len = lines[Program.globalCursorY].Length;
if (len >= Program.globalCursorX) return true;
Program.cursorx = (ushort)len;
Program.globalCursorX = (ushort)len;
Console.SetCursorPosition(Program.cursorx, Program.cursory);
}
return true;
}
else if (Program.keyInfo.Key == ConsoleKey.UpArrow)
{
if (Program.globalCursorY == 0) { }
else
{
string[] lines = Program.currentFileData.Split("~\n");
Console.SetCursorPosition(Program.cursorx, Program.cursory - 1);
Program.cursory--;
Program.globalCursorY--;
var len = lines[Program.globalCursorY].Length;
if (len >= Program.globalCursorX) return true;
Program.cursorx = (ushort)len;
Program.globalCursorX = (ushort)len;
Console.SetCursorPosition(Program.cursorx, Program.cursory);
}
return true;
}
else if (Program.keyInfo.Key == ConsoleKey.RightArrow)
{
string[] lines = Program.currentFileData.Split("~\n");
if (Program.globalCursorX >= lines[Program.globalCursorY].Length) return true;
if (Program.cursorx == Program.width - 1) { }
else
{
Console.SetCursorPosition(Program.cursorx + 1, Program.cursory);
Program.cursorx++;
Program.globalCursorX++;
}
return true;
}
return false;
}
}
}
<file_sep>namespace poco
{
class Functions
{
public static string[] stringArrayPush(string[] array, string data)
{
System.Array.Resize(ref array, array.Length + 1);
array[array.GetUpperBound(0)] = data;
return array;
}
}
}
<file_sep>using System;
using System.Threading;
namespace poco
{
class Program
{
//so many public static's jesus christ
public static bool alt = false;
public static bool shift = false;
public static bool control = false;
/*
mode: 0 = type
mode: 1 = normal
*/
//public static byte mode = 1;
public static bool toQuit = false;
public static ushort width;
public static ushort height;
public static ushort cursorx = 0;
public static ushort cursory = 0;
public static uint globalCursorX = 0;
public static uint globalCursorY = 0;
public static char key;
public static ConsoleKeyInfo cki = new ConsoleKeyInfo();
public static ConsoleKeyInfo keyInfo;
public static string currentFileData;
public static string currentPath;
static void Main(string[] args)
{
System.Console.Clear();
width = (ushort)Console.WindowWidth;
height = (ushort)Console.WindowHeight;
try
{
Files.loadFile(args[0]);
currentPath = args[0];
} catch (Exception e){
try {
currentPath = args[0];
} catch { }
}
//ConsoleFuncs.writeAtColor("hi", 0, 0, ConsoleColor.Red, ConsoleColor.Blue);
//ConsoleFuncs.writeAtColor("hi2", 0, 1, ConsoleColor.DarkYellow, ConsoleColor.Magenta);
//ConsoleFuncs.writeAtColor(" ", 0, 0, ConsoleColor.White, ConsoleColor.White);
do
{
while (Console.KeyAvailable == false)
Thread.Sleep(10); // Loop until input is entered.
cki = Console.ReadKey(true);
width = (ushort)Console.WindowWidth;
height = (ushort)Console.WindowHeight;
keyInfo = cki;
key = keyInfo.KeyChar;
HandleInput.main();
} while (toQuit == false);
}
}
}<file_sep>using System;
namespace poco
{
class ConsoleFuncs
{
public static void writeAt(string s, int x, int y)
{
try
{
Console.SetCursorPosition(x, y);
Console.Write(s);
}
catch (ArgumentOutOfRangeException e)
{
Console.Clear();
Console.WriteLine(e.Message);
}
}
public static void writeAtColor(string s, int x, int y, ConsoleColor fore, ConsoleColor back)
{
try
{
Console.SetCursorPosition(x, y);
Console.ForegroundColor = fore;
Console.BackgroundColor = back;
Console.Write(s);
Console.ResetColor();
}
catch (ArgumentOutOfRangeException e)
{
Console.Clear();
Console.WriteLine(e.Message);
}
}
public static void writeLine(string line, ushort y)
{
ushort currentX = 0;
char[] charArr = line.ToCharArray();
foreach (char ch in charArr)
{
if(currentX < Program.width)
{
ConsoleFuncs.writeAt(ch.ToString(), currentX, y);
currentX++;
} else if(y < Program.height)
{
currentX = 0;
y++;
ConsoleFuncs.writeAt(ch.ToString(), currentX, y);
currentX++;
}
}
}
}
}<file_sep>using System.IO;
using System.Threading.Tasks;
namespace poco
{
class Files
{
public static string[] readFile(string path)
{
System.IO.StreamReader file = new System.IO.StreamReader(path);
int counter = 0;
string line;
string[] fileLines = {};
while ((line = file.ReadLine()) != null)
{
fileLines = Functions.stringArrayPush(fileLines, line);
counter++;
}
file.Close();
Program.currentFileData = string.Join("\n", fileLines);
return fileLines;
}
public static void loadFile(string path)
{
System.Console.Clear();
readFile(path);
System.Console.Write(Program.currentFileData);
}
public static async void saveFile(string path)
{
string[] lines = Program.currentFileData.Split("~\n");
var i = 0;
foreach(string line in lines)
{
lines[i] = line.Replace("!~", "~");
i++;
}
try
{
System.IO.File.Delete(path);
} catch { File.Create(path); }
await File.WriteAllLinesAsync(path, lines);
}
}
}
|
a370a194b24ff6d99e15f640f1626ab0d86233e2
|
[
"C#"
] | 5
|
C#
|
lillyliv/pocoEditor
|
8e44bad60f0343be4c0372445f065425bc88a7a8
|
9e292567d8c74792be4a4085733fb56e8432dc81
|
refs/heads/master
|
<repo_name>DelNaga/ABSA_Assessment<file_sep>/ABSA_Assessment/Models/Client.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace ABSA_Assessment.Models
{
public class Client
{
[Key]
public int ClientId { get; set; }
public string Surname { get; set; }
public string FirstName { get; set; }
public int IdentificationId { get; set; }
//To avoid eager loading of the identification type model with each client.
public virtual Identification IdentificationType { get; set; }
public string IdNumber { get; set; }
//Date remains local, as DOB is not subject to UTC corrections.
public DateTime DateOfBirth { get; set; }
}
}<file_sep>/ABSA_Assessment/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ABSA_Assessment.Context;
using ABSA_Assessment.Models;
using System.Net;
namespace ABSA_Assessment.Controllers
{
public class HomeController : Controller
{
private ABSA_DbContext mDataContext;
public HomeController()
{
mDataContext = new ABSA_DbContext();
}
public ActionResult Index()
{
ViewBag.Title = "View/Edit Client";
return View();
}
public ActionResult GetClient()
{
return Json(mDataContext.Clients.Select(x => new { x.ClientId, x.FirstName, x.Surname, x.IdentificationId, x.IdNumber, x.DateOfBirth }).FirstOrDefault(), JsonRequestBehavior.AllowGet);
}
public ActionResult GetIdentificationTypes()
{
return Json(mDataContext.IdentificationTypes.Select(x => new { x.IdentificationId, x.IdentificationDescription }).ToList(), JsonRequestBehavior.AllowGet);
}
public ActionResult SetClient(Client updatedClient)
{
var originalClient = mDataContext.Clients.Find(updatedClient.ClientId);
if (originalClient != null)
{
originalClient.FirstName = updatedClient.FirstName;
originalClient.Surname = updatedClient.Surname;
originalClient.IdentificationId = updatedClient.IdentificationId;
originalClient.IdentificationType = mDataContext.IdentificationTypes.Find(updatedClient.IdentificationId);
originalClient.IdNumber = updatedClient.IdNumber;
originalClient.DateOfBirth = updatedClient.DateOfBirth;
mDataContext.SaveChanges();
}
return Json(updatedClient);
}
}
}<file_sep>/ABSA_Assessment/Scripts/Controllers/ClientController.js
/*var ClientController = function ($scope, ClientService) {
console.dir(ClientService);
$scope.models = {
apptitle: "View/Edit Client"
}
$scope.Client = null;*/
/*ClientService.GetClient().then(function (response) {
alert("this fires);
console.dir(response);
}, function () {
alert('this fails');
});*/
/*}
ClientController.$inject = ['$scope'];*/<file_sep>/ABSA_Assessment/Models/Identification.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace ABSA_Assessment.Models
{
public class Identification
{
[Key]
public int IdentificationId { get; set; }
public string IdentificationDescription { get; set; }
public virtual ICollection<Client> Clients { get; set; }
}
}<file_sep>/ABSA_Assessment/Models/ABSA_DbContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using ABSA_Assessment.Models;
namespace ABSA_Assessment.Context
{
public class ABSA_DbContext : DbContext
{
public ABSA_DbContext()
: base("name=ABSA_Assessment")
{ }
public DbSet<Client> Clients { get; set; }
public DbSet<Identification> IdentificationTypes { get; set; }
}
}
|
05e530af82c29429f4f49a06e92a1332bfb2213f
|
[
"JavaScript",
"C#"
] | 5
|
C#
|
DelNaga/ABSA_Assessment
|
df1307deaf80babf17e3b71db051fd7c07b51c69
|
6ee8298113b7ec4d7d453865c0f0162cd3683dd1
|
refs/heads/master
|
<file_sep>console.log("Hola mundo");
console.log("Subscribee al canal");
|
ebb9965912a23d78f008e7a52c64c2916b3b89d5
|
[
"JavaScript"
] | 1
|
JavaScript
|
cplusplus11v2/demo-repo2
|
03071fcd34ab0c76c076a42a31d469781d092f3c
|
c8f776731a31dfab4138824013ebebeeb8a856dd
|
refs/heads/master
|
<file_sep>export interface Server {
isOnline: boolean;
name: string;
gameName: string;
mapName: string;
numPlayers: number;
maxPlayers: number;
gameMode: string;
hasPassword: boolean;
hostIp: string;
hostPort: number;
queryPort: number;
isDedicated: boolean;
isRanked: boolean;
hasAntiCheat: boolean;
operatingSystem: string;
hasAutoRecord: boolean;
demoIndexUri: string;
hasVoip: boolean;
sponsorText: string;
communityLogoUri: string;
team1: string;
team2: string;
numBots: number;
mapSize: number;
hasGlobalUnlocks: boolean;
reservedSlots: number;
hasNoVehicles: boolean;
responseTime: number;
players: Player[];
}
export interface Team {
name: string;
score: number;
players: Player[];
}
export interface Player {
name: string;
pid: number;
team: number;
teamScore: number;
kills: number;
deaths: number;
totalScore: number;
ping: number;
isBot: boolean;
rank: number;
countryCode: string;
}
<file_sep># BF2ServerList
Experimenting with React and TypeScript. Bundling with webpack.
Demo: http://bf2.nihlen.net/servers
|
ad58afd1093b958cb79f4bb2454774c3a828948e
|
[
"Markdown",
"TypeScript"
] | 2
|
TypeScript
|
nihlen/BF2ServerList
|
77592fc340dffd32e174f29618d99acbbadddc50
|
583b9ac8680d3eafd95c5b4b9cb8fd5021674992
|
refs/heads/master
|
<file_sep>package DTPL.editor;
/*Generated by MPS */
import jetbrains.mps.nodeEditor.DefaultNodeEditor;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.openapi.editor.EditorContext;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.nodeEditor.cells.EditorCell_Constant;
import jetbrains.mps.nodeEditor.cellProviders.CellProviderWithRole;
import jetbrains.mps.lang.editor.cellProviders.RefCellCellProvider;
import jetbrains.mps.nodeEditor.EditorManager;
import jetbrains.mps.nodeEditor.InlineCellProvider;
import jetbrains.mps.lang.editor.cellProviders.PropertyCellProvider;
import jetbrains.mps.openapi.editor.style.Style;
import jetbrains.mps.editor.runtime.style.StyleImpl;
import jetbrains.mps.editor.runtime.style.StyleAttributes;
import java.awt.Color;
import jetbrains.mps.nodeEditor.cells.EditorCell_Indent;
import jetbrains.mps.openapi.editor.style.StyleRegistry;
import jetbrains.mps.nodeEditor.MPSColors;
public class InterfejsRefTokRefProcesRef_Editor extends DefaultNodeEditor {
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return this.createCollection_xwq4zb_a(editorContext, node);
}
private EditorCell createCollection_xwq4zb_a(EditorContext editorContext, SNode node) {
EditorCell_Collection editorCell = EditorCell_Collection.createIndent2(editorContext, node);
editorCell.setCellId("Collection_xwq4zb_a");
editorCell.setBig(true);
editorCell.addEditorCell(this.createConstant_xwq4zb_a0(editorContext, node));
editorCell.addEditorCell(this.createConstant_xwq4zb_b0(editorContext, node));
editorCell.addEditorCell(this.createRefCell_xwq4zb_c0(editorContext, node));
editorCell.addEditorCell(this.createConstant_xwq4zb_d0(editorContext, node));
editorCell.addEditorCell(this.createIndentCell_xwq4zb_e0(editorContext, node));
editorCell.addEditorCell(this.createConstant_xwq4zb_f0(editorContext, node));
editorCell.addEditorCell(this.createRefCell_xwq4zb_g0(editorContext, node));
editorCell.addEditorCell(this.createConstant_xwq4zb_h0(editorContext, node));
editorCell.addEditorCell(this.createIndentCell_xwq4zb_i0(editorContext, node));
editorCell.addEditorCell(this.createConstant_xwq4zb_j0(editorContext, node));
editorCell.addEditorCell(this.createRefCell_xwq4zb_k0(editorContext, node));
editorCell.addEditorCell(this.createConstant_xwq4zb_l0(editorContext, node));
return editorCell;
}
private EditorCell createConstant_xwq4zb_a0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "in:");
editorCell.setCellId("Constant_xwq4zb_a0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_xwq4zb_b0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "[");
editorCell.setCellId("Constant_xwq4zb_b0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefCell_xwq4zb_c0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new RefCellCellProvider(node, editorContext);
provider.setRole("interfejs_ref");
provider.setNoTargetText("<no interfejs_ref>");
EditorCell editorCell;
provider.setAuxiliaryCellProvider(new InterfejsRefTokRefProcesRef_Editor._Inline_xwq4zb_a2a());
editorCell = provider.createEditorCell(editorContext);
if (editorCell.getRole() == null) {
editorCell.setReferenceCell(true);
editorCell.setRole("interfejs_ref");
}
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
public static class _Inline_xwq4zb_a2a extends InlineCellProvider {
public _Inline_xwq4zb_a2a() {
super();
}
public EditorCell createEditorCell(EditorContext editorContext) {
return this.createEditorCell(editorContext, this.getSNode());
}
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return this.createProperty_xwq4zb_a0c0(editorContext, node);
}
private EditorCell createProperty_xwq4zb_a0c0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new PropertyCellProvider(node, editorContext);
provider.setRole("name");
provider.setNoTargetText("<no name>");
provider.setReadOnly(true);
EditorCell editorCell;
editorCell = provider.createEditorCell(editorContext);
editorCell.setCellId("property_name");
Style style = new StyleImpl();
style.set(StyleAttributes.BACKGROUND_COLOR, 0, (Color) null);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
}
private EditorCell createConstant_xwq4zb_d0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "]");
editorCell.setCellId("Constant_xwq4zb_d0");
Style style = new StyleImpl();
style.set(StyleAttributes.BACKGROUND_COLOR, 0, (Color) null);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createIndentCell_xwq4zb_e0(EditorContext editorContext, SNode node) {
EditorCell_Indent editorCell = new EditorCell_Indent(editorContext, node);
return editorCell;
}
private EditorCell createConstant_xwq4zb_f0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "-->");
editorCell.setCellId("Constant_xwq4zb_f0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, 0, StyleRegistry.getInstance().getSimpleColor(MPSColors.red));
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefCell_xwq4zb_g0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new RefCellCellProvider(node, editorContext);
provider.setRole("tok_podataka_ref");
provider.setNoTargetText("<no tok_podataka_ref>");
EditorCell editorCell;
provider.setAuxiliaryCellProvider(new InterfejsRefTokRefProcesRef_Editor._Inline_xwq4zb_a6a());
editorCell = provider.createEditorCell(editorContext);
if (editorCell.getRole() == null) {
editorCell.setReferenceCell(true);
editorCell.setRole("tok_podataka_ref");
}
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
public static class _Inline_xwq4zb_a6a extends InlineCellProvider {
public _Inline_xwq4zb_a6a() {
super();
}
public EditorCell createEditorCell(EditorContext editorContext) {
return this.createEditorCell(editorContext, this.getSNode());
}
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return this.createProperty_xwq4zb_a0g0(editorContext, node);
}
private EditorCell createProperty_xwq4zb_a0g0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new PropertyCellProvider(node, editorContext);
provider.setRole("name");
provider.setNoTargetText("<no name>");
provider.setReadOnly(true);
EditorCell editorCell;
editorCell = provider.createEditorCell(editorContext);
editorCell.setCellId("property_name_1");
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
}
private EditorCell createConstant_xwq4zb_h0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "-->");
editorCell.setCellId("Constant_xwq4zb_h0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, 0, StyleRegistry.getInstance().getSimpleColor(MPSColors.red));
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createIndentCell_xwq4zb_i0(EditorContext editorContext, SNode node) {
EditorCell_Indent editorCell = new EditorCell_Indent(editorContext, node);
return editorCell;
}
private EditorCell createConstant_xwq4zb_j0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "(");
editorCell.setCellId("Constant_xwq4zb_j0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, 0, StyleRegistry.getInstance().getSimpleColor(MPSColors.orange));
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefCell_xwq4zb_k0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new RefCellCellProvider(node, editorContext);
provider.setRole("proces_ref");
provider.setNoTargetText("<no proces_ref>");
EditorCell editorCell;
provider.setAuxiliaryCellProvider(new InterfejsRefTokRefProcesRef_Editor._Inline_xwq4zb_a01a());
editorCell = provider.createEditorCell(editorContext);
if (editorCell.getRole() == null) {
editorCell.setReferenceCell(true);
editorCell.setRole("proces_ref");
}
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, 0, StyleRegistry.getInstance().getSimpleColor(MPSColors.orange));
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
public static class _Inline_xwq4zb_a01a extends InlineCellProvider {
public _Inline_xwq4zb_a01a() {
super();
}
public EditorCell createEditorCell(EditorContext editorContext) {
return this.createEditorCell(editorContext, this.getSNode());
}
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return this.createProperty_xwq4zb_a0k0(editorContext, node);
}
private EditorCell createProperty_xwq4zb_a0k0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new PropertyCellProvider(node, editorContext);
provider.setRole("name");
provider.setNoTargetText("<no name>");
provider.setReadOnly(true);
EditorCell editorCell;
editorCell = provider.createEditorCell(editorContext);
editorCell.setCellId("property_name_2");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, 0, StyleRegistry.getInstance().getSimpleColor(MPSColors.orange));
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
}
private EditorCell createConstant_xwq4zb_l0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, ")");
editorCell.setCellId("Constant_xwq4zb_l0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, 0, StyleRegistry.getInstance().getSimpleColor(MPSColors.orange));
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
}
<file_sep>package DTPL.constraints;
/*Generated by MPS */
import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor;
import jetbrains.mps.smodel.adapter.ids.MetaIdFactory;
import java.util.Map;
import jetbrains.mps.smodel.adapter.ids.SReferenceLinkId;
import jetbrains.mps.smodel.runtime.ReferenceConstraintsDescriptor;
import java.util.HashMap;
import jetbrains.mps.smodel.runtime.base.BaseReferenceConstraintsDescriptor;
import org.jetbrains.annotations.Nullable;
import jetbrains.mps.smodel.runtime.ReferenceScopeProvider;
import jetbrains.mps.smodel.runtime.base.BaseScopeProvider;
import org.jetbrains.mps.openapi.model.SNodeReference;
import jetbrains.mps.scope.Scope;
import jetbrains.mps.smodel.IOperationContext;
import jetbrains.mps.smodel.runtime.ReferenceConstraintsContext;
import java.util.List;
import org.jetbrains.mps.openapi.model.SNode;
import java.util.ArrayList;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import jetbrains.mps.scope.ListScope;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.smodel.SNodePointer;
public class InterfejsRefTokRefProcesRef_Constraints extends BaseConstraintsDescriptor {
public InterfejsRefTokRefProcesRef_Constraints() {
super(MetaIdFactory.conceptId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd0306fd6L));
}
@Override
protected Map<SReferenceLinkId, ReferenceConstraintsDescriptor> getNotDefaultSReferenceLinks() {
Map<SReferenceLinkId, ReferenceConstraintsDescriptor> references = new HashMap<SReferenceLinkId, ReferenceConstraintsDescriptor>();
references.put(MetaIdFactory.refId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd0306fd6L, 0x2c5a37ebd0306fd7L), new BaseReferenceConstraintsDescriptor(MetaIdFactory.refId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd0306fd6L, 0x2c5a37ebd0306fd7L), this) {
@Override
public boolean hasOwnScopeProvider() {
return true;
}
@Nullable
@Override
public ReferenceScopeProvider getScopeProvider() {
return new BaseScopeProvider() {
@Override
public SNodeReference getSearchScopeValidatorNode() {
return breakingNode_mit8ze_a0a0a0a0a1a0b0a1a1;
}
@Override
public Scope createScope(final IOperationContext operationContext, final ReferenceConstraintsContext _context) {
{
List<SNode> nlist_interfejs = new ArrayList<SNode>();
SNode node_dk = SNodeOperations.getNodeAncestor(_context.getEnclosingNode(), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, "DTPL.structure.DijagramKonteksta"), false, false);
for (SNode node_dtpeitp : SLinkOperations.getChildren(node_dk, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, 0x2c5a37ebd02362caL, "dtp_element_interfejs_tok"))) {
SNode node_i = SLinkOperations.getTarget(node_dtpeitp, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02362c7L, 0x2c5a37ebd02362c8L, "interfejs"));
ListSequence.fromList(nlist_interfejs).addElement(node_i);
}
return new ListScope(nlist_interfejs) {
public String getName(SNode child) {
SNode node_i = (SNode) child;
return SPropertyOperations.getString(node_i, MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name"));
}
};
}
}
};
}
});
references.put(MetaIdFactory.refId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd0306fd6L, 0x2c5a37ebd0306fdbL), new BaseReferenceConstraintsDescriptor(MetaIdFactory.refId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd0306fd6L, 0x2c5a37ebd0306fdbL), this) {
@Override
public boolean hasOwnScopeProvider() {
return true;
}
@Nullable
@Override
public ReferenceScopeProvider getScopeProvider() {
return new BaseScopeProvider() {
@Override
public SNodeReference getSearchScopeValidatorNode() {
return breakingNode_mit8ze_a0a0a0a0a1a0b0a2a1;
}
@Override
public Scope createScope(final IOperationContext operationContext, final ReferenceConstraintsContext _context) {
{
List<SNode> nlist_tok_podatak = new ArrayList<SNode>();
if ((SLinkOperations.getTarget(_context.getReferenceNode(), MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd0306fd6L, 0x2c5a37ebd0306fd7L, "interfejs_ref")) != null)) {
SNode node_i = SLinkOperations.getTarget(_context.getReferenceNode(), MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd0306fd6L, 0x2c5a37ebd0306fd7L, "interfejs_ref"));
// dijagram konteksat
SNode node_dk = SNodeOperations.getNodeAncestor(_context.getEnclosingNode(), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, "DTPL.structure.DijagramKonteksta"), false, false);
for (SNode node_dtpeitp : SLinkOperations.getChildren(node_dk, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, 0x2c5a37ebd02362caL, "dtp_element_interfejs_tok"))) {
SNode node_i_i = SLinkOperations.getTarget(node_dtpeitp, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02362c7L, 0x2c5a37ebd02362c8L, "interfejs"));
if (SPropertyOperations.getString(node_i_i, MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name")).equals(SPropertyOperations.getString(node_i, MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name")))) {
// uzmi njegove tokove
for (SNode node_itp : SLinkOperations.getChildren(node_dtpeitp, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02362c7L, 0x2c5a37ebd023c537L, "in_interfejs_tok_podataka_proces"))) {
ListSequence.fromList(nlist_tok_podatak).addElement(SLinkOperations.getTarget(node_itp, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02379c3L, 0x2c5a37ebd023c4e4L, "tok_podatak")));
}
}
}
}
return new ListScope(nlist_tok_podatak) {
public String getName(SNode child) {
SNode node_i = (SNode) child;
return SPropertyOperations.getString(node_i, MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name"));
}
};
}
}
};
}
});
return references;
}
private static SNodePointer breakingNode_mit8ze_a0a0a0a0a1a0b0a1a1 = new SNodePointer("r:d1323bac-5479-4158-b8f2-09045725c39d(DTPL.constraints)", "3195928371522544415");
private static SNodePointer breakingNode_mit8ze_a0a0a0a0a1a0b0a2a1 = new SNodePointer("r:d1323bac-5479-4158-b8f2-09045725c39d(DTPL.constraints)", "3195928371522672907");
}
<file_sep>package DTPL.actions;
/*Generated by MPS */
import jetbrains.mps.openapi.actions.descriptor.NodeFactory;
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.mps.openapi.model.SModel;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
public class node_factories_Dijagram {
public static class NodeFactory_3195928371522202942 implements NodeFactory {
public void setup(SNode newNode, SNode sampleNode, SNode enclosingNode, SModel model) {
SPropertyOperations.set(newNode, MetaAdapterFactory.getProperty(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02b9082L, 0x2c5a37ebd02b9083L, "level"), "" + (0));
{
final SNode dk = enclosingNode;
if (SNodeOperations.isInstanceOf(dk, MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, "DTPL.structure.DijagramKonteksta"))) {
SLinkOperations.setTarget(newNode, MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02b9082L, 0x2c5a37ebd02d4604L, "koji_se_dekomponuje_proces_ref"), SLinkOperations.getTarget(dk, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, 0x2c5a37ebd022d54cL, "proces")));
SPropertyOperations.set(newNode, MetaAdapterFactory.getProperty(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02b9082L, 0x2c5a37ebd02b9083L, "level"), "" + (1));
}
}
if (SPropertyOperations.getInteger(newNode, MetaAdapterFactory.getProperty(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02b9082L, 0x2c5a37ebd02b9083L, "level")) == 0) {
SNode node_d = (SNode) enclosingNode;
SPropertyOperations.set(newNode, MetaAdapterFactory.getProperty(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02b9082L, 0x2c5a37ebd02b9083L, "level"), "" + (SPropertyOperations.getInteger(node_d, MetaAdapterFactory.getProperty(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02b9082L, 0x2c5a37ebd02b9083L, "level")) + 1));
}
}
}
}
<file_sep>package DTPL.editor;
/*Generated by MPS */
import jetbrains.mps.nodeEditor.EditorAspectDescriptorBase;
import java.util.Collection;
import jetbrains.mps.openapi.editor.descriptor.ConceptEditor;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SConceptOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import java.util.Collections;
public class EditorAspectDescriptorImpl extends EditorAspectDescriptorBase {
public Collection<ConceptEditor> getDeclaredEditors(SAbstractConcept concept) {
{
SAbstractConcept cncpt = ((SAbstractConcept) concept);
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02362c7L, "DTPL.structure.DTPElementInterfejsTokProces"))) {
return Collections.<ConceptEditor>singletonList(new DTPElementInterfejsTokProces_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02dce72L, "DTPL.structure.DTPElementProces"))) {
return Collections.<ConceptEditor>singletonList(new DTPElementProces_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d527L, "DTPL.structure.DTPModel"))) {
return Collections.<ConceptEditor>singletonList(new DTPModel_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02b9082L, "DTPL.structure.Dijagram"))) {
return Collections.<ConceptEditor>singletonList(new Dijagram_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, "DTPL.structure.DijagramKonteksta"))) {
return Collections.<ConceptEditor>singletonList(new DijagramKonteksta_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d524L, "DTPL.structure.Interfejs"))) {
return Collections.<ConceptEditor>singletonList(new Interfejs_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd0306fd6L, "DTPL.structure.InterfejsRefTokRefProcesRef"))) {
return Collections.<ConceptEditor>singletonList(new InterfejsRefTokRefProcesRef_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02379c3L, "DTPL.structure.InterfejsTokProces"))) {
return Collections.<ConceptEditor>singletonList(new InterfejsTokProces_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d51eL, "DTPL.structure.Proces"))) {
return Collections.<ConceptEditor>singletonList(new Proces_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x3fe263f784c89337L, "DTPL.structure.ProcesRefTokRefInterfejsRef"))) {
return Collections.<ConceptEditor>singletonList(new ProcesRefTokRefInterfejsRef_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd024fa9aL, "DTPL.structure.ProcesTokInterfejs"))) {
return Collections.<ConceptEditor>singletonList(new ProcesTokInterfejs_Editor());
}
if (SConceptOperations.isExactly(SNodeOperations.asSConcept(cncpt), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d521L, "DTPL.structure.TokPodatka"))) {
return Collections.<ConceptEditor>singletonList(new TokPodatka_Editor());
}
}
return Collections.<ConceptEditor>emptyList();
}
}
<file_sep>package DTPL.constraints;
/*Generated by MPS */
import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor;
import jetbrains.mps.smodel.adapter.ids.MetaIdFactory;
import java.util.Map;
import jetbrains.mps.smodel.adapter.ids.SReferenceLinkId;
import jetbrains.mps.smodel.runtime.ReferenceConstraintsDescriptor;
import java.util.HashMap;
import jetbrains.mps.smodel.runtime.base.BaseReferenceConstraintsDescriptor;
import org.jetbrains.annotations.Nullable;
import jetbrains.mps.smodel.runtime.ReferenceScopeProvider;
import jetbrains.mps.smodel.runtime.base.BaseScopeProvider;
import org.jetbrains.mps.openapi.model.SNodeReference;
import jetbrains.mps.scope.Scope;
import jetbrains.mps.smodel.IOperationContext;
import jetbrains.mps.smodel.runtime.ReferenceConstraintsContext;
import java.util.List;
import org.jetbrains.mps.openapi.model.SNode;
import java.util.ArrayList;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import jetbrains.mps.scope.ListScope;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.smodel.SNodePointer;
public class ProcesRefTokRefInterfejsRef_Constraints extends BaseConstraintsDescriptor {
public ProcesRefTokRefInterfejsRef_Constraints() {
super(MetaIdFactory.conceptId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x3fe263f784c89337L));
}
@Override
protected Map<SReferenceLinkId, ReferenceConstraintsDescriptor> getNotDefaultSReferenceLinks() {
Map<SReferenceLinkId, ReferenceConstraintsDescriptor> references = new HashMap<SReferenceLinkId, ReferenceConstraintsDescriptor>();
references.put(MetaIdFactory.refId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x3fe263f784c89337L, 0x3fe263f784c8933dL), new BaseReferenceConstraintsDescriptor(MetaIdFactory.refId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x3fe263f784c89337L, 0x3fe263f784c8933dL), this) {
@Override
public boolean hasOwnScopeProvider() {
return true;
}
@Nullable
@Override
public ReferenceScopeProvider getScopeProvider() {
return new BaseScopeProvider() {
@Override
public SNodeReference getSearchScopeValidatorNode() {
return breakingNode_evix3g_a0a0a0a0a1a0b0a1a1;
}
@Override
public Scope createScope(final IOperationContext operationContext, final ReferenceConstraintsContext _context) {
{
List<SNode> nlist_tok_podatak = new ArrayList<SNode>();
if ((SLinkOperations.getTarget(_context.getReferenceNode(), MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x3fe263f784c89337L, 0x3fe263f784c8933aL, "proces_ref")) != null)) {
SNode node_i = SLinkOperations.getTarget(_context.getReferenceNode(), MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x3fe263f784c89337L, 0x3fe263f784c8933aL, "proces_ref"));
// dijagram konteksat
SNode node_dk = SNodeOperations.getNodeAncestor(_context.getEnclosingNode(), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, "DTPL.structure.DijagramKonteksta"), false, false);
for (SNode node_dtpeitp : SLinkOperations.getChildren(node_dk, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, 0x2c5a37ebd02362caL, "dtp_element_interfejs_tok"))) {
for (SNode node_pti : SLinkOperations.getChildren(node_dtpeitp, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02362c7L, 0x2c5a37ebd02561daL, "out_proces_tok_interfejs"))) {
SNode node_p = (SNode) SLinkOperations.getTarget(node_pti, MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd024fa9aL, 0x2c5a37ebd0256147L, "proces_ref"));
ListSequence.fromList(nlist_tok_podatak).addElement(SLinkOperations.getTarget(node_pti, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd024fa9aL, 0x2c5a37ebd024fa9dL, "tok_podataka")));
}
}
}
return new ListScope(nlist_tok_podatak) {
public String getName(SNode child) {
SNode node_i = (SNode) child;
return SPropertyOperations.getString(node_i, MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name"));
}
};
}
}
};
}
});
references.put(MetaIdFactory.refId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x3fe263f784c89337L, 0x3fe263f784c89338L), new BaseReferenceConstraintsDescriptor(MetaIdFactory.refId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x3fe263f784c89337L, 0x3fe263f784c89338L), this) {
@Override
public boolean hasOwnScopeProvider() {
return true;
}
@Nullable
@Override
public ReferenceScopeProvider getScopeProvider() {
return new BaseScopeProvider() {
@Override
public SNodeReference getSearchScopeValidatorNode() {
return breakingNode_evix3g_a0a0a0a0a1a0b0a2a1;
}
@Override
public Scope createScope(final IOperationContext operationContext, final ReferenceConstraintsContext _context) {
{
List<SNode> nlist_interfejs = new ArrayList<SNode>();
if ((SLinkOperations.getTarget(_context.getReferenceNode(), MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x3fe263f784c89337L, 0x3fe263f784c8933dL, "tok_podataka_ref")) != null)) {
SNode node_dk = SNodeOperations.getNodeAncestor(_context.getEnclosingNode(), MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, "DTPL.structure.DijagramKonteksta"), false, false);
for (SNode node_dtpeitp : SLinkOperations.getChildren(node_dk, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, 0x2c5a37ebd02362caL, "dtp_element_interfejs_tok"))) {
for (SNode node_pti : SLinkOperations.getChildren(node_dtpeitp, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02362c7L, 0x2c5a37ebd02561daL, "out_proces_tok_interfejs"))) {
SNode node_tp = (SNode) SLinkOperations.getTarget(node_pti, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd024fa9aL, 0x2c5a37ebd024fa9dL, "tok_podataka"));
if (SPropertyOperations.getString(node_tp, MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name")).equals(SPropertyOperations.getString(SLinkOperations.getTarget(_context.getReferenceNode(), MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x3fe263f784c89337L, 0x3fe263f784c8933dL, "tok_podataka_ref")), MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name")))) {
ListSequence.fromList(nlist_interfejs).addElement(SLinkOperations.getTarget(node_pti, MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd024fa9aL, 0x2c5a37ebd0256146L, "interfejs_ref")));
}
}
}
}
return new ListScope(nlist_interfejs) {
public String getName(SNode child) {
SNode node_i = (SNode) child;
return SPropertyOperations.getString(node_i, MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name"));
}
};
}
}
};
}
});
return references;
}
private static SNodePointer breakingNode_evix3g_a0a0a0a0a1a0b0a1a1 = new SNodePointer("r:d1323bac-5479-4158-b8f2-09045725c39d(DTPL.constraints)", "4603351683862128329");
private static SNodePointer breakingNode_evix3g_a0a0a0a0a1a0b0a2a1 = new SNodePointer("r:d1323bac-5479-4158-b8f2-09045725c39d(DTPL.constraints)", "4603351683862367144");
}
<file_sep>package DTPL.constraints;
/*Generated by MPS */
import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor;
import jetbrains.mps.smodel.adapter.ids.MetaIdFactory;
public class DijagramKonteksta_Constraints extends BaseConstraintsDescriptor {
public DijagramKonteksta_Constraints() {
super(MetaIdFactory.conceptId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL));
}
}
<file_sep>package DTPL.actions;
/*Generated by MPS */
import jetbrains.mps.openapi.actions.descriptor.NodeFactory;
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.mps.openapi.model.SModel;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
public class node_factories_InterfejsTokProces {
public static class NodeFactory_3195928371521635826 implements NodeFactory {
public void setup(SNode newNode, SNode sampleNode, SNode enclosingNode, SModel model) {
// ko je roditelj
{
final SNode dtpeitk = enclosingNode;
if (SNodeOperations.isInstanceOf(dtpeitk, MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02362c7L, "DTPL.structure.DTPElementInterfejsTokProces"))) {
SNode node_dtpeitp = (SNode) enclosingNode;
SNode node_i = SLinkOperations.getTarget(node_dtpeitp, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02362c7L, 0x2c5a37ebd02362c8L, "interfejs"));
SNode node_p = SLinkOperations.getTarget(((SNode) SNodeOperations.getParent(node_dtpeitp)), MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, 0x2c5a37ebd022d54cL, "proces"));
SLinkOperations.setTarget(newNode, MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02379c3L, 0x2c5a37ebd024a0a9L, "interfejs_ref"), node_i);
SLinkOperations.setTarget(newNode, MetaAdapterFactory.getReferenceLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02379c3L, 0x2c5a37ebd024faa0L, "proces_ref"), node_p);
}
}
}
}
}
<file_sep>package DTPL.intentions;
/*Generated by MPS */
import jetbrains.mps.intentions.IntentionDescriptorBase;
import jetbrains.mps.intentions.IntentionFactory;
import java.util.Collection;
import jetbrains.mps.intentions.IntentionExecutable;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import jetbrains.mps.intentions.IntentionType;
import jetbrains.mps.smodel.SNodePointer;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.openapi.editor.EditorContext;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import java.util.Collections;
import jetbrains.mps.intentions.IntentionExecutableBase;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SConceptOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.intentions.IntentionDescriptor;
public final class intention_create_DijagramKonteksta_Intention extends IntentionDescriptorBase implements IntentionFactory {
private Collection<IntentionExecutable> myCachedExecutable;
public intention_create_DijagramKonteksta_Intention() {
super(MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d527L, "DTPL.structure.DTPModel"), IntentionType.NORMAL, false, new SNodePointer("r:c1a533f2-440f-422a-87a0-5f169e325728(DTPL.intentions)", "3195928371524749049"));
}
@Override
public String getPresentation() {
return "intention_create_DijagramKonteksta";
}
@Override
public boolean isApplicable(final SNode node, final EditorContext editorContext) {
if (!(isApplicableToNode(node, editorContext))) {
return false;
}
return true;
}
private boolean isApplicableToNode(final SNode node, final EditorContext editorContext) {
if ((SLinkOperations.getTarget(node, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d527L, 0x2c5a37ebd022d572L, "dijagram_konteksta")) == null)) {
return true;
}
return false;
}
@Override
public boolean isSurroundWith() {
return false;
}
public Collection<IntentionExecutable> instances(final SNode node, final EditorContext context) {
if (myCachedExecutable == null) {
myCachedExecutable = Collections.<IntentionExecutable>singletonList(new intention_create_DijagramKonteksta_Intention.IntentionImplementation());
}
return myCachedExecutable;
}
/*package*/ final class IntentionImplementation extends IntentionExecutableBase {
public IntentionImplementation() {
}
@Override
public String getDescription(final SNode node, final EditorContext editorContext) {
return "Kreiraj Dijagram Konteksta";
}
@Override
public void execute(final SNode node, final EditorContext editorContext) {
SNode node_dk = SConceptOperations.createNewNode(SNodeOperations.asInstanceConcept(MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, "DTPL.structure.DijagramKonteksta")));
SNode node_p = SConceptOperations.createNewNode(SNodeOperations.asInstanceConcept(MetaAdapterFactory.getConcept(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d51eL, "DTPL.structure.Proces")));
SPropertyOperations.set(node_p, MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name"), SPropertyOperations.getString(node, MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name")));
SLinkOperations.setTarget(node_dk, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d54bL, 0x2c5a37ebd022d54cL, "proces"), node_p);
SLinkOperations.setTarget(node, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d527L, 0x2c5a37ebd022d572L, "dijagram_konteksta"), node_dk);
}
@Override
public IntentionDescriptor getDescriptor() {
return intention_create_DijagramKonteksta_Intention.this;
}
}
}
<file_sep>package DTPL.constraints;
/*Generated by MPS */
import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor;
import jetbrains.mps.smodel.adapter.ids.MetaIdFactory;
import java.util.Map;
import jetbrains.mps.smodel.adapter.ids.SPropertyId;
import jetbrains.mps.smodel.runtime.PropertyConstraintsDescriptor;
import java.util.HashMap;
import jetbrains.mps.smodel.runtime.base.BasePropertyConstraintsDescriptor;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
public class DTPModel_Constraints extends BaseConstraintsDescriptor {
public DTPModel_Constraints() {
super(MetaIdFactory.conceptId(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd022d527L));
}
@Override
protected Map<SPropertyId, PropertyConstraintsDescriptor> getNotDefaultSProperties() {
Map<SPropertyId, PropertyConstraintsDescriptor> properties = new HashMap<SPropertyId, PropertyConstraintsDescriptor>();
properties.put(MetaIdFactory.propId(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L), new BasePropertyConstraintsDescriptor(MetaIdFactory.propId(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L), this) {
@Override
public boolean hasOwnValidator() {
return true;
}
@Override
public boolean validateValue(SNode node, String propertyValue) {
String propertyName = "name";
if ((SPropertyOperations.getString(propertyValue)).startsWith("IS")) {
return true;
}
System.err.println("ERR...");
return false;
}
});
return properties;
}
}
<file_sep>package DTPL.editor;
/*Generated by MPS */
import jetbrains.mps.nodeEditor.DefaultNodeEditor;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.openapi.editor.EditorContext;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.nodeEditor.cells.EditorCell_Constant;
import jetbrains.mps.nodeEditor.cellProviders.CellProviderWithRole;
import jetbrains.mps.lang.editor.cellProviders.RefCellCellProvider;
import jetbrains.mps.nodeEditor.EditorManager;
import jetbrains.mps.nodeEditor.InlineCellProvider;
import jetbrains.mps.lang.editor.cellProviders.PropertyCellProvider;
import jetbrains.mps.openapi.editor.style.Style;
import jetbrains.mps.editor.runtime.style.StyleImpl;
import jetbrains.mps.editor.runtime.style.StyleAttributes;
import java.awt.Color;
import jetbrains.mps.nodeEditor.cells.EditorCell_Indent;
import jetbrains.mps.lang.editor.cellProviders.SingleRoleCellProvider;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SContainmentLink;
import jetbrains.mps.nodeEditor.cellMenu.DefaultChildSubstituteInfo;
import jetbrains.mps.openapi.editor.style.StyleRegistry;
import jetbrains.mps.nodeEditor.MPSColors;
public class InterfejsTokProces_Editor extends DefaultNodeEditor {
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return this.createCollection_z1co8e_a(editorContext, node);
}
private EditorCell createCollection_z1co8e_a(EditorContext editorContext, SNode node) {
EditorCell_Collection editorCell = EditorCell_Collection.createIndent2(editorContext, node);
editorCell.setCellId("Collection_z1co8e_a");
editorCell.setBig(true);
editorCell.addEditorCell(this.createConstant_z1co8e_a0(editorContext, node));
editorCell.addEditorCell(this.createConstant_z1co8e_b0(editorContext, node));
editorCell.addEditorCell(this.createRefCell_z1co8e_c0(editorContext, node));
editorCell.addEditorCell(this.createConstant_z1co8e_d0(editorContext, node));
editorCell.addEditorCell(this.createIndentCell_z1co8e_e0(editorContext, node));
editorCell.addEditorCell(this.createRefNode_z1co8e_f0(editorContext, node));
editorCell.addEditorCell(this.createIndentCell_z1co8e_g0(editorContext, node));
editorCell.addEditorCell(this.createConstant_z1co8e_h0(editorContext, node));
editorCell.addEditorCell(this.createRefCell_z1co8e_i0(editorContext, node));
editorCell.addEditorCell(this.createConstant_z1co8e_j0(editorContext, node));
return editorCell;
}
private EditorCell createConstant_z1co8e_a0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "in:");
editorCell.setCellId("Constant_z1co8e_a0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_z1co8e_b0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "[");
editorCell.setCellId("Constant_z1co8e_b0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefCell_z1co8e_c0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new RefCellCellProvider(node, editorContext);
provider.setRole("interfejs_ref");
provider.setNoTargetText("<no interfejs_ref>");
EditorCell editorCell;
provider.setAuxiliaryCellProvider(new InterfejsTokProces_Editor._Inline_z1co8e_a2a());
editorCell = provider.createEditorCell(editorContext);
if (editorCell.getRole() == null) {
editorCell.setReferenceCell(true);
editorCell.setRole("interfejs_ref");
}
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
public static class _Inline_z1co8e_a2a extends InlineCellProvider {
public _Inline_z1co8e_a2a() {
super();
}
public EditorCell createEditorCell(EditorContext editorContext) {
return this.createEditorCell(editorContext, this.getSNode());
}
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return this.createProperty_z1co8e_a0c0(editorContext, node);
}
private EditorCell createProperty_z1co8e_a0c0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new PropertyCellProvider(node, editorContext);
provider.setRole("name");
provider.setNoTargetText("<no name>");
provider.setReadOnly(true);
EditorCell editorCell;
editorCell = provider.createEditorCell(editorContext);
editorCell.setCellId("property_name");
Style style = new StyleImpl();
style.set(StyleAttributes.BACKGROUND_COLOR, 0, (Color) null);
style.set(StyleAttributes.READ_ONLY, 0, true);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
}
private EditorCell createConstant_z1co8e_d0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "]");
editorCell.setCellId("Constant_z1co8e_d0");
Style style = new StyleImpl();
style.set(StyleAttributes.BACKGROUND_COLOR, 0, (Color) null);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createIndentCell_z1co8e_e0(EditorContext editorContext, SNode node) {
EditorCell_Indent editorCell = new EditorCell_Indent(editorContext, node);
return editorCell;
}
private EditorCell createRefNode_z1co8e_f0(EditorContext editorContext, SNode node) {
SingleRoleCellProvider provider = new InterfejsTokProces_Editor.tok_podatakSingleRoleHandler_z1co8e_f0(node, MetaAdapterFactory.getContainmentLink(0x4fade4743af4300L, 0xad5bb5d24df72c43L, 0x2c5a37ebd02379c3L, 0x2c5a37ebd023c4e4L, "tok_podatak"), editorContext);
return provider.createCell();
}
private class tok_podatakSingleRoleHandler_z1co8e_f0 extends SingleRoleCellProvider {
public tok_podatakSingleRoleHandler_z1co8e_f0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) {
super(ownerNode, containmentLink, context);
}
protected EditorCell createChildCell(SNode child) {
EditorCell editorCell = super.createChildCell(child);
installCellInfo(child, editorCell);
return editorCell;
}
private void installCellInfo(SNode child, EditorCell editorCell) {
editorCell.setSubstituteInfo(new DefaultChildSubstituteInfo(myOwnerNode, myContainmentLink.getDeclarationNode(), myEditorContext));
if (editorCell.getRole() == null) {
editorCell.setRole("tok_podatak");
}
}
@Override
protected EditorCell createEmptyCell() {
EditorCell editorCell = super.createEmptyCell();
editorCell.setCellId("empty_tok_podatak");
installCellInfo(null, editorCell);
return editorCell;
}
protected String getNoTargetText() {
return "<no tok_podatak>";
}
}
private EditorCell createIndentCell_z1co8e_g0(EditorContext editorContext, SNode node) {
EditorCell_Indent editorCell = new EditorCell_Indent(editorContext, node);
return editorCell;
}
private EditorCell createConstant_z1co8e_h0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "(");
editorCell.setCellId("Constant_z1co8e_h0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, 0, StyleRegistry.getInstance().getSimpleColor(MPSColors.orange));
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefCell_z1co8e_i0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new RefCellCellProvider(node, editorContext);
provider.setRole("proces_ref");
provider.setNoTargetText("<no proces_ref>");
EditorCell editorCell;
provider.setAuxiliaryCellProvider(new InterfejsTokProces_Editor._Inline_z1co8e_a8a());
editorCell = provider.createEditorCell(editorContext);
if (editorCell.getRole() == null) {
editorCell.setReferenceCell(true);
editorCell.setRole("proces_ref");
}
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, 0, StyleRegistry.getInstance().getSimpleColor(MPSColors.orange));
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
public static class _Inline_z1co8e_a8a extends InlineCellProvider {
public _Inline_z1co8e_a8a() {
super();
}
public EditorCell createEditorCell(EditorContext editorContext) {
return this.createEditorCell(editorContext, this.getSNode());
}
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return this.createProperty_z1co8e_a0i0(editorContext, node);
}
private EditorCell createProperty_z1co8e_a0i0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new PropertyCellProvider(node, editorContext);
provider.setRole("name");
provider.setNoTargetText("<no name>");
provider.setReadOnly(true);
EditorCell editorCell;
editorCell = provider.createEditorCell(editorContext);
editorCell.setCellId("property_name_1");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, 0, StyleRegistry.getInstance().getSimpleColor(MPSColors.orange));
style.set(StyleAttributes.READ_ONLY, 0, true);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
}
private EditorCell createConstant_z1co8e_j0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, ")");
editorCell.setCellId("Constant_z1co8e_j0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, 0, StyleRegistry.getInstance().getSimpleColor(MPSColors.orange));
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
}
|
a0fed5d521f002f9da99bee80162bf65e03d3a68
|
[
"Java"
] | 10
|
Java
|
dariyo/MPS_SSA
|
3baa5b2f529707d4e618f41139ef2544463b7fd7
|
2362416969d1cfb1a48c53c9805f272a8ba16258
|
refs/heads/master
|
<repo_name>dutchessssssss/configs<file_sep>/Scripts/bashfunctions.sh
function JAM
{
cd /home/philip/Code/ludemdare35/LD35
}
function h
{
history |grep $1
}
function glog
{
git log --oneline --graph --all
}
|
e23bdb396f7f5fbf1bf3fcbbbc3bc6b601f3685f
|
[
"Shell"
] | 1
|
Shell
|
dutchessssssss/configs
|
48f9ad7297e0609b269a55879a3c8c35f389ded3
|
30c28508814d0df2761dcbae388ab5ad0aac87f1
|
refs/heads/master
|
<file_sep># Represents a game date, time and location
class Slot:
def __init__(self, game_date, game_time, game_location):
self.game_date = game_date
self.game_time = game_time
self.game_location = game_location
<file_sep># Imports all important modules
from gameinfo import GameDate
from gameinfo import GameTime
from gameinfo import GameLocation
from team import Team
from match import Match
from slot import Slot
<file_sep># Base class for recording game date, field, and time information
class GameInfo:
opt = 1
def __init__(self, label, weight):
self.label = label
self.weight = weight
opt = 0
def __hash__(self):
return hash((self.id, self.label, self.weight))
def __eq__(self, other):
return (self.id, self.label, self.weight) == (other.id, other.label, other.weight)
# Represents a game date
class GameDate(GameInfo):
pass
# Represents a game time
class GameTime(GameInfo):
pass
# Represents a game location
class GameLocation(GameInfo):
pass
<file_sep># Represents a match
class Match:
def __init__(self, division, team_one, team_two):
self.division = division
self.teams = set([team_one, team_two])
|
5c24aba15e1deefa5dc99730c10011c6ac9179aa
|
[
"Python"
] | 4
|
Python
|
johnlarusic/sportsched
|
2c6f0e769dfca2909141abd49a42c8991c8bc341
|
830cf1d94f7cd8e11bea21e6d8d3bc75d3670914
|
refs/heads/master
|
<file_sep>PHP blog & PHP templater
<file_sep><?php
include_once('inc/C_Controller.php');
class C_Base extends C_Controller//
protected $conn;
protected $header;
protected $title;
protected $main_menu;
protected $content;
protected $comments;
public function __construct() {
$this->header = "Главная";
$this->title = "My blog";
$this->comments = "";
$main_menu = $this->Template("theme/main_menu.php", array(
"current" => $this->header));
$this->main_menu = $main_menu;
$this->content = "";
}
public function Before() {
// Языковая настройка.
setlocale(LC_ALL, 'ru_RU.UTF-8');
mb_internal_encoding('UTF-8');
$this->conn = $this->startup();
}
public function Render() {
$page = $this->Template("theme/main.php", array(
"top_title" => $this->top_title,
"main_menu" => $this->main_menu,
"title" => $this->title,
"content" => $this->content,
"comments" => $this->comments
));
echo $page;
}
private function startup() {
$conn = new M_Mysql();
}
}
<file_sep><?php
include_once('inc\C_Base');
include_once('model\M_Data');
class C_Article extends C_Base{
public function __construct(){
parent::__construct();
}
public function index() {
// Извлечение статей.
$articles = M_Data::articles_all();
$error = false;
if (($articles == false) || (count($articles) <= 0)) {
$error = true;
}
//Загаловки
$previews = $this->Template("theme/previews.php", array(
"error" => $error,
"articles" => M_Data::articles_intro($articles)
));
//Основной контент
$this->content = $this->Template("theme/center.php", array(
"width" => "content_full-width",
"content" => $previews
));
}
public function article() {
}
}
<file_sep><?PHP
include_once('model/M_Mysql.php');
$connector = M_Mysql->getInstance();
class C_Admin extends C_Base{
private $user;
private $panel;
public function __construct($connector){
$this->panel = $this->Template('theme/admin.php', $this);
}
public function get_user(){
return $this->user;
}
public function set_user($name, $pass, $role){
}
}
?><file_sep><?php
include_once('M_Mysql.php');
class M_Data{
private $data; // data object
public function __construct($link){
}
public function get_data(){
return $data;
}
}
?><file_sep><?PHP
include_once('model/M_Mysql.php');
$connector = M_Mysql->getInstance();
class C_Comment extends C_Base{
private $comment;
private $connector;
public function __construct($connector){
$this->connector = $connector;
}
public function get_comment(){
$this->comment = $this->Template('theme/article.php', $this);
}
public function edit_comment(){
$this->comment = $this->Template('theme/edit.php', $this);
}
}
?>
|
cb4b58d8d797b961bc3967e7a04b0632e3677119
|
[
"Markdown",
"PHP"
] | 6
|
Markdown
|
paulkotov/PHP-geekbrains.ru
|
673fb469c9575c0b9d88a7b744c9d5ba530fdeea
|
1f4c7cca7c2a99eb5a8c348ffb90e9d5693330e8
|
refs/heads/master
|
<repo_name>jaguar17171/spokes-eventlist<file_sep>/README.md
EventList
======
> The `EventList` object provides functions to retrieve calendar events from iOS and Android.
Installation
============
Install this plugin using PhoneGap/Cordova CLI (iOS and Android)
cordova plugin add https://github.com/jaguar17171/spokes-eventlist.git
Methods
-------
- EventList.findByDateRange
EventList.findByDateRange
=================
EventList.findByDateRange(startDate, endDate, successCallback, errorCallback);
Description
-----------
Returns a list of calendar events with participants for a specified date range.
Supported Platforms
-------------------
- iOS
- Android
Quick Example
-------------
EventList.findByDateRange('2014-04-07', '2014-04-14', function() {}, function() {});
<file_sep>/src/android/EventList.java
package com.biffnstein.cordova.eventlist;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract.Attendees;
import android.text.format.DateUtils;
public class EventList extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if (action.equals("findByDateRange")) {
ContentResolver contentResolver = this.webView.getContext().getContentResolver();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuilder message = new StringBuilder();
message.append("[");
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now);
ContentUris.appendId(builder, now + (DateUtils.DAY_IN_MILLIS * 7));
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "_id", "title", "eventLocation", "begin", "end", "allDay"}, null,//"Events.calendar_id=" + id,
null, "startDay ASC, startMinute ASC");
boolean isFirst = true;
while (eventCursor.moveToNext()) {
int _id = eventCursor.getInt(0);// + 1;
String title = eventCursor.getString(1);
String location = eventCursor.getString(2);
Date startDate = new Date(eventCursor.getLong(3));//.getString(3);
Date endDate = new Date(eventCursor.getLong(4));//.getString(4);
String allDay = !eventCursor.getString(5).equals("0") ? "true" : "false";
Cursor participantsCursor = contentResolver.query(Uri.parse("content://com.android.calendar/attendees"),
new String[] { "event_id", "attendeeName", "attendeeEmail" },Attendees.EVENT_ID + "=" + _id,
null, null);
StringBuilder participants = new StringBuilder();
participants.append("[");
boolean firstParticipant = true;
while(participantsCursor.moveToNext()) {
String participantName = participantsCursor.getString(1);
String participantEmail = participantsCursor.getString(2);
if (!firstParticipant) {
participants.append(",");
}
participants.append("{\"name\":\"" + participantName + "\",\"email\":\"" + participantEmail + "\"}");
firstParticipant = false;
}
participants.append("]");
if (!isFirst) {
message.append(",");
}
message.append("{\"id\":" + _id + ",\"title\":\"" + title + "\",\"location\":\"" + location + "\",\"startDate\":\"" + df.format(startDate) + "\",\"endDate\":\"" + df.format(endDate) + "\",\"participants\":" + participants + ",\"allDay\":\"" + allDay + "\"}");
isFirst = false;
}
message.append("]");
callbackContext.success(new JSONArray(message.toString()));
return true;
}
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
}
return false;
}
}
|
3c2d2c0eb6ec4f87fb61b262c7065d497ff68b08
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
jaguar17171/spokes-eventlist
|
72ed2fb985d4d0e3644e5f0d8462df3c1ea86c8d
|
be40fd62cf0ecbd5185c1cd04fbbfdb9be7216b3
|
refs/heads/master
|
<repo_name>devkloud/Competences<file_sep>/user_comp.php
<?php
$index = true;
// Inclusion de fluxbb
define('PUN_ROOT', '../home/');
require PUN_ROOT.'include/common.php';
if ($pun_user['is_guest'] == 1) { // L'utilisateur n'est pas connecté
header('Location: login.php');
} elseif (isset($_POST['submit'])) {
// Configuration et connexion MySql
require_once ('config.php');
// Définition des variables
$donnees = array();
$user = array();
// Récupération des compétences de l'utilisateur
$noms = $connexion->query("SELECT users.id,
competences_categories.nom AS categorie,
competences_designation.designation,
competences_users.note,
competences_users.commentaire
FROM `competences_users`
RIGHT JOIN `users` ON users.id=competences_users.users_id
LEFT JOIN `competences_designation` ON competences_designation.id=competences_users.designation_id
LEFT JOIN `competences_categories` ON competences_categories.id=competences_designation.categories_id
WHERE users.id = ".$connexion->quote($pun_user['id'], PDO::PARAM_INT)."
ORDER BY competences_categories.nom, competences_designation.designation ASC"); // Récupération des infos de l'utilisateur
$noms->setFetchMode(PDO::FETCH_OBJ); // Transformation en objet
$user = $noms->fetchAll(); // Traitement de l'objet
$noms->closeCursor(); // Fermeture
// Récupération des désignations/catégories
$noms = $connexion->query("SELECT competences_categories.nom AS categorie,
competences_designation.designation
FROM `competences_designation`
LEFT JOIN `competences_categories` ON competences_categories.id=competences_designation.categories_id
ORDER BY competences_categories.nom, competences_designation.designation ASC"); // Récupération des infos
$noms->setFetchMode(PDO::FETCH_OBJ); // Transformation en objet
$donnees = $noms->fetchAll(); // Traitement de l'objet
$noms->closeCursor(); // Fermeture
// Récupération des désignation
$noms = $connexion->query("SELECT id, designation
FROM `competences_designation`
ORDER BY competences_designation.id ASC"); // Récupération des infos
$noms->setFetchMode(PDO::FETCH_OBJ); // Transformation en objet
$designations = $noms->fetchAll(); // Traitement de l'objet
$noms->closeCursor(); // Fermeture
require ('functions.php');
// Création du tableau des donnees
$post = array();
foreach ($designations as $d) {
if ($d->commentaire==NULL) {
$d->commentaire=" ";
}
if (isset($_POST[$d->designation])) {
$post[] = array('user'=>$pun_user['id'], 'designation'=>$d->id, 'note'=>$_POST[$d->designation], 'commentaire'=>$_POST[$d->designation.'_commentaire']);
} else {
$post[] = array('user'=>$pun_user['id'], 'designation'=>$d->id, 'note'=>0, 'commentaire'=>$_POST[$d->designation.'_commentaire']);
}
}
// Envoi en bdd
update_user($post);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Gestion des compétences</title>
<script src='js/jquery-1.4.2.min.js' type="text/javascript" language="javascript">
</script>
<script src='js/jquery.rating.js' type="text/javascript" language="javascript">
</script>
<link href='css/jquery.rating.css' type="text/css" rel="stylesheet"/>
</head>
<body>
<div id="container">
<? foreach ($donnees as $d): ?>
<? if (isset($cat) && $cat != $d->categorie): //Gestion des catégories ?>
</table>
</fieldset>
<fieldset>
<legend>
<?= $d->categorie?>
</legend>
<table>
<? elseif (!isset($cat)): ?>
<fieldset>
<legend>
<?= $d->categorie?>
</legend>
<table>
<?endif ; //endGestion des catégories ?>
<tr>
<td>
<?= $d->designation?>
</td>
<td>
<? for ($i = 1; $i < 6; $i++): ?>
<input type="radio" name="<?= $d->designation ?>" value="<?= $i ?>" class="star" disabled="true"
<? if ($i == $_POST[$d->designation]): ?>
checked="checked"
<? endif; ?>
/>
<? endfor; ?>
</td>
<td>
<input type="text" name="<?= $d->designation.'.commentaire' ?>" disabled="true"
<? if ($_POST[$d->designation.'_commentaire']): ?>
value="<?= $_POST[$d->designation.'_commentaire'] ?>"
<? endif; ?>
/>
</td>
</tr>
<? $cat = $d->categorie; ?>
<? endforeach; ?>
</table>
</fieldset>
<a href="index.php" title="Accueil">Retour au tableau des compétences</a>
</div>
</body>
</html>
<?php } ?>
<file_sep>/dump.php
<?php
// Configuration et connexion MySql
$index = true;
require_once('config.php');
// Définition des variables
$donnees = array();
// Récupération des désignation
$noms = $connexion->query("SELECT users.id,
users.username,
competences_categories.nom AS categorie,
competences_designation.designation,
competences_users.note,
competences_users.commentaire
FROM competences_users
RIGHT JOIN users ON users.id=competences_users.users_id
LEFT JOIN competences_designation ON competences_designation.id=competences_users.designation_id
LEFT JOIN competences_categories ON competences_categories.id=competences_designation.categories_id
ORDER BY users.id,competences_categories.nom ASC"); // Récupération des infos
$noms->setFetchMode(PDO::FETCH_OBJ); // Transformation en objet
$donnees = $noms->fetchAll(); // Traitement de l'objet
$noms->closeCursor(); // Fermeture
// Dump
echo '<pre>';
print_r($donnees);
echo '</pre>';
?><file_sep>/designation.php
<?php
if (isset($_GET['a'])) {
$action = $_GET['a'];
} else {
$action = 'index';
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
$index = true;
// Inclusion de fluxbb
define('PUN_ROOT', '../home/');
require PUN_ROOT.'include/common.php';
require 'functions.php';
if ($pun_user['is_guest'] == 1) { // L'utilisateur n'est pas connecté
header('Location: login.php');
exit();
} elseif ($pun_user['group_id'] == 1 || $pun_user['group_id'] == 2 || $pun_user['group_id'] == 11) {
// Configuration et connexion MySql
require_once ('config.php');
$sql = "SELECT competences_designation.id,
competences_designation.designation,
competences_designation.categories_id,
competences_categories.nom
FROM `competences_designation`
RIGHT JOIN `competences_categories` ON competences_categories.id=competences_designation.categories_id
ORDER BY competences_categories.nom ASC";
$query = $connexion->query($sql);
$designations = $query->fetchAll(PDO::FETCH_OBJ);
$query->closeCursor();
/* Création d'une désignation */
if ($action == 'new' && isset($_POST['submit']) && isset($_POST['des']) && isset($_POST['cat'])) {
$des = $connexion->quote($_POST['des'], PDO::PARAM_STR);
$cat = $connexion->quote($_POST['cat'], PDO::PARAM_STR);
$query = $connexion->query("SELECT id FROM `competences_categories` WHERE nom=".$cat);
$id = $query->fetch();
$query->closeCursor();
$cid = $id[0];
$sql = "INSERT INTO `competences_designation` (designation, categories_id) VALUES(".$des.", ".$cid.")";
if ($connexion->exec($sql)) {
$created = TRUE;
} else {
$created = FALSE;
}
} elseif ($action == 'new' && !isset($_POST['submit']) && !isset($_POST['des'])) {
$sql = "SELECT nom FROM `competences_categories`";
$query = $connexion->query($sql);
$categories = $query->fetchAll(PDO::FETCH_ASSOC);
$query->closeCursor();
}
/* Suppresion d'une désignation */
if ($action == 'delete' && isset($id)) {
$id = $connexion->quote($id, PDO::PARAM_INT);
$sql = "SELECT * FROM competences_designation WHERE id=".$id;
$query = $connexion->query($sql);
$array = $query->fetchAll(PDO::FETCH_ASSOC);
if (isset($array[0])) {
$sql = "DELETE FROM `competences_designation` WHERE id=".$id;
if ($connexion->exec($sql)) {
$deleted = TRUE;
} else {
$deleted = FALSE;
}
} else {
$deleted = FALSE;
}
$query->closeCursor();
}
/* Edition d'une désignation */
if ($action == 'edit' && isset($id) && isset($_POST['submit']) && isset($_POST['des']) && isset($_POST['cat'])) {
$des = $connexion->quote($_POST['des'], PDO::PARAM_STR);
$did = $connexion->quote($id, PDO::PARAM_INT);
$cat = $connexion->quote($_POST['cat'], PDO::PARAM_STR);
$query = $connexion->query("SELECT id FROM `competences_categories` WHERE nom=".$cat);
$id = $query->fetch();
$query->closeCursor();
$cid = $id[0];
$sql = "SELECT * FROM `competences_designation` WHERE id=".$did;
$query = $connexion->query($sql);
$array = $query->fetchAll(PDO::FETCH_ASSOC);
if (isset($array[0])) {
$sql = "UPDATE `competences_designation` SET designation=".$des.", categories_id=".$cid." WHERE id=".$did;
if ($connexion->query($sql)) {
$edited = TRUE;
} else {
$edited = FALSE;
}
} else {
$edited = FALSE;
}
$query->closeCursor();
} elseif ($action == 'edit' && isset($id) && !isset($_POST['submit']) && !isset($_POST['des'])) {
$did = $connexion->quote($id, PDO::PARAM_INT);
$sql = "SELECT competences_designation.designation FROM `competences_designation` WHERE competences_designation.id=".$did;
$query = $connexion->query($sql);
$nom = $query->fetch();
$query->closeCursor();
$sql = "SELECT nom FROM `competences_categories`";
$query = $connexion->query($sql);
$categories = $query->fetchAll(PDO::FETCH_ASSOC);
$query->closeCursor();
foreach ($designations as $des) {
if ($des->designation == $nom[0]) {
$current = $des->nom;
}
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Gestion des désignations</title>
</head>
<body>
<div id="container">
<? if ($action == 'index'): /* Liste des désignations */?>
<a href="?a=new">Nouvelle désignation</a>
<table id="designations">
<thead>
<tr>
<th>
Désignation
</th>
<th>
Catégorie
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
<? foreach ($designations as $des): ?>
<tr>
<td>
<?= $des->designation?>
</td>
<td>
<?= $des->nom?>
</td>
<td>
<a href="?a=delete&id=<?= $des->id ?>">Delete</a> <a href="?a=edit&id=<?= $des->id ?>">Edit</a>
</td>
</tr>
<? endforeach; ?>
</tbody>
</table>
<? elseif ($action == 'delete' && isset($deleted)): /* Suppression d'une désignation */?>
<? if ($deleted == TRUE): ?>
<p>
La désignation
<?= $des[0]['nom']?>
à bien été supprimée !
</p>
<? else : ?>
<p>
La désignation n'a pas été supprimée !
</p>
<? endif; ?>
<a href="?a=index">Retour aux désignations</a>
<? elseif ($action == 'new'): /* Création d'une désignation */?>
<? if (isset($created) && $created == TRUE): ?>
<p>
La désignation
<?= $des?>
à bien été crée !
</p>
<? elseif (isset($created) && $created == FALSE): ?>
<p>
La désignation
<?= $des?>
n'a pas été crée !
</p>
<? endif; ?>
<form id="new" method="post">
<fieldset>
<legend>
Nouvelle désignation
</legend>
<input type="text" name="des" />
<select name="cat">
<? foreach ($categories as $cat): ?>
<option value="<?= $cat['nom'] ?>">
<?= $cat['nom']?>
</option>
<? endforeach; ?>
</select>
<input type="submit" name="submit" value="Créer" />
</fieldset>
</form><a href="?a=index">Retour aux désignations</a>
<? elseif ($action == 'edit' && isset($id)): /* Edition d'une désignation */?>
<? if (isset($edited) && $edited == TRUE): ?>
<p>
La désignation
<?= $des?>
à bien été éditée !
</p>
<? elseif (isset($edited) && $edited == FALSE): ?>
<p>
La désignation
<?= $des?>
n'a pas été éditée !
</p>
<? endif; ?>
<form id="edit" method="post">
<fieldset>
<legend>
Edition de désignation
</legend>
<input type="text" name="des" value="<?= $nom[0] ?>" />
<select name="cat">
<? foreach ($categories as $cat): ?>
<? if ($current == $cat['nom']): ?>
<option value="<?= $cat['nom'] ?>" selected="selected">
<?= $cat['nom']?>
</option>
<? else : ?>
<option value="<?= $cat['nom'] ?>">
<?= $cat['nom']?>
</option>
<? endif; ?>
<? endforeach; ?>
</select>
<input type="submit" name="submit" value="Editer" />
</fieldset>
</form><a href="?a=index">Retour aux désignations</a>
<? endif; ?>
<a href="index.php" title="Accueil">Retour au tableau des compétences</a>
</div>
</body>
</html>
<?php
}
else {
exit('Vous n\'êtes pas autorisés à venir ici !');
}
?>
<file_sep>/user.php
<?php
$index = true;
// Inclusion de fluxbb
define('PUN_ROOT', '../home/');
require PUN_ROOT.'include/common.php';
require 'functions.php';
if ($pun_user['is_guest'] == 1) { // L'utilisateur n'est pas connecté
header('Location: login.php');
} else {
// Configuration et connexion MySql
require_once ('config.php');
// Définition des variables
$donnees = array();
$user = array();
// Récupération des compétences de l'utilisateur
$noms = $connexion->query("SELECT users.id,
competences_categories.nom AS categorie,
competences_designation.designation,
competences_users.note,
competences_users.commentaire
FROM competences_users
RIGHT JOIN users ON users.id=competences_users.users_id
LEFT JOIN competences_designation ON competences_designation.id=competences_users.designation_id
LEFT JOIN competences_categories ON competences_categories.id=competences_designation.categories_id
WHERE users.id = ".$connexion->quote($pun_user['id'], PDO::PARAM_INT)."
ORDER BY competences_categories.nom, competences_designation.designation ASC"); // Récupération des infos de l'utilisateur
$noms->setFetchMode(PDO::FETCH_OBJ); // Transformation en objet
$user = $noms->fetchAll(); // Traitement de l'objet
$noms->closeCursor(); // Fermeture
// Récupération des désignations/catégories
$noms = $connexion->query("SELECT competences_categories.nom AS categorie,
competences_designation.designation
FROM competences_designation
LEFT JOIN competences_categories ON competences_categories.id=competences_designation.categories_id
ORDER BY competences_categories.nom, competences_designation.designation ASC"); // Récupération des infos
$noms->setFetchMode(PDO::FETCH_OBJ); // Transformation en objet
$donnees = $noms->fetchAll(); // Traitement de l'objet
$noms->closeCursor(); // Fermeture
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Gestion des compétences</title>
<script src='js/jquery-1.4.2.min.js' type="text/javascript" language="javascript">
</script>
<script src='js/jquery.rating.js' type="text/javascript" language="javascript">
</script>
<link href='css/jquery.rating.css' type="text/css" rel="stylesheet"/>
</head>
<body>
<div id="container">
<form id="competences" action="user_comp.php" method="post">
<? foreach($donnees as $d): ?>
<? if(isset($cat) && $cat != $d->categorie): //Gestion des catégories ?>
</table>
</fieldset>
<fieldset>
<legend><?= $d->categorie ?></legend>
<table>
<? elseif(!isset($cat)): ?>
<fieldset>
<legend><?= $d->categorie ?></legend>
<table>
<?endif; //endGestion des catégories ?>
<tr>
<td><?= $d->designation ?></td>
<td><? for($i = 1; $i<6; $i++): //Star-rating ?>
<input type="radio" name="<?= $d->designation ?>" value="<?= $i ?>" class="star" <? $note = note($d->designation); if($note != FALSE && $note == $i): ?>checked="checked"<? endif; ?> />
<? endfor; //endStar-rating ?>
</td>
<td><input type="text" name="<?= $d->designation.'.commentaire' ?>" value="<?= commentaire($d->designation) ?>" /></td>
</tr>
<? $cat = $d->categorie; ?>
<? endforeach; ?>
</table>
</fieldset>
<input type="submit" name="submit" value="Envoyer" />
</form>
</div>
</body>
</html>
<?php } ?>
<file_sep>/login.php
<?php
// Inclusion de fluxbb
define('PUN_ROOT', '../home/');
require PUN_ROOT.'include/common.php';
if ($pun_user['is_guest'] != 1) { // L'utilisateur est déjà connecté
header('Location: user.php');
exit;
} elseif (isset($_POST['user']) && isset($_POST['pass'])) { // Forumlaire correctement envoyé, on passe à la suite
// Authentification
$username = pun_trim($_POST['user']);
$password = pun_trim($_POST['pass']);
authenticate_user($username, $password);
// Définition du cookie
$now = get_microtime();
$expire = $now + 1209600;
pun_setcookie($pun_user['id'], $pun_user['password'], $expire);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Connexion</title>
</head>
<body>
<div id="container">
<?php if ($pun_user['is_guest'] == 1) { // Utilisateur guest, premier affichage ?>
<fieldset>
<legend>
Connexion
</legend>
<p>
Vous pouvez vous connecter ici avec vos identifiants utilisés lors de
l'inscription sur le <a href="../home/index.php">forum</a>.
</p>
<form name="login" method="post">
<label>
Nom d'utilisateur :<input name="user" type="text" />
</label>
<label>
Mot de passe :<input name="pass" type="<PASSWORD>" />
</label><input type="submit" name="submit" value="Connexion" />
</form>
</fieldset>
<?php } else { // Confirmation de connexion ?>
<p>
Vous êtes bien connectés avec le nom <?= $pun_user['username'] ?>!
<a href="user.php">Ajouter vos compétences ?</a>
</p>
<?php } ?>
</div>
</body>
</html>
<file_sep>/index.php
<?php
$index = true;
// Inclusion de fluxbb
ini_set('display_errors','Off');
define('PUN_ROOT', '../home/');
require PUN_ROOT.'include/common.php';
// Récupération et traitement des données
// Configuration et connexion MySql
require 'config.php';
// Définition des variables
$donnees = array();
// Récupération des désignation
$noms = $connexion->query("SELECT users.id,
users.username,
competences_categories.nom AS categorie,
competences_designation.designation,
competences_users.note,
competences_users.commentaire
FROM `competences_users`
RIGHT JOIN `users` ON users.id=competences_users.users_id
LEFT JOIN `competences_designation` ON competences_designation.id=competences_users.designation_id
LEFT JOIN `competences_categories` ON competences_categories.id=competences_designation.categories_id
WHERE users.id != 1
ORDER BY users.id,competences_categories.nom ASC"); // Récupération des infos
$noms->setFetchMode(PDO::FETCH_OBJ); // Transformation en objet
$donnees = $noms->fetchAll(); // Traitement de l'objet
$noms->closeCursor(); // Fermeture
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Compétences</title>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script>
<link rel="stylesheet" href="css/hot-sneaks/jquery-ui-1.8.2.custom.css" type="text/css" media="screen" />
<style type="text/css" media="screen">
table {
width: 100%;
}
tr.odd {
background-color: #E2E4FF;
}
</style>
</head>
<body>
<div id="container">
<ul>
<? if ($pun_user['is_guest']): ?>
<li><a href="login.php" title="Connexion">Connectez-vous pour ajouter ou modifier vos compétences.<a></li>
<? else: ?>
<li><a href="user.php" title="Compétences">Ajoutez ou modifiez vos compétences.<a></li>
<? endif; ?>
<? if ($pun_user['group_id'] == 1 || $pun_user['group_id'] == 2 || $pun_user['group_id'] == 11): ?>
<li><a href="categorie.php" title="Catégories">Gérer les catégories</a></li>
<li><a href="designation.php" title="Désignations">Gérer les désignations</a></li>
<? endif; ?>
</ul>
<table id="competences">
<thead>
<tr>
<th>Username</th>
<th>Catégorie</th>
<th>Désignation</th>
<th>Note</th>
<th>Commentaire</th>
</tr>
</thead>
<tbody>
<? foreach ($donnees as $i) : ?>
<tr>
<td><?= $i->username ?></td>
<td><?= $i->categorie ?></td>
<td><?= $i->designation ?></td>
<td><?= $i->note ?></td>
<td><?= $i->commentaire ?></td>
</tr>
<? endforeach; ?>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready( function() {
$('#competences').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"oLanguage": {
"sUrl": "js/french.txt"
}
});
});
</script>
</body>
</html>
<file_sep>/functions.php
<?php
/**
* Vérifie si il y a un commentaire pour la désignation spécifiée dans les données utilisateur
* @param string $designation
* @return string $commentaire
*/
function commentaire($des) {
global $user;
foreach ($user as $d) {
if ($d->designation == $des && $d->commentaire != FALSE) {
return ($d->commentaire);
}
}
}
/**
* Vérifie si il y a une note pour la désignation spécifiée dans les données utilisateur
* @param string $designation
* @return string $note
*/
function note($des) {
global $user;
foreach ($user as $d) {
if ($d->designation == $des && $d->note != FALSE) {
return ($d->note);
}
}
}
/**
* Envoi des données utilisateur en base de données
* @param array $donnees
*/
function update_user($donnees) {
global $connexion;
foreach ($donnees as $d) {
$sql="SELECT COUNT(*) FROM `competences_users`
WHERE users_id=".$connexion->quote($d['user'], PDO::PARAM_INT)."
AND designation_id=".$connexion->quote($d['designation'], PDO::PARAM_INT);
$array=$connexion->query($sql)->fetch();
if ($array[0] > 0) {
if ($d['note'] == 0) {
$sql="DELETE FROM `competences_users` WHERE users_id=".$connexion->quote($d['user'], PDO::PARAM_INT)." AND designation_id=".$connexion->quote($d['designation'], PDO::PARAM_INT);
$connexion->exec($sql);
} else {
$sql="UPDATE `competences_users` SET note=".$connexion->quote($d['note'], PDO::PARAM_INT).", commentaire=".$connexion->quote($d['commentaire'], PDO::PARAM_STR)." WHERE users_id=".$connexion->quote($d['user'], PDO::PARAM_INT)." AND designation_id=".$connexion->quote($d['designation'], PDO::PARAM_INT);
$connexion->query($sql);
}
} else {
if ($d['note'] > 0) {
$sql="INSERT INTO `competences_users`(users_id, designation_id, note, commentaire) VALUES(".$connexion->quote($d['user'], PDO::PARAM_INT).", ".$connexion->quote($d['designation'], PDO::PARAM_INT).", ".$connexion->quote($d['note'], PDO::PARAM_INT).", ".$connexion->quote($d['commentaire'], PDO::PARAM_STR).")";
$connexion->exec($sql);
}
}
}
}
?>
<file_sep>/categorie.php
<?php
if (isset($_GET['a'])) {
$action = $_GET['a'];
} else {
$action='index';
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
$index = true;
// Inclusion de fluxbb
define('PUN_ROOT', '../home/');
require PUN_ROOT.'include/common.php';
require 'functions.php';
if ($pun_user['is_guest'] == 1) { // L'utilisateur n'est pas connecté
header('Location: login.php');
exit();
} elseif ($pun_user['group_id'] == 1 || $pun_user['group_id'] == 2 || $pun_user['group_id'] == 11) {
// Configuration et connexion MySql
require_once ('config.php');
$sql = "SELECT * FROM competences_categories ORDER BY competences_categories.nom ASC";
$query = $connexion->query($sql);
$categories = $query->fetchAll(PDO::FETCH_OBJ);
$query->closeCursor();
/* Création d'une catégorie */
if ($action == 'new' && isset($_POST['submit']) && isset($_POST['cat'])) {
$cat=$connexion->quote($_POST['cat'], PDO::PARAM_STR);
$sql = "INSERT INTO `competences_categories` (nom) VALUES(".$cat.")";
if ($connexion->exec($sql)) {
$created = TRUE;
} else {
$created = FALSE;
}
}
/* Suppresion d'une catégorie */
if ($action == 'delete' && isset($id)) {
$id=$connexion->quote($id, PDO::PARAM_INT);
$sql="SELECT * FROM competences_categories WHERE id=".$id." ORDER BY competences_categories.nom ASC";
$query=$connexion->query($sql);
$array=$query->fetchAll(PDO::FETCH_ASSOC);
if (isset($array[0])) {
$sql = "DELETE FROM `competences_categories` WHERE id=".$id;
if ($connexion->exec($sql)) {
$deleted = TRUE;
} else {
$deleted = FALSE;
}
} else {
$deleted = FALSE;
}
$query->closeCursor();
}
/* Edition d'une catégorie */
if ($action == 'edit' && isset($id) && isset($_POST['submit']) && isset($_POST['cat'])) {
$cat=$connexion->quote($_POST['cat'], PDO::PARAM_STR);
$id=$connexion->quote($id, PDO::PARAM_INT);
$sql="SELECT * FROM `competences_categories` WHERE id=".$id;
$query=$connexion->query($sql);
$array=$query->fetchAll(PDO::FETCH_ASSOC);
if (isset($array[0])) {
$sql="UPDATE `competences_categories` SET nom=".$cat." WHERE id=".$id;
if ($connexion->query($sql)) {
$edited=TRUE;
} else {
$edited=FALSE;
}
}else {
$edited=FALSE;
}
$query->closeCursor();
} elseif ($action == 'edit' && isset($id) && !isset($_POST['submit']) && !isset($_POST['cat'])) {
$sql="SELECT nom FROM `competences_categories` WHERE id=".$id;
$query=$connexion->query($sql);
$nom=$query->fetch();
$query->closeCursor();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Gestion des catégories</title>
</head>
<body>
<div id="container">
<? if ($action == 'index'): ?>
<a href="?a=new">Nouvelle catégorie</a>
<table id="categories">
<thead>
<tr>
<th>
Catégorie
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
<? foreach ($categories as $cat): ?>
<tr>
<td>
<?= $cat->nom?>
</td>
<td>
<a href="?a=delete&id=<?= $cat->id ?>">Delete</a> <a href="?a=edit&id=<?= $cat->id ?>">Edit</a>
</td>
</tr>
<? endforeach; ?>
</tbody>
</table>
<? elseif ($action == 'delete' && isset($deleted)): ?>
<? if($deleted == TRUE): ?>
<p>La catégorie <?= $cat[0]['nom'] ?> à bien été supprimée !</p>
<? else: ?>
<p>La catégorie n'a pas été supprimée !</p>
<? endif; ?>
<a href="?a=index">Retour aux catégories</a>
<? elseif ($action == 'new'): ?>
<? if (isset($created) && $created==TRUE):?>
<p>La catégorie <?= $cat ?> à bien été crée !</p>
<? elseif (isset($created) && $created==FALSE): ?>
<p>La catégorie <?= $cat ?> n'a pas été crée !</p>
<? endif; ?>
<form id="new" method="post">
<fieldset>
<legend>Nouvelle catégorie</legend>
<input type="text" name="cat" />
<input type="submit" name="submit" value="Créer" />
</fieldset>
</form>
<a href="?a=index">Retour aux catégories</a>
<? elseif ($action == 'edit' && isset($id)): ?>
<? if (isset($edited) && $edited==TRUE):?>
<p>La catégorie <?= $cat ?> à bien été éditée !</p>
<? elseif (isset($edited) && $edited==FALSE): ?>
<p>La catégorie <?= $cat ?> n'a pas été éditée !</p>
<? endif; ?>
<form id="edit" method="post">
<fieldset>
<legend>Edition de catégorie</legend>
<input type="text" name="cat" value="<?= $nom[0] ?>" />
<input type="submit" name="submit" value="Editer" />
</fieldset>
</form>
<a href="?a=index">Retour aux catégories</a>
<? endif; ?>
<a href="index.php" title="Accueil">Retour au tableau des compétences</a>
</div>
</body>
</html>
<?php
}
else {
exit('Vous n\'êtes pas autorisés à venir ici !');
}
?>
|
dc6af29246df244b9d15f8c9d432b0feddde521f
|
[
"PHP"
] | 8
|
PHP
|
devkloud/Competences
|
f9359dce46af2b0a99765713e891826bb63089f1
|
a0b51a84b76110635020fb7e9f20811eaf8e53c4
|
refs/heads/master
|
<repo_name>lancewux/demo-react-ie8-simple<file_sep>/src/index-comment.js
/**
* CANNOT use `import` to import `es5-shim`,
* because `import` will be transformed to `Object.defineProperty` by babel,
* `Object.defineProperty` doesn't exists in IE8,
* (but will be polyfilled after `require('es5-shim')` executed).
*/
// es5-shim.js是给Javascript engine打补丁的, 所以必须最先加载。
// es5-shim 如实地模拟EcmaScript 5的函数,比如Array.prototype.forEach;而es5-sham是尽可能滴模拟EcmaScript 5的函数,比如 Object.create
require('es5-shim');
require('es5-shim/es5-sham');
/**
* CANNOT use `import` to import `react` or `react-dom`,
* because `import` will run `react` before `require('es5-shim')`.
*/
// import React from 'react';
// import ReactDOM from 'react-dom';
const React = require('react');
const ReactDOM = require('react-dom');
import marked from 'marked';
const data = [
{id: 1, author: "<NAME>", text: "This is one comment"},
{id: 2, author: "<NAME>", text: "This is *another* comment"}
];
function createXmlHttp() {
let xmlHttp = null;
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
return xmlHttp;
}
const WelcomeBox = React.createClass({
render: function() {
return (
<div className="comment">
<p>welcome {this.props.name}</p>
</div>
);
}
});
const Timer = React.createClass({
getInitialState: function () {
return {secondsElapsed: 0}
},
tick: function () {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentDidMount: function () {
this.interval = setInterval(this.tick, 1000);
},
componentWillUnmount: function () {
clearInterval(this.interval);
},
render: function() {
return (
<div>
<h3>welcome {this.props.name}</h3>
<h3>Time Elapsed: {this.state.secondsElapsed} seconds.</h3>
</div>
);
}
});
const Comment = React.createClass({
rawMarkup: function() {
const __html = marked(this.props.children.toString(), {sanitize: true});
return { __html };
},
render: function() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={this.rawMarkup()} />
</div>
);
}
});
const CommentList = React.createClass({
render: function() {
const commentNodes = this.props.data.map((comment) => {
return (
<Comment author={comment.author} key={comment.id}>{comment.text}</Comment>
)
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
const CommentForm = React.createClass({
getInitialState: () => {
return {author: '', text: ''};
},
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
handleTextChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
const author = this.state.author.trim();
const text = this.state.text.trim();
if(!author || !text) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
// this.setState({author: '', text: ''});
},
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your name" value={this.state.author} onChange={this.handleAuthorChange} />
<input type="text" placeholder="Say something..." value={this.state.text} onChange={this.handleTextChange} />
<input type="submit" value="Post" />
</form>
);
}
});
const CommentBox = React.createClass({
getInitialState: () => {
return {data: []}
},
loadCommentsFromServer: function() {
const xmlHttp = createXmlHttp();
if(xmlHttp) {
xmlHttp.onreadystatechange = () => {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
console.log(xmlHttp.responseText);
this.setState({data: [{id: 1, author: "<NAME>", text: "This is one comment"}]});
}
};
xmlHttp.open('get', this.props.url, true);
xmlHttp.setRequestHeader('Content-Type', "application/x-www-form-urlencoded");
const body = JSON.stringify({name: 'jack'});
xmlHttp.send(body);
}
},
handleCommentSubmit: function(comment) {
const xmlHttp = createXmlHttp();
if(xmlHttp) {
xmlHttp.onreadystatechange = () => {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
const data = JSON.parse(xmlHttp.responseText);
console.log(data);
this.setState({data: data});
}
};
xmlHttp.open('post', this.props.url, true);
xmlHttp.setRequestHeader("Content-Type", "application/json");//application/x-www-form-urlencoded
// console.log(comment);
const body = JSON.stringify(comment);
// const body= 'name=jack';
console.log(body);
xmlHttp.send(body);
}
},
componentDidMount: function() {
this.loadCommentsFromServer();
// setInterval(this.loadCommentsFromServer, this.props.pollInterval)
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data}/>
<CommentForm onCommentSubmit={this.handleCommentSubmit}/>
</div>
);
}
});
ReactDOM.render(
// <Timer name="Jone"/>,
<CommentBox url="http://127.0.0.1:3001/api/comments" pollInterval={2000}/>,
// <MarkdownEditor/>,
document.getElementById('root')
);
<file_sep>/src/redux/actions.jsx
export const addPerson = (person) => ({
type: 'ADD',
person: person
})
export const deletePerson = () => ({
type: 'DELETE'
})
<file_sep>/src/router/index.jsx
import { Router, Route, Redirect, IndexRoute, browserHistory, hashHistory} from 'react-router'
const React = require('react')
import Home from '../pages/Home'
import About from '../pages/About'
const RouteConfig = (
<Router history={browserHistory}>
<Route path="/" component={Home}>
<IndexRoute component={About} />//首页
<Redirect from='*' to='/' />
</Route>
</Router>
)
export default RouteConfig
<file_sep>/src/index-router.js
require('es5-shim');
require('es5-shim/es5-sham');
const React = require('react');
const ReactDOM = require('react-dom');
import { Router, Route, hashHistory, IndexRoute } from 'react-router'
import { browserHistory } from 'react-router'
import App from './App'
import About from './About'
import Repos from './Repos'
import Repo from './Repo'
import Home from './Home'
ReactDOM.render(
(
<Router history={browserHistory}>
<Route path="/" component={App}>
{/* add it here, as a child of `/` */}
<IndexRoute component={Home}/>
<Route path="/repos" component={Repos}>
<Route path="/repos/:userName/:repoName" component={Repo}/>
</Route>
<Route path="/about" component={About}/>
</Route>
</Router>
),
document.getElementById('root')
);<file_sep>/src/redux/reducers.jsx
import { combineReducers } from 'redux'
export default combineReducers({
person,
animal
})
const person = (state = [], action) => {
switch (action.type) {
case 'ADD':
return [...state, action.person]
case 'DELETE':
return state.slice(0, state.length - 2)
default:
return state
}
}
const animal = (state = [], action) => {
switch (action.type) {
case 'ADD':
return [...state, action.animal]
case 'DELETE':
return state.length - 1 > 0 ? state.slice(0, state.length - 2) : []
default:
return state
}
}
|
26f59ddd995b708ebb91542570b6d2550664265a
|
[
"JavaScript"
] | 5
|
JavaScript
|
lancewux/demo-react-ie8-simple
|
b357a9970744bc9db1d8ee07da07575be1ff8266
|
7ebe36ad4f619ab451d75e88c734cbdb8519b618
|
refs/heads/master
|
<file_sep># Utopia AB Tests
[](https://travis-ci.com/utopia-php/ab)

[](https://appwrite.io/discord)
Utopia AB Tests library is simple and lite library for managing AB tests on the server side. This library is aiming to be as simple and easy to learn and use. This library is maintained by the [Appwrite team](https://appwrite.io).
Although this library is part of the [Utopia Framework](https://github.com/utopia-php/framework) project it is dependency free and can be used as standalone with any other PHP project or framework.
## Getting Started
Install using composer:
```bash
composer require utopia-php/ab
```
```php
<?php
require_once '../vendor/autoload.php';
use Utopia\AB\Test;
$test = new Test('example');
$test
->variation('title1', 'Hello World', 40) // 40% probability
->variation('title2', 'Foo Bar', 30) // 30% probability
->variation('title3', function () { // 30% probability
return 'Title from a callback function';
}, 30)
;
$debug = [];
for($i=0; $i<10000; $i++) {
$debug[$test->run()]++;
}
var_dump($debug);
```
If no probability value is passed to the variation, all variations with no probability values will be given equal values from the remaining 100% of the test variations.
When passing a closure as value for your variation the callback will be executed only once the test is being run using the Test::run() method.
## System Requirements
Utopia Framework requires PHP 7.4 or later. We recommend using the latest PHP version whenever possible.
## Authors
**<NAME>**
+ [https://twitter.com/eldadfux](https://twitter.com/eldadfux)
+ [https://github.com/eldadfux](https://github.com/eldadfux)
## Copyright and license
The MIT License (MIT) [http://www.opensource.org/licenses/mit-license.php](http://www.opensource.org/licenses/mit-license.php)
<file_sep><?php
/**
* Utopia PHP Framework
*
* @package AB
* @subpackage Tests
*
* @link https://github.com/utopia-php/framework
* @author <NAME> <<EMAIL>>
* @version 1.0 RC4
* @license The MIT License (MIT) <http://www.opensource.org/licenses/mit-license.php>
*/
namespace Utopia\Tests;
use Utopia\AB\Test;
use PHPUnit\Framework\TestCase;
class TestTest extends TestCase
{
/**
* @var Test
*/
protected $test = null;
public function setUp(): void
{
$this->test = new Test('unit-test');
}
public function tearDown(): void
{
$this->test = null;
}
public function testTest()
{
$this->test
->variation('title1', 'Title: Hello World', 40) // 40% probability
->variation('title2', 'Title: Foo Bar', 30) // 30% probability
->variation('title3', function () {
return 'Title: Title from a callback function';
}, 30) // 30% probability
;
for($i=0; $i<100; $i++) {
$value = $this->test->run();
$this->assertStringStartsWith('Title:', $value);
}
$this->test
->variation('title1', 'Title: Hello World', 100) // 100% probability
->variation('title2', 'Title: Foo Bar', 0) // 0% probability
->variation('title3', function () {
return 'Title: Title from a callback function';
}, 0) // 0% probability
;
for($i=0; $i<100; $i++) {
$value = $this->test->run();
$this->assertEquals('Title: Hello World', $value);
}
$test = new Test('another-test');
$test
->variation('option1', 'title1')
->variation('option2', 'title2')
->variation('option3', 'title3')
;
$test->run();
$results = Test::results();
$this->assertArrayHasKey('unit-test', $results);
$this->assertArrayHasKey('another-test', $results);
}
}<file_sep><?php
namespace Utopia\AB;
use Exception;
class Test
{
/**
* @var array
*/
static protected $results = [];
/**
* Get Result of All Tests
*
* @return array
*/
static public function results()
{
return self::$results;
}
/**
* Test Name
*
* @var string
*/
protected $name = '';
/**
* Test Variations
*
* @var array
*/
protected $variations = [];
/**
* Test Variations Probabilities
*
* @var array
*/
protected $probabilities = [];
/**
* Test constructor.
*
* @param string $name
*/
public function __construct(string $name)
{
$this->name = $name;
}
/**
* Add a New Variation to Test
*
* @param string $name
* @param mixed $value
* @param $probability
* @return $this
*/
public function variation(string $name, $value, int $probability = null): self
{
$this->variations[$name] = $value;
$this->probabilities[$name] = $probability;
return $this;
}
/**
* Run Test and Get Result
*
* @throws Exception
*
* @return mixed
*/
public function run()
{
$result = $this->chance();
$return = $this->variations[$result];
if (\is_callable($return)) {
$return = $return();
}
self::$results[$this->name] = $return;
return $return;
}
/**
* Get Random Variation Based on Probabilities Chance
*
* @throws Exception
* @return string
*/
protected function chance(): string
{
$sum = 0;
$empty = 0;
foreach ($this->probabilities as $name => $value) {
$sum += $value;
if (empty($value)) {
$empty++;
}
}
if ($sum > 100) {
throw new Exception('Test Error: Total variation probabilities is bigger than 100%');
}
if ($sum < 100) { // Auto set probability when it has no value
foreach ($this->probabilities as $name => $value) {
if (empty($value)) {
$this->probabilities[$name] = (100 - $sum) / $empty;
}
}
}
$number = \rand(0, (int)\array_sum($this->probabilities) * 10);
$starter = 0;
$return = '';
foreach ($this->probabilities as $key => $val) {
$starter += $val * 10;
if ($number <= $starter) {
$return = $key;
break;
}
}
return $return;
}
}
|
c5c8b051c0a3f680b73b393291468775b1269ff6
|
[
"Markdown",
"PHP"
] | 3
|
Markdown
|
deek121477/ab
|
628a5c5458968c9636e4decf0e4d41ce09493c15
|
43fcc25ddfb2b77d96c79966345e2fff24adaa6f
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
# freq,word_count , tf, num_docs_containing, idf, tf_idf forked(and modified) from from https://gist.github.com/AloneRoad/1605037
# to do extend the base case, lemmatization , dispersion plots & concordance in NLTK and other hacks on base below
#stop words not correctly parsing, need to fix that
"""
usage : sim (dict) has the relavant tf-idf scores of doc{1,2,3,4} with base query
sorted_x simply has the tf-idf scores rank ordered in descending order
Using this as the base case - I will write custom job feed in tf_idf_linkedin_Jobfeed.py
"""
import re , nltk
from nltk.tokenize import RegexpTokenizer
#import tokenize
from itertools import chain
from nltk import bigrams, trigrams
import math, string
import urllib2, urllib
import csv
import operator # for sorting the values of a dict
"""x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))"""
# TD-idf small example
doc_list =["data mining machine learning python NLP NLTK predictive modelling","Big data relevance machine learning","analytics predictive modelling" , "data munging tatistics predictive modelling NLTK natutal language"]
#Base Query
query="search relevance data engineer "
query_name="query"
top_k=3
# list_of_words is a dict which has the summary of top_k words in the doc
#for docs in doc_list , build doc_names
doc_names=[]
for i in range(0,len(doc_list)):
doc_names.append('doc'+str(i+1))
tokenizer = RegexpTokenizer('\w+|\$[\d\.]+|\S+')
def freq(word, doc,docs):
return docs[doc]['tokens'].count(word)
def word_count(docs,doc):
return len(docs[doc]['tokens'])
def tf(word, doc,docs):
return (freq(word, doc,docs) / float(word_count(docs,doc)))
def num_docs_containing(word, list_of_docs,docs,doc_names):
count = 0
for document in doc_names:
if freq(word,document,docs) > 0:
count += 1
return count
def idf(word, list_of_docs,docs,doc_names):
if num_docs_containing(word, list_of_docs,docs,doc_names)!=0:
return math.log(len(list_of_docs) /
float(num_docs_containing(word, list_of_docs,docs,doc_names)))
else :
return 0
def tf_idf(word, doc, list_of_docs,docs,doc_names):
return (tf(word, doc,docs) * idf(word, list_of_docs,docs,doc_names))
docs={}
i=0
for doc_no in doc_names:
docs[doc_no] = {'freq': {}, 'tf': {}, 'idf': {},'tf-idf': {}, 'tokens': []}
tokens = tokenizer.tokenize(doc_list[i])
docs[doc_no]['tokens']=tokens
i=i+1
for doc_no in doc_names:
for token in docs[doc_no]['tokens']:
docs[doc_no]['freq'][token]=freq(token, doc_no,docs)
docs[doc_no]['tf'][token]=tf(token, doc_no,docs)
docs[doc_no]['idf'][token]=idf(token, doc_list,docs,doc_names)
docs[doc_no]['tf-idf'][token]=tf_idf(token, doc_no, doc_list,docs,doc_names)
#post this the whole docs (dict of dict of 'freq', 'tf', 'idf','tf-idf', 'tokens', of which we will need only tf-idf list, corresponding to the individual tokens in that doc
#print docs
"""
# To test & understand the base code use the doc_list input.
# The functions from Marcelo's had some severe flaws, which I rectified, and I hope you will be able to see them now. for one, IDF can NEVER be negative, unless you use the augmented/custom tf-idf , see more at wiki-
http://en.wikipedia.org/wiki/Tf%E2%80%93idf
"""
#Build the global vocab now
global_vocab =[]
for doc_no in doc_names:
for token in set(docs[doc_no]['tokens']):
if token not in global_vocab:
global_vocab.append(token)
elif token in global_vocab:
pass
#print global_vocab -> All (global)terms in the corpus
dict_tf_idf={}
for token in global_vocab:
dict_tf_idf[token] = dict((str(doc_no), '') for doc_no in doc_names)
for token in global_vocab :
for doc_no in doc_names:
if token in global_vocab and token in docs[doc_no]['tokens']:
dict_tf_idf[token][doc_no] = docs[doc_no]['tf-idf'][token]
elif token in global_vocab and token not in docs[doc_no]['tokens']:
dict_tf_idf[token][doc_no] = 0
#print dict_tf_idf
list_of_words={}
# Find what are the top terms by tf-id per doc- ie what terms summarize a doc
for doc_no in doc_names[0:len(doc_names)] :
x=docs[doc_no]['tf-idf']
sorted_y = sorted(x.iteritems(), key=operator.itemgetter(1))
sorted_y.reverse()
list_of_words[doc_no]=[sorted_y[0:top_k]]
#print list_of_words
#sorted_y has the sorted list by tf-ids
# Now we need to do two things 1) Find the Sim(query,doc) and find tf-idf for the base against the whole corpus 2) For each doc_name, find the k most significant words
# TD-IDF of query
query_dict={}
docs_entire={}
# z is the merged corpus including the query+ docs
entire_corpus_list=[]
entire_corpus_list=doc_list
entire_corpus_list.append(query)
entire_corpus_names=[]
entire_corpus_names=doc_names
entire_corpus_names.append(query_name)
query_dict[query_name] = {'freq': {}, 'tf': {}, 'idf': {},'tf-idf': {}, 'tokens': []}
tokens = tokenizer.tokenize(query)
query_dict[query_name]['tokens']=tokens
for token in query_dict[query_name]['tokens']:
query_dict[query_name]['freq'][token]=freq(token, query_name,query_dict)
query_dict[query_name]['tf'][token]=tf(token, query_name,query_dict)
docs_entire = dict(docs.items() + query_dict.items())
for token in query_dict[query_name]['tokens']:
query_dict[query_name]['idf'][token]=idf(token, entire_corpus_list,docs_entire,entire_corpus_names)#list_of_docs,docs,doc_names
query_dict[query_name]['tf-idf'][token]=tf_idf(token, query_name, entire_corpus_list,docs_entire,entire_corpus_names)
#updating global var for tokens only in base query is not required since tf-idf when doing similarity will be 0 anyways.
query_dict_tf_idf={}
for token in global_vocab:
query_dict_tf_idf[token] = {query_name:{}}
for token in global_vocab :
if token in global_vocab and token in query_dict[query_name]['tokens']:
query_dict_tf_idf[token][query_name] = query_dict[query_name]['tf-idf'][token]
else:
#if token in global_vocab and token not in query_dict[query_name]['tokens']:
query_dict_tf_idf[token][query_name]= 0
#print query_dict_tf_idf
# merging both the doc_tf_idf_dicts and dict_tf_idf
sim={}
for doc_name in doc_names[0:len(doc_names)-1] :
sim[str(doc_name),query_name] = {'tf-idf': 0}
for doc_name in doc_names[0:len(doc_names)-1] :
normalize_query=0
normalize_doc=0
for token in dict_tf_idf.keys():
if dict_tf_idf[token][doc_name] !=0 and query_dict_tf_idf[token][query_name] !=0 :
#print "printing the values of the tf-idf of tokens"
#print doc_name, token, dict_tf_idf[token][doc_name] , query_dict_tf_idf[token][query_name]
sim[str(doc_name),query_name]['tf-idf']= sim[str(doc_name),query_name]['tf-idf']+dict_tf_idf[token][doc_name]*query_dict_tf_idf[token][query_name]
normalize_doc=dict_tf_idf[token][doc_name]*dict_tf_idf[token][doc_name]+normalize_doc
normalize_query=query_dict_tf_idf[token][query_name]*query_dict_tf_idf[token][query_name]+normalize_query
#print doc_name, token, sim[str(doc_name),query_name]['tf-idf'] , normalize_doc, normalize_query
else :
pass
if (math.sqrt(normalize_query)*math.sqrt(normalize_doc)) !=0:
sim[str(doc_name),query_name]['tf-idf']=sim[str(doc_name),query_name]['tf-idf']/(math.sqrt(normalize_query)*math.sqrt(normalize_doc))
#print sim[str(doc_name),query_name]['tf-idf']
#print " "
else :
sim[str(doc_name),query_name]['tf-idf']=0.0
#print sim[str(doc_name),query_name]['tf-idf']
#print " "
# Rank order the sim values across the docs
x={}
for items in sim.keys():
x[items]=sim[items]['tf-idf']
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
sorted_x.reverse()
#sorted_x.reverse() has the list of docs sorted by top tf-idf
#unit test the sim for tf-idf - write everything to csv file
f=open("C:\Users\ekta\Desktop\unittest_tf_idf_Linkedin10.csv", "wb")
mywriter = csv.writer(f,dialect='excel')
#Note I am re-using m on purpose
for doc_no in doc_names[0:len(doc_name)]:
mywriter.writerow([doc_no])
m=docs[doc_no]['tf'].keys()
m.insert(0,"keys")
mywriter.writerow(m)
m=docs[doc_no]['tf'].values()
m.insert(0,"tf")
mywriter.writerow(m)
m=docs[doc_no]['idf'].values()
m.insert(0,"idf")
mywriter.writerow(m)
m=docs[doc_no]['tf-idf'].values()
m.insert(0,"tf-idf")
mywriter.writerow(m)
mywriter.writerow([""])
mywriter.writerow([query_name])
m=query_dict['query']['tf'].keys()
m.insert(0,"keys")
mywriter.writerow(m)
m=query_dict['query']['tf'].values()
m.insert(0,"tf")
mywriter.writerow(m)
m=query_dict['query']['idf'].values()
m.insert(0,"idf")
mywriter.writerow(m)
m=query_dict['query']['tf-idf'].values()
m.insert(0,"tf-idf")
mywriter.writerow(m)
mywriter.writerow([""])
f.close()
<file_sep>Creating-Custom-job-feeds-for-Linkedin
======================================
This project has two parts
Part 1 : Creating a quick csv file from the job pages from Linkedin using url_open & clean html contructs (for quick-win) and having some predefined filters, for location, and other advanced filters.
In general all the 'jobs" at linkedin follow one of the below categories -:
1. The job you're looking for is no longer active
2 We can't find the job you're looking for
3 The job passes your filtering criteria (location, Skill-specific keywords etc)
4 The job is active, but does not pass your ltering criteria
Looping constructs extend this list and can virtually go (snoop) around a lot more pages
I exploit this to find and narrow down our corpus so that the tokenization in part 2, which is based on urls of interest from part 1 , is smart and quick
Part 2 : I use the TF-IDF on the base (resume of interest) and other jobs (urls shortlisted from Part 1, or otherwise), and develop similarity between the Job posting and the base resume.
Finally I will do the visualizable in Gephi.
<file_sep># See also tf_idf_linkedin.py for a much simpler example. See the file file for credits on 3 functions on tf-idf.
#Author : <NAME>, <EMAIL>
#tf_idf_linkedin_Jobfeed.py
import re , nltk
from nltk.tokenize import RegexpTokenizer
#import tokenize
from itertools import chain
from nltk import bigrams, trigrams
import math, string
import urllib2, urllib
import csv
import operator
#Base Query
query="data mining machine learning python NLP NLTK predictive modelling artificial intelligence research scientist auction theory applied science collective intelligence analytics analyst"
query=query.lower()
query_name="query"
doc_names=[]
top_k=10
# list_of_words is a dict which has the summary of top_k words in the doc
#for docs in doc_list , build doc_names
Y=[5796385, 6052768, 6175979, 6216895, 6222577, 6583427, 6584834, 6626351, 6723434, 6811983, 6836724, 6979495]
url=[]
for k in range(0,len(Y)):
temp="http://www.linkedin.com/jobs?viewJob=&jobId="+str(Y[k])+"&trk=rj_jshp"
url.append(temp)
doc_list=[]
#doc_names=raw.split("\n")[0].replace(" - Job | LinkedIn","").strip()
stopwords2=["after","about","jobs", "join","also","across","additional","agreement","area","community","company","companys","cookie","copy","copyright","corporate","corporation","could","create","current","computer","expertise","external","faster","focusedon","half","hired","home","people","new","following","full","fulltime","functions","services","show","sign","similar","skills","solutions","staff","starts","requires","policy","post","presentations","privacy","problems","products"]
for k in range(0,len(url)):
html = urllib.urlopen(url[k]).read()
raw = nltk.clean_html(html)
if (raw.find("The job you’re looking for is no longer active")>=1 or raw.find("We can’t find the job you’re looking for")>=1):
pass
elif (raw.find("Bangalore")!=-1 or raw.find("Bengaluru")!=-1):
doc_names.append(raw.split("\n")[0].replace(" - Job | LinkedIn","").strip())
index_begin=raw.find("main content starts below")
if index_begin !=-1 :
index_begin=index_begin+len("main content starts below")
elif index_begin ==-1 :
index_begin==raw.find("Skip to main content")
if (index_begin!=-1):
index_begin=index_begin+len("Skip to main content")
index_end=raw.find("Sign in to view similar jobs")
if index_end !=-1 and index_begin !=-1:
raw=raw[index_begin:index_end]
elif index_end !=-1 or index_begin !=-1:
pass
# if we dont find both these contents, then just skip
special_punct=["/", ":" ,"-","&","(",")","{","}"]
for i in range(0,len(special_punct)):
if special_punct[i] in raw:
raw=raw.replace(special_punct[i]," ")
for c in string.punctuation:
raw= raw.replace(c,"")
raw=raw.lower()
doc_list.append(raw)
# string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
stopwords = nltk.corpus.stopwords.words('english')
stopwords.append(stopwords2)
stopwords=list(chain.from_iterable(stopwords))
tokenizer = RegexpTokenizer('\w+|\$[\d\.]+|\S+')
def freq(word, doc,docs):
return docs[doc]['tokens'].count(word)
def word_count(docs,doc):
return len(docs[doc]['tokens'])
def tf(word, doc,docs):
return (freq(word, doc,docs) / float(word_count(docs,doc)))
def num_docs_containing(word, list_of_docs,docs,doc_names):
count = 0
for document in doc_names:
if freq(word,document,docs) > 0:
count += 1
return count
def idf(word, list_of_docs,docs,doc_names):
if num_docs_containing(word, list_of_docs,docs,doc_names)!=0:
return math.log(len(list_of_docs) /
float(num_docs_containing(word, list_of_docs,docs,doc_names)))
else :
return 0
def tf_idf(word, doc, list_of_docs,docs,doc_names):
return (tf(word, doc,docs) * idf(word, list_of_docs,docs,doc_names))
docs={}
i=0
for doc_no in doc_names:
docs[doc_no] = {'freq': {}, 'tf': {}, 'idf': {},'tf-idf': {}, 'tokens': []}
tokens = tokenizer.tokenize(doc_list[i])
docs[doc_no]['tokens']=tokens
i=i+1
for doc_no in doc_names:
for token in docs[doc_no]['tokens']:
docs[doc_no]['freq'][token]=freq(token, doc_no,docs)
docs[doc_no]['tf'][token]=tf(token, doc_no,docs)
docs[doc_no]['idf'][token]=idf(token, doc_list,docs,doc_names)
docs[doc_no]['tf-idf'][token]=tf_idf(token, doc_no, doc_list,docs,doc_names)
#post this the whole docs (dict of dict of 'freq', 'tf', 'idf','tf-idf', 'tokens', of which we will need only tf-idf list, corresponding to the individual tokens in that doc
#print docs
#Build the global vocab now
global_vocab =[]
for doc_no in doc_names:
for token in set(docs[doc_no]['tokens']):
if token not in global_vocab:
global_vocab.append(token)
elif token in global_vocab:
pass
#print global_vocab -> All (global)terms in the corpus
dict_tf_idf={}
for token in global_vocab:
dict_tf_idf[token] = dict((str(doc_no), '') for doc_no in doc_names)
for token in global_vocab :
for doc_no in doc_names:
if token in global_vocab and token in docs[doc_no]['tokens']:
dict_tf_idf[token][doc_no] = docs[doc_no]['tf-idf'][token]
elif token in global_vocab and token not in docs[doc_no]['tokens']:
dict_tf_idf[token][doc_no] = 0
#print dict_tf_idf
list_of_words={}
# Find what are the top terms by tf-id per doc- ie what terms summarize a doc
for doc_no in doc_names[0:len(doc_names)] :
x=docs[doc_no]['tf-idf']
sorted_y = sorted(x.iteritems(), key=operator.itemgetter(1))
sorted_y.reverse()
list_of_words[doc_no]=[sorted_y[0:top_k]]
#print list_of_words
# Now we need to do two things 1) Find the Sim(query,doc) and find tf-idf for the base against the whole corpus 2) For each doc_name, find the k most significant words
# TD-IDF of query
query_dict={}
docs_entire={}
# z is the merged corpus including the query+ docs
entire_corpus_list=[]
entire_corpus_list=doc_list
entire_corpus_list.append(query)
entire_corpus_names=[]
entire_corpus_names=doc_names
entire_corpus_names.append(query_name)
query_dict[query_name] = {'freq': {}, 'tf': {}, 'idf': {},'tf-idf': {}, 'tokens': []}
tokens = tokenizer.tokenize(query)
query_dict[query_name]['tokens']=tokens
for token in query_dict[query_name]['tokens']:
query_dict[query_name]['freq'][token]=freq(token, query_name,query_dict)
query_dict[query_name]['tf'][token]=tf(token, query_name,query_dict)
docs_entire = dict(docs.items() + query_dict.items())
for token in query_dict[query_name]['tokens']:
query_dict[query_name]['idf'][token]=idf(token, entire_corpus_list,docs_entire,entire_corpus_names)#list_of_docs,docs,doc_names
query_dict[query_name]['tf-idf'][token]=tf_idf(token, query_name, entire_corpus_list,docs_entire,entire_corpus_names)
#updating global var for tokens only in base query is not required since tf-idf when doing similarity will be 0 anyways.
query_dict_tf_idf={}
for token in global_vocab:
query_dict_tf_idf[token] = {query_name:{}}
for token in global_vocab :
if token in global_vocab and token in query_dict[query_name]['tokens']:
query_dict_tf_idf[token][query_name] = query_dict[query_name]['tf-idf'][token]
else:
#if token in global_vocab and token not in query_dict[query_name]['tokens']:
query_dict_tf_idf[token][query_name]= 0
#print query_dict_tf_idf
# merging both the doc_tf_idf_dicts and dict_tf_idf
sim={}
for doc_name in doc_names[0:len(doc_names)-1] :
sim[str(doc_name),query_name] = {'tf-idf': 0}
for doc_name in doc_names[0:len(doc_names)-1] :
normalize_query=0
normalize_doc=0
for token in dict_tf_idf.keys():
if dict_tf_idf[token][doc_name] !=0 and query_dict_tf_idf[token][query_name] !=0 :
sim[str(doc_name),query_name]['tf-idf']= sim[str(doc_name),query_name]['tf-idf']+dict_tf_idf[token][doc_name]*query_dict_tf_idf[token][query_name]
normalize_doc=dict_tf_idf[token][doc_name]*dict_tf_idf[token][doc_name]+normalize_doc
normalize_query=query_dict_tf_idf[token][query_name]*query_dict_tf_idf[token][query_name]+normalize_query
else :
pass
if (math.sqrt(normalize_query)*math.sqrt(normalize_doc)) !=0:
sim[str(doc_name),query_name]['tf-idf']=sim[str(doc_name),query_name]['tf-idf']/(math.sqrt(normalize_query)*math.sqrt(normalize_doc))
else :
sim[str(doc_name),query_name]['tf-idf']=0.0
# Rank order the sim values across the docs
x={}
for items in sim.keys():
x[items]=sim[items]['tf-idf']
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
sorted_x.reverse()
#sorted_x.reverse() has the list of docs sorted by top tf-idf
#The sim for tf-idf - write everything to csv file
f=open("C:\Users\ekta\Desktop\unittest_tf_idf_Linkedin5.csv", "wb")
mywriter = csv.writer(f,dialect='excel')
#Note I am re-using m on purpose
for doc_no in doc_names[0:len(doc_names)-1]:
mywriter.writerow([doc_no])
m=docs[doc_no]['tf'].keys()
m.insert(0,"keys")
mywriter.writerow(m)
m=docs[doc_no]['tf'].values()
m.insert(0,"tf")
mywriter.writerow(m)
m=docs[doc_no]['idf'].values()
m.insert(0,"idf")
mywriter.writerow(m)
m=docs[doc_no]['tf-idf'].values()
m.insert(0,"tf-idf")
mywriter.writerow(m)
mywriter.writerow([""])
mywriter.writerow([query_name])
m=query_dict['query']['tf'].keys()
m.insert(0,"keys")
mywriter.writerow(m)
m=query_dict['query']['tf'].values()
m.insert(0,"tf")
mywriter.writerow(m)
m=query_dict['query']['idf'].values()
m.insert(0,"idf")
mywriter.writerow(m)
m=query_dict['query']['tf-idf'].values()
m.insert(0,"tf-idf")
mywriter.writerow(m)
mywriter.writerow([""])
f.close()
# Write 3 csv files with final results
#writing realtionships
f=open("C:\Users\ekta\Desktop\unittest_tf_idf_Linkedin51.csv", "wb")
mywriter = csv.writer(f,dialect='excel')
mywriter.writerow(["Job description","Tf-Idf value"])
for i in range(0,len(doc_names)-1):
mywriter.writerow([sorted_x[i][0][0],sorted_x[i][1]])
f.close()
#,list_of_words[sorted_x[i][0][0]]]
f=open("C:\Users\ekta\Desktop\unittest_tf_idf_Linkedin52.csv", "wb")
mywriter = csv.writer(f,dialect='excel')
mywriter.writerow(["Job description"])
mywriter.writerow([""])
#,"list_of_words","Tf-idf values"])
for i in range(0,len(doc_names)-1):
mywriter.writerow([sorted_x[i][0][0]])
mywriter.writerow(["list_of_words","Tf-idf values"])
for m in range(0,top_k):
mywriter.writerow([list_of_words[sorted_x[i][0][0]][0][m][0], list_of_words[sorted_x[i][0][0]][0][m][1]])
mywriter.writerow([""])
f.close()
<file_sep>#building list of urls to build custom job feed to pass into the TF-IDF NLTK file
# To do error handling for urls not found and similar jobs etc..
# Explore & compare the similar logic with linkedin's REST API
# Author : <NAME>, <EMAIL>
import os
import nltk, re
import socket
import matplotlib
#from urllib import urlopen
import csv
import urllib2
import urllib
#os.environ['http_proxy']=''
list_url=[]
m=0
company_name=[]
Title_Position=[]
posted_date=[]
Functions=[]
Industries=[]
#Y1=range(1000000:2000000)
#Y2=range(6000000:6999999)
#temp="http://www.linkedin.com/jobs?viewJob=&jobId="+str(Y2[k])+"&trk=rj_jshp"
url1=["http://www.linkedin.com/jobs?jobId=6836724&viewJob=&trk=rj_jshp", "http://www.linkedin.com/jobs?viewJob=&jobId=6175979&trk=rj_jshp", "http://www.linkedin.com/jobs?viewJob=&jobId=6723434&trk=rj_jshp" , "http://www.linkedin.com/jobs?viewJob=&jobId=6052768&trk=rj_jshp","http://www.linkedin.com/jobs?viewJob=&jobId=69999&trk=rj_jshp","http://www.linkedin.com/jobs?viewJob=&jobId=6&trk=rj_jshp"]
#for k in range(0,len(Y2)):
#temp="http://www.linkedin.com/jobs?viewJob=&jobId="+str(Y2[k])+"&trk=rj_jshp"
for k1 in range(0,len(url1)):
html = urllib.urlopen(url1[k1]).read()
raw = nltk.clean_html(html)
if (raw.find("The job you’re looking for is no longer active")>=1 or raw.find("We can’t find the job you’re looking for")>=1):
pass
elif (raw.find("Bangalore")!=-1 or raw.find("Bengaluru")!=-1):
print 'going here'
# appending only "local" jobs and job posted in August
# not filtering by "recency" which can be had from "Posted" field, since if the job does not display "no longer active" means, it must be active
list_url.append(url1[k1])
Title_Position.append(raw.split("\n")[0].strip())
index_begin=Title_Position[m].find(" at ")
index_end=Title_Position[m].find(" in ")
#index bewteen at and in else "N/A"
if index_begin !=-1 and index_end !=-1 :
company_name.append(Title_Position[m][index_begin+4:index_end].strip())
else :
company_name.append("NA")
#index bewteen at and in else "N/A"
#finding posted on - pattern Posted: \n August 2, 2013 \n\n Type
index_begin=raw.find("Posted: ")
index_end=raw.find("Type:")
if index_begin !=-1 and index_end !=-1 :
posted_date.append(raw[index_begin+8:index_end].replace("\n","").strip())
else :
posted_date.append("NA")
#Functions & Industries
index_begin=raw.find("Functions: ")
index_end=raw.find("Industries:")
if index_begin !=-1 and index_end !=-1 :
Functions.append(raw[index_begin+11:index_end].replace("\n","").strip())
else :
Functions.append("NA")
#industries
index_begin=raw.find("Industries:")
index_end=raw.find("Job ID:")
if index_begin !=-1 and index_end !=-1 :
Industries.append(raw[index_begin+11:index_end].replace("\n","").strip())
else :
Industries.append("NA")
#similar jobs
"""index_begin=raw.find("Similar Jobs")
index_end=raw.find("Sign in to view similar jobs")
if index_begin !=-1 and index_end !=-1 :
Industries.append(raw(index_begin+12:index_end).replace("\n","").strip())
else :
Industries.append("NA") """
m=m+1
if len(list_url)<1:
print "no Active job in this list"
#else print the list of active jobs in a csv file
else :
mywriter = csv.writer(open("C:\Users\ekta\Desktop\LinkedinCustomJobFeed.csv", "wb"))
head = ("Company Name","Title of Position", "Job Posting Url", "Posted on","Functions","Industry")
mywriter.writerow(head)
for i in range(0,len(list_url)):
mywriter.writerow([company_name[i],Title_Position[i],list_url[i],posted_date[i],Functions[i],Industries[i]])
print ' Finished writing the csv file '
|
6d7b517af773d735346f2f235832140ca63976e9
|
[
"Markdown",
"Python"
] | 4
|
Python
|
ekta1007/Creating-Custom-job-feeds-for-Linkedin
|
f89ef844751a13f5774fbf70f37aee26fb87c705
|
2f95f4f51ed8951f8626576fa30b6ac37fdaa20d
|
refs/heads/master
|
<file_sep>from django.contrib import admin
from .models import Car, CarStatus, Customer, Driver, Location, RentCar
admin.site.register(Car)
admin.site.register(CarStatus)
admin.site.register(Customer)
admin.site.register(Driver)
admin.site.register(Location)
admin.site.register(RentCar)
<file_sep># Generated by Django 2.1.7 on 2019-02-17 03:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Car',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('brand_name', models.CharField(max_length=100)),
('model_name', models.CharField(max_length=100)),
('car_number', models.CharField(max_length=100)),
('total_seat', models.CharField(max_length=2)),
],
),
]
<file_sep>"""rent_car URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from .views import *
urlpatterns = [
path('', IndexView.as_view(), name="index"),
path('add_car', AddCarView.as_view(), name="add_car"),
path('car/<car_id>', EditCarView.as_view(), name="edit_car"),
path('car/<car_id>/delete', DeleteCarView.as_view(), name="delete_car"),
path('add_customer', AddCustomerView.as_view(), name="add_customer"),
path('customer/<customer_id>', EditCustomerView.as_view(), name="edit_customer"),
path('customer/<customer_id>/delete', DeleteCustomerView.as_view(), name="delete_customer"),
path('add_driver', AddDriverView.as_view(), name="add_driver"),
path('driver/<driver_id>', EditDriverView.as_view(), name="edit_driver"),
path('driver/<driver_id>/delete', DeleteDriverView.as_view(), name="delete_driver"),
path('add_location', AddLocationView.as_view(), name="add_location"),
path('location/<location_id>', EditLocationView.as_view(), name="edit_location"),
path('location/<location_id>/delete', DeleteLocationView.as_view(), name="delete_location"),
path('add_rent_car', AddRentCarView.as_view(), name="add_rent_car"),
path('rent_car/<rent_car_id>', EditRentCarView.as_view(), name="edit_rent_car"),
path('rent_car/<rent_car_id>/delete', DeleteRentCarView.as_view(), name="delete_rent_car"),
path('add_car_status', AddCarStatusView.as_view(), name="add_car_status"),
path('car_status/<car_status_id>', EditCarStatusView.as_view(), name="edit_car_status"),
path('car_status/<car_status_id>/delete', DeleteCarStatusView.as_view(), name="delete_car_status"),
]
<file_sep>from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.generic import *
from django.views.generic.edit import FormView
from .forms import AddCarForm, AddCustomerForm, AddCarStatusForm, AddDriverForm, AddLocationForm, AddRentCarForm
from .models import Car, CarStatus, Customer, Driver, Location, RentCar
## ================================== Index Page ============================================
class IndexView(TemplateView):
template_name = 'rent_cars/index.html'
def cards(self):
context = {
'total_car' : Car.objects.all().count,
'on_travel' : CarStatus.objects.filter(car_status='OT').count,
'in_service' : CarStatus.objects.filter(car_status='IS').count,
'advance_booking' : CarStatus.objects.filter(car_status='AB').count,
}
return context
def get(self,request, **kwargs):
context = {
'cars' : Car.objects.all(),
'available_cars': Car.objects.filter(carstatus__car_status='AV')
}
context['cards'] = self.cards()
return render(request, self.template_name, context)
## ================================== Car Information Page ============================================
class AddCarView(FormView):
template_name = 'rent_cars/add_car.html'
form_class = AddCarForm
def get(self,request, **kwargs):
context = {
'cars': Car.objects.all(),
'form': self.form_class
}
return render(request, self.template_name, context)
def post(self,request, **kwargs):
model = AddCarForm(request.POST)
model.save()
context = {
'cars': Car.objects.all(),
'form': self.form_class
}
return render(request, self.template_name, context)
class EditCarView(TemplateView):
template_name = 'rent_cars/edit_car.html'
def get(self,request, car_id, **kwargs):
context = {
'car': Car.objects.get(pk=car_id),
}
return render(request, self.template_name, context)
def post(self,request, car_id, **kwargs):
car_update = Car.objects.get(id=car_id)
car_update.brand_name=request.POST['brand_name']
car_update.model_name=request.POST['model_name']
car_update.car_number=request.POST['car_number']
car_update.total_seat=request.POST['total_seat']
car_update.save()
context = {
'car': Car.objects.get(id=car_id),
}
return render(request, self.template_name, context)
class DeleteCarView(TemplateView):
template_name = 'rent_cars/edit_car.html'
def get(self,request, car_id, **kwargs):
return redirect("/add_car")
def post(self,request, car_id, **kwargs):
car_delete = Car.objects.get(id=car_id)
car_delete.delete()
return redirect("/add_car")
## ================================== Car Status Page ============================================
class AddCarStatusView(FormView):
template_name = 'rent_cars/add_car_status.html'
form_class = AddCarStatusForm
def get(self,request, **kwargs):
context = {
'car_statuss': CarStatus.objects.all(),
'form' : self.form_class
}
return render(request, self.template_name, context)
def post(self,request, **kwargs):
model = AddCarStatusForm(request.POST)
model.save()
context = {
'car_statuss': CarStatus.objects.all(),
'form' : self.form_class
}
return render(request, self.template_name, context)
class EditCarStatusView(TemplateView):
template_name = 'rent_cars/edit_car_status.html'
def get(self,request, car_status_id, **kwargs):
context = {
'cars' : Car.objects.all(),
'car_status': CarStatus.objects.get(pk=car_status_id),
}
return render(request, self.template_name, context)
def post(self,request, car_status_id, **kwargs):
car = Car.objects.get(car_number=request.POST['car_number'])
car_status_update = CarStatus.objects.get(id=car_status_id)
car_status_update.car_number=car
car_status_update.car_status=request.POST['car_status']
car_status_update.save()
context = {
'cars' : Car.objects.all(),
'car_status': CarStatus.objects.get(id=car_status_id),
}
return render(request, self.template_name, context)
class DeleteCarStatusView(TemplateView):
template_name = 'rent_cars/edit_car_status.html'
def get(self,request, car_status, **kwargs):
return redirect("/add_car_status")
def post(self,request, car_status_id, **kwargs):
car_status_delete = CarStatus.objects.get(id=car_status_id)
car_status_delete.delete()
return redirect("/add_car_status")
## ================================== Customer Information Page ============================================
class AddCustomerView(FormView):
template_name = 'rent_cars/add_customer.html'
form_class = AddCustomerForm
def get(self,request, **kwargs):
context = {
'customers': Customer.objects.all(),
'form' : self.form_class
}
return render(request, self.template_name, context)
def post(self,request, **kwargs):
model = AddCustomerForm(request.POST)
model.save()
context = {
'customers': Customer.objects.all(),
'form' : self.form_class
}
return render(request, self.template_name, context)
class EditCustomerView(TemplateView):
template_name = 'rent_cars/edit_customer.html'
def get(self,request, customer_id, **kwargs):
context = {
'customer': Customer.objects.get(pk=customer_id),
}
return render(request, self.template_name, context)
def post(self,request, customer_id, **kwargs):
customer_update = Customer.objects.get(id=customer_id)
customer_update.first_name=request.POST['first_name']
customer_update.last_name=request.POST['last_name']
customer_update.phone_number=request.POST['phone_number']
customer_update.present_address=request.POST['present_address']
customer_update.save()
context = {
'customer': Customer.objects.get(id=customer_id),
}
return render(request, self.template_name, context)
class DeleteCustomerView(TemplateView):
template_name = 'rent_cars/edit_customer.html'
def get(self,request, customer_id, **kwargs):
return redirect("/add_car")
def post(self,request, customer_id, **kwargs):
customer_delete = Customer.objects.get(id=customer_id)
customer_delete.delete()
return redirect("/add_customer")
## ================================== Driver Information Page ============================================
class AddDriverView(FormView):
template_name = 'rent_cars/add_driver.html'
form_class = AddDriverForm
def get(self,request, **kwargs):
context = {
'drivers': Driver.objects.all(),
'form' : self.form_class
}
return render(request, self.template_name, context)
def post(self,request, **kwargs):
model = AddDriverForm(request.POST)
model.save()
context = {
'drivers': Driver.objects.all(),
'form' : self.form_class
}
return render(request, self.template_name, context)
class EditDriverView(TemplateView):
template_name = 'rent_cars/edit_driver.html'
def get(self,request, driver_id, **kwargs):
context = {
'driver': Driver.objects.get(pk=driver_id),
}
return render(request, self.template_name, context)
def post(self,request, driver_id, **kwargs):
driver_update = Driver.objects.get(id=driver_id)
driver_update.first_name=request.POST['first_name']
driver_update.last_name=request.POST['last_name']
driver_update.phone_number=request.POST['phone_number']
driver_update.driving_licence_no=request.POST['driving_licence_no']
driver_update.present_address=request.POST['present_address']
driver_update.permanent_address=request.POST['permanent_address']
driver_update.save()
context = {
'driver': Driver.objects.get(id=driver_id),
}
return render(request, self.template_name, context)
class DeleteDriverView(TemplateView):
template_name = 'rent_cars/edit_driver.html'
def get(self,request, driver_id, **kwargs):
return redirect("/add_driver")
def post(self,request, driver_id, **kwargs):
driver_delete = Driver.objects.get(id=driver_id)
driver_delete.delete()
return redirect("/add_driver")
## ================================== Location Information Page ============================================
class AddLocationView(FormView):
template_name = 'rent_cars/add_location.html'
form_class = AddLocationForm
def get(self,request, **kwargs):
context = {
'locations': Location.objects.all(),
'form' : self.form_class
}
return render(request, self.template_name, context)
def post(self,request, **kwargs):
model = AddLocationForm(request.POST)
model.save()
context = {
'locations': Location.objects.all(),
'form' : self.form_class
}
return render(request, self.template_name, context)
class EditLocationView(TemplateView):
template_name = 'rent_cars/edit_location.html'
def get(self,request, location_id, **kwargs):
context = {
'location': Location.objects.get(pk=location_id),
}
return render(request, self.template_name, context)
def post(self,request, location_id, **kwargs):
location_update = Location.objects.get(id=location_id)
location_update.district_name=request.POST['district_name']
location_update.distance_from_dhaka=request.POST['distance_from_dhaka']
location_update.save()
context = {
'location': Location.objects.get(id=location_id),
}
return render(request, self.template_name, context)
class DeleteLocationView(TemplateView):
template_name = 'rent_cars/edit_location.html'
def get(self,request, location, **kwargs):
return redirect("/add_location")
def post(self,request, location_id, **kwargs):
location_delete = Location.objects.get(id=location_id)
location_delete.delete()
return redirect("/add_location")
## ================================== Car Rent Page ============================================
class AddRentCarView(FormView):
template_name = 'rent_cars/add_rent_car.html'
form_class = AddRentCarForm
def get(self,request, **kwargs):
context = {
'rent_cars': RentCar.objects.all(),
'form' : self.form_class
}
return render(request, self.template_name, context)
def post(self,request, **kwargs):
model = AddRentCarForm(request.POST)
model.save()
context = {
'rent_cars': RentCar.objects.all(),
'form' : self.form_class
}
return render(request, self.template_name, context)
class EditRentCarView(TemplateView):
template_name = 'rent_cars/edit_rent_car.html'
def get(self,request, rent_car_id, **kwargs):
context = {
'customers': Customer.objects.all(),
'cars' : Car.objects.all(),
'drivers' : Driver.objects.all(),
'locations': Location.objects.all(),
'rent_car' : RentCar.objects.get(pk=rent_car_id),
}
return render(request, self.template_name, context)
def post(self,request, rent_car_id, **kwargs):
customer = Customer.objects.get(first_name=request.POST['customer'] )
journey_from = Location.objects.get(district_name=request.POST['journey_from'] )
car = Car.objects.get(car_number=request.POST['car'])
driver = Driver.objects.get(first_name=request.POST['driver'] )
rent_car_update = RentCar.objects.get(id=rent_car_id)
rent_car_update.customer=customer
rent_car_update.journey_from=journey_from
rent_car_update.journey_to=request.POST['journey_to']
rent_car_update.journey_date=request.POST['journey_date']
rent_car_update.car=car
rent_car_update.driver=driver
rent_car_update.cost=request.POST['cost']
rent_car_update.save()
context = {
'customers': Customer.objects.all(),
'cars' : Car.objects.all(),
'drivers' : Driver.objects.all(),
'locations': Location.objects.all(),
'rent_car' : RentCar.objects.get(id=rent_car_id),
}
return render(request, self.template_name, context)
class DeleteRentCarView(TemplateView):
template_name = 'rent_cars/edit_rent_car.html'
def get(self,request, rent_car, **kwargs):
return redirect("/add_rent_car")
def post(self,request, rent_car_id, **kwargs):
rent_car_delete = RentCar.objects.get(id=rent_car_id)
rent_car_delete.delete()
return redirect("/add_rent_car")
<file_sep># Generated by Django 2.1.7 on 2019-02-26 13:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rent_cars', '0003_customer'),
]
operations = [
migrations.CreateModel(
name='Driver',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=20)),
('last_name', models.CharField(max_length=20)),
('phone_number', models.CharField(max_length=20)),
('driving_licence_no', models.CharField(max_length=200)),
('present_address', models.CharField(max_length=200)),
('permanent_address', models.CharField(max_length=200)),
],
),
migrations.AlterField(
model_name='carstatus',
name='car_status',
field=models.CharField(choices=[('AB', 'Available'), ('OT', 'On Travel'), ('IS', 'In Service'), ('AB', 'Booked')], max_length=2),
),
]
<file_sep># Generated by Django 2.1.7 on 2019-02-27 12:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('rent_cars', '0005_location'),
]
operations = [
migrations.CreateModel(
name='RentCar',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('journey_to', models.CharField(max_length=20)),
('journey_date', models.DateTimeField()),
('cost', models.IntegerField()),
('car', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rent_cars.Car')),
('custoner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rent_cars.Customer')),
('driver', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rent_cars.Driver')),
('journey_from', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rent_cars.Location')),
],
),
migrations.AlterField(
model_name='carstatus',
name='car_status',
field=models.CharField(choices=[('AV', 'Available'), ('OT', 'On Travel'), ('IS', 'In Service'), ('AB', 'Booked')], max_length=2),
),
]
<file_sep>from django import forms
from .models import Car, Customer, Driver, Location, RentCar, CarStatus
class AddCarForm(forms.ModelForm):
class Meta:
model = Car
fields= '__all__'
widgets = {
'brand_name': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter brand name',}),
'model_name': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter model name',}),
'car_number': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter car number',}),
'total_seat': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter total seat in car',}),
}
help_texts = {
# 'brand_name': "We'll never share your email with anyone else.",
}
error_messages = {
'total_seat': {
'max_length': "We'll never share your email with anyone else.",
}
}
class AddCustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields= '__all__'
widgets = {
'first_name' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter first name',}),
'last_name' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter last name',}),
'phone_number' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter phone number',}),
'present_address': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter present address',}),
}
help_texts = {
# 'brand_name': "We'll never share your email with anyone else.",
}
error_messages = {
"""
'total_seat': {
'max_length': "We'll never share your email with anyone else.",
}
"""
}
class AddDriverForm(forms.ModelForm):
class Meta:
model = Driver
fields= '__all__'
widgets = {
'first_name' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter first name',}),
'last_name' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter last name',}),
'phone_number' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter phone number',}),
'driving_licence_no': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter driving licence number',}),
'present_address' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter present address',}),
'permanent_address' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter permanent address',}),
}
help_texts = {
# 'brand_name': "We'll never share your email with anyone else.",
}
error_messages = {
"""
'total_seat': {
'max_length': "We'll never share your email with anyone else.",
}
"""
}
class AddLocationForm(forms.ModelForm):
class Meta:
model = Location
fields= '__all__'
widgets = {
'district_name' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter district name',}),
'distance_from_dhaka' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter distance',}),
}
help_texts = {
# 'brand_name': "We'll never share your email with anyone else.",
}
error_messages = {
"""
'total_seat': {
'max_length': "We'll never share your email with anyone else.",
}
"""
}
class AddRentCarForm(forms.ModelForm):
class Meta:
model = RentCar
fields= '__all__'
widgets = {
'customer' : forms.Select(attrs={'class': 'form-control'}),
'journey_from' : forms.Select(attrs={'class': 'form-control'}),
'journey_to' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter journey to',}),
'journey_date' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter journey at',}),
'car' : forms.Select(attrs={'class': 'form-control','placeholder': 'Enter car number',}),
'driver' : forms.Select(attrs={'class': 'form-control'}),
'cost' : forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter journey cost',}),
}
help_texts = {
# 'brand_name': "We'll never share your email with anyone else.",
}
error_messages = {
"""
'total_seat': {
'max_length': "We'll never share your email with anyone else.",
}
"""
}
class AddCarStatusForm(forms.ModelForm):
class Meta:
model = CarStatus
fields= '__all__'
widgets = {
'car_number' : forms.Select(attrs={'class': 'form-control'}),
'car_status' : forms.Select(attrs={'class': 'form-control'}),
}
help_texts = {
# 'brand_name': "We'll never share your email with anyone else.",
}
error_messages = {
"""
'total_seat': {
'max_length': "We'll never share your email with anyone else.",
}
"""
}
<file_sep># Generated by Django 2.1.7 on 2019-02-26 13:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rent_cars', '0004_auto_20190226_1906'),
]
operations = [
migrations.CreateModel(
name='Location',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('district_name', models.CharField(max_length=20)),
('distance_from_dhaka', models.CharField(max_length=20)),
],
),
]
<file_sep>from django.db import models
class Car(models.Model):
brand_name = models.CharField(max_length=100)
model_name = models.CharField(max_length=100)
car_number = models.CharField(max_length=100)
total_seat = models.CharField(max_length=2)
def __str__(self):
return self.car_number
class CarStatus(models.Model):
status = (
('AV', 'Available'),
('OT', 'On Travel'),
('IS', 'In Service'),
('AB', 'Booked'),
)
car_number = models.ForeignKey(Car, on_delete=models.CASCADE)
car_status = models.CharField(max_length=2, choices=status)
def __str__(self):
return self.car_status
class Customer(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
phone_number = models.CharField(max_length=20)
present_address = models.CharField(max_length=200)
def __str__(self):
return self.first_name
class Driver(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
phone_number = models.CharField(max_length=20)
driving_licence_no = models.CharField(max_length=200)
present_address = models.CharField(max_length=200)
permanent_address = models.CharField(max_length=200)
def __str__(self):
return self.first_name
class Location(models.Model):
district_name = models.CharField(max_length=20)
distance_from_dhaka = models.CharField(max_length=20)
def __str__(self):
return self.district_name
class RentCar(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
journey_from = models.ForeignKey(Location, on_delete=models.CASCADE)
journey_to = models.CharField(max_length=20)
journey_date = models.DateTimeField()
car = models.ForeignKey(Car, on_delete=models.CASCADE)
driver = models.ForeignKey(Driver, on_delete=models.CASCADE)
cost = models.IntegerField()
def __str__(self):
return self.car.car_number<file_sep># Generated by Django 2.1.7 on 2019-02-18 12:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('rent_cars', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CarStatus',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('car_status', models.CharField(choices=[('OT', 'On Travel'), ('IS', 'In Service'), ('AB', 'Booked')], max_length=2)),
('car_number', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rent_cars.Car')),
],
),
]
|
2c1488575313b32ac467a2598baf553038a3963a
|
[
"Python"
] | 10
|
Python
|
Ashikunnabi/rent_a_car
|
f188032781bbcdcab48f9033f2b8f4dee3560b56
|
31ccfd87c2cd149100f2831b1ca79377ff643bbd
|
refs/heads/master
|
<file_sep>Rails.application.routes.draw do
resources :bookings
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get "/homepage" => "bookings#homepage", as: "homepage"
root 'bookings#homepage'
get "/bookings_today" => "bookings#bookings_today", as: "bookings_today"
get '/login' => 'sessions#new'
post '/login' => 'sessions#create'
get '/logout' => 'sessions#destroy'
get '/signup' => 'users#new', as: "signup"
post '/users' => 'users#create'
get "/users/index" => 'users#index'
end
<file_sep>require 'rails_helper'
RSpec.describe Booking, type: :model do
context 'validation test' do
it 'ensures name presence' do
booking = Booking.new(name: 'name').save
expect(booking).to eq(false)
end
it 'ensures no_ppl presence' do
booking = Booking.new(no_ppl: '2').save
expect(booking).to eq(false)
end
it 'ensures phone_no presence' do
booking = Booking.new(phone_no: '0123456789').save
expect(booking).to eq(false)
end
it 'ensures date_time presence' do
booking = Booking.new(date_time: '2018-12-31').save
expect(booking).to eq(false)
end
it 'ensures date_time presence' do
booking = Booking.new(message: 'This is message').save
expect(booking).to eq(false)
end
it 'ensures new records save successfully' do
booking = Booking.new(name: 'name', no_ppl: '2', phone_no: '0123456789', date_time: '2018-12-31', message: 'this is message').save
expect(booking).to eq(true)
end
end
end
<file_sep>require 'rails_helper'
RSpec.feature "Users", type: :feature do
describe "User", :type => :feature do
it "create new user" do
visit '/signup'
within('form') do
fill_in 'user_username', with: 'Ali'
fill_in 'user_password', with: 'ali'
end
click_button 'Submit'
expect(page).to have_content 'User successfully created.'
end
end
end
<file_sep>class CreateBookings < ActiveRecord::Migration[5.1]
def change
create_table :bookings do |t|
t.string :name, null: false
t.string :no_ppl, null: false
t.datetime :date_time, null: false
t.string :phone_no, null: false
t.string :message, null: false
t.timestamps
end
end
end
<file_sep>class UsersController < ApplicationController
def new
end
def create
user = User.new(user_params)
if user.save
redirect_to '/users/index', notice: 'User successfully created.'
else
redirect_to '/signup'
end
end
def index
@users = User.all
end
private
def user_params
params.fetch(:user).permit(:username, :password, :role, :image)
end
end
|
c6c3f25cff6b45d3236627fb2a36ca68728143cc
|
[
"Ruby"
] | 5
|
Ruby
|
kokchun32/mcstanley
|
f4b755c84b91e48aec73b4fcbade2de788c13088
|
c911ab684ff65d0094081a583a1eb3211173688c
|
refs/heads/main
|
<repo_name>traeger22/proyecto-laravel<file_sep>/app/Http/Controllers/SedeController.php
<?php
namespace App\Http\Controllers;
use App\Models\Sede;
use Illuminate\Http\Request;
class SedeController extends Controller
{
public function index(){
//este metodo se encarga de mostrar el conteniedo de la tabla
$sede = Sede::paginate(15);
return view('sedes.index', compact('sede'));
}
public function create(){
//se encarga de mostrar el formulario de crear datos
return view('sede.create');
}
public function store(request $request){
$sede = new Sede();
$sede->nombre = $request->nombre;
$sede->codigo_dane = $request->codigo_dane;
$sede->establecimiento_id = $request->establecimiento_id;
$sede-> save();
return redirect()->route('sedes.show', $sede->id);
}
public function show($id){
//show
$sede = Sede::find($id);
//return $sede;
return view('sedes.show', compact('sede'));
}
public function edit(sede $sede){
//se encarga de editar datos de la aplicacion
// $sede = Sede::find($id);
return view('sedes.edit',compact('sede'));
}
public function update(request $request, sede $sede){
// se encarga de actualizar datos
//return view('sedes.update');
$sede->nombre = $request->nombre;
$sede->codigo_dane = $request->codigo_dane;
$sede->establecimiento_id = $request->establecimiento_id;
$sede->save();
return redirect()->route('sedes.show', $sede->id);
}
public function destroy(sede $sede){
//se encarga de borrar datos de la base de datos
$sede->delete();
return redirect()->route('sedes.index');
// return view('sedes.destroy');
}
}
<file_sep>/app/Models/Establecimiento.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Establecimiento extends Model
{
use HasFactory;
public function secretaria()
{
return $this->belongsTo(Secretaria::class);
}
public function sedes()
{
return $this->hasMany(Sede::class);
}
}
<file_sep>/app/Http/Controllers/EstablecimientoController.php
<?php
namespace App\Http\Controllers;
use App\Models\Establecimiento;
use Illuminate\Http\Request;
class EstablecimientoController extends Controller
{
public function index(){
//este metodo se encarga de mostrar el conteniedo de la tabla
$establecimiento = Establecimiento::paginate(15);
return view('establecimientos.index', compact('establecimiento'));
}
public function create(){
//se encarga de mostrar el formulario de crear datos
return view('establecimientos.create');
}
public function store(request $request){
$establecimiento = new Establecimiento();
$establecimiento->codigo_dane = $request->codigo_dane;
$establecimiento->nombre = $request->nombre;
$establecimiento->secretaria_id = $request->secretaria_id;
$establecimiento-> save();
return redirect()->route('establecimientos.show', $establecimiento->id);
}
public function show($id){
//show
$establecimiento = Establecimiento::find($id);
//return $establecimiento;
return view('establecimientos.show', compact('establecimiento'));
}
public function edit(establecimiento $establecimiento){
//se encarga de editar datos de la aplicacion
// $departamento = Departamento::find($id);
return view('establecimientos.edit',compact('establecimiento'));
}
public function update(request $request, establecimiento $establecimiento){
// se encarga de actualizar datos
//return view('departamentos.update');
$establecimiento->codigo_dane = $request->codigo_dane;
$establecimiento->nombre = $request->nombre;
$establecimiento->secretaria_id = $request->secretaria_id;
$establecimiento->save();
return redirect()->route('establecimientos.show', $establecimiento->id);
}
public function destroy(establecimiento $establecimiento){
//se encarga de borrar datos de la base de datos
$establecimiento->delete();
return redirect()->route('establecimientos.index');
// return view('departamentos.destroy');
}
}
<file_sep>/database/seeders/SedeSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Establecimiento;
use App\Models\Sede;
use App\Models\Secretaria;
use GuzzleHttp\Promise\Create;
use Illuminate\Database\Seeder;
class SedeSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
/*$sede = new Sede();
$sede->nombre = "laravel";
$sede->codigo_dane = "28485688";
$sede->establecimiento_id= 2;
$sede->save();*/
Sede::factory(50)->create();
Secretaria::factory(50)->create();
Establecimiento::factory(50)->Create();
}
}
<file_sep>/app/Http/Controllers/SecretariaController.php
<?php
namespace App\Http\Controllers;
use App\Models\Secretaria;
use Illuminate\Http\Request;
class SecretariaController extends Controller
{
public function index(){
//este metodo se encarga de mostrar el conteniedo de la tabla
$secretaria = Secretaria::paginate(15);
return view('secretarias.index', compact('secretaria'));
}
public function create(){
//se encarga de mostrar el formulario de crear datos
return view('secretarias.create');
}
public function store(request $request){
$secretaria = new Secretaria();
$secretaria->nombre = $request->nombre;
$secretaria->ubicacion = $request->ubicacion;
$secretaria-> save();
return redirect()->route('secretarias.show', $secretaria->id);
}
public function show($id){
//show
$secretaria = Secretaria::find($id);
//return
return view('secretarias.show', compact('secretaria'));
}
public function edit(secretaria $secretaria){
//se encarga de editar datos de la aplicacion
return view('secretarias.edit',compact('secretaria'));
}
public function update(request $request, secretaria $secretaria){
$secretaria->nombre = $request->nombre;
$secretaria->ubicacion = $request->ubicacion;
$secretaria->save();
return redirect()->route('secretarias.show', $secretaria->id);
}
public function destroy(secretaria $secretaria){
//se encarga de borrar datos de la base de datos
$secretaria->delete();
return redirect()->route('secretarias.index');
}
}
|
a6cb5cc1195222ee3fa6864212c66251e4019b30
|
[
"PHP"
] | 5
|
PHP
|
traeger22/proyecto-laravel
|
fe31be79bc1a09a5b8b2a197a182f4ccb832fd1f
|
013623bd3e44d905ea58275eb7e7ba28c8decfac
|
refs/heads/master
|
<file_sep>from django.conf.urls import patterns, url
from django.views import generic
from cuentas_por_pagar import views
urlpatterns = patterns('',
(r'^GenerarPolizas/$', views.generar_polizas_View),
(r'^PreferenciasEmpresa/$', views.preferenciasEmpresa_View),
#Plantilla Poliza
(r'^plantilla_poliza/$', views.plantilla_poliza_manageView),
(r'^plantilla_poliza/(?P<id>\d+)/', views.plantilla_poliza_manageView),
(r'^plantilla_poliza/eliminar/(?P<id>\d+)/', views.plantilla_poliza_delete),
)<file_sep> #encoding:utf-8
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
import datetime, time
from inventarios.models import *
from inventarios.views import c_get_next_key
#Paginacion
# user autentication
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, AdminPasswordChangeForm
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required, permission_required
from django.utils.encoding import smart_str, smart_unicode
@login_required(login_url='/login/')
def index(request):
return render_to_response('index.html', {}, context_instance=RequestContext(request))# Create your views here.
def get_folio_poliza(tipo_poliza, fecha=None):
""" folio de una poliza """
try:
if tipo_poliza.tipo_consec == 'M':
tipo_poliza_det = TipoPolizaDet.objects.get(tipo_poliza = tipo_poliza, mes=fecha.month, ano = fecha.year)
elif tipo_poliza.tipo_consec == 'E':
tipo_poliza_det = TipoPolizaDet.objects.get(tipo_poliza = tipo_poliza, ano=fecha.year, mes=0)
elif tipo_poliza.tipo_consec == 'P':
tipo_poliza_det = TipoPolizaDet.objects.get(tipo_poliza = tipo_poliza, mes=0, ano =0)
except ObjectDoesNotExist:
if tipo_poliza.tipo_consec == 'M':
tipo_poliza_det = TipoPolizaDet.objects.create(id=c_get_next_key('ID_CATALOGOS'), tipo_poliza=tipo_poliza, ano=fecha.year, mes=fecha.month, consecutivo = 1,)
elif tipo_poliza.tipo_consec == 'E':
#Si existe permanente toma su consecutivo para crear uno nuevo si no existe inicia en 1
consecutivo = TipoPolizaDet.objects.filter(tipo_poliza = tipo_poliza, mes=0, ano =0).aggregate(max = Sum('consecutivo'))['max']
if consecutivo == None:
consecutivo = 1
tipo_poliza_det = TipoPolizaDet.objects.create(id=c_get_next_key('ID_CATALOGOS'), tipo_poliza=tipo_poliza, ano=fecha.year, mes=0, consecutivo=consecutivo,)
elif tipo_poliza.tipo_consec == 'P':
consecutivo = TipoPolizaDet.objects.all().aggregate(max = Sum('consecutivo'))['max']
if consecutivo == None:
consecutivo = 1
tipo_poliza_det = TipoPolizaDet.objects.create(id=c_get_next_key('ID_CATALOGOS'), tipo_poliza=tipo_poliza, ano=0, mes=0, consecutivo = consecutivo,)
return tipo_poliza_det<file_sep>Django==1.4.3
autocomplete_light==1.1.16
fdb==1.0<file_sep># this grabs the requirements from requirements.txt
REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()]
setup(
install_requires=REQUIREMENTS
)<file_sep>#encoding:utf-8
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from inventarios.models import *
from cuentas_por_cobrar.forms import *
from ventas.views import get_folio_poliza
import datetime, time
from django.db.models import Q
#Paginacion
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# user autentication
from django.contrib.auth.decorators import login_required, permission_required
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum, Max
from django.db import connection
from inventarios.views import c_get_next_key
import ventas
@login_required(login_url='/login/')
def preferenciasEmpresa_View(request, template_name='herramientas/preferencias_empresa_CC.html'):
try:
informacion_contable = InformacionContable_CC.objects.all()[:1]
informacion_contable = informacion_contable[0]
except:
informacion_contable = InformacionContable_CC()
msg = ''
if request.method == 'POST':
form = InformacionContableManageForm(request.POST, instance=informacion_contable)
if form.is_valid():
form.save()
msg = 'Datos Guardados Exitosamente'
else:
form = InformacionContableManageForm(instance=informacion_contable)
plantillas = PlantillaPolizas_CC.objects.all()
c= {'form':form,'msg':msg,'plantillas':plantillas,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def plantilla_poliza_manageView(request, id = None, template_name='herramientas/plantilla_poliza_CC.html'):
message = ''
if id:
plantilla = get_object_or_404(PlantillaPolizas_CC, pk=id)
else:
plantilla =PlantillaPolizas_CC()
if request.method == 'POST':
plantilla_form = PlantillaPolizaManageForm(request.POST, request.FILES, instance=plantilla)
plantilla_items = PlantillaPoliza_items_formset(ConceptoPlantillaPolizaManageForm, extra=1, can_delete=True)
plantilla_items_formset = plantilla_items(request.POST, request.FILES, instance=plantilla)
if plantilla_form.is_valid() and plantilla_items_formset .is_valid():
plantilla = plantilla_form.save(commit = False)
plantilla.save()
#GUARDA CONCEPTOS DE PLANTILLA
for concepto_form in plantilla_items_formset :
Detalleplantilla = concepto_form.save(commit = False)
#PARA CREAR UNO NUEVO
if not Detalleplantilla.id:
Detalleplantilla.plantilla_poliza_CC = plantilla
plantilla_items_formset .save()
return HttpResponseRedirect('/cuentas_por_cobrar/PreferenciasEmpresa/')
else:
plantilla_items = PlantillaPoliza_items_formset(ConceptoPlantillaPolizaManageForm, extra=1, can_delete=True)
plantilla_form= PlantillaPolizaManageForm(instance=plantilla)
plantilla_items_formset = plantilla_items(instance=plantilla)
c = {'plantilla_form': plantilla_form, 'formset': plantilla_items_formset , 'message':message,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
<file_sep> #encoding:utf-8
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from inventarios.models import *
from inventarios.forms import *
import datetime, time
from django.db.models import Q
from django.forms.formsets import formset_factory, BaseFormSet
from django.forms.models import inlineformset_factory
#Paginacion
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# user autentication
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, AdminPasswordChangeForm
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required, permission_required
from django.db import connection
import xlrd
from django.utils.encoding import smart_str, smart_unicode
##########################################
## ##
## LOGIN ##
## ##
##########################################
def ingresar(request):
# if not request.user.is_anonymous():
# return HttpResponseRedirect('/')
if request.method == 'POST':
formulario = AuthenticationForm(request.POST)
if formulario.is_valid:
usuario = request.POST['username']
clave = request.POST['password']
acceso = authenticate(username=usuario, password=clave)
if acceso is not None:
if acceso.is_active:
login(request, acceso)
return HttpResponseRedirect('/')
else:
return render_to_response('noactivo.html', context_instance=RequestContext(request))
else:
return render_to_response('login.html',{'form':formulario, 'message':'Nombre de usaurio o password no validos',}, context_instance=RequestContext(request))
else:
formulario = AuthenticationForm()
return render_to_response('login.html',{'form':formulario, 'message':'',}, context_instance=RequestContext(request))
def logoutUser(request):
logout(request)
return HttpResponseRedirect('/')
def c_get_next_key(seq_name):
""" return next value of sequence """
c = connection.cursor()
c.execute("SELECT GEN_ID( ID_DOCTOS , 1 ) FROM RDB$DATABASE;")
row = c.fetchone()
return int(row[0])
##########################################
## ##
## INVENTARIOS FISICOS ##
## ##
##########################################
@login_required(login_url='/login/')
def invetariosFisicos_View(request, template_name='Inventarios Fisicos/inventarios_fisicos.html'):
inventarios_fisicos_list = DoctosInvfis.objects.all().order_by('-fecha')
paginator = Paginator(inventarios_fisicos_list, 15) # Muestra 5 inventarios por pagina
page = request.GET.get('page')
#####PARA PAGINACION##############
try:
inventarios_fisicos = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
inventarios_fisicos = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
inventarios_fisicos = paginator.page(paginator.num_pages)
c = {'inventarios_fisicos':inventarios_fisicos}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def invetarioFisico_manageView(request, id = None, template_name='Inventarios Fisicos/inventario_fisico.html'):
message = ''
hay_repetido = False
if id:
InventarioFisico = get_object_or_404(DoctosInvfis, pk=id)
else:
InventarioFisico = DoctosInvfis()
if request.method == 'POST':
InventarioFisico_form = DoctosInvfisManageForm(request.POST, request.FILES, instance=InventarioFisico)
#PARA CARGAR DATOS DE EXCEL
if 'excel' in request.POST:
input_excel = request.FILES['file_inventario']
book = xlrd.open_workbook(file_contents=input_excel.read())
sheet = book.sheet_by_index(0)
articulos = Articulos.objects.filter(es_almacenable='S')
inventarioFisico_items = inventarioFisico_items_formset(DoctosInvfisDetManageForm, extra=articulos.count(), can_delete=True)
lista = []
lista_articulos = []
for i in range(sheet.nrows):
clave_articulo = get_object_or_404(ClavesArticulos, clave=sheet.cell_value(i,0))
if clave_articulo and clave_articulo.articulo.es_almacenable=='S':
if clave_articulo.articulo.id in lista_articulos:
message = 'El Articulo [%s] con clave [%s] esta repetido en el archivo de excel por favor corrigelo para continuar '% (clave_articulo.articulo.nombre, clave_articulo.clave)
hay_repetido = True
lista.append({'articulo': clave_articulo.articulo, 'unidades':int(sheet.cell_value(i,1)),})
lista_articulos.append(clave_articulo.articulo.id)
articulos_enceros = Articulos.objects.exclude(pk__in=lista_articulos).filter(es_almacenable='S')
for i in articulos_enceros:
#clave_articulo = ClavesArticulos.objects.filter(articulo__id=i.id)
articulosclav = ClavesArticulos.objects.filter(articulo__id=i.id)
if articulosclav:
lista.append({'articulo': i, 'clave':articulosclav[0].clave , 'unidades':0,})
else:
lista.append({'articulo': i, 'clave':'', 'unidades':0,})
InventarioFisicoItems_formset = inventarioFisico_items(initial=lista)
#GUARDA CAMBIOS EN INVENTARIO FISICO
else:
inventarioFisico_items = inventarioFisico_items_formset(DoctosInvfisDetManageForm, extra=1, can_delete=True)
InventarioFisicoItems_formset = inventarioFisico_items(request.POST, request.FILES, instance=InventarioFisico)
if InventarioFisico_form.is_valid() and InventarioFisicoItems_formset.is_valid():
inventarioFisico = InventarioFisico_form.save(commit = False)
#CARGA NUEVO ID
if not inventarioFisico.id:
inventarioFisico.id = c_get_next_key('ID_DOCTOS')
inventarioFisico.save()
#GUARDA ARTICULOS DE INVENTARIO FISICO
for articulo_form in InventarioFisicoItems_formset:
DetalleInventarioFisico = articulo_form.save(commit = False)
#PARA CREAR UNO NUEVO
if not DetalleInventarioFisico.id:
DetalleInventarioFisico.id = -1
DetalleInventarioFisico.docto_invfis = inventarioFisico
InventarioFisicoItems_formset.save()
return HttpResponseRedirect('/InventariosFisicos/')
else:
inventarioFisico_items = inventarioFisico_items_formset(DoctosInvfisDetManageForm, extra=1, can_delete=True)
InventarioFisico_form= DoctosInvfisManageForm(instance=InventarioFisico)
InventarioFisicoItems_formset = inventarioFisico_items(instance=InventarioFisico)
c = {'InventarioFisico_form': InventarioFisico_form, 'formset': InventarioFisicoItems_formset, 'message':message,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def invetarioFisico_delete(request, id = None):
inventario_fisico = get_object_or_404(DoctosInvfis, pk=id)
inventario_fisico.delete()
return HttpResponseRedirect('/InventariosFisicos/')
##########################################
## ##
## ENTRADAS ##
## ##
##########################################
@login_required(login_url='/login/')
def entradas_View(request, template_name='Entradas/entradas.html'):
entradas_list = DoctosIn.objects.filter(naturaleza_concepto='E').order_by('-fecha')
paginator = Paginator(entradas_list, 15) # Muestra 5 inventarios por pagina
page = request.GET.get('page')
#####PARA PAGINACION##############
try:
entradas = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
entradas = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
entradas = paginator.page(paginator.num_pages)
c = {'entradas':entradas}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def entrada_manageView(request, id = None, template_name='Entradas/entrada.html'):
message = ''
hay_repetido = False
if id:
Entrada = get_object_or_404(DoctosIn, pk=id)
else:
Entrada = DoctosIn()
if request.method == 'POST':
Entrada_form = DoctosInManageForm(request.POST, request.FILES, instance=Entrada)
#PARA CARGAR DATOS DE EXCEL
if 'excel' in request.POST:
input_excel = request.FILES['file_inventario']
book = xlrd.open_workbook(file_contents=input_excel.read())
sheet = book.sheet_by_index(0)
articulos = Articulos.objects.filter(es_almacenable='S')
Entrada_items = doctoIn_items_formset(DoctosInDetManageForm, extra=articulos.count(), can_delete=True)
lista = []
lista_articulos = []
for i in range(sheet.nrows):
clave_articulo = get_object_or_404(ClavesArticulos, clave=sheet.cell_value(i,0))
if clave_articulo and clave_articulo.articulo.es_almacenable=='S':
if clave_articulo.articulo.id in lista_articulos:
message = 'El Articulo [%s] esta repetido en el archivo de excel por favor corrigelo para continuar '% clave_articulo.articulo.nombre
hay_repetido = True
lista.append({'articulo': clave_articulo.articulo, 'clave':clave_articulo.clave, 'unidades':int(sheet.cell_value(i,1)),})
lista_articulos.append(clave_articulo.articulo.id)
articulos_enceros = Articulos.objects.exclude(pk__in=lista_articulos).filter(es_almacenable='S')
for i in articulos_enceros:
#clave_articulo = ClavesArticulos.objects.filter(articulo__id=i.id)
articulosclav = ClavesArticulos.objects.filter(articulo__id=i.id)
if articulosclav:
lista.append({'articulo': i, 'clave':articulosclav[0].clave , 'unidades':0,})
else:
lista.append({'articulo': i, 'clave':'', 'unidades':0,})
EntradaItems_formset = Entrada_items(initial=lista)
#GUARDA CAMBIOS EN INVENTARIO FISICO
else:
Entrada_items = doctoIn_items_formset(DoctosInDetManageForm, extra=1, can_delete=True)
EntradaItems_formset = Entrada_items(request.POST, request.FILES, instance=Entrada)
if Entrada_form.is_valid() and EntradaItems_formset.is_valid():
Entrada = Entrada_form.save(commit = False)
#CARGA NUEVO ID
if not Entrada.id:
Entrada.id = c_get_next_key('ID_DOCTOS')
Entrada.naturaleza_concepto = 'E'
Entrada.save()
#GUARDA ARTICULOS DE INVENTARIO FISICO
for articulo_form in EntradaItems_formset:
DetalleEntrada = articulo_form.save(commit = False)
#PARA CREAR UNO NUEVO
if not DetalleEntrada.id:
DetalleEntrada.id = -1
DetalleEntrada.almacen = Entrada.almacen
DetalleEntrada.concepto = Entrada.concepto
DetalleEntrada.docto_invfis = Entrada
EntradaItems_formset.save()
return HttpResponseRedirect('/Entradas/')
else:
Entrada_items = doctoIn_items_formset(DoctosInDetManageForm, extra=1, can_delete=True)
Entrada_form= DoctosInManageForm(instance=Entrada)
EntradaItems_formset = Entrada_items(instance=Entrada)
c = {'Entrada_form': Entrada_form, 'formset': EntradaItems_formset, 'message':message,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def entrada_delete(request, id = None):
entrada = get_object_or_404(DoctosIn, pk=id)
entrada.delete()
return HttpResponseRedirect('/Entradas/')
##########################################
## ##
## SALIDAS ##
## ##
##########################################
@login_required(login_url='/login/')
def salidas_View(request, template_name='Salidas/salidas.html'):
salidas_list = DoctosIn.objects.filter(naturaleza_concepto='S').order_by('-fecha')
paginator = Paginator(salidas_list, 15) # Muestra 5 inventarios por pagina
page = request.GET.get('page')
#####PARA PAGINACION##############
try:
salidas = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
salidas = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
salidas = paginator.page(paginator.num_pages)
c = {'salidas':salidas}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def salida_manageView(request, id = None, template_name='Salidas/salida.html'):
message = ''
hay_repetido = False
if id:
Salida = get_object_or_404(DoctosIn, pk=id)
else:
Salida = DoctosIn()
if request.method == 'POST':
Salida_form = DoctosInManageForm(request.POST, request.FILES, instance=Salida)
#PARA CARGAR DATOS DE EXCEL
if 'excel' in request.POST:
input_excel = request.FILES['file_inventario']
book = xlrd.open_workbook(file_contents=input_excel.read())
sheet = book.sheet_by_index(0)
articulos = Articulos.objects.filter(es_almacenable='S')
Salida_items = doctoIn_items_formset(DoctosInDetManageForm, extra=articulos.count(), can_delete=True)
lista = []
lista_articulos = []
for i in range(sheet.nrows):
clave_articulo = get_object_or_404(ClavesArticulos, clave=sheet.cell_value(i,0))
if clave_articulo and clave_articulo.articulo.es_almacenable=='S':
if clave_articulo.articulo.id in lista_articulos:
message = 'El Articulo [%s] esta repetido en el archivo de excel por favor corrigelo para continuar '% clave_articulo.articulo.nombre
hay_repetido = True
lista.append({'articulo': clave_articulo.articulo, 'clave':clave_articulo.clave, 'unidades':int(sheet.cell_value(i,1)),})
lista_articulos.append(clave_articulo.articulo.id)
articulos_enceros = Articulos.objects.exclude(pk__in=lista_articulos).filter(es_almacenable='S')
for i in articulos_enceros:
#clave_articulo = ClavesArticulos.objects.filter(articulo__id=i.id)
articulosclav = ClavesArticulos.objects.filter(articulo__id=i.id)
if articulosclav:
lista.append({'articulo': i, 'clave':articulosclav[0].clave , 'unidades':0,})
else:
lista.append({'articulo': i, 'clave':'', 'unidades':0,})
SalidaItems_formset = Salida_items(initial=lista)
#GUARDA CAMBIOS EN INVENTARIO FISICO
else:
Salida_items = doctoIn_items_formset(DoctosInDetManageForm, extra=1, can_delete=True)
SalidaItems_formset = Salida_items(request.POST, request.FILES, instance=Salida)
if Salida_form.is_valid() and SalidaItems_formset.is_valid():
Salida = Salida_form.save(commit = False)
#CARGA NUEVO ID
if not Salida.id:
Salida.id = c_get_next_key('ID_DOCTOS')
Salida.save()
#GUARDA ARTICULOS DE INVENTARIO FISICO
for articulo_form in SalidaItems_formset:
DetalleSalida = articulo_form.save(commit = False)
#PARA CREAR UNO NUEVO
if not DetalleSalida.id:
DetalleSalida.id = -1
DetalleSalida.almacen = Salida.almacen
DetalleSalida.concepto = Salida.concepto
DetalleSalida.docto_invfis = Salida
SalidaItems_formset.save()
return HttpResponseRedirect('/Salidas/')
else:
Salida_items = doctoIn_items_formset(DoctosInDetManageForm, extra=1, can_delete=True)
Salida_form= DoctosInManageForm(instance=Salida)
SalidaItems_formset = Salida_items(instance=Salida)
c = {'Salida_form': Salida_form, 'formset': SalidaItems_formset, 'message':message,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def salida_delete(request, id = None):
salida = get_object_or_404(DoctosIn, pk=id)
salida.delete()
return HttpResponseRedirect('/Salidas/')
<file_sep>#encoding:utf-8
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from inventarios.models import *
#from contabilidad.forms import *
import datetime, time
from django.db.models import Q
#Paginacion
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# user autentication
from django.contrib.auth.decorators import login_required, permission_required
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum, Max
@login_required(login_url='/login/')
def polizas_View(request, template_name='polizas/polizas.html'):
polizas_list = DoctoCo.objects.filter(estatus='N').order_by('-fecha')
paginator = Paginator(polizas_list, 15) # Muestra 5 inventarios por pagina
page = request.GET.get('page')
#####PARA PAGINACION##############
try:
polizas = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
polizas = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
polizas = paginator.page(paginator.num_pages)
c = {'polizas':polizas}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def polizas_pendientesView(request, template_name='polizas/polizas_pendientes.html'):
#polizas_list = DoctoCo.objects.using('db_chuy').filter(estatus='P').order_by('-fecha')
polizas_list = DoctoCo.objects.filter(estatus='P').order_by('-fecha')
paginator = Paginator(polizas_list, 15) # Muestra 5 inventarios por pagina
page = request.GET.get('page')
#####PARA PAGINACION##############
try:
polizas = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
polizas = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
polizas = paginator.page(paginator.num_pages)
c = {'polizas':polizas}
return render_to_response(template_name, c, context_instance=RequestContext(request))
<file_sep>from django.db import models
from datetime import datetime
from django.db.models.signals import pre_save
from django.core import urlresolvers
from inventarios.models import *
class DoctoVe(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_VE_ID')
folio = models.CharField(max_length=9, db_column='FOLIO')
fecha = models.DateField(db_column='FECHA')
contabilizado = models.CharField(default='N', max_length=1, db_column='CONTABILIZADO')
cliente = models.ForeignKey(Cliente, db_column='CLIENTE_ID')
descripcion = models.CharField(blank=True, null=True, max_length=200, db_column='DESCRIPCION')
tipo = models.CharField(max_length=1, db_column='TIPO_DOCTO')
importe_neto = models.DecimalField(max_digits=15, decimal_places=2, db_column='IMPORTE_NETO')
total_impuestos = models.DecimalField(max_digits=15, decimal_places=2, db_column='TOTAL_IMPUESTOS')
moneda = models.ForeignKey(Moneda, db_column='MONEDA_ID')
tipo_cambio = models.DecimalField(max_digits=18, decimal_places=6, db_column='TIPO_CAMBIO')
estado = models.CharField(max_length=1, db_column='ESTATUS')
condicion_pago = models.ForeignKey(CondicionPago, db_column='COND_PAGO_ID')
#almacen = models.ForeignKey(Almacenes, db_column='ALMACEN_ID')
#condicion_pago = models.ForeignKey(CondicionesPago, on_delete= models.SET_NULL, blank=True, null=True, db_column='COND_PAGO_ID')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'doctos_ve'
class DoctoVeDet(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_VE_DET_ID')
docto_ve = models.ForeignKey(DoctoVe, on_delete= models.SET_NULL, blank=True, null=True, db_column='DOCTO_VE_ID')
articulo = models.ForeignKey(Articulos, on_delete= models.SET_NULL, blank=True, null=True, db_column='ARTICULO_ID')
unidades = models.DecimalField(max_digits=18, decimal_places=5, db_column='UNIDADES')
precio_unitario = models.DecimalField(max_digits=18, decimal_places=6, db_column='PRECIO_UNITARIO')
porcentaje_decuento = models.DecimalField(max_digits=9, decimal_places=6, db_column='PCTJE_DSCTO')
precio_total_neto = models.DecimalField(max_digits=15, decimal_places=2, db_column='PRECIO_TOTAL_NETO')
class Meta:
db_table = u'doctos_ve_det'
class DoctoVeLigas(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_VE_LIGA_ID')
factura = models.ForeignKey(DoctoVe, db_column='DOCTO_VE_FTE_ID', related_name='factura')
devolucion = models.ForeignKey(DoctoVe, db_column='DOCTO_VE_DEST_ID', related_name='devolucion')
class Meta:
db_table = u'doctos_ve_ligas'
class LibresFacturasV(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_VE_ID')
segmento_1 = models.CharField(max_length=99, db_column='SEGMENTO_1')
segmento_2 = models.CharField(max_length=99, db_column='SEGMENTO_2')
segmento_3 = models.CharField(max_length=99, db_column='SEGMENTO_3')
segmento_4 = models.CharField(max_length=99, db_column='SEGMENTO_4')
segmento_5 = models.CharField(max_length=99, db_column='SEGMENTO_5')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'libres_fac_ve'
class LibresDevFacV(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_VE_ID')
segmento_1 = models.CharField(max_length=99, db_column='SEGMENTO_1')
segmento_2 = models.CharField(max_length=99, db_column='SEGMENTO_2')
segmento_3 = models.CharField(max_length=99, db_column='SEGMENTO_3')
segmento_4 = models.CharField(max_length=99, db_column='SEGMENTO_4')
segmento_5 = models.CharField(max_length=99, db_column='SEGMENTO_5')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'libres_devfac_ve'
################################################################
#### ####
#### MODELOS EXTRA A BASE DE DATOS MICROSIP ####
#### ####
################################################################
class InformacionContable_V(models.Model):
tipo_poliza_ve = models.ForeignKey(TipoPoliza, blank=True, null=True, related_name='tipo_poliza_ve')
tipo_poliza_dev = models.ForeignKey(TipoPoliza, blank=True, null=True, related_name='tipo_poliza_dev')
condicion_pago_contado = models.ForeignKey(CondicionPago, blank=True, null=True)
depto_general_cont = models.ForeignKey(DeptoCo)
def __unicode__(self):
return u'%s'% self.id
class PlantillaPolizas_V(models.Model):
nombre = models.CharField(max_length=200)
TIPOS = (('F', 'Facturas'),('D', 'Devoluciones'),)
tipo = models.CharField(max_length=2, choices=TIPOS, default='F')
def __unicode__(self):
return u'%s'%self.nombre
class DetallePlantillaPolizas_V(models.Model):
TIPOS = (('C', 'Cargo'),('A', 'Abono'),)
VALOR_TIPOS =(
('Ventas', 'Ventas'),
('Clientes', 'Clientes'),
('Bancos', 'Bancos'),
('Descuentos', 'Descuentos'),
('Devoluciones','Devoluciones'),
('IVA', 'IVA'),
('Segmento_1', 'Segmento 1'),
('Segmento_2', 'Segmento 2'),
('Segmento_3', 'Segmento 3'),
('Segmento_4', 'Segmento 4'),
('Segmento_5', 'Segmento 5'),
)
VALOR_IVA_TIPOS = (('A', 'Ambos'),('I', 'Solo IVA'),('0', 'Solo 0%'),)
VALOR_CONTADO_CREDITO_TIPOS = (('Ambos', 'Ambos'),('Contado', 'Contado'),('Credito', 'Credito'),)
posicion = models.CharField(max_length=2)
plantilla_poliza_v = models.ForeignKey(PlantillaPolizas_V)
cuenta_co = models.ForeignKey(CuentaCo)
tipo = models.CharField(max_length=2, choices=TIPOS, default='C')
asiento_ingora = models.CharField(max_length=2, blank=True, null=True)
valor_tipo = models.CharField(max_length=20, choices=VALOR_TIPOS)
valor_iva = models.CharField(max_length=2, choices=VALOR_IVA_TIPOS, default='A')
valor_contado_credito = models.CharField(max_length=10, choices=VALOR_CONTADO_CREDITO_TIPOS, default='Ambos')
def __unicode__(self):
return u'%s'%self.id
<file_sep>import autocomplete_light
from inventarios.models import Articulos, DoctosInvfisDet
from django.contrib import admin
class DoctosInvfisDetAdmin(admin.ModelAdmin):
articulo = autocomplete_light.modelform_factory(Articulos)
admin.site.register(DoctosInvfisDet, DoctosInvfisDetAdmin)
admin.site.register(Articulos)
<file_sep>import autocomplete_light
from models import Articulos
autocomplete_light.register(Articulos, search_fields=('nombre',),
autocomplete_js_attributes={'placeholder': 'Nombre ..'})<file_sep>#encoding:utf-8
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from inventarios.models import *
from models import *
from forms import *
import datetime, time
from django.db.models import Q
from datetime import timedelta
from decimal import *
from cuentas_por_pagar.views import get_totales_cuentas_by_segmento
from django.core import serializers
#Paginacion
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# user autentication
from django.contrib.auth.decorators import login_required, permission_required
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum, Max
from django.db import connection
from inventarios.views import c_get_next_key
from main.views import get_folio_poliza
##########################################
## ##
## POLIZAS ##
## ##
##########################################
@login_required(login_url='/login/')
def preferenciasEmpresa_View(request, template_name='herramientas/preferencias_empresa.html'):
try:
informacion_contable = InformacionContable_V.objects.all()[:1]
informacion_contable = informacion_contable[0]
except:
informacion_contable = InformacionContable_V()
msg = ''
if request.method == 'POST':
form = InformacionContableManageForm(request.POST, instance=informacion_contable)
if form.is_valid():
form.save()
msg = 'Datos Guardados Exitosamente'
else:
form = InformacionContableManageForm(instance=informacion_contable)
plantillas = PlantillaPolizas_V.objects.all()
c= {'form':form,'msg':msg,'plantillas':plantillas,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
def get_descuento_total_ve(facturaID):
c = connection.cursor()
c.execute("SELECT SUM(A.dscto_arts + A.dscto_extra_importe) AS TOTAL FROM CALC_TOTALES_DOCTO_VE(%s,'S') AS A;"% facturaID)
row = c.fetchone()
return int(row[0])
def get_totales_doctos_ve(cuenta_contado= None, documento= None, conceptos_poliza=None, totales_cuentas=None, msg='', error='', depto_co=None):
#Si es una factura
if documento.tipo == 'F':
campos_particulares = LibresFacturasV.objects.filter(pk=documento.id)[0]
#Si es una devolucion
elif documento.tipo == 'D':
campos_particulares = LibresDevFacV.objects.filter(pk=documento.id)[0]
try:
cuenta_cliente = CuentaCo.objects.get(cuenta=documento.cliente.cuenta_xcobrar).cuenta
except ObjectDoesNotExist:
cuenta_cliente = None
#Para saber si es contado o es credito
es_contado = documento.condicion_pago == cuenta_contado
impuestos = documento.total_impuestos * documento.tipo_cambio
importe_neto = documento.importe_neto * documento.tipo_cambio
total = impuestos + importe_neto
descuento = get_descuento_total_ve(documento.id) * documento.tipo_cambio
clientes = total - descuento
bancos = 0
iva_efec_cobrado = 0
iva_pend_cobrar = 0
ventas_16_credito = 0
ventas_16_contado = 0
ventas_0_credito = 0
ventas_0_contado = 0
ventas_0 = DoctoVeDet.objects.filter(docto_ve= documento).extra(
tables =['impuestos_articulos', 'impuestos'],
where =
[
"impuestos_articulos.ARTICULO_ID = doctos_ve_det.ARTICULO_ID",
"impuestos.IMPUESTO_ID = impuestos_articulos.IMPUESTO_ID",
"impuestos.PCTJE_IMPUESTO = 0 ",
],
).aggregate(ventas_0 = Sum('precio_total_neto'))['ventas_0']
if ventas_0 == None:
ventas_0 = 0
ventas_0 = ventas_0 * documento.tipo_cambio
ventas_16 = total - ventas_0 - impuestos
#si llega a haber un proveedor que no tenga cargar impuestos
if ventas_16 < 0:
ventas_0 += ventas_16
ventas_16 = 0
msg = 'Existe al menos una documento donde el proveedor [no tiene indicado cargar inpuestos] POR FAVOR REVISTA ESO!!'
if crear_polizas_por == 'Dia':
msg = '%s, REVISA LAS POLIZAS QUE SE CREARON'% msg
error = 1
#SI LA FACTURA ES A CREDITO
if not es_contado:
ventas_16_credito = ventas_16
ventas_0_credito = ventas_0
iva_pend_cobrar = impuestos
clientes = total - descuento
elif es_contado:
ventas_16_contado = ventas_16
ventas_0_contado = ventas_0
iva_efec_cobrado = impuestos
bancos = total - descuento
asientos_a_ingorar = []
for concepto in conceptos_poliza:
if concepto.valor_tipo == 'Segmento_1' and not campos_particulares.segmento_1 == None:
asientos_a_ingorar.append(concepto.asiento_ingora)
if concepto.valor_tipo == 'Segmento_2' and not campos_particulares.segmento_2 == None:
asientos_a_ingorar.append(concepto.asiento_ingora)
if concepto.valor_tipo == 'Segmento_3' and not campos_particulares.segmento_3 == None:
asientos_a_ingorar.append(concepto.asiento_ingora)
if concepto.valor_tipo == 'Segmento_4' and not campos_particulares.segmento_4 == None:
asientos_a_ingorar.append(concepto.asiento_ingora)
if concepto.valor_tipo == 'Segmento_5' and not campos_particulares.segmento_5 == None:
asientos_a_ingorar.append(concepto.asiento_ingora)
for concepto in conceptos_poliza:
importe = 0
cuenta = []
clave_cuenta_tipoAsiento = []
if concepto.valor_tipo == 'Segmento_1' and not campos_particulares.segmento_1 == None:
totales_cuentas, error, msg = get_totales_cuentas_by_segmento(campos_particulares.segmento_1, totales_cuentas, depto_co, concepto.tipo, error, msg, documento.folio, concepto.asiento_ingora)
elif concepto.valor_tipo == 'Segmento_2' and not campos_particulares.segmento_2 == None:
totales_cuentas, error, msg = get_totales_cuentas_by_segmento(campos_particulares.segmento_2, totales_cuentas, depto_co, concepto.tipo, error, msg, documento.folio, concepto.asiento_ingora)
elif concepto.valor_tipo == 'Segmento_3' and not campos_particulares.segmento_3 == None:
totales_cuentas, error, msg = get_totales_cuentas_by_segmento(campos_particulares.segmento_3, totales_cuentas, depto_co, concepto.tipo, error, msg, documento.folio, concepto.asiento_ingora)
elif concepto.valor_tipo == 'Segmento_4' and not campos_particulares.segmento_4 == None:
totales_cuentas, error, msg = get_totales_cuentas_by_segmento(campos_particulares.segmento_4, totales_cuentas, depto_co, concepto.tipo, error, msg, documento.folio, concepto.asiento_ingora)
elif concepto.valor_tipo == 'Segmento_5' and not campos_particulares.segmento_5 == None:
totales_cuentas, error, msg = get_totales_cuentas_by_segmento(campos_particulares.segmento_5, totales_cuentas, depto_co, concepto.tipo, error, msg, documento.folio, concepto.asiento_ingora)
elif concepto.valor_tipo == 'Ventas' and not concepto.posicion in asientos_a_ingorar:
if concepto.valor_contado_credito == 'Credito':
if concepto.valor_iva == '0':
importe = ventas_0_credito
elif concepto.valor_iva == 'I':
importe = ventas_16_credito
elif concepto.valor_iva == 'A':
importe = ventas_0_credito + ventas_16_credito
elif concepto.valor_contado_credito == 'Contado':
if concepto.valor_iva == '0':
importe = ventas_0_contado
elif concepto.valor_iva == 'I':
importe = ventas_16_contado
elif concepto.valor_iva == 'A':
importe = ventas_0_contado + ventas_16_contado
elif concepto.valor_contado_credito == 'Ambos':
if concepto.valor_iva == '0':
importe = ventas_0_credito + ventas_0_contado
elif concepto.valor_iva == 'I':
importe = ventas_16_credito + ventas_16_contado
elif concepto.valor_iva == 'A':
importe = ventas_0_credito + ventas_0_contado + ventas_16_credito + ventas_16_contado
cuenta = concepto.cuenta_co.cuenta
elif concepto.valor_tipo == 'IVA' and not concepto.posicion in asientos_a_ingorar:
if concepto.valor_contado_credito == 'Credito':
importe = iva_pend_cobrar
elif concepto.valor_contado_credito == 'Contado':
importe = iva_efec_cobrado
elif concepto.valor_contado_credito == 'Ambos':
importe = iva_pend_cobrar + iva_efec_cobrado
cuenta = concepto.cuenta_co.cuenta
elif concepto.valor_tipo == 'Clientes' and not concepto.posicion in asientos_a_ingorar:
if concepto.valor_iva == 'A':
importe = clientes
if cuenta_cliente == None:
cuenta = concepto.cuenta_co.cuenta
else:
cuenta = cuenta_cliente
elif concepto.valor_tipo == 'Bancos' and not concepto.posicion in asientos_a_ingorar:
if concepto.valor_iva == 'A':
importe = bancos
cuenta = concepto.cuenta_co.cuenta
elif concepto.valor_tipo == 'Descuentos' and not concepto.posicion in asientos_a_ingorar:
importe = descuento
cuenta = concepto.cuenta_co.cuenta
clave_cuenta_tipoAsiento = "%s/%s:%s"% (cuenta, depto_co, concepto.tipo)
importe = importe
#Se es tipo segmento pone variables en cero para que no se calculen otra ves valores por ya estan calculados
if concepto.valor_tipo == 'Segmento_1' or concepto.valor_tipo == 'Segmento_2' or concepto.valor_tipo == 'Segmento_3' or concepto.valor_tipo == 'Segmento_4' or concepto.valor_tipo == 'Segmento_5':
importe = 0
if not clave_cuenta_tipoAsiento == [] and importe > 0:
if clave_cuenta_tipoAsiento in totales_cuentas:
totales_cuentas[clave_cuenta_tipoAsiento] = [totales_cuentas[clave_cuenta_tipoAsiento][0] + Decimal(importe),int(concepto.posicion)]
else:
totales_cuentas[clave_cuenta_tipoAsiento] = [Decimal(importe),int(concepto.posicion)]
return totales_cuentas, error, msg
def crear_polizas(documentos, depto_co, informacion_contable, msg, plantilla=None, descripcion = '', crear_polizas_por='',crear_polizas_de=None, tipo_poliza=''):
error = 0
DocumentosData = []
cuenta = ''
importe = 0
conceptos_poliza = DetallePlantillaPolizas_V.objects.filter(plantilla_poliza_v=plantilla).order_by('posicion')
moneda_local = get_object_or_404(Moneda,es_moneda_local='S')
documento_numero = 0
polizas = []
detalles_polizas = []
totales_cuentas = {}
for documento_no, documento in enumerate(documentos):
es_contado = documento.condicion_pago == informacion_contable.condicion_pago_contado
siguente_documento = documentos[(documento_no +1)%len(documentos)]
documento_numero = documento_no
totales_cuentas, error, msg = get_totales_doctos_ve(informacion_contable.condicion_pago_contado, documento, conceptos_poliza, totales_cuentas, msg, error, depto_co)
if error == 0:
#Cuando la fecha de la documento siguiente sea diferente y sea por DIA, o sea la ultima
if (not documento.fecha == siguente_documento.fecha and crear_polizas_por == 'Dia') or documento_no +1 == len(documentos) or crear_polizas_por == 'Documento':
if tipo_poliza == 'F':
tipo_poliza = informacion_contable.tipo_poliza_ve
elif tipo_poliza == 'D':
tipo_poliza = informacion_contable.tipo_poliza_dev
tipo_poliza_det = get_folio_poliza(tipo_poliza, documento.fecha)
#PREFIJO
prefijo = tipo_poliza.prefijo
if not tipo_poliza.prefijo:
prefijo = ''
#Si no tiene una descripcion el documento se pone lo que esta indicado en la descripcion general
descripcion_doc = documento.descripcion
if documento.descripcion == None or crear_polizas_por=='Dia' or crear_polizas_por == 'Periodo':
descripcion_doc = descripcion
referencia = documento.folio
if crear_polizas_por == 'Dia':
referencia = ''
poliza = DoctoCo(
id = c_get_next_key('ID_DOCTOS'),
tipo_poliza = tipo_poliza,
poliza = '%s%s'% (prefijo,("%09d" % tipo_poliza_det.consecutivo)[len(prefijo):]),
fecha = documento.fecha,
moneda = moneda_local,
tipo_cambio = 1,
estatus = 'P', cancelado= 'N', aplicado = 'N', ajuste = 'N', integ_co = 'S',
descripcion = descripcion_doc,
forma_emitida = 'N', sistema_origen = 'CO',
nombre = '',
grupo_poliza_periodo = None,
integ_ba = 'N',
usuario_creador = 'SYSDBA',
fechahora_creacion = datetime.datetime.now(), usuario_aut_creacion = None,
usuario_ult_modif = 'SYSDBA', fechahora_ult_modif = datetime.datetime.now(), usuario_aut_modif = None,
usuario_cancelacion = None, fechahora_cancelacion = None, usuario_aut_cancelacion = None,
)
polizas.append(poliza)
#CONSECUTIVO DE FOLIO DE POLIZA
tipo_poliza_det.consecutivo += 1
tipo_poliza_det.save()
posicion = 1
totales_cuentas = totales_cuentas.items()
for cuenta_depto_tipoAsiento, importe in totales_cuentas:
cuenta_deptotipoAsiento = cuenta_depto_tipoAsiento.split('/')
cuenta_co = CuentaCo.objects.get(cuenta=cuenta_deptotipoAsiento[0])
depto_tipoAsiento = cuenta_deptotipoAsiento[1].split(':')
depto_co = DeptoCo.objects.get(clave=depto_tipoAsiento[0])
tipo_asiento = depto_tipoAsiento[1]
detalle_poliza = DoctosCoDet(
id = -1,
docto_co = poliza,
cuenta = cuenta_co,
depto_co = depto_co,
tipo_asiento = tipo_asiento,
importe = importe[0],
importe_mn = 0,#PENDIENTE
ref = referencia,
descripcion = '',
posicion = posicion,
recordatorio = None,
fecha = documento.fecha,
cancelado = 'N', aplicado = 'N', ajuste = 'N',
moneda = moneda_local,
)
posicion +=1
detalles_polizas.append(detalle_poliza)
#DE NUEVO COMBIERTO LA VARIABLE A DICCIONARIO
totales_cuentas = {}
DocumentosData.append ({
'folio' :poliza.poliza,
})
DoctoVe.objects.filter(id=documento.id).update(contabilizado = 'S')
if error == 0:
DoctoCo.objects.bulk_create(polizas)
DoctosCoDet.objects.bulk_create(detalles_polizas)
else:
DocumentosData = []
polizas = []
detalles_polizas = []
return DocumentosData, msg
def generar_polizas(fecha_ini=None, fecha_fin=None, ignorar_documentos_cont=True, crear_polizas_por='Documento', crear_polizas_de='', plantilla_facturas='', plantilla_devoluciones='', descripcion= ''):
error = 0
msg = ''
documentosData = []
documentosGenerados = []
documentosDataDevoluciones = []
try:
informacion_contable = InformacionContable_V.objects.all()[:1]
informacion_contable = informacion_contable[0]
except ObjectDoesNotExist:
error = 1
#Si estadefinida la informacion contable no hay error!!!
if error == 0:
facturas = []
devoluciones= []
if ignorar_documentos_cont:
if crear_polizas_de == 'F' or crear_polizas_de == 'FD':
facturas = DoctoVe.objects.filter(Q(estado='N')|Q(estado='D'), tipo ='F', contabilizado ='N', fecha__gte=fecha_ini, fecha__lte=fecha_fin).order_by('fecha')[:99]
elif crear_polizas_de == 'D' or crear_polizas_de == 'FD':
devoluciones = DoctoVe.objects.filter(estado = 'N').filter(tipo ='D', contabilizado ='N', fecha__gte=fecha_ini, fecha__lte=fecha_fin).order_by('fecha')[:99]
else:
if crear_polizas_de == 'F' or crear_polizas_de == 'FD':
facturas = DoctoVe.objects.filter(Q(estado='N')|Q(estado='D'), tipo ='F', fecha__gte=fecha_ini, fecha__lte=fecha_fin).order_by('fecha')[:99]
elif crear_polizas_de == 'D' or crear_polizas_de == 'FD':
devoluciones = DoctoVe.objects.filter(estado = 'N').filter(tipo = 'D', fecha__gte=fecha_ini, fecha__lte=fecha_fin).order_by('fecha')[:99]
#PREFIJO
prefijo = informacion_contable.tipo_poliza_ve.prefijo
if not informacion_contable.tipo_poliza_ve.prefijo:
prefijo = ''
if crear_polizas_de == 'F' or crear_polizas_de == 'FD':
documentosData, msg = crear_polizas(facturas, informacion_contable.depto_general_cont, informacion_contable, msg, plantilla_facturas, descripcion, crear_polizas_por, crear_polizas_de, 'F')
documentosGenerados = documentosData
if crear_polizas_de == 'D' or crear_polizas_de == 'FD':
documentosDataDevoluciones, msg = crear_polizas(devoluciones, informacion_contable.depto_general_cont, informacion_contable, msg, plantilla_devoluciones, descripcion, crear_polizas_por, crear_polizas_de, 'D')
elif error == 1 and msg=='':
msg = 'No se han derfinido las preferencias de la empresa para generar polizas [Por favor definelas primero en Configuracion > Preferencias de la empresa]'
return documentosGenerados, documentosDataDevoluciones, msg
@login_required(login_url='/login/')
def facturas_View(request, template_name='herramientas/generar_polizas.html'):
documentosData = []
polizas_de_devoluciones = []
msg = ''
if request.method == 'POST':
form = GenerarPolizasManageForm(request.POST)
if form.is_valid():
fecha_ini = form.cleaned_data['fecha_ini']
fecha_fin = form.cleaned_data['fecha_fin']
ignorar_documentos_cont = form.cleaned_data['ignorar_documentos_cont']
crear_polizas_por = form.cleaned_data['crear_polizas_por']
crear_polizas_de = form.cleaned_data['crear_polizas_de']
plantilla_facturas = form.cleaned_data['plantilla']
plantilla_devoluciones = form.cleaned_data['plantilla_2']
descripcion = form.cleaned_data['descripcion']
if (crear_polizas_de == 'F' and not plantilla_facturas== None) or (crear_polizas_de == 'D' and not plantilla_devoluciones== None) or (crear_polizas_de == 'FD' and not plantilla_facturas== None and not plantilla_devoluciones== None):
msg = 'es valido'
documentosData, polizas_de_devoluciones, msg = generar_polizas(fecha_ini, fecha_fin, ignorar_documentos_cont, crear_polizas_por, crear_polizas_de, plantilla_facturas, plantilla_devoluciones, descripcion)
else:
error =1
msg = 'Seleciona una plantilla'
if (crear_polizas_de == 'F' or crear_polizas_de=='FD') and documentosData == []:
msg = 'Lo siento, no se encontraron facturas para este filtro'
elif (crear_polizas_de == 'D' or crear_polizas_de=='FD') and polizas_de_devoluciones == []:
msg = 'Lo siento, no se encontraron devoluciones para este filtro'
if crear_polizas_de == 'FD' and documentosData == [] and polizas_de_devoluciones == []:
msg = 'Lo siento, no se encontraron facturas ni devoluciones para este filtro'
else:
form = GenerarPolizasManageForm()
c = {'documentos':documentosData, 'polizas_de_devoluciones':polizas_de_devoluciones,'msg':msg,'form':form,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def plantilla_poliza_manageView(request, id = None, template_name='herramientas/plantilla_poliza.html'):
message = ''
if id:
plantilla = get_object_or_404(PlantillaPolizas_V, pk=id)
else:
plantilla =PlantillaPolizas_V()
if request.method == 'POST':
plantilla_form = PlantillaPolizaManageForm(request.POST, request.FILES, instance=plantilla)
plantilla_items = PlantillaPoliza_items_formset(ConceptoPlantillaPolizaManageForm, extra=1, can_delete=True)
plantilla_items_formset = plantilla_items(request.POST, request.FILES, instance=plantilla)
if plantilla_form.is_valid() and plantilla_items_formset .is_valid():
plantilla = plantilla_form.save(commit = False)
plantilla.save()
#GUARDA CONCEPTOS DE PLANTILLA
for concepto_form in plantilla_items_formset :
Detalleplantilla = concepto_form.save(commit = False)
#PARA CREAR UNO NUEVO
if not Detalleplantilla.id:
Detalleplantilla.plantilla_poliza_v = plantilla
plantilla_items_formset .save()
return HttpResponseRedirect('/ventas/PreferenciasEmpresa/')
else:
plantilla_items = PlantillaPoliza_items_formset(ConceptoPlantillaPolizaManageForm, extra=1, can_delete=True)
plantilla_form= PlantillaPolizaManageForm(instance=plantilla)
plantilla_items_formset = plantilla_items(instance=plantilla)
c = {'plantilla_form': plantilla_form, 'formset': plantilla_items_formset , 'message':message,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def plantilla_poliza_delete(request, id = None):
plantilla = get_object_or_404(PlantillaPolizas_V, pk=id)
plantilla.delete()
return HttpResponseRedirect('/ventas/PreferenciasEmpresa/')
<file_sep>
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.views import generic
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
dajaxice_autodiscover()
import autocomplete_light
autocomplete_light.autodiscover()
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
(r'^$', 'main.views.index'),
#Descomentar esta linea para habilitar inventarios
#url(r'^inventarios/', include('inventarios.urls', namespace='Inventarios')),
#url(r'^inventarios/', 'inventarios.views.index'),
#Descomentar esta linea para habilitar ventas
url(r'^ventas/', include('ventas.urls', namespace='ventas')),
#url(r'^ventas/', 'inventarios.views.index'),
url(r'^cuentas_por_pagar/', include('cuentas_por_pagar.urls', namespace='cuentas_por_pagar')),
#url(r'^cuentas_por_cobrar/', include('cuentas_por_cobrar.urls', namespace='cuentas_por_cobrar')),
#url(r'^contabilidad/', include('contabilidad.urls', namespace='contabilidad')),
url(r'autocomplete/', include('autocomplete_light.urls')),
#url(r'^admin/', include(admin.site.urls)),
#LOGIN
url(r'^login/$','inventarios.views.ingresar'),
url(r'^logout/$', 'inventarios.views.logoutUser'),
)
urlpatterns += staticfiles_urlpatterns()<file_sep>#encoding:utf-8
from django import forms
import autocomplete_light
from ventas.models import *
from django.contrib.auth.models import User
from django.forms.models import BaseInlineFormSet, inlineformset_factory
from cuentas_por_cobrar.models import *
class InformacionContableManageForm(forms.ModelForm):
condicion_pago_contado = forms.ModelChoiceField(queryset= CondicionPago.objects.all(), required=True)
class Meta:
model = InformacionContable_CC
class GenerarPolizasManageForm(forms.Form):
fecha_ini = forms.DateField()
fecha_fin = forms.DateField()
ignorar_documentos_cont = forms.BooleanField(required=False, initial=True)
CREAR_POR = (
('Documento', 'Documento'),
('Dia', 'Dia'),
('Periodo', 'Periodo'),
)
crear_polizas_por = forms.ChoiceField(choices=CREAR_POR)
plantilla = forms.ModelChoiceField(queryset= PlantillaPolizas_CC.objects.all(), required=True)
#plantilla_2 = forms.ModelChoiceField(queryset= PlantillaPolizas_V.objects.all(), required=True)
descripcion = forms.CharField(max_length=100, required=False)
crear_polizas_de = forms.ModelChoiceField(queryset= ConceptoCc.objects.filter(crear_polizas='S'), required=True)
class PlantillaPolizaManageForm(forms.ModelForm):
tipo = forms.ModelChoiceField(queryset= ConceptoCc.objects.filter(crear_polizas='S'), required=True)
class Meta:
model = PlantillaPolizas_CC
class ConceptoPlantillaPolizaManageForm(forms.ModelForm):
cuenta_co = forms.ModelChoiceField(queryset=CuentaCo.objects.all().order_by('cuenta'), required=True)
class Meta:
model = DetallePlantillaPolizas_CC
def PlantillaPoliza_items_formset(form, formset = BaseInlineFormSet, **kwargs):
return inlineformset_factory(PlantillaPolizas_CC, DetallePlantillaPolizas_CC, form, formset, **kwargs)<file_sep>from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
from inventarios.models import *
from django.core import serializers
from django.http import HttpResponse
from models import *
@dajaxice_register(method='GET')
def args_example(request, text):
return simplejson.dumps({'message':'Your message is %s!' % text})
@dajaxice_register(method='GET')
def obtener_plantillas(request, tipo_plantilla):
#se obtiene la provincia
plantillas = []
if tipo_plantilla =='F' or tipo_plantilla == 'D':
plantillas = PlantillaPolizas_V.objects.filter(tipo=tipo_plantilla)
#se devuelven las ciudades en formato json, solo nos interesa obtener como json
#el id y el nombre de las ciudades.
data = serializers.serialize("json", plantillas, fields=('id','nombre'))
return HttpResponse(data, mimetype="application/javascript")
@dajaxice_register(method='GET')
def obtener_plantillas_cp(request, tipo_plantilla):
#se obtiene la provincia
plantillas = PlantillaPolizas_CP.objects.filter(tipo=tipo_plantilla)
#se devuelven las ciudades en formato json, solo nos interesa obtener como json
#el id y el nombre de las ciudades.
data = serializers.serialize("json", plantillas, fields=('id','nombre'))
return HttpResponse(data, mimetype="application/javascript")
@dajaxice_register(method='GET')
def genera_polizas_cp(request, formulario):
form = ExampleForm(deserialize_form(formulario))
form = cuentas_por_pagar.generar_polizas_ajax(form)
form = serializers.serialize("json", form)
return HttpResponse(form, mimetype="application/javascript")<file_sep>microsip_web
============
INSTALACION DE APLICACION
/////////////RESPALDAR/////////////////
1) Respaldar microsip app
2) Respaldar microsip bases de datos
3) Respaldar firebird de archivos de programa
/////////////REINSTALAR FIREBIRD/////////////////
4) Reinstalar firbird Server **poner no nada borrar archivos** (EN INSTALCION INDICAR Copiar la libreria cliente de firebird al directorio<system>)
/////////////INTALAR PYTHON, SETUPTOOLS Y PIP ////////////////////
5) Instalar python y Agregar en variables de entorno
a) Instalar 2.7.3 de la pagina http://www.python.org/download/
b) Agregar en variables de entorno de python con "SET PATH=%PATH%;C:\Python27;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts;"
6) Instalar setuptools-0.6c11.win32-py2.7 de la pagina https://pypi.python.org/pypi/setuptools
7) Copiar carpeta de pip-1.3 a escritorio e instalar pip de carpeta pip-1.3 con python setup.py install porar carpeta pip de escritorio
/////////////INTALAR APLICACION Y LIBRERIAS NESESARIAS////////////////////
8) Instalar requerimentos de aplicacion con "pip install -r requirements.txt"
copiar carpeta de firebird de instaladores a C:\Python27\Lib\site-packages y C:\Python27\Lib\site-packages\django\db\backends
/////////////SYNCRONISAR BASE DE DATOS PYTHON ////////////////////
9) Sincronizar base de datos con python manage.py syncdb
10) CONFIGURAR INICIADOR DE SERVIDOR CON IP Y RUTAS
11)
////////////////////DEFINIR CAMPOS PARTICULARES PARA TABLAS//////////////////////////////
///////////////////PARA CUENTAS POR PAGAR/////////////////////////////////////////
class LibresCargosCP(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_CP_ID')
segmento_1 = models.CharField(max_length=99, db_column='SEGMENTO_1')
segmento_2 = models.CharField(max_length=99, db_column='SEGMENTO_2')
segmento_3 = models.CharField(max_length=99, db_column='SEGMENTO_3')
segmento_4 = models.CharField(max_length=99, db_column='SEGMENTO_4')
segmento_5 = models.CharField(max_length=99, db_column='SEGMENTO_5')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'libres_cargos_cp'
/////////////////PARA VENTAS//////////////////////
class LibresFacturasV(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_VE_ID')
segmento_1 = models.CharField(max_length=99, db_column='SEGMENTO_1')
segmento_2 = models.CharField(max_length=99, db_column='SEGMENTO_2')
segmento_3 = models.CharField(max_length=99, db_column='SEGMENTO_3')
segmento_4 = models.CharField(max_length=99, db_column='SEGMENTO_4')
segmento_5 = models.CharField(max_length=99, db_column='SEGMENTO_5')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'libres_fac_ve'
class LibresDevFacV(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_VE_ID')
segmento_1 = models.CharField(max_length=99, db_column='SEGMENTO_1')
segmento_2 = models.CharField(max_length=99, db_column='SEGMENTO_2')
segmento_3 = models.CharField(max_length=99, db_column='SEGMENTO_3')
segmento_4 = models.CharField(max_length=99, db_column='SEGMENTO_4')
segmento_5 = models.CharField(max_length=99, db_column='SEGMENTO_5')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'libres_devfac_ve'
11) LISTO
7) Instalar django-firebird con el comando "pip install django-fiebird"
8) LISTO
CONFIGURACION EN APACHE
Primero que nada es necesario instalar apache (xampserver)
1)Descargar el modulo mod_wsgi de "http://code.google.com/p/modwsgi/downloads/list" y gurdarlo en la rota "C:\wamp\bin\apache\apache2.2.22\modules"
Agregar la siguiente inea de configuracion en apache
LoadModule wsgi_module modules/mod_wsgi.so
2) Agregar estas lineas al archivo de configuracion de apache
WSGIScriptAlias / "C:/wamp/www/microsip_web/microsip_web/django.wsgi"
Alias /static/ C:/wamp/www/microsip_web/inventarios/static/
AUTOCOMPLETE
Documentacion en: http://django-autocomplete-light.rtfd.org
Repocitorio en github https://github.com/yourlabs/django-autocomplete-light
1) Instalar el paquete con django-autocomplete-light:
pip install django-autocomplete-light
2) En carpeta static copiar carpeta autocomplete_light de css y js
3) En carpeta templetes copiar carpeta autocomplete_light de templetes
4) Agregar archivo autocomplete_light_registry.py a carpeta de aplicacion
5) En formulario donde se desee aplicar poner el codigo segun el modelo a usar (archivo forms.py):
#agregar al primcipio del archivo
import autocomplete_light
#agregar despues de class Meta:
"widgets = autocomplete_light.get_widgets_dict(DoctosInvfisDet)"
I guess a test would be to install a package with pip using a --index-url=file:////localhost/c$/some/package/index where /index contains subdirectories of projects:
/index
/pkg
/pkg-0.0.1.tar.gz
The pip command: pip install --index-url=file:////localhost/c$/some/package/index pkg should find and install pkg-0.0.1.tar.gz.
MIGRATIONS
Follow these steps:
Export your data to a fixture using the dumpdata management command
Drop the table
Run syncdb
Reload your data from the fixture using the loaddata management command
<file_sep>#encoding:utf-8
from django.db import models
from datetime import datetime
from django.db.models.signals import pre_save
from django.core import urlresolvers
class Moneda(models.Model):
id = models.AutoField(primary_key=True, db_column='MONEDA_ID')
es_moneda_local = models.CharField(default='N', max_length=1, db_column='ES_MONEDA_LOCAL')
class Meta:
db_table = u'monedas'
class Paises(models.Model):
PAIS_ID = models.AutoField(primary_key=True)
name = models.CharField(max_length=50, db_column='NOMBRE')
class Meta:
db_table = u'paises'
class ActivosFijos(models.Model):
class Meta:
db_table = u'activos_fijos'
class AcumCuentasCoTemp(models.Model):
class Meta:
db_table = u'acum_cuentas_co_temp'
class Aduanas(models.Model):
class Meta:
db_table = u'aduanas'
class Agentes(models.Model):
AGENTE_ID = models.AutoField(primary_key=True)
class Meta:
db_table = u'agentes'
class Almacenes(models.Model):
ALMACEN_ID = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=50, db_column='NOMBRE')
def __unicode__(self):
return self.nombre
class Meta:
db_table = u'almacenes'
class Articulos(models.Model):
id = models.AutoField(primary_key=True, db_column='ARTICULO_ID')
nombre = models.CharField(max_length=100, db_column='NOMBRE')
es_almacenable = models.CharField(default='S', max_length=1, db_column='ES_ALMACENABLE')
def __unicode__(self):
return u'%s' % self.nombre
class Meta:
db_table = u'articulos'
class ArticulosClientes(models.Model):
class Meta:
db_table = u'articulos_clientes'
class ArticulosDiscretos(models.Model):
class Meta:
db_table = u'articulos_discretos'
class Atributos(models.Model):
class Meta:
db_table = u'atributos'
class Bancos(models.Model):
BANCO_ID = models.AutoField(primary_key=True)
class Meta:
db_table = u'bancos'
class Beneficiarios(models.Model):
BENEFICIARIO_ID = models.AutoField(primary_key=True)
class Meta:
db_table = u'beneficiarios'
class Bitacora(models.Model):
class Meta:
db_table = u'bitacora'
class BookmarksReportes(models.Model):
class Meta:
db_table = u'bookmarks_reportes'
class Cajas(models.Model):
class Meta:
db_table = u'cajas'
class CajasCajeros(models.Model):
class Meta:
db_table = u'cajas_cajeros'
class Cajeros(models.Model):
class Meta:
db_table = u'cajeros'
class CapasCostos(models.Model):
class Meta:
db_table = u'capas_costos'
class CapasPedimentos(models.Model):
class Meta:
db_table = u'capas_pedimentos'
class CargosPeriodicosCc(models.Model):
class Meta:
db_table = u'cargos_periodicos_cc'
class CentrosCosto(models.Model):
id = models.AutoField(primary_key=True, db_column='CENTRO_COSTO_ID')
nombre = models.CharField(max_length=50, db_column='NOMBRE')
es_predet = models.CharField(default='N', max_length=1, db_column='ES_PREDET')
usuario_creador = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_CREADOR')
fechahora_creacion = models.DateTimeField(blank=True, null=True, db_column='FECHA_HORA_CREACION')
usuario_aut_creacion = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_AUT_CREACION')
usuario_ult_modif = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_ULT_MODIF')
fechahora_ult_modif = models.DateTimeField(blank=True, null=True, db_column='FECHA_HORA_ULT_MODIF')
usuario_aut_modif = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_AUT_MODIF')
def __unicode__(self):
return self.nombre
class Meta:
db_table = u'centros_costo'
class CertCfdProv(models.Model):
class Meta:
db_table = u'cert_cfd_prov'
class CfdRecibidos(models.Model):
class Meta:
db_table = u'cfd_recibidos'
class Ciudades(models.Model):
class Meta:
db_table = u'ciudades'
class RolesClavesArticulos(models.Model):
id = models.AutoField(primary_key=True, db_column='ROL_CLAVE_ART_ID')
nombre = models.CharField(max_length=50, db_column='NOMBRE')
es_ppal = models.CharField(default='N', max_length=1, db_column='ES_PPAL')
class Meta:
db_table = u'roles_claves_articulos'
class ClavesArticulos(models.Model):
id = models.AutoField(primary_key=True, db_column='CLAVE_ARTICULO_ID')
clave = models.CharField(max_length=20, db_column='CLAVE_ARTICULO')
articulo = models.ForeignKey(Articulos, db_column='ARTICULO_ID')
rol = models.ForeignKey(RolesClavesArticulos, db_column='ROL_CLAVE_ART_ID')
def __unicode__(self):
return u'%s' % self.clave
class Meta:
db_table = u'claves_articulos'
class ClavesCatSec(models.Model):
class Meta:
db_table = u'claves_cat_sec'
class ClavesClientes(models.Model):
class Meta:
db_table = u'claves_clientes'
class ClavesEmpleados(models.Model):
class Meta:
db_table = u'claves_empleados'
class ClavesProveedores(models.Model):
class Meta:
db_table = u'claves_proveedores'
class Proveedor(models.Model):
id = models.AutoField(primary_key=True, db_column='PROVEEDOR_ID')
nombre = models.CharField(max_length=100, db_column='NOMBRE')
cuenta_xpagar = models.CharField(max_length=9, db_column='CUENTA_CXP')
cuenta_anticipos = models.CharField(max_length=9, db_column='CUENTA_ANTICIPOS')
moneda = models.ForeignKey(Moneda, db_column='MONEDA_ID')
def __unicode__(self):
return u'%s' % self.nombre
class Meta:
db_table = u'proveedores'
class Cobradores(models.Model):
class Meta:
db_table = u'cobradores'
class ComandosDispositivos(models.Model):
class Meta:
db_table = u'comandos_dispositivos'
class ComandosTiposDispositivos(models.Model):
class Meta:
db_table = u'comandos_tipos_dispositivos'
class ComisCobTipoCli(models.Model):
class Meta:
db_table = u'comis_cob_tipo_cli'
class ComisCobZona(models.Model):
class Meta:
db_table = u'comis_cob_zona'
class ComisVenArt(models.Model):
class Meta:
db_table = u'comis_ven_art'
class ComisVenCli(models.Model):
class Meta:
db_table = u'comis_ven_cli'
class ComisVenGrupo(models.Model):
class Meta:
db_table = u'comis_ven_grupo'
class ComisVenLinea(models.Model):
class Meta:
db_table = u'comis_ven_linea'
class ComisVenTipoCli(models.Model):
class Meta:
db_table = u'comis_ven_tipo_cli'
class ComisVenZona(models.Model):
class Meta:
db_table = u'comis_ven_zona'
class CompromArticulos(models.Model):
class Meta:
db_table = u'comprom_articulos'
class ConceptosBa(models.Model):
class Meta:
db_table = u'conceptos_ba'
class ConceptoCp(models.Model):
id = models.AutoField(primary_key=True, db_column='CONCEPTO_CP_ID')
nombre_abrev = models.CharField(max_length=30, db_column='NOMBRE_ABREV')
crear_polizas = models.CharField(default='N', max_length=1, db_column='CREAR_POLIZAS')
cuenta_contable = models.CharField(max_length=30, db_column='CUENTA_CONTABLE')
clave_tipo_poliza = models.CharField(max_length=1, db_column='TIPO_POLIZA')
descripcion_poliza = models.CharField(max_length=200, db_column='DESCRIPCION_POLIZA')
def __unicode__(self):
return self.nombre_abrev
class Meta:
db_table = u'conceptos_cp'
class ConceptosDim(models.Model):
class Meta:
db_table = u'conceptos_dim'
class ConceptosEmp(models.Model):
class Meta:
db_table = u'conceptos_emp'
class ConceptosIn(models.Model):
CONCEPTO_IN_ID = models.AutoField(primary_key=True)
nombre_abrev = models.CharField(max_length=30, db_column='NOMBRE_ABREV')
def __unicode__(self):
return self.nombre_abrev
class Meta:
db_table = u'conceptos_in'
class ConceptosNo(models.Model):
class Meta:
db_table = u'conceptos_no'
class CondicionPago(models.Model):
id = models.AutoField(primary_key=True, db_column='COND_PAGO_ID')
nombre = models.CharField(max_length=50, db_column='NOMBRE')
def __unicode__(self):
return self.nombre
class Meta:
db_table = u'condiciones_pago'
class CondicionPagoCp(models.Model):
id = models.AutoField(primary_key=True, db_column='COND_PAGO_ID')
nombre = models.CharField(max_length=50, db_column='NOMBRE')
def __unicode__(self):
return self.nombre
class Meta:
db_table = u'condiciones_pago_cp'
class ConfTicketsCajas(models.Model):
class Meta:
db_table = u'conf_tickets_cajas'
class ConfTicketsCajasPrns(models.Model):
class Meta:
db_table = u'conf_tickets_cajas_prns'
class ConsignatariosCm(models.Model):
class Meta:
db_table = u'consignatarios_cm'
class CuentasBancarias(models.Model):
class Meta:
db_table = u'cuentas_bancarias'
class CuentaCo(models.Model):
id = models.AutoField(primary_key=True, db_column='CUENTA_ID')
nombre = models.CharField(max_length=50, db_column='NOMBRE')
cuenta = models.CharField(max_length=50, db_column='CUENTA_PT')
def __unicode__(self):
return u'%s (%s)' % (self.cuenta, self.nombre)
class Meta:
db_table = u'cuentas_co'
class CuentasNo(models.Model):
class Meta:
db_table = u'cuentas_no'
class DeptoCo(models.Model):
id = models.AutoField(primary_key=True, db_column='DEPTO_CO_ID')
clave = models.CharField(max_length=1, db_column='CLAVE')
def __unicode__(self):
return u'%s' % self.clave
class Meta:
db_table = u'deptos_co'
class DeptosNo(models.Model):
class Meta:
db_table = u'deptos_no'
class DescripPolizas(models.Model):
class Meta:
db_table = u'descrip_polizas'
class DesgloseEnDiscretos(models.Model):
class Meta:
db_table = u'desglose_en_discretos'
class DesgloseEnDiscretosCm(models.Model):
class Meta:
db_table = u'desglose_en_discretos_cm'
class DesgloseEnDiscretosInvfis(models.Model):
class Meta:
db_table = u'desglose_en_discretos_invfis'
class DesgloseEnDiscretosPv(models.Model):
class Meta:
db_table = u'desglose_en_discretos_pv'
class DesgloseEnDiscretosVe(models.Model):
class Meta:
db_table = u'desglose_en_discretos_ve'
class DesgloseEnPedimentos(models.Model):
class Meta:
db_table = u'desglose_en_pedimentos'
class DirsClientes(models.Model):
class Meta:
db_table = u'dirs_clientes'
class Dispositivos(models.Model):
class Meta:
db_table = u'dispositivos'
class DispositivosCajas(models.Model):
class Meta:
db_table = u'dispositivos_cajas'
class DoctosBa(models.Model):
class Meta:
db_table = u'doctos_ba'
class DoctosCm(models.Model):
class Meta:
db_table = u'doctos_cm'
class DoctosCmDet(models.Model):
class Meta:
db_table = u'doctos_cm_det'
class DoctosCmLigas(models.Model):
class Meta:
db_table = u'doctos_cm_ligas'
class DoctosCmLigasDet(models.Model):
class Meta:
db_table = u'doctos_cm_ligas_det'
class DoctosCmProeve(models.Model):
class Meta:
db_table = u'doctos_cm_proeve'
##########################################
## ##
## POLIZAS ##
## ##
##########################################
class Recordatorio(models.Model):
id = models.AutoField(primary_key=True, db_column='RECORDATORIO_ID')
class Meta:
db_table = u'recordatorios'
class GrupoPolizasPeriodoCo(models.Model):
id = models.AutoField(primary_key=True, db_column='GRUPO_POL_PERIOD_ID')
class Meta:
db_table = 'grupos_polizas_period_co'
class TipoPoliza(models.Model):
id = models.AutoField(primary_key=True, db_column='TIPO_POLIZA_ID')
clave = models.CharField(max_length=1, db_column='CLAVE')
nombre = models.CharField(max_length=30, db_column='NOMBRE')
tipo_consec = models.CharField(max_length=1, db_column='TIPO_CONSEC')
prefijo = models.CharField(max_length=1, db_column='PREFIJO')
def __unicode__(self):
return u'%s' % self.nombre
class Meta:
db_table = u'tipos_polizas'
class TipoPolizaDet(models.Model):
id = models.AutoField(primary_key=True, db_column='TIPO_POLIZA_DET_ID')
tipo_poliza = models.ForeignKey(TipoPoliza, db_column='TIPO_POLIZA_ID')
ano = models.SmallIntegerField(db_column='ANO')
mes = models.SmallIntegerField(db_column='MES')
consecutivo = models.IntegerField(db_column='CONSECUTIVO')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'tipos_polizas_det'
class DoctoCo(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_CO_ID')
tipo_poliza = models.ForeignKey(TipoPoliza, db_column='TIPO_POLIZA_ID')
poliza = models.CharField(max_length=9, db_column='POLIZA')
fecha = models.DateField(db_column='FECHA')
moneda = models.ForeignKey(Moneda, db_column='MONEDA_ID')
tipo_cambio = models.DecimalField(max_digits=18, decimal_places=6, db_column='TIPO_CAMBIO')
estatus = models.CharField(default='N', max_length=1, db_column='ESTATUS')
cancelado = models.CharField(default='N', max_length=1, db_column='CANCELADO')
aplicado = models.CharField(default='S', max_length=1, db_column='APLICADO')
ajuste = models.CharField(default='N', max_length=1, db_column='AJUSTE')
integ_co = models.CharField(default='S', max_length=1, db_column='INTEG_CO')
descripcion = models.CharField(blank=True, null=True, max_length=200, db_column='DESCRIPCION')
forma_emitida = models.CharField(default='N', max_length=1, db_column='FORMA_EMITIDA')
sistema_origen = models.CharField(max_length=2, db_column='SISTEMA_ORIGEN')
nombre = models.CharField(blank=True, null=True, max_length=30, db_column='NOMBRE')
grupo_poliza_periodo = models.ForeignKey(GrupoPolizasPeriodoCo, blank=True, null=True, db_column='GRUPO_POL_PERIOD_ID')
integ_ba = models.CharField(default='N', max_length=1, db_column='INTEG_BA')
usuario_creador = models.CharField(max_length=31, db_column='USUARIO_CREADOR')
fechahora_creacion = models.DateTimeField(auto_now_add=True, db_column='FECHA_HORA_CREACION')
usuario_aut_creacion = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_AUT_CREACION')
usuario_ult_modif = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_ULT_MODIF')
fechahora_ult_modif = models.DateTimeField(auto_now=True, blank=True, null=True, db_column='FECHA_HORA_ULT_MODIF')
usuario_aut_modif = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_AUT_MODIF')
usuario_cancelacion = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_CANCELACION')
fechahora_cancelacion = models.DateTimeField(auto_now=True, blank=True, null=True, db_column='FECHA_HORA_CANCELACION')
usuario_aut_cancelacion = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_AUT_CANCELACION')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'doctos_co'
class DoctosCoDet(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_CO_DET_ID')
docto_co = models.ForeignKey(DoctoCo, db_column='DOCTO_CO_ID')
cuenta = models.ForeignKey(CuentaCo, db_column='CUENTA_ID')
depto_co = models.ForeignKey(DeptoCo, db_column='DEPTO_CO_ID')
tipo_asiento= models.CharField(default='C', max_length=1, db_column='TIPO_ASIENTO')
importe = models.DecimalField(max_digits=15, decimal_places=2, db_column='IMPORTE')
importe_mn = models.DecimalField(max_digits=15, decimal_places=2, db_column='IMPORTE_MN')
ref = models.CharField(max_length=10, db_column='REFER')
descripcion = models.CharField(blank=True, null=True, max_length=200, db_column='DESCRIPCION')
posicion = models.IntegerField(default=0)
recordatorio= models.ForeignKey(Recordatorio, blank=True, null=True, db_column='RECORDATORIO_ID')
fecha = models.DateField(db_column='FECHA')
cancelado = models.CharField(default='N', max_length=1, db_column='CANCELADO')
aplicado = models.CharField(default='N', max_length=1, db_column='APLICADO')
ajuste = models.CharField(default='N', max_length=1, db_column='AJUSTE')
moneda = models.ForeignKey(Moneda, db_column='MONEDA_ID')
class Meta:
db_table = u'doctos_co_det'
class DoctosCp(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_CP_ID')
concepto = models.ForeignKey(ConceptoCp, db_column='CONCEPTO_CP_ID')
folio = models.CharField(max_length=9, db_column='FOLIO')
naturaleza_concepto = models.CharField(max_length=1, db_column='NATURALEZA_CONCEPTO')
fecha = models.DateField(auto_now=True, db_column='FECHA')
proveedor = models.ForeignKey(Proveedor, db_column='PROVEEDOR_ID')
cancelado = models.CharField(default='N', max_length=1, db_column='CANCELADO')
aplicado = models.CharField(default='S', max_length=1, db_column='APLICADO')
descripcion = models.CharField(blank=True, null=True, max_length=200, db_column='DESCRIPCION')
contabilizado = models.CharField(default='N', blank=True, null=True, max_length=1, db_column='CONTABILIZADO')
tipo_cambio = models.DecimalField(max_digits=18, decimal_places=6, db_column='TIPO_CAMBIO')
condicion_pago = models.ForeignKey(CondicionPagoCp, db_column='COND_PAGO_ID')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'doctos_cp'
class ImportesDoctosCP(models.Model):
id = models.AutoField(primary_key=True, db_column='IMPTE_DOCTO_CP_ID')
docto_cp = models.ForeignKey(DoctosCp, db_column='DOCTO_CP_ID')
importe_neto = models.DecimalField(max_digits=15, decimal_places=2, db_column='IMPORTE')
total_impuestos = models.DecimalField(max_digits=15, decimal_places=2, db_column='IMPUESTO')
class Meta:
db_table = u'importes_doctos_cp'
class DoctosEntreSis(models.Model):
class Meta:
db_table = u'doctos_entre_sis'
class DoctosIn(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_IN_ID')
folio = models.CharField(max_length=50, db_column='FOLIO')
almacen = models.ForeignKey(Almacenes, db_column='ALMACEN_ID')
descripcion = models.CharField(blank=True, null=True, max_length=200, db_column='DESCRIPCION')
concepto = models.ForeignKey(ConceptosIn, db_column='CONCEPTO_IN_ID')
naturaleza_concepto = models.CharField(default='S', max_length=1, db_column='NATURALEZA_CONCEPTO')
fecha = models.DateField(auto_now=True, db_column='FECHA')
cancelado = models.CharField(default='N', blank=True, null=True, max_length=1, db_column='CANCELADO')
aplicado = models.CharField(default='S',blank=True, null=True, max_length=1, db_column='APLICADO')
forma_emitida = models.CharField(default='N', blank=True, null=True, max_length=1, db_column='FORMA_EMITIDA')
contabilizado = models.CharField(default='N', blank=True, null=True, max_length=1, db_column='CONTABILIZADO')
sistema_origen = models.CharField(default='PV', max_length=2, db_column='SISTEMA_ORIGEN')
usuario_creador = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_CREADOR')
fechahora_creacion = models.DateTimeField(auto_now_add=True, db_column='FECHA_HORA_CREACION')
usuario_ult_modif = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_ULT_MODIF')
fechahora_ult_modif = models.DateTimeField(auto_now=True, blank=True, null=True, db_column='FECHA_HORA_ULT_MODIF')
class Meta:
db_table = u'doctos_in'
class DoctosInvfis(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_INVFIS_ID')
almacen = models.ForeignKey(Almacenes, db_column='ALMACEN_ID')
folio = models.CharField(max_length=9, db_column='FOLIO')
fecha = models.DateField(auto_now=True, db_column='FECHA')
cancelado = models.CharField(default='N', blank=True, null=True, max_length=1, db_column='CANCELADO')
aplicado = models.CharField(default='N',blank=True, null=True, max_length=1, db_column='APLICADO')
descripcion = models.CharField(blank=True, null=True, max_length=200, db_column='DESCRIPCION')
usuario_creador = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_CREADOR')
fechahora_creacion = models.DateTimeField(auto_now_add=True, db_column='FECHA_HORA_CREACION')
usuario_aut_creacion= models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_AUT_CREACION')
usuario_ult_modif = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_ULT_MODIF')
fechahora_ult_modif = models.DateTimeField(auto_now=True, blank=True, null=True, db_column='FECHA_HORA_ULT_MODIF')
usuario_aut_modif = models.CharField(blank=True, null=True, max_length=31, db_column='USUARIO_AUT_MODIF')
class Meta:
db_table = u'doctos_invfis'
class DoctosInvfisDet(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_INVFIS_DET_ID')
docto_invfis= models.ForeignKey(DoctosInvfis, db_column='DOCTO_INVFIS_ID')
clave = models.CharField(blank=True, null=True, max_length=20, db_column='CLAVE_ARTICULO')
articulo = models.ForeignKey(Articulos, db_column='ARTICULO_ID')
unidades = models.IntegerField(default=0, blank=True, null=True, db_column='UNIDADES')
class Meta:
db_table = u'doctos_invfis_det'
class DoctosInDet(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_IN_DET_ID')
doctosIn = models.ForeignKey(DoctosIn, db_column='DOCTO_IN_ID')
almacen = models.ForeignKey(Almacenes, db_column='ALMACEN_ID')
concepto = models.ForeignKey(ConceptosIn, db_column='CONCEPTO_IN_ID')
claveArticulo = models.CharField(blank=True, null=True, max_length=20, db_column='CLAVE_ARTICULO')
articulo = models.ForeignKey(Articulos, db_column='ARTICULO_ID')
tipo_movto = models.CharField(default='E', max_length=1, db_column='TIPO_MOVTO')
unidades = models.IntegerField(default=0, blank=True, null=True, db_column='UNIDADES')
costo_unitario = models.DecimalField(default=0, blank=True, null=True, max_digits=18, decimal_places=2, db_column='COSTO_UNITARIO')
costo_total = models.DecimalField(default=0, blank=True, null=True, max_digits=15, decimal_places=2, db_column='COSTO_TOTAL')
metodo_costeo = models.CharField(default='C', max_length=1, db_column='METODO_COSTEO')
cancelado = models.CharField(default='N', blank=True, null=True, max_length=1, db_column='CANCELADO')
aplicado = models.CharField(default='N', blank=True, null=True, max_length=1, db_column='APLICADO')
costeo_pend = models.CharField(default='N', blank=True, null=True, max_length=1, db_column='COSTEO_PEND')
pedimento_pend = models.CharField(default='N', blank=True, null=True, max_length=1, db_column='PEDIMENTO_PEND')
rol = models.CharField(default='N', max_length=1, db_column='ROL')
fecha = models.DateField(auto_now=True, blank=True, null=True, db_column='FECHA')
#centros_costo = models.ForeignKey(CentrosCosto, db_column='CENTRO_COSTO_ID', blank=True, null=True,)
class Meta:
db_table = u'doctos_in_det'
#######################################################VENTAS###############################################################################################
############################################################################################################################################################
############################################################################################################################################################
############################################################################################################################################################
############################################################################################################################################################
class Cliente(models.Model):
id = models.AutoField(primary_key=True, db_column='CLIENTE_ID')
nombre = models.CharField(max_length=9, db_column='NOMBRE')
cuenta_xcobrar = models.CharField(max_length=9, db_column='CUENTA_CXC')
class Meta:
db_table = u'clientes'
class TiposImpuestos(models.Model):
id = models.AutoField(primary_key=True, db_column='TIPO_IMPTO_ID')
nombre = models.CharField(max_length=30, db_column='NOMBRE')
tipo = models.CharField(max_length=30, db_column='TIPO')
class Meta:
db_table = u'tipos_impuestos'
class Impuestos(models.Model):
id = models.AutoField(primary_key=True, db_column='IMPUESTO_ID')
tipoImpuesto = models.ForeignKey(TiposImpuestos, on_delete= models.SET_NULL, blank=True, null=True, db_column='TIPO_IMPTO_ID')
nombre = models.CharField(max_length=30, db_column='NOMBRE')
porcentaje = models.DecimalField(default=0, blank=True, null=True, max_digits=9, decimal_places=6, db_column='PCTJE_IMPUESTO')
class Meta:
db_table = u'impuestos'
class ImpuestosArticulo(models.Model):
id = models.AutoField(primary_key=True, db_column='IMPUESTO_ART_ID')
articulo = models.ForeignKey(Articulos, on_delete= models.SET_NULL, blank=True, null=True, db_column='ARTICULO_ID')
impuesto = models.ForeignKey(Impuestos, on_delete= models.SET_NULL, blank=True, null=True, db_column='IMPUESTO_ID')
class Meta:
db_table = u'impuestos_articulos'
class LibresCargosCP(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_CP_ID')
segmento_1 = models.CharField(max_length=99, db_column='SEGMENTO_1')
segmento_2 = models.CharField(max_length=99, db_column='SEGMENTO_2')
segmento_3 = models.CharField(max_length=99, db_column='SEGMENTO_3')
segmento_4 = models.CharField(max_length=99, db_column='SEGMENTO_4')
segmento_5 = models.CharField(max_length=99, db_column='SEGMENTO_5')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'libres_cargos_cp'
#############################################################################################################################################################
##################################################MODELOS DE APLICACION DJANGO###############################################################################
#############################################################################################################################################################
class InformacionContable_CP(models.Model):
condicion_pago_contado = models.ForeignKey(CondicionPagoCp, blank=True, null=True)
def __unicode__(self):
return u'%s'% self.id
class PlantillaPolizas_CP(models.Model):
nombre = models.CharField(max_length=200)
tipo = models.ForeignKey(ConceptoCp)
def __unicode__(self):
return u'%s'%self.nombre
class DetallePlantillaPolizas_CP(models.Model):
TIPOS = (('C', 'Cargo'),('A', 'Abono'),)
VALOR_TIPOS =(
('Compras', 'Compras'),
('Proveedores', 'Proveedores'),
('Bancos', 'Bancos'),
('Fletes', 'Fletes'),
('Descuentos', 'Descuentos'),
('Devoluciones','Devoluciones'),
('Anticipos','Anticipos'),
('IVA', 'IVA'),
('Segmento_1', 'Segmento 1'),
('Segmento_2', 'Segmento 2'),
('Segmento_3', 'Segmento 3'),
('Segmento_4', 'Segmento 4'),
('Segmento_5', 'Segmento 5'),
)
VALOR_IVA_TIPOS = (('A', 'Ambos'),('I', 'Solo IVA'),('0', 'Solo 0%'),)
VALOR_CONTADO_CREDITO_TIPOS = (('Ambos', 'Ambos'),('Contado', 'Contado'),('Credito', 'Credito'),)
posicion = models.CharField(max_length=2)
plantilla_poliza_CP = models.ForeignKey(PlantillaPolizas_CP)
cuenta_co = models.ForeignKey(CuentaCo)
tipo = models.CharField(max_length=2, choices=TIPOS, default='C')
asiento_ingora = models.CharField(max_length=2, blank=True, null=True)
valor_tipo = models.CharField(max_length=20, choices=VALOR_TIPOS)
valor_iva = models.CharField(max_length=2, choices=VALOR_IVA_TIPOS, default='A')
valor_contado_credito = models.CharField(max_length=10, choices=VALOR_CONTADO_CREDITO_TIPOS, default='Ambos')
def __unicode__(self):
return u'%s'%self.id
#############################################################################################################################################################
#############################################################################################################################################################
#############################################################################################################################################################<file_sep>#encoding:utf-8
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from inventarios.models import *
from cuentas_por_pagar.forms import *
from main.views import get_folio_poliza
import json
from decimal import *
import datetime, time
from django.db.models import Q
#Paginacion
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# user autentication
from django.contrib.auth.decorators import login_required, permission_required
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum, Max
from django.db import connection
from inventarios.views import c_get_next_key
import ventas
@login_required(login_url='/login/')
def preferenciasEmpresa_View(request, template_name='herramientas/preferencias_empresa_CP.html'):
try:
informacion_contable = InformacionContable_CP.objects.all()[:1]
informacion_contable = informacion_contable[0]
except:
informacion_contable = InformacionContable_CP()
msg = ''
if request.method == 'POST':
form = InformacionContableManageForm(request.POST, instance=informacion_contable)
if form.is_valid():
form.save()
msg = 'Datos Guardados Exitosamente'
else:
form = InformacionContableManageForm(instance=informacion_contable)
plantillas = PlantillaPolizas_CP.objects.all()
c= {'form':form,'msg':msg,'plantillas':plantillas,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
def get_totales_cuentas_by_segmento(segmento='',totales_cuentas=[], depto_co=None, concepto_tipo=None, error=0, msg='', documento_folio='', asiento_ingora=0):
importe = 0
cuenta = []
clave_cuenta_tipoAsiento = []
segmento = segmento.split(',')
if not segmento == []:
for importe_segmento in segmento:
cuenta_cantidad = importe_segmento.split('=')
cuenta_depto= cuenta_cantidad[0].split("/")
try:
cuenta = CuentaCo.objects.get(cuenta=cuenta_depto[0]).cuenta
except ObjectDoesNotExist:
error = 2
msg = 'NO EXISTE almenos una [CUENTA CONTABLE] indicada en un segmento en el documento con folio[%s], Corrigelo para continuar'% documento_folio
if len(cuenta_depto) == 2:
try:
depto = DeptoCo.objects.get(clave=cuenta_depto[1]).clave
except ObjectDoesNotExist:
error = 2
msg = 'NO EXISTE almenos un [DEPARTEMENTO CONTABLE] indicado en un segmento en el documento con folio [%s], Corrigelo para continuar'% documento_folio
else:
depto = depto_co
try:
importe = float(cuenta_cantidad[1])
except:
error = 3
msg = 'Cantidad incorrecta en un segmento en el documento [%s], Corrigelo para continuar'% documento_folio
if error == 0:
clave_cuenta_tipoAsiento = "%s/%s:%s"% (cuenta, depto, concepto_tipo)
importe = importe
if not clave_cuenta_tipoAsiento == [] and importe > 0:
if clave_cuenta_tipoAsiento in totales_cuentas:
totales_cuentas[clave_cuenta_tipoAsiento] = [totales_cuentas[clave_cuenta_tipoAsiento][0] + Decimal(importe),int(asiento_ingora)]
else:
totales_cuentas[clave_cuenta_tipoAsiento] = [Decimal(importe),int(asiento_ingora)]
return totales_cuentas, error, msg
def get_totales_documento_cuentas(cuenta_contado = None, documento=None, conceptos_poliza=None, totales_cuentas=None, msg='', error=''):
campos_particulares = LibresCargosCP.objects.filter(pk=documento.id)[0]
try:
cuenta_proveedor = CuentaCo.objects.get(cuenta=documento.proveedor.cuenta_xpagar).cuenta
except ObjectDoesNotExist:
cuenta_proveedor = None
error = 1
msg ='no se encontro el proveedor'
depto_co = get_object_or_404(DeptoCo, pk=76).clave
#Para saber si es contado o es credito
if documento.naturaleza_concepto == 'C':
es_contado = documento.condicion_pago == cuenta_contado
else:
es_contado = False
importesDocto = ImportesDoctosCP.objects.filter(docto_cp=documento)[0]
impuestos = importesDocto.total_impuestos * documento.tipo_cambio
importe_neto = importesDocto.importe_neto * documento.tipo_cambio
total = impuestos + importe_neto
descuento = 0
proveedores = total - descuento
bancos = 0
compras_0 = 0
compras_16 = 0
compras_16_credito = 0
compras_0_credito = 0
compras_16_contado = 0
compras_0_contado = 0
iva_pend_pagar = 0
iva_efec_pagado = 0
if impuestos <= 0:
compras_0 = importe_neto
else:
compras_16 = importe_neto
#si llega a haber un proveedor que no tenga cargar impuestos
if compras_16 < 0:
compras_0 += compras_16
compras_16 = 0
msg = 'Existe al menos una documento donde el proveedor [no tiene indicado cargar inpuestos] POR FAVOR REVISTA ESO!!'
if crear_polizas_por == 'Dia':
msg = '%s, REVISA LAS POLIZAS QUE SE CREARON'% msg
error = 1
#Si es a credito
if not es_contado:
compras_16_credito = compras_16
compras_0_credito = compras_0
iva_pend_pagar = impuestos
elif es_contado:
compras_16_contado = compras_16
compras_0_contado = compras_0
iva_efec_pagado = impuestos
asientos_a_ingorar = []
for concepto in conceptos_poliza:
if concepto.valor_tipo == 'Segmento_1' and not campos_particulares.segmento_1 == None:
asientos_a_ingorar.append(concepto.asiento_ingora)
if concepto.valor_tipo == 'Segmento_2' and not campos_particulares.segmento_2 == None:
asientos_a_ingorar.append(concepto.asiento_ingora)
if concepto.valor_tipo == 'Segmento_3' and not campos_particulares.segmento_3 == None:
asientos_a_ingorar.append(concepto.asiento_ingora)
if concepto.valor_tipo == 'Segmento_4' and not campos_particulares.segmento_4 == None:
asientos_a_ingorar.append(concepto.asiento_ingora)
if concepto.valor_tipo == 'Segmento_5' and not campos_particulares.segmento_5 == None:
asientos_a_ingorar.append(concepto.asiento_ingora)
for concepto in conceptos_poliza:
importe = 0
cuenta = []
clave_cuenta_tipoAsiento = []
if concepto.valor_tipo == 'Segmento_1' and not campos_particulares.segmento_1 == None:
totales_cuentas, error, msg = get_totales_cuentas_by_segmento(campos_particulares.segmento_1, totales_cuentas, depto_co, concepto.tipo, error, msg, documento.folio, concepto.asiento_ingora)
elif concepto.valor_tipo == 'Segmento_2' and not campos_particulares.segmento_2 == None:
totales_cuentas, error, msg = get_totales_cuentas_by_segmento(campos_particulares.segmento_2, totales_cuentas, depto_co, concepto.tipo, error, msg, documento.folio, concepto.asiento_ingora)
elif concepto.valor_tipo == 'Segmento_3' and not campos_particulares.segmento_3 == None:
totales_cuentas, error, msg = get_totales_cuentas_by_segmento(campos_particulares.segmento_3, totales_cuentas, depto_co, concepto.tipo, error, msg, documento.folio, concepto.asiento_ingora)
elif concepto.valor_tipo == 'Segmento_4' and not campos_particulares.segmento_4 == None:
totales_cuentas, error, msg = get_totales_cuentas_by_segmento(campos_particulares.segmento_4, totales_cuentas, depto_co, concepto.tipo, error, msg, documento.folio, concepto.asiento_ingora)
elif concepto.valor_tipo == 'Segmento_5' and not campos_particulares.segmento_5 == None:
totales_cuentas, error, msg = get_totales_cuentas_by_segmento(campos_particulares.segmento_5, totales_cuentas, depto_co, concepto.tipo, error, msg, documento.folio, concepto.asiento_ingora)
elif concepto.valor_tipo == 'Compras' and not concepto.posicion in asientos_a_ingorar:
if concepto.valor_contado_credito == 'Credito':
if concepto.valor_iva == '0':
importe = compras_0_credito
elif concepto.valor_iva == 'I':
importe = compras_16_credito
elif concepto.valor_iva == 'A':
importe = compras_0_credito + compras_16_credito
elif concepto.valor_contado_credito == 'Contado':
if concepto.valor_iva == '0':
importe = compras_0_contado
elif concepto.valor_iva == 'I':
importe = compras_16_contado
elif concepto.valor_iva == 'A':
importe = compras_0_contado + compras_16_contado
elif concepto.valor_contado_credito == 'Ambos':
if concepto.valor_iva == '0':
importe = compras_0_credito + compras_0_contado
elif concepto.valor_iva == 'I':
importe = compras_16_credito + compras_16_contado
elif concepto.valor_iva == 'A':
importe = compras_0_credito + compras_0_contado + compras_16_credito + compras_16_contado
cuenta = concepto.cuenta_co.cuenta
elif concepto.valor_tipo == 'IVA' and not concepto.posicion in asientos_a_ingorar:
if concepto.valor_contado_credito == 'Credito':
importe = iva_pend_pagar
elif concepto.valor_contado_credito == 'Contado':
importe = iva_efec_pagado
elif concepto.valor_contado_credito == 'Ambos':
importe = iva_pend_pagar + iva_efec_pagado
cuenta = concepto.cuenta_co.cuenta
elif concepto.valor_tipo == 'Proveedores' and not concepto.posicion in asientos_a_ingorar:
if concepto.valor_iva == 'A':
importe = proveedores
if cuenta_proveedor == None:
cuenta = concepto.cuenta_co.cuenta
else:
cuenta = cuenta_proveedor
elif concepto.valor_tipo == 'Bancos' and not concepto.posicion in asientos_a_ingorar:
if concepto.valor_iva == 'A':
importe = bancos
cuenta = concepto.cuenta_co.cuenta
elif concepto.valor_tipo == 'Descuentos' and not concepto.posicion in asientos_a_ingorar:
importe = descuento
cuenta = concepto.cuenta_co.cuenta
clave_cuenta_tipoAsiento = "%s/%s:%s"% (cuenta, depto_co, concepto.tipo)
importe = importe
#Se es tipo segmento pone variables en cero para que no se calculen otra ves valores por ya estan calculados
if concepto.valor_tipo == 'Segmento_1' or concepto.valor_tipo == 'Segmento_2' or concepto.valor_tipo == 'Segmento_3' or concepto.valor_tipo == 'Segmento_4' or concepto.valor_tipo == 'Segmento_5':
importe = 0
if not clave_cuenta_tipoAsiento == [] and importe > 0:
if clave_cuenta_tipoAsiento in totales_cuentas:
totales_cuentas[clave_cuenta_tipoAsiento] = [totales_cuentas[clave_cuenta_tipoAsiento][0] + Decimal(importe),int(concepto.posicion)]
else:
totales_cuentas[clave_cuenta_tipoAsiento] = [Decimal(importe),int(concepto.posicion)]
return totales_cuentas, error, msg
def crear_polizas(documentos, depto_co, informacion_contable, msg, plantilla=None, descripcion = '', crear_polizas_por='',crear_polizas_de=None,):
error = 0
DocumentosData = []
cuenta = ''
importe = 0
conceptos_poliza = DetallePlantillaPolizas_CP.objects.filter(plantilla_poliza_CP=plantilla).order_by('posicion')
moneda_local = get_object_or_404(Moneda,es_moneda_local='S')
documento_numero = 0
polizas = []
detalles_polizas = []
totales_cuentas = {}
for documento_no, documento in enumerate(documentos):
if documento.naturaleza_concepto == 'C':
es_contado = documento.condicion_pago == informacion_contable.condicion_pago_contado
else:
es_contado = False
siguente_documento = documentos[(documento_no +1)%len(documentos)]
documento_numero = documento_no
totales_cuentas, error, msg = get_totales_documento_cuentas(informacion_contable.condicion_pago_contado, documento, conceptos_poliza, totales_cuentas, msg, error)
if error == 0:
#Cuando la fecha de la documento siguiente sea diferente y sea por DIA, o sea la ultima
if (not documento.fecha == siguente_documento.fecha and crear_polizas_por == 'Dia') or documento_no +1 == len(documentos) or crear_polizas_por == 'Documento':
tipo_poliza = TipoPoliza.objects.filter(clave=documento.concepto.clave_tipo_poliza)[0]
tipo_poliza_det = get_folio_poliza(tipo_poliza, documento.fecha)
#PREFIJO
prefijo = tipo_poliza.prefijo
if not tipo_poliza.prefijo:
prefijo = ''
#Si no tiene una descripcion el documento se pone lo que esta indicado en la descripcion general
descripcion_doc = documento.descripcion
if documento.descripcion == None or crear_polizas_por=='Dia' or crear_polizas_por == 'Periodo':
descripcion_doc = descripcion
referencia = documento.folio
if crear_polizas_por == 'Dia':
referencia = ''
poliza = DoctoCo(
id = c_get_next_key('ID_DOCTOS'),
tipo_poliza = tipo_poliza,
poliza = '%s%s'% (prefijo,("%09d" % tipo_poliza_det.consecutivo)[len(prefijo):]),
fecha = documento.fecha,
moneda = moneda_local,
tipo_cambio = 1,
estatus = 'P', cancelado= 'N', aplicado = 'N', ajuste = 'N', integ_co = 'S',
descripcion = descripcion_doc,
forma_emitida = 'N', sistema_origen = 'CO',
nombre = '',
grupo_poliza_periodo = None,
integ_ba = 'N',
usuario_creador = 'SYSDBA',
fechahora_creacion = datetime.datetime.now(), usuario_aut_creacion = None,
usuario_ult_modif = 'SYSDBA', fechahora_ult_modif = datetime.datetime.now(), usuario_aut_modif = None,
usuario_cancelacion = None, fechahora_cancelacion = None, usuario_aut_cancelacion = None,
)
polizas.append(poliza)
#GUARDA LA PILIZA
#poliza_o = poliza.save()
#CONSECUTIVO DE FOLIO DE POLIZA
tipo_poliza_det.consecutivo += 1
tipo_poliza_det.save()
posicion = 1
totales_cuentas = totales_cuentas.items()
for cuenta_depto_tipoAsiento, importe in totales_cuentas:
cuenta_deptotipoAsiento = cuenta_depto_tipoAsiento.split('/')
cuenta_co = CuentaCo.objects.get(cuenta=cuenta_deptotipoAsiento[0])
depto_tipoAsiento = cuenta_deptotipoAsiento[1].split(':')
depto_co = DeptoCo.objects.get(clave=depto_tipoAsiento[0])
tipo_asiento = depto_tipoAsiento[1]
detalle_poliza = DoctosCoDet(
id = -1,
docto_co = poliza,
cuenta = cuenta_co,
depto_co = depto_co,
tipo_asiento = tipo_asiento,
importe = importe[0],
importe_mn = 0,#PENDIENTE
ref = referencia,
descripcion = '',
posicion = posicion,
recordatorio = None,
fecha = documento.fecha,
cancelado = 'N', aplicado = 'N', ajuste = 'N',
moneda = moneda_local,
)
posicion +=1
detalles_polizas.append(detalle_poliza)
#DE NUEVO COMBIERTO LA VARIABLE A DICCIONARIO
totales_cuentas = {}
DocumentosData.append ({
'folio' :poliza.poliza,
})
DoctosCp.objects.filter(id=documento.id).update(contabilizado = 'S')
if error == 0:
DoctoCo.objects.bulk_create(polizas)
DoctosCoDet.objects.bulk_create(detalles_polizas)
else:
DocumentosData = []
polizas = []
detalles_polizas = []
return msg, DocumentosData
def generar_polizas(fecha_ini=None, fecha_fin=None, ignorar_documentos_cont=True, crear_polizas_por='Documento', crear_polizas_de='', plantilla='', descripcion= ''):
error = 0
msg = ''
documentosCPData = []
try:
informacion_contable = InformacionContable_CP.objects.all()[:1]
informacion_contable = informacion_contable[0]
except ObjectDoesNotExist:
error = 1
#Si estadefinida la informacion contable no hay error!!!
if error == 0:
if ignorar_documentos_cont:
documentosCP = DoctosCp.objects.filter(contabilizado ='N', concepto= crear_polizas_de , fecha__gte=fecha_ini, fecha__lte=fecha_fin).order_by('fecha')[:99]
else:
documentosCP = DoctosCp.objects.filter(concepto= crear_polizas_de , fecha__gte=fecha_ini, fecha__lte=fecha_fin).order_by('fecha')[:99]
msg, documentosCPData = crear_polizas(documentosCP, get_object_or_404(DeptoCo, pk=76), informacion_contable, msg , plantilla, descripcion, crear_polizas_por, crear_polizas_de)
elif error == 1 and msg=='':
msg = 'No se han derfinido las preferencias de la empresa para generar polizas [Por favor definelas primero en Configuracion > Preferencias de la empresa]'
return documentosCPData, msg
@login_required(login_url='/login/')
def generar_polizas_View(request, template_name='herramientas/generar_polizas_CP.html'):
documentosData = []
msg = msg_resultados = ''
if request.method == 'POST':
form = GenerarPolizasManageForm(request.POST)
if form.is_valid():
fecha_ini = form.cleaned_data['fecha_ini']
fecha_fin = form.cleaned_data['fecha_fin']
ignorar_documentos_cont = form.cleaned_data['ignorar_documentos_cont']
crear_polizas_por = form.cleaned_data['crear_polizas_por']
crear_polizas_de = form.cleaned_data['crear_polizas_de']
plantilla = form.cleaned_data['plantilla']
descripcion = form.cleaned_data['descripcion']
msg = 'es valido'
documentosData, msg = generar_polizas(fecha_ini, fecha_fin, ignorar_documentos_cont, crear_polizas_por, crear_polizas_de, plantilla, descripcion)
if documentosData == []:
msg_resultados = 'Lo siento, no se encontraron resultados para este filtro'
else:
form = GenerarPolizasManageForm()
c = {'documentos':documentosData,'msg':msg,'form':form, 'msg_resultados':msg_resultados,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def plantilla_poliza_manageView(request, id = None, template_name='herramientas/plantilla_poliza_CP.html'):
message = ''
if id:
plantilla = get_object_or_404(PlantillaPolizas_CP, pk=id)
else:
plantilla =PlantillaPolizas_CP()
if request.method == 'POST':
plantilla_form = PlantillaPolizaManageForm(request.POST, request.FILES, instance=plantilla)
plantilla_items = PlantillaPoliza_items_formset(ConceptoPlantillaPolizaManageForm, extra=1, can_delete=True)
plantilla_items_formset = plantilla_items(request.POST, request.FILES, instance=plantilla)
if plantilla_form.is_valid() and plantilla_items_formset .is_valid():
plantilla = plantilla_form.save(commit = False)
plantilla.save()
#GUARDA CONCEPTOS DE PLANTILLA
for concepto_form in plantilla_items_formset :
Detalleplantilla = concepto_form.save(commit = False)
#PARA CREAR UNO NUEVO
if not Detalleplantilla.id:
Detalleplantilla.plantilla_poliza_CP = plantilla
plantilla_items_formset .save()
return HttpResponseRedirect('/cuentas_por_pagar/PreferenciasEmpresa/')
else:
plantilla_items = PlantillaPoliza_items_formset(ConceptoPlantillaPolizaManageForm, extra=1, can_delete=True)
plantilla_form= PlantillaPolizaManageForm(instance=plantilla)
plantilla_items_formset = plantilla_items(instance=plantilla)
c = {'plantilla_form': plantilla_form, 'formset': plantilla_items_formset , 'message':message,}
return render_to_response(template_name, c, context_instance=RequestContext(request))
@login_required(login_url='/login/')
def plantilla_poliza_delete(request, id = None):
plantilla = get_object_or_404(PlantillaPolizas_CP, pk=id)
plantilla.delete()
return HttpResponseRedirect('/cuentas_por_pagar/PreferenciasEmpresa/')<file_sep>Django==1.4.3
django-autocomplete_light==1.1.16
fdb==1.0
django-dajaxice==0.5.5
xlrd==0.8.0<file_sep>#encoding:utf-8
from django import forms
import autocomplete_light
from ventas.models import *
from django.contrib.auth.models import User
from django.forms.models import BaseInlineFormSet, inlineformset_factory
from inventarios.models import *
class InformacionContableManageForm(forms.ModelForm):
tipo_poliza_ve = forms.ModelChoiceField(queryset= TipoPoliza.objects.all(), required=True)
condicion_pago_contado = forms.ModelChoiceField(queryset= CondicionPago.objects.all(), required=True)
class Meta:
model = InformacionContable_V
class GenerarPolizasManageForm(forms.Form):
fecha_ini = forms.DateField()
fecha_fin = forms.DateField()
ignorar_documentos_cont = forms.BooleanField(required=False, initial=True)
CREAR_POR = (
('Documento', 'Documento'),
('Dia', 'Dia'),
('Periodo', 'Periodo'),
)
crear_polizas_por = forms.ChoiceField(choices=CREAR_POR)
plantilla = forms.ModelChoiceField(queryset= PlantillaPolizas_V.objects.filter(tipo='F'), required=False)
plantilla_2 = forms.ModelChoiceField(queryset= PlantillaPolizas_V.objects.filter(tipo='D'), required=False)
descripcion = forms.CharField(max_length=100, required=False)
CREAR_DE = (
('', '---------------'),
('F', 'Facturas'),
('D', 'Devoluciones'),
('FD', 'Facturas y Devoluciones'),
)
crear_polizas_de = forms.ChoiceField(choices=CREAR_DE)
class PlantillaPolizaManageForm(forms.ModelForm):
class Meta:
model = PlantillaPolizas_V
class ConceptoPlantillaPolizaManageForm(forms.ModelForm):
posicion = forms.RegexField(regex=r'^(?:\+|-)?\d+$', widget=forms.TextInput(attrs={'class':'span1',}), required= True)
cuenta_co = forms.ModelChoiceField(queryset=CuentaCo.objects.all().order_by('cuenta'), required=True)
asiento_ingora = forms.RegexField(regex=r'^(?:\+|-)?\d+$', widget=forms.TextInput(attrs={'class':'span1'}), required= False)
class Meta:
model = DetallePlantillaPolizas_V
def PlantillaPoliza_items_formset(form, formset = BaseInlineFormSet, **kwargs):
return inlineformset_factory(PlantillaPolizas_V, DetallePlantillaPolizas_V, form, formset, **kwargs)<file_sep>#encoding:utf-8
from django.db import models
from datetime import datetime
from django.db.models.signals import pre_save
from django.core import urlresolvers
from inventarios.models import *
class ConceptoCc(models.Model):
id = models.AutoField(primary_key=True, db_column='CONCEPTO_CC_ID')
nombre_abrev = models.CharField(max_length=30, db_column='NOMBRE_ABREV')
crear_polizas = models.CharField(default='N', max_length=1, db_column='CREAR_POLIZAS')
cuenta_contable = models.CharField(max_length=30, db_column='CUENTA_CONTABLE')
clave_tipo_poliza = models.CharField(max_length=1, db_column='TIPO_POLIZA')
descripcion_poliza = models.CharField(max_length=200, db_column='DESCRIPCION_POLIZA')
def __unicode__(self):
return self.nombre_abrev
class Meta:
db_table = u'conceptos_cc'
class DoctosCc(models.Model):
id = models.AutoField(primary_key=True, db_column='DOCTO_CC_ID')
concepto = models.ForeignKey(ConceptoCc, db_column='CONCEPTO_CC_ID')
folio = models.CharField(max_length=9, db_column='FOLIO')
naturaleza_concepto = models.CharField(max_length=1, db_column='NATURALEZA_CONCEPTO')
fecha = models.DateField(auto_now=True, db_column='FECHA')
cliente = models.ForeignKey(Cliente, db_column='CLIENTE_ID')
cancelado = models.CharField(default='N', max_length=1, db_column='CANCELADO')
aplicado = models.CharField(default='S', max_length=1, db_column='APLICADO')
descripcion = models.CharField(blank=True, null=True, max_length=200, db_column='DESCRIPCION')
contabilizado = models.CharField(default='N', blank=True, null=True, max_length=1, db_column='CONTABILIZADO')
tipo_cambio = models.DecimalField(max_digits=18, decimal_places=6, db_column='TIPO_CAMBIO')
condicion_pago = models.ForeignKey(CondicionPago, db_column='COND_PAGO_ID')
def __unicode__(self):
return u'%s' % self.id
class Meta:
db_table = u'doctos_cc'
################################################################
#### ####
#### MODELOS EXTRA A BASE DE DATOS MICROSIP ####
#### ####
################################################################
class InformacionContable_CC(models.Model):
condicion_pago_contado = models.ForeignKey(CondicionPago, blank=True, null=True)
def __unicode__(self):
return u'%s'% self.id
class PlantillaPolizas_CC(models.Model):
nombre = models.CharField(max_length=200)
tipo = models.ForeignKey(ConceptoCc)
def __unicode__(self):
return u'%s'%self.nombre
class DetallePlantillaPolizas_CC(models.Model):
TIPOS = (('C', 'Cargo'),('A', 'Abono'),)
VALOR_TIPOS =(
('Compras', 'Compras'),
('Proveedores', 'Proveedores'),
('Bancos', 'Bancos'),
('Fletes', 'Fletes'),
('Descuentos', 'Descuentos'),
('Devoluciones','Devoluciones'),
('Anticipos','Anticipos'),
('IVA', 'IVA'),
)
VALOR_IVA_TIPOS = (('A', 'Ambos'),('I', 'Solo IVA'),('0', 'Solo 0%'),)
VALOR_CONTADO_CREDITO_TIPOS = (('Ambos', 'Ambos'),('Contado', 'Contado'),('Credito', 'Credito'),)
plantilla_poliza_CC = models.ForeignKey(PlantillaPolizas_CC)
cuenta_co = models.ForeignKey(CuentaCo)
tipo = models.CharField(max_length=2, choices=TIPOS, default='C')
valor_tipo = models.CharField(max_length=20, choices=VALOR_TIPOS)
valor_iva = models.CharField(max_length=2, choices=VALOR_IVA_TIPOS, default='A')
valor_contado_credito = models.CharField(max_length=10, choices=VALOR_CONTADO_CREDITO_TIPOS, default='Ambos')
def __unicode__(self):
return u'%s'%self.id
<file_sep>#encoding:utf-8
from django import forms
import autocomplete_light
from inventarios.models import *
from django.contrib.auth.models import User
from django.forms.models import BaseInlineFormSet, inlineformset_factory
class DoctosInManageForm(forms.ModelForm):
file_inventario = forms.CharField(widget=forms.FileInput, required = False)
class Meta:
model = DoctosIn
exclude = (
'cancelado',
'aplicado',
'forma_emitida',
'contabilizado',
'sistema_origen',
'naturaleza_concepto',
'usuario_creador',
'fechahora_creacion',
'usuario_ult_modif',
'fechahora_ult_modif',
)
class DoctosInDetManageForm(forms.ModelForm):
class Meta:
widgets = autocomplete_light.get_widgets_dict(DoctosInDet)
model = DoctosInDet
exclude = (
'tipo_movto',
'almacen',
'concepto',
'metodo_costeo',
'rol',
'cancelado',
'aplicado',
'costeo_pend',
'pedimento_pend',
'fecha',)
class DoctosInvfisManageForm(forms.ModelForm):
file_inventario = forms.CharField(widget=forms.FileInput, required = False)
class Meta:
model = DoctosInvfis
exclude = (
'cancelado',
'aplicado',
'usuario_creador',
'fechahora_creacion',
'usuario_aut_creacion',
'usuario_ult_modif',
'fechahora_ult_modif',
'usuario_aut_modif',
)
class DoctosInvfisDetManageForm(forms.ModelForm):
class Meta:
widgets = autocomplete_light.get_widgets_dict(DoctosInvfisDet)
model = DoctosInvfisDet
exclude = (
'claveArticulo',
)
def doctoIn_items_formset(form, formset = BaseInlineFormSet, **kwargs):
return inlineformset_factory(DoctosIn, DoctosInDet, form, formset, **kwargs)
def inventarioFisico_items_formset(form, formset = BaseInlineFormSet, **kwargs):
return inlineformset_factory(DoctosInvfis, DoctosInvfisDet, form, formset, **kwargs)
<file_sep>#encoding:utf-8
from django import forms
import autocomplete_light
from ventas.models import *
from django.contrib.auth.models import User
from django.forms.models import BaseInlineFormSet, inlineformset_factory
from inventarios.models import *
class InformacionContableManageForm(forms.ModelForm):
condicion_pago_contado = forms.ModelChoiceField(queryset= CondicionPagoCp.objects.all(), required=True)
class Meta:
model = InformacionContable_CP
class GenerarPolizasManageForm(forms.Form):
fecha_ini = forms.DateField()
fecha_fin = forms.DateField()
ignorar_documentos_cont = forms.BooleanField(required=False, initial=True)
CREAR_POR = (
('Documento', 'Documento'),
('Dia', 'Dia'),
('Periodo', 'Periodo'),
)
crear_polizas_por = forms.ChoiceField(choices=CREAR_POR)
plantilla = forms.ModelChoiceField(queryset= PlantillaPolizas_CP.objects.all(), required=True)
#plantilla_2 = forms.ModelChoiceField(queryset= PlantillaPolizas_V.objects.all(), required=True)
descripcion = forms.CharField(max_length=100, required=False)
crear_polizas_de = forms.ModelChoiceField(queryset= ConceptoCp.objects.filter(crear_polizas='S'), required=True)
class PlantillaPolizaManageForm(forms.ModelForm):
tipo = forms.ModelChoiceField(queryset= ConceptoCp.objects.filter(crear_polizas='S'), required=True)
class Meta:
model = PlantillaPolizas_CP
class ConceptoPlantillaPolizaManageForm(forms.ModelForm):
posicion = forms.RegexField(regex=r'^(?:\+|-)?\d+$', widget=forms.TextInput(attrs={'class':'span1'}), required= False)
cuenta_co = forms.ModelChoiceField(queryset=CuentaCo.objects.all().order_by('cuenta'), required=True)
asiento_ingora = forms.RegexField(regex=r'^(?:\+|-)?\d+$', widget=forms.TextInput(attrs={'class':'span1'}), required= False)
class Meta:
model = DetallePlantillaPolizas_CP
def PlantillaPoliza_items_formset(form, formset = BaseInlineFormSet, **kwargs):
return inlineformset_factory(PlantillaPolizas_CP, DetallePlantillaPolizas_CP, form, formset, **kwargs)
|
9e987963782cd9280d4c1236ce72567480e25276
|
[
"Markdown",
"Python",
"Text",
"reStructuredText"
] | 22
|
Python
|
ruff0/microsip_web-1
|
e5590a65b121c1036ec08905df33d5ff634219d0
|
3e1843071f533db2418a2de63519162561a64ccf
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.