language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 405 | 3.796875 | 4 |
[] |
no_license
|
print("hello world")
message = "hello world"
print(message)
name = "add lovelace"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("\tPython")
print("\nPython")
favorite_language = "Python "
print(favorite_language)
favorite_language.rstrip()
print(favorite_language.rstrip())
print(3**3)
|
Java
|
UTF-8
| 2,484 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
package org.dmc.services;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import org.json.JSONObject;
public class ServiceLogger {
private static FileHandler logFileHandler;
private static SimpleFormatter logFileFormatter;
private static Logger logger;
private static Logger rootLogger;
private final String LOGFILE = Config.LOG_FILE;
private static ServiceLogger serviceLoggerInstance = null;
protected ServiceLogger() {
try {
this.setup();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public static void log (String logTag, String message) {
if (serviceLoggerInstance == null) {
serviceLoggerInstance = new ServiceLogger();
}
logger.info(logTag + ": " + message);
}
/**
* Exception Logging
* @param logTag
* @param e
*/
public static void logException (String logTag, DMCServiceException e) {
String logMessage = null;
if (serviceLoggerInstance == null) {
serviceLoggerInstance = new ServiceLogger();
}
JSONObject logJson = new JSONObject();
logJson.put("Class", logTag);
logJson.put("Error", e.getError());
logJson.put("HttpStatus Code", e.getHttpStatusCode());
logJson.put("Message", e.getMessage());
logMessage += "\n---------------------------------------------------------------------------------------------------------------\n";
logMessage +="DMC EXCEPTION: ";
logMessage +=logJson.toString();
logMessage += "\n---------------------------------------------------------------------------------------------------------------\n";
logger.info(logMessage);
}
private void setup() throws IOException {
logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
//Log to the file by default
logger.setLevel(Level.INFO);
logFileHandler = new FileHandler(LOGFILE);
logger.addHandler(logFileHandler);
//disable console logging by default
logger.setUseParentHandlers(false);
//Use the Simple file formatter
logFileFormatter = new SimpleFormatter();
logFileHandler.setFormatter(logFileFormatter);
//Log to console if enabled in config
if (Config.CONSOLE_LOGGING) {
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.ALL);
logger.addHandler(consoleHandler);
}
}
}
|
Python
|
UTF-8
| 861 | 3.5625 | 4 |
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
###
# File: c:\Users\olivi.000\Dropbox\Public\My Library\IT\SW Programming\sego\Intro to Python\ch04\snippets_py\Exercise 4.9.py
# Project: c:\Users\olivi.000\Dropbox\Public\My Library\IT\SW Programming\sego\Intro to Python\ch04\snippets_py
# Created Date: Tuesday, April 21st 2020, 11:13:14 pm
# Author: Olivia Serna
# Description:
# -----
# Last Modified: Thu Apr 23 2020
# Modified By: Olivia Serna
# -----
# Copyright (c) 2020 OLI CO. LTD.
#
# Know thy self, know thy enemy. A thousand battles, a thousand victories
# -----
# HISTORY:
# Date By Comments
# ---------- --- ----------------------------------------------------------
###
def C2F (c_degrees):
return (c_degrees * (9/5)) + 32
print ("Farenheit Celcius")
print ("------------------")
for i in range (101):
print (f'{i:>9.1f} {C2F(i):>7.1f}')
|
Java
|
UTF-8
| 3,913 | 3.265625 | 3 |
[] |
no_license
|
package com.atcafuc.java;
import org.junit.Test;
import java.io.*;
/**
* 处理流之一:缓冲流的使用
*
* 1.缓冲流
* BufferedInputStream
* BufferedOutputStream
* BufferedReader
* BufferedWriter
*
* 2.作用:提供流的读取、写入的速度
* 提高读写速度的原因:内部提供了一个缓冲区
*
* @author jh
* @create 2021-08-26 14:21
*/
public class BufferedTest {
/*
实现为文本文件的复制
*/
@Test
public void test() {
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File("8-26.jpg");
File destFile = new File("8-26.2.jpg");
//2.造流
//2.1 造字节流
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
//2.2 造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[10];
int len;
while((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
//要求:先关闭外层的流,再关闭内层的流
try {
if(bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bis != null)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
//说明:关闭外层流的同时,内层的流也会自动进行关闭。
// fis.close();
// fos.close();
}
}
//文件复制的方法
public void copy(String srcPath,String destPath){
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File(srcPath);
File destFile = new File(destPath);
//2.造流
//2.1 造字节流
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
//2.2 造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[1024];
int len;
while((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
//要求:先关闭外层的流,再关闭内层的流
try {
if(bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bis != null)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
//说明:关闭外层流的同时,内层的流也会自动进行关闭。
// fis.close();
// fos.close();
}
}
@Test
public void testCopy(){
long start = System.currentTimeMillis();
copy("22.avi","22-1.avi");
long end = System.currentTimeMillis();
System.out.println("复制时间为" + (end - start)); //time 147
}
@Test
public void test1(){
byte b = 124;
byte b1 = (byte) (b ^5);
}
}
|
Java
|
UTF-8
| 2,494 | 4.125 | 4 |
[] |
no_license
|
package Q2;
class MyThread1 extends Thread{
MyThread1(String name){
super(name);
}
public void run() {
System.out.println("Hello this is thread: "+ this.getName());
System.out.println("Thread "+this.getName()+ " will now sleep:");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThread2 extends Thread{
MyThread2(String name){
super(name);
}
@Override
public void run() {
System.out.println("Hello this is thread: "+ this.getName());
System.out.println("Thread "+this.getName()+ " will now sleep:");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThread3 extends Thread{
MyThread3(String name){
super(name);
}
@Override
public void run() {
System.out.println("Hello this is thread: "+ this.getName());
System.out.println("Thread "+this.getName()+ " will now sleep:");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Calling yield on "+ this.getName()+" this will now stop:");
Thread.yield();
}
}
public class q2 {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1("sania");
MyThread2 t2 = new MyThread2("maria");
MyThread3 t3 = new MyThread3("serena");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
System.out.println("Now the thread t1 will run:");
t1.run();
System.out.println("Now threads t1, t2, t3 will start:");
t1.start();
t2.start();
t3.start();
System.out.println("The priority of thread t1 is :"+ t1.getPriority());
System.out.println("The priority of thread t2 is :"+ t2.getPriority());
System.out.println("The priority of thread t3 is :"+ t3.getPriority());
System.out.println("Thread t3 now will be suspended.");
t3.suspend();
System.out.println("Thread t3 now will be resumed.");
t3.resume();
try {
System.out.println("Calling join method on thread t1. ");
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
Java
|
UTF-8
| 1,292 | 2.453125 | 2 |
[
"MIT"
] |
permissive
|
package de.aaaaaaah.velcom.backend.access.entities;
import java.time.Instant;
import java.util.Collection;
public class Commit {
private final RepoId repoId;
private final CommitHash hash;
private final Collection<CommitHash> parentHashes;
private final String author;
private final Instant authorDate;
private final String committer;
private final Instant committerDate;
private final String message;
public Commit(RepoId repoId, CommitHash hash, Collection<CommitHash> parentHashes,
String author, Instant authorDate, String committer, Instant committerDate,
String message) {
this.repoId = repoId;
this.hash = hash;
this.parentHashes = parentHashes;
this.author = author;
this.authorDate = authorDate;
this.committer = committer;
this.committerDate = committerDate;
this.message = message;
}
public RepoId getRepoId() {
return repoId;
}
public CommitHash getHash() {
return hash;
}
public Collection<CommitHash> getParentHashes() {
return parentHashes;
}
public String getAuthor() {
return author;
}
public Instant getAuthorDate() {
return authorDate;
}
public String getCommitter() {
return committer;
}
public Instant getCommitterDate() {
return committerDate;
}
public String getMessage() {
return message;
}
}
|
Python
|
UTF-8
| 556 | 2.984375 | 3 |
[] |
no_license
|
#!usr/bin/env python
import requests
target_url = ""//your target url
data_dict = {"username": "123", "password": "", "Login": "submit"}
with open("<file_for_passwords>", "r") as wordlist_file://put the password list inside the " < > "
for line in wordlist_file:
word = line.strip()
data_dict["password"] = word
response = requests.post(target_url, data=data_dict)
if "Login failed" not in response.content:
print("[+] Got the password --> " + word)
exit()
print("[+] Reached end of line.")
|
Java
|
UTF-8
| 3,854 | 1.671875 | 2 |
[] |
no_license
|
/**
* generated by Xtext 2.13.0
*/
package uofa.lbirdsey.castle.casl.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import uofa.lbirdsey.castle.casl.CaslPackage;
import uofa.lbirdsey.castle.casl.Interaction;
import uofa.lbirdsey.castle.casl.Interactions;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Interactions</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link uofa.lbirdsey.castle.casl.impl.InteractionsImpl#getInteractions <em>Interactions</em>}</li>
* </ul>
*
* @generated
*/
public class InteractionsImpl extends MinimalEObjectImpl.Container implements Interactions
{
/**
* The cached value of the '{@link #getInteractions() <em>Interactions</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getInteractions()
* @generated
* @ordered
*/
protected EList<Interaction> interactions;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected InteractionsImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return CaslPackage.eINSTANCE.getInteractions();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Interaction> getInteractions()
{
if (interactions == null)
{
interactions = new EObjectContainmentEList<Interaction>(Interaction.class, this, CaslPackage.INTERACTIONS__INTERACTIONS);
}
return interactions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case CaslPackage.INTERACTIONS__INTERACTIONS:
return ((InternalEList<?>)getInteractions()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case CaslPackage.INTERACTIONS__INTERACTIONS:
return getInteractions();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case CaslPackage.INTERACTIONS__INTERACTIONS:
getInteractions().clear();
getInteractions().addAll((Collection<? extends Interaction>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case CaslPackage.INTERACTIONS__INTERACTIONS:
getInteractions().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case CaslPackage.INTERACTIONS__INTERACTIONS:
return interactions != null && !interactions.isEmpty();
}
return super.eIsSet(featureID);
}
} //InteractionsImpl
|
Markdown
|
UTF-8
| 1,404 | 2.6875 | 3 |
[] |
no_license
|
最近做的h5项目中有一个微信登录功能,将自己遇到的一些坑记录一下
前提:
1. 一个公众号
2. appid
首先就是在自己的vue项目中引入微信的接口
`<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>`
接着我们就可以在自己的login.vue中调用微信函数`WxLogin`
在login.vue中的mounted
```javascript
var obj = new WxLogin({
id:"div", //div的id
appid: "公众号里的appid",
scope: "snsapi_login",
redirect_uri: "http%3a%2f%2f96ac7d.natappfree.cc%2f%23%2fjump",//urlencode编码
});
```
解释一下redirect_url:
1. 如果是在开发环境,也就是用8080端口,网站还没有域名时,但是需要外网穿透,这时候你需要下一个natapp,可以帮你改自己的域名。(natapp不要下在c盘,我的下在c盘打不开,换到d盘就打开了,natapp的配置官网讲的很清楚)
2. 要用**urlencode编码**把redirect_url转化一下,这个百度转码工具就可以了
3. **域名有了要修改微信开放平台里的授权回调域**,这样才不会报参数错误
现在你就可以扫码登录了,空白页作为跳转中转站jump.vue,也就是上面的重定向地址,在这个地址里可以就收到code。code作为参数向后端发一次axios请求,得到用户信息
|
Markdown
|
UTF-8
| 4,144 | 3.484375 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
+++
date = "2016-07-12T20:20:27+01:00"
description = "Tutorial on using find, a UNIX and Linux command for walking a file hierarchy. Examples of finding a file by name, finding and deleting a file, finding a directory and searching by modification time and permissions."
image = "images/covers/find.png"
caption = "The UNIX and Linux find command"
slug = "unix-find"
tags = ["UNIX"]
title = "Linux and Unix find command tutorial with examples"
+++
## What is the find command in UNIX?
The `find` command in UNIX is a command line utility for walking a file
hierarchy. It can be used to find files and directories and perform subsequent
operations on them. It supports searching by file, folder, name, creation date,
modification date, owner and permissions. By using the `- exec` other UNIX
commands can be executed on files or folders found.
## How to find a single file by name
To find a single file by name pass the `-name` option to `find` along with the
name of the file you are looking for.
Suppose the following directory structure exists shown here as the output of the
`tree` command.
```sh
foo
├── bar
├── baz
│ └── foo.txt
└── bop
```
The file `foo.txt` can be located with the `find` by using the `-name` option.
```sh
find ./foo -name foo.txt
./foo/baz/foo.txt
```
## How to find and delete a file
To find and delete a file pass the `-delete` option to `find`. This will delete
the file with no undo so be careful.
```sh
find ./foo -name foo.txt -delete
```
To be prompted to confirm deletion combine `-exec` with `rm -i`.
```sh
find ./foo -name foo.txt -exec rm -i {} \;
```
Comparing the efficiency of these methods when operating on 10000 files we can
see that using `-delete` is far more efficient.
```sh
touch {0..10000}.txt
time find ./ -type f -name "*.txt" -exec rm {} \;
find ./ -type f -name "*.txt" -exec rm {} \; 3.95s user 1.44s system 99% cpu 5.402 total
touch {0..10000}.txt
time find ./ -type f -name '*.txt' -delete
find ./ -type f -name '*.txt' -delete 0.03s user 0.06s system 98% cpu 0.090 total
```
## How to find a directory
To find a directory specify the option `-type d` with `find`.
```sh
find ./foo -type d -name bar
./foo/bar
```
## How to find files by modification time
To find files by modification time use the `-mtime` option followed by the
number of days to look for. The number can be a positive or negative value. A
negative value equates to less then so `-1` will find files modified within the
last day. Similarly `+1` will find files modified more than one day ago.
```sh
find ./foo -mtime -1
find ./foo -mtime +1
```
## How to find files by permission
To find files by permission use the `-perm` option and pass the value you want
to search for. The following example will find files that everyone can read,
write and execute.
```sh
find ./foo -perm 777
```
## How to find and operate on files
To find and operate on file us the `-exec` option. This allows a command to be
executed on files that are found.
```sh
find ./foo -type f -name bar -exec chmod 777 {} \;
```
## How to find and replace in a range of files
To find and replace across a range of files the `find` command may be combined
with another utility like `sed` to operate on the files by using the `-exec`
option. In the following example any occurrence of find is replaced with
replace.
```sh
find ./ -type f -exec sed -i 's/find/replace/g' {} \;
```
## How to search for text within multiple files
Another use of combining `find` with `exec` is to search for text within
multiple files.
```sh
find ./ -type f -name "*.md" -exec grep 'foo' {} \;
```
## Further reading
- [find man page][1]
- [A collection of Unix/Linux find command examples][2]
- [Find Command in Unix and Linux Examples][3]
- [Some examples of using UNIX find command][4]
[1]: http://linux.die.net/man/1/find
[2]: http://alvinalexander.com/unix/edu/examples/find.shtml
[3]: http://www.folkstalk.com/2011/12/101-examples-of-using-find-command-in.html
[4]:
http://www.ling.ohio-state.edu/~kyoon/tts/unix-help/unix-find-command-examples.htm
[5]: /images/articles/find.png
|
Rust
|
UTF-8
| 3,219 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
//! amqpr-api is AMQP client api library.
//! You can talk with AMQP server via channel controller provided by this crate.
//! There is two kind of channel controllers; GlobalChannelController and LocalChannelController.
//!
extern crate bytes;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate futures;
#[macro_use]
extern crate log;
extern crate tokio_core;
extern crate tokio_io;
extern crate amqpr_codec;
macro_rules! try_stream_ready {
($polled: expr) => {
match $polled {
Ok(::futures::Async::Ready(Some(frame))) => frame,
Ok(::futures::Async::Ready(None)) =>
return Err(::errors::Error::from(::errors::ErrorKind::UnexpectedConnectionClose).into()),
Ok(::futures::Async::NotReady) => return Ok(::futures::Async::NotReady),
Err(e) => return Err(e.into()),
}
}
}
pub mod channel;
pub mod exchange;
pub mod queue;
pub mod basic;
pub mod subscribe_stream;
pub mod publish_sink;
pub mod handshake;
pub mod errors;
pub(crate) mod common;
pub use handshake::start_handshake;
pub use channel::open_channel;
pub use exchange::declare_exchange;
pub use queue::{bind_queue, declare_queue};
pub use basic::{get_delivered, start_consume};
pub use basic::publish::publish;
pub use subscribe_stream::subscribe_stream;
pub use publish_sink::publish_sink;
use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream};
use errors::Error;
use amqpr_codec::Frame;
type RawSocket = tokio_io::codec::Framed<tokio_core::net::TcpStream, amqpr_codec::Codec>;
pub struct AmqpSocket(RawSocket);
impl Stream for AmqpSocket {
type Item = Frame;
type Error = Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
self.0.poll().map_err(|io_err| Error::from(io_err))
}
}
impl Sink for AmqpSocket {
type SinkItem = Frame;
type SinkError = Error;
fn start_send(&mut self, item: Frame) -> StartSend<Frame, Error> {
self.0
.start_send(item)
.map_err(|io_err| Error::from(io_err))
}
fn poll_complete(&mut self) -> Poll<(), Error> {
self.0.poll_complete().map_err(|io_err| Error::from(io_err))
}
fn close(&mut self) -> Poll<(), Error> {
self.0.close().map_err(|io_err| Error::from(io_err))
}
}
/// This struct is useful when the case such as some functions require `S: Stream + Sink` but your socket is
/// separeted into `Stream` and `Sink`.
pub struct InOut<In: Stream, Out: Sink>(pub In, pub Out);
impl<In: Stream, Out: Sink> Stream for InOut<In, Out> {
type Item = In::Item;
type Error = In::Error;
fn poll(&mut self) -> Result<Async<Option<In::Item>>, In::Error> {
self.0.poll()
}
}
impl<In: Stream, Out: Sink> Sink for InOut<In, Out> {
type SinkItem = Out::SinkItem;
type SinkError = Out::SinkError;
fn start_send(
&mut self,
item: Out::SinkItem,
) -> Result<AsyncSink<Out::SinkItem>, Out::SinkError> {
self.1.start_send(item)
}
fn poll_complete(&mut self) -> Result<Async<()>, Out::SinkError> {
self.1.poll_complete()
}
fn close(&mut self) -> Result<Async<()>, Out::SinkError> {
self.1.close()
}
}
|
Java
|
UTF-8
| 8,088 | 1.96875 | 2 |
[] |
no_license
|
package com.dartrix.proyectoagenda;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class MostrarAsignacionActivity extends Activity {
final Context cnt = this;
String s;
Activity currentActivity = this;
DBproyectoAgenda sql = new DBproyectoAgenda(this, "Agendarium", null, 1);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verasig_layout);
Intent i = getIntent();
Bundle b = i.getExtras();
if (b!=null){
s = (String) b.get("id");
}
final DBproyectoAgenda sql = new DBproyectoAgenda(this, "Agendarium", null, 1);
llenarDatos(sql.traerAsignacion(s));
Button button = (Button) findViewById(R.id.calificar);
// add button listener
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(cnt);
dialog.setContentView(R.layout.custom_calificar_dialog);
Button calificar = (Button) dialog.findViewById(R.id.calificar);
Button cancelar = (Button) dialog.findViewById(R.id.cancelar);
// if button is clicked, close the custom dialog
calificar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView cal = (TextView)dialog.findViewById(R.id.calificacion);
sql.editarAsignacionCalificacion(s, cal.getText().toString());
sql.actualizarAcumuladoMateria(Integer.toString(sql.traerAsignacion(s).getMateriaFK()));
llenarDatos(sql.traerAsignacion(s));
dialog.dismiss();
Toast.makeText(getApplicationContext(),"Asignacion calificada",Toast.LENGTH_SHORT).show();
}
});
cancelar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(getApplicationContext(),"Cancelado",Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
});
}
@Override
protected void onResume() {
super.onResume();
setContentView(R.layout.verasig_layout);
Intent i = getIntent();
Bundle b = i.getExtras();
if (b!=null){
s = (String) b.get("id");
}
final DBproyectoAgenda sql = new DBproyectoAgenda(this, "Agendarium", null, 1);
llenarDatos(sql.traerAsignacion(s));
Button button = (Button) findViewById(R.id.calificar);
// add button listener
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(cnt);
dialog.setContentView(R.layout.custom_calificar_dialog);
Button calificar = (Button) dialog.findViewById(R.id.calificar);
Button cancelar = (Button) dialog.findViewById(R.id.cancelar);
// if button is clicked, close the custom dialog
calificar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView cal = (TextView)dialog.findViewById(R.id.calificacion);
sql.editarAsignacionCalificacion(s, cal.getText().toString());
llenarDatos(sql.traerAsignacion(s));
sql.actualizarAcumuladoMateria(Integer.toString(sql.traerAsignacion(s).getMateriaFK()));
dialog.dismiss();
Toast.makeText(getApplicationContext(),"Asignacion calificada",Toast.LENGTH_SHORT).show();
}
});
cancelar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(getApplicationContext(),"Cancelado",Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
});
}
public void llenarDatos(Asignacion as){
TextView titulo = (TextView)findViewById(R.id.titulo);
TextView fechahora = (TextView)findViewById(R.id.fechahora);
TextView materia = (TextView)findViewById(R.id.materia);
TextView tipo = (TextView)findViewById(R.id.tipo);
TextView calificacion = (TextView)findViewById(R.id.calificacion);
TextView desc = (TextView)findViewById(R.id.descripcion);
Log.d("dat",as.getNombre());
titulo.setText(as.getNombre());
fechahora.setText(as.getFechalimite() + " " + as.getHoralimite());
DBproyectoAgenda sql = new DBproyectoAgenda(this, "Agendarium", null, 1);
Materia m = sql.traerMateria(Integer.toString(as.getMateriaFK()));
materia.setText(m.getNombreMateria());
tipo.setText(as.getTipo());
if (as.getCalificacion().equals("0")){
calificacion.setText("Sin calificar");
}else{
calificacion.setText(as.getCalificacion());
}
Button circulo = (Button)findViewById(R.id.circulo);
switch (as.getTipo()){
case "Tarea":
circulo.setBackgroundTintList(getResources().getColorStateList(R.color.colorTarea));
break;
case "Exposicion":
circulo.setBackgroundTintList(getResources().getColorStateList(R.color.colorExposicion));
break;
case "Proyecto":
circulo.setBackgroundTintList(getResources().getColorStateList(R.color.colorProyecto));
break;
case "Examen":
circulo.setBackgroundTintList(getResources().getColorStateList(R.color.colorExamen));
break;
}
desc.setText(as.getDescripcion());
}
public void eliminarAsign(View v){
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle("Agendarium");
builder1.setMessage("Desea borrar esta materia? (Se borraran todas las asignaciones)");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Si",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
sql.eliminarAsignacion(s);
currentActivity.finish();
Toast.makeText(currentActivity,"Asignacion borrada.",Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
public void abrir (View v){
Intent i = new Intent(this, EditarAsignaturaActivity.class);
i.putExtra("id",s);
startActivity(i);
}
}
|
JavaScript
|
UTF-8
| 142 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
async function(iter) {
var result = 0;
for (var value of iter) {
result += await value;
if (result > 10)
break;
}
return result;
}
|
C++
|
UTF-8
| 6,717 | 2.796875 | 3 |
[] |
no_license
|
int Int = 11;
int S1 = 2;
int S2 = 3;
int S3 = 4;
byte com = 0;
int CG = 1;
void setup()
{
Serial.begin(9600);
pinMode(Int, OUTPUT); // lights up when command from group 1 is recognized
pinMode(S1, OUTPUT); // lights up when subgroup x command 1 is recognized
pinMode(S2, OUTPUT); // lights up when subgroup x command 2 is recognized
pinMode(S3, OUTPUT); // lights up when subgroup x command 3 is recognized
delay(2000);
Serial.write(0xAA); // wait for input
Serial.write(0x37); // enter compact mode
delay(1000);
Serial.write(0xAA); // wait for input
Serial.write(0x21); // import group 1
Serial.println();
Serial.write(0x11); // //REMOVE LATERERERERERERRERER <------------------------------
Serial.println(" = Voice 1");
Serial.write(0x12); // //REMOVE LATERERERERERERRERER <------------------------------
Serial.println(" = Voice 2");
Serial.write(0x13); // //REMOVE LATERERERERERERRERER <------------------------------
Serial.println(" = Voice 3");
}
void loop()
{
while(Serial.available())
{
com = Serial.read();
switch(com)
{
case 0x11: // current group: command 1
if (CG == 1) // if current group is 1 (initializer group)
{
digitalWrite(Int, HIGH); // turn on the Int LED
Serial.println("Switched to SG1"); //REMOVE LATERERERERERERRERER <------------------------------
Serial.write(0x22); // switch voice checks to group 2
CG = 2; // switch actions to group 2 (command subgroup for initializer 1)
}
else
{
if (CG == 2) // if current group is 2 (command subgroup for initializer 1)
{
digitalWrite(S1, HIGH); // turn on the S1 LED
delay(100);
digitalWrite(Int, LOW); // turn off the Int LED
delay(1000);
digitalWrite(S1, LOW); // turn off the S1 LED
Serial.println("SG1 Command 1; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------
Serial.write(0x21); // switch voice checks to group 1
CG = 1; // switch back to initializer group
}
if (CG == 3) // if current group is 3 (command subgroup for initializer 2)
{
digitalWrite(Int, LOW); // turn off the Int LED
Serial.println("SG2 Command 1; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------
Serial.write(0x21); // switch voice checks to group 1
CG = 1; // switch back to initializer group
}
if (CG == 4) // if current group is 4 (command subgroup for initializer 3)
{
digitalWrite(Int, LOW); // turn off the Int LED
Serial.write(0x21); // switch voice checks to group 1
CG = 1; // switch back to initializer group
}
}
break;
//-----------------------------------------------
case 0x12:
if (CG == 1) // if current group is 1 (initializer group)
{
digitalWrite(Int, HIGH); // turn on the Int LED
Serial.println("Switched to SG2"); //REMOVE LATERERERERERERRERER <------------------------------
Serial.write(0x23); // switch voice checks to group 3
CG = 3; // switch actions to group 3 (command subgroup for initializer 2)
}
else
{
if (CG == 2) // if current group is 2 (command subgroup for initializer 1)
{
digitalWrite(S2, HIGH); // turn on the S2 LED
delay(100);
digitalWrite(Int, LOW); // turn off the Int LED
delay(1000);
digitalWrite(S2, LOW); // turn off the S1 LED
Serial.println("SG1 Command 2; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------
Serial.write(0x21); // switch voice checks to group 1
CG = 1; // switch back to initializer group
}
if (CG == 3) // if current group is 3 (command subgroup for initializer 2)
{
digitalWrite(Int, LOW); // turn off the Int LED
Serial.println("SG2 Command 2; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------
Serial.write(0x21); // switch voice checks to group 1
CG = 1; // switch back to initializer group
}
if (CG == 4) // if current group is 4 (command subgroup for initializer 3)
{
digitalWrite(Int, LOW); // turn off the Int LED
Serial.write(0x21); // switch voice checks to group 1
CG = 1; // switch back to initializer group
}
}
break;
//-----------------------------------------------
case 0x13:
if (CG == 1) // if current group is 1 (initializer group)
{
digitalWrite(Int, HIGH); // turn on the Int LED
Serial.write(0x24); // switch voice checks to group 4
CG = 4; // switch actions to group 4 (command subgroup for initializer 4)
}
else
{
if (CG == 2) // if current group is 2 (command subgroup for initializer 1)
{
digitalWrite(S3, HIGH); // turn on the S3 LED
delay(100);
digitalWrite(Int, LOW); // turn off the Int LED
delay(1000);
digitalWrite(S3, LOW); // turn off the S3 LED
Serial.println("SG1 Command 3; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------
Serial.write(0x21); // switch voice checks to group 1
CG = 1; // switch back to initializer group
}
if (CG == 3) // if current group is 3 (command subgroup for initializer 2)
{
digitalWrite(Int, LOW); // turn off the Int LED
Serial.println("SG2 Command 3; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------
Serial.write(0x21); // switch voice checks to group 1
CG = 1; // switch back to initializer group
}
if (CG == 4) // if current group is 4 (command subgroup for initializer 3)
{
digitalWrite(Int, LOW); // turn off the Int LED
Serial.write(0x21); // switch voice checks to group 1
CG = 1; // switch back to initializer group
}
}
break;
//-----------------------------------------------
case 0x14:
break;
//-----------------------------------------------
case 0x15:
break;
//-----------------------------------------------
}
}
}
|
C#
|
UTF-8
| 1,582 | 2.609375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Xml.Serialization;
using testFileUpload.Core.Types;
namespace testFileUpload.Core.Models
{
[Serializable]
[XmlRoot("Transaction")]
public class XmlTransaction
{
[XmlAttribute] [MaxLength(50)] public string Id { get; set; }
//Date Format yyyy-MM-ddThh:mm:ss e.g. 2019-0123T13:45:10
public DateTime TransactionDate { get; set; }
public PaymentDetails PaymentDetails { get; set; }
public XmlStatus Status { get; set; }
}
public class PaymentDetails
{
public decimal Amount { get; set; }
public string CurrencyCode { get; set; }
}
[XmlRoot("Transactions")]
public class TransactionFile : List<XmlTransaction>
{
}
public static class TransactionHelper
{
public static string ToXml<T>(this T transaction)
{
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
using var stringWriter = new StringWriter();
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringWriter, transaction, ns);
return stringWriter.ToString();
}
public static T FromXml<T>(this string xmlText)
{
using (var stringReader = new StringReader(xmlText))
{
var serializer = new XmlSerializer(typeof(T));
return (T) serializer.Deserialize(stringReader);
}
}
}
}
|
PHP
|
UTF-8
| 1,119 | 2.953125 | 3 |
[] |
no_license
|
<?php
require_once 'connectDB.php';
//$conn = connectDB();
$sql = "select cateId, cateName, modifyDate from category";
$result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>CATEGORY FORM </h2>
<p>This is function of adminstrator to insert, edit, delete one category.</p>
<p><a href="Adding_Category.php"> New Category</a></p>
<table style="width:100%" border = "1">
<tr>
<th>Catgory Id</th>
<th>Category Name</th>
<th>Modify Date</th>
<th></th>
<th></th>
</tr>
<?php if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo $row['cateId']?> </td>
<td><?php echo $row['cateName']?></td>
<td><?php echo $row['modifyDate']?></td>
<td><a href="delete_category.php?id=<?php echo $row['cateId']?>">Delete</a></td>
<td><a href="Adding_Category.php?id=<?php echo $row['cateId']?>">Edit</a></td>
</tr>
<?php }
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</table>
</body>
</html>
|
Java
|
UTF-8
| 2,913 | 3.09375 | 3 |
[] |
no_license
|
package hangman;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class EvilHangmanGame implements IEvilHangmanGame {
private KeyPartPair kpp;
public Partition mypart;
private int gcount;
private ArrayList<String> guessedletters = new ArrayList<>();
public Key gamekey;
public boolean winstatus = false;
public EvilHangmanGame() {
// TODO Auto-generated constructor stub
}
@Override
public void startGame(File dictionary, int wordLength) {
// TODO Auto-generated method stub
// check wordlength ********************* >= 2
setGcount(0);
try {
Scanner sc = new Scanner(dictionary);
mypart = new Partition();
while (sc.hasNext()) {
mypart.add(sc.next());
}
sc.close();
mypart.setWordLength(wordLength);
gamekey = new Key(wordLength);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public Set<String> makeGuess(char guess) throws GuessAlreadyMadeException {
// TODO Auto-generated method stub
this.checkGuessMade(guess);
kpp = new KeyPartPair(mypart, guess);
Set<String> output = new TreeSet<>();
output = kpp.getBestSet();
addGuessedLetter(guess);
mypart.words = output;
//System.out.print(output);
return output;
}
public int getGcount() {
return gcount;
}
public void setGcount(int gcount) {
this.gcount = gcount;
}
public void addGuessedLetter(char in) {
String temp = Character.toString(in);
guessedletters.add(temp);
}
public void addGuessedLetter(String in) {
guessedletters.add(in);
}
public String printGuessedLetters() {
StringBuilder sb = new StringBuilder();
Collections.sort(guessedletters);
for (String s : guessedletters) {
sb.append(s + " ");
}
return sb.toString();
}
public void checkGuessMade(char in) throws GuessAlreadyMadeException {
for (int x = 0; x < guessedletters.size(); x += 1) {
if (guessedletters.get(x).charAt(0) == in) {
throw new GuessAlreadyMadeException();
}
}
}
public boolean gameRunning(EvilHangmanGame game) {
if (game.getGcount() == 0) {
return false;
}
if (game.gamekey.checkIfWordFull()) {
winstatus = true;
return false;
}
if (game.winstatus) {
return false;
}
return true;
}
public boolean checkGuessValid(String in) {
if (in.length() != 1) {
return false;
}
char dachar = in.charAt(0);
if (!Character.isLetter(dachar)) {
return false;
}
return true;
}
public int haveTheyWon(char letter) {
Key partitionkey = mypart.getPartsKey(letter);
if (partitionkey == null) {
winstatus = true;
return 0;
} else if (partitionkey.getCount() > 0) {
gamekey.addletters(partitionkey);
return partitionkey.getCount();
} else {
gcount -= 1;
return -1;
}
}
}
|
Python
|
UTF-8
| 2,347 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
import importFile
import kmeans
import bisecting_kmeans
import fuzzyCmeans
import utils
from sklearn import metrics
import sys
def main(algorithm, data, cl_labels, min_k, max_k, max_iterations, epsilon):
results, silhouette, chs, ssws, ssbs, ars, hom, comp = [], [], [], [], [], [], [], []
membership, centroids, labels = [], [], []
for c in range(min_k, max_k + 1):
if algorithm == 'kmeans':
labels, centroids = kmeans.kmeans(data, c)
elif algorithm == 'bisecting_kmeans':
labels, centroids = bisecting_kmeans.bisecting_kmeans(data, c)
elif algorithm == 'fuzzy_cmeans':
membership, centroids = fuzzyCmeans.execute(data, max_iterations, c, epsilon)
labels = fuzzyCmeans.get_labels(len(data), membership)
silhouette.append((c, metrics.silhouette_score(data, labels, metric='euclidean')))
chs.append((c, metrics.calinski_harabaz_score(data, labels)))
ssws.append((c, utils.get_ssw(data, centroids, labels)))
ssbs.append((c, utils.get_ssb(centroids)))
ars.append((c, metrics.adjusted_rand_score(cl_labels, labels)))
hom.append((c, metrics.homogeneity_score(cl_labels, labels)))
comp.append((c, metrics.completeness_score(cl_labels, labels)))
results.append(("Silhouette", "", zip(*silhouette)[0], "", zip(*silhouette)[1], 333, "blue"))
results.append(("Calinski-Harabaz Index", "", zip(*chs)[0], "", zip(*chs)[1], 334, "blue"))
results.append(("Intra cluster Variance", "", zip(*ssws)[0], "", zip(*ssws)[1], 331, "blue"))
results.append(("Inter cluster Variance", "", zip(*ssbs)[0], "", zip(*ssbs)[1], 332, "blue"))
results.append(("Adjusted Rand Index", "", zip(*ars)[0], "", zip(*ars)[1], 335, "orange"))
results.append(("Homogeneity", "", zip(*hom)[0], "", zip(*hom)[1], 336, "orange"))
results.append(("Completeness", "", zip(*comp)[0], "", zip(*comp)[1], 337, "orange"))
print(labels)
utils.plot_results(results, algorithm)
arguments = sys.argv
file_name = arguments[1]
class_name = arguments[2]
algo = arguments[3]
minimum_k = int(arguments[4])
maximum_k = int(arguments[5])
max_iter = int(arguments[6])
epsilon_ = float(arguments[7])
da, classif = importFile.read_file(file_name, class_name)
main(algo, da, classif, minimum_k, maximum_k, max_iter, epsilon_)
|
Java
|
UTF-8
| 427 | 2.703125 | 3 |
[] |
no_license
|
package com.saptar.dijkstra.driver;
import com.saptar.warshallflyod.engine.WarshallFlyod;
public class WarshallFlyodDriver {
final static int INF = 99999, V = 4;
public static void main(String[] args) {
int graph[][] = { { 0, 5, INF, 10 }, { INF, 0, 3, INF },
{ INF, INF, 0, 1 }, { INF, INF, INF, 0 } };
WarshallFlyod a = new WarshallFlyod();
// Print the solution
a.flyodWarshal(graph);
}
}
|
Markdown
|
UTF-8
| 381 | 2.578125 | 3 |
[] |
no_license
|
# myASR
Final project for EE516 PMP at UW. Matlab implementation of a simple speaker independent, isolated word, whole-word model, single Gaussian per state, diagonal covariance Gaussian, automatic speech recognition (ASR) system, using the ten-word vocabulary W = {“zero”, “one”, “two”, “three”, ... "nine"}.
See FinalProjectWriteUp.pdf for further information.
|
C#
|
UTF-8
| 498 | 3.078125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp.Decorator
{
class ConcreteDecoratorB:Decorator
{
public override double Operation(double Prices)
{
Prices = Prices * 0.5;
AddedBehavior();
Console.WriteLine("打5折后值为:" + Prices);
return base.Operation(Prices);
}
private void AddedBehavior() {
//本类独有的方法,区别于
}
}
}
|
Python
|
UTF-8
| 16,765 | 3.265625 | 3 |
[] |
no_license
|
import numpy as np
import cPickle as pickle
def _list2UT(l, N):
"""Return a list of the rows of an NxN upper triangular"""
mat = []
start = 0
for i in range(N):
mat.append(l[start:start+N-i])
start += N-i
return mat
def _UT2list(m):
"""Return the elements of an NxN upper triangular in row major order"""
return np.array([item for thing in m for item in thing])
def _unsort(l, ind):
"""Scramble and return a list l by indexes ind"""
l0 = np.zeros(len(l))
for i, x in zip(ind, l):
l0[i]=x
return l0
def _symmetrize(A):
"""Form a symmetric matrix out of a list of upper triangle elements
Example:
>>> A = [[0, 1, 2], [3, 4], [5]]
>>> symmetrize(A)
array([[ 0., 1., 2.],
[ 1., 3., 4.],
[ 2., 4., 5.]])
"""
N = len(A)
As = np.zeros((N, N))
for i, t in enumerate(A):
As[i, i:]=t
return As + As.T - np.diag(As.diagonal())
def _tile_arrays(A):
"""Take a symmetric array, A, size N x N, where N is even and return
an array [ N x N ; N - 1 ]
[ N - 1 ; A[1, 1] ]
such that the lower to exploit symmetries.
Example (N=2):
>>> A = array([[0, 1, 2],
>>> ... [1, 3, 4],
>>> ... [2, 4, 6]])
>>> tile_arrays(tmp)
array([[ 0., 1., 2., 1.],
[ 1., 3., 4., 3.],
[ 2., 4., 6., 4.],
[ 1., 3., 4., 3.]])
"""
N = 2*(np.shape(A)[0]-1)
A_ref = np.zeros((N,N))
A_ref[:N/2+1,:N/2+1]=A
A_ref[N/2:,:N/2+1] = A_ref[N/2:0:-1,:N/2+1]
A_ref[:,N/2:] = A_ref[:,N/2:0:-1]
return A_ref
def _list_to_fft_mat(lis, index, N):
lis = _unsort(lis, index)
mat = _list2UT(lis, N/2+1)
mat = _symmetrize(mat) # Make use of symmetries to
mat = _tile_arrays(mat) # to construct the whole array.
return mat
def form_wl(N):
#fwl = 10*N
fwl = 6000.
wl = np.array([[fwl/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000
for i in range(j, N)]
for j in range(N)])
return _symmetrize(wl)
def yield_wl(i, j, fwl=6000):
if i == j == 0:
return 16000
else:
return fwl/np.sqrt(i**2+j**2)
def prop(u, d, k):
"""Return the propagator for a layer of depth d and viscosity u with a
harmonic load of order k
As defined in Cathles 1975, p41, III-12.
"""
y = k*d
s = np.sinh(y)
c = np.cosh(y)
cp = c + y*s
cm = c - y*s
sp = s + y*c
sm = s - y*c
s = y*s
c = y*c
return np.array([[cp, c, sp/u, s/u],
[-c, cm, -s/u, sm/u],
[sp*u, s*u, cp, c],
[-s*u, sm*u, -c, cm]])
def exp_decay_const(earth, i, j):
"""Return the 2D exponential decay constant for order harmonic unit loads.
Parameters
----------
earth - the earth object containing the parameters...
i, j (int) - the x, y order numbers of the harmonic load
Returns
-------
tau - the exponential decay constant for harmonic load i,j, in yrs
The resulting decay, dec(i, j) = 1-np.exp(elapsed_time * 1000./tauc(i, j)),
along with lithospheric filter can be returned using earth.get_resp.
"""
wl = yield_wl(i, j, fwl=600*10) # wavelength
ak = 2*np.pi/wl # wavenumber
# ----- Interior to Surface integration ----- #
# uses propagator method from Cathles 1975
# initialize two interior boundary vectors
# assuming solution stays finite in the substratum (Cathles 1975, p41)
cc = np.array([[1., 0., 1., 0.],
[0., 1., 0., 1.]])
# Determine the necessary start depth (start lower for longer wavelengths)
# to solve a roundoff problem with the matrix method.
#TODO look into stability problem here
if wl < 40:
lstart = 9
elif wl < 200:
lstart = 6
elif wl < 500:
lstart = 4
else:
lstart = 0
# integrate from starting depth to surface, layer by layer
for dd, uu, in zip(earth.d[lstart:], earth.u[lstart:]):
p = prop(uu, dd, ak)
for k, c in enumerate(cc):
cc[k,:] = p.dot(c)
# initialize the inegration constants
x = np.zeros(2)
# solve for them, assuming 1 dyne normal load at surface
x[0] = cc[1,2]/(cc[0,2]*cc[1,3]-cc[0,3]*cc[1,2])
x[1] = -cc[0,2]/(cc[0,2]*cc[1,3]-cc[0,3]*cc[1,2])
# multiply into the solution
for k in range(2):
cc[k,:]=x[k]*cc[k,:]
# form the final solution
cc = np.sum(cc, axis=0)
# As cc[1] gives the surface velocity, the exponential time constant is
# its reciprocal (see Cathles 1975, p43)
# 1955600 = 2/rho (~3.313) /g (~9.8) * (1/pi*1e8) unit conversion to years
tau = 1955600.*ak/cc[1]
return tau
class FlatEarthBase(object):
"""A Base class for 2D, flat earth models. Provides methods for saving,
adding descriptions, and returning response.
User must define a method for generating taus,
"""
def __init__(self):
self.taus = None
self.ak = None
self.alpha = None
self.index = None
self.N = None
def __call__(self, t_dur):
return self.get_resp(t_dur)
def save(self, filename):
pickle.dump(self, open(filename, 'wb'))
def get_resp(self, t_dur):
"""Calculate and return earth response to a unit load in an fft_mat.
Parameters
----------
t_dur (float) - the duration, in cal ka BP, of applied load
"""
# Convert tau list to fft matrix
taus = _list_to_fft_mat(self.taus, self.index, self.N)
resp = (1-np.exp(t_dur/taus))/self.alpha
return resp
def set_N(self, N):
self.N = N
class EarthNLayer(FlatEarthBase):
"""Return the isostatic response of a 2D earth with n viscosity layers.
The response is calculated from a viscous profile overlain by an elastic
lithosphere in the fourier domain.
"""
def __init__(self, u=None, d=None, fr23=10., g=9.8, rho=3.313):
if u is None:
self.u = np.array([1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,0.018])
else:
self.u = u
if d is None:
self.d = np.array([400.,300.,300.,300.,300.,300.,
300.,200.,215.,175.,75. ])
else:
self.d = d
self.NLayers = len(self.u)
self.fr23=fr23
self.g=g
self.rho=rho
def reset_params_list(self, params, arglist):
"""Set the full mantle rheology and calculate the decay constants.
self.N must have been set already.
"""
us = ds = fr23 = N = None
i=0
if 'us' in arglist:
us = params[i:i+self.NLayers]
i += self.NLayers
if 'ds' in arglist:
ds = params[i:i+self.NLayers]
i += self.NLayers
if 'fr23' in arglist:
fr23 = params[i]
i += 1
if 'N' in arglist:
N = params[i]
self.reset_params(us, ds, fr23, N)
def reset_params(self, us=None, ds=None, fr23=None, N=None):
if us is not None: self.u = us
if ds is not None: self.d = ds
self.fr23 = fr23 or self.fr23
N = N or self.N
self.calc_taus(N)
def set_taus(self, taus):
self.taus=taus
def calc_taus(self, N=None):
"""Generate and store a list of exponential decay constants.
The procedure sets class data:
N (the maximum order number calculated)
taus (decay constants by increasing wavenumber)
ak (wavenumbers in increasing order)
index (the sorting key to reorder taus to increasing wavenumber)
alpha (the lithospheric filter values in FFTmat format)
Parameters
----------
N (int) - the maximum order number. Resulting earth parameters ak,
taus, and alpha will be size NxN when in FFTmat format.
For description of formats, see help(_list_to_fft_mat)
"""
self.N = N or self.N
taus = [[exp_decay_const(self, i, j) for i in xrange(j, N/2+1)]
for j in xrange(N/2+1)]
#TODO Generalize to arbitrary wavelengths using GridObject?
wl = np.array([[6000/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000
for i in range(j, N/2+1)]
for j in range(N/2+1)])
wl = _UT2list(wl)
self.ak = 2*np.pi/np.array(wl)
# Sort by increasing order number
self.index = range(len(self.ak))
self.index.sort(key=self.ak.__getitem__)
self.ak = self.ak[self.index]
self.taus = _UT2list(taus)[self.index]*1e-3 # and convert to kyrs
# the Lithosphere filter, sorted by wave number
# factor of 1e8 is for unit conversion
self.alpha = 1.+((self.ak)**4)*self.fr23/self.g/self.rho*1e8
# Augment the decay times by the Lithosphere filter
self.taus = self.taus/self.alpha
# Turn the Lithosphere filter and taus into a matrix that matches the
# frequencey matrix from an NxN fft.
self.alpha = _list_to_fft_mat(self.alpha, self.index, self.N)
class EarthTwoLayer(FlatEarthBase):
"""Return the isostatic response of a flat earth with two layers.
The response is calculated analytically in the fourier domain from a
uniform mantle of viscosity u overlain by an elastic lithosphere with
flexural rigidty fr23.
"""
def __init__(self, u, fr23, g=9.8, rho=3.313):
self.u = u
self.fr23 = fr23
self.g = g
self.rho = rho
def reset_params_list(self, params, arglist):
params = dict(zip(arglist, xs))
self.reset_params(params)
def reset_params(self, u=None, fr23=None, N=None):
self.u = u or self.u
self.fr23 = fr23 or self.fr23
N = N or self.N
self.calc_taus(N)
def calc_taus(self, N=None):
"""Generate and store a list of exponential decay constants.
The procedure sets class data:
N (the maximum order number calculated)
taus (decay constants in flattend upper diagonal list)
ak (wavenumbers in increasing order)
index (the sorting key to reorder taus to increasing wavenumber)
alpha (the lithospheric filter values in FFTmat format)
Parameters
----------
N (int) - the maximum order number. Resulting earth parameters ak,
taus, and alpha will be size NxN when in FFTmat format.
For description of formats, see help(_list_to_fft_mat)
"""
N = N or self.N
#TODO Generalize to arbitrary wavelengths
wl = np.array([[6000/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000
for i in range(j, N/2+1)]
for j in range(N/2+1)])
wl = _UT2list(wl)
self.ak = 2*np.pi/np.array(wl)
# Sort by increasing order number
self.index = range(len(self.ak))
self.index.sort(key=self.ak.__getitem__)
self.ak = self.ak[self.index]
self.taus = -2*self.u*self.ak/self.g/self.rho
# Unit conversion so result is in kyrs:
# u in Pa s=kg/m s, ak in 1/km, g in m/s2, rho in g/cc
# and np.pi*1e7 s/yr
self.taus = self.taus*(1./np.pi)*1e5
# the Lithosphere filter, sorted by wave number
# factor of 1e8 is for unit conversion
self.alpha = 1.+((self.ak)**4)*self.fr23/self.g/self.rho*1e8
# Augment the decay times by the Lithosphere filter
self.taus = self.taus/self.alpha
# Turn the Lithosphere filter and taus into a matrix that matches the
# frequencey matrix from an NxN fft.
self.alpha = _list_to_fft_mat(self.alpha, self.index, self.N)
class EarthThreeLayer(FlatEarthBase):
"""Return the isostatic response of a flat earth with three layers.
The response is calculated analytically in the fourier domain from a
two layer mantle whose lower layer, of viscosity u1, is overlain layer
of viscosity u2 and width h, which in turn is overlain by an elastic
lithosphere with flexural rigidty fr23.
"""
def __init__(self, u1, u2, fr23, h, g=9.8, rho=3.313):
self.g = g
self.rho = rho
self.u1 = u1
self.u2 = u2
self.fr23 = fr23
self.h = h
def reset_params_list(self, params, arglist):
params = dict(zip(arglist, xs))
self.reset_params(params)
def reset_params(self, u1=None, u2=None, fr23=None, h=None, N=None):
self.u1 = u1 or self.u1
self.u2 = u2 or self.u2
self.fr23 = fr23 or self.fr23
self.h = h or self.h
N = N or self.N
self.calc_taus(N)
def get_params(self):
return [self.u1, self.u2, self.fr23, self.h]
def calc_taus(self, N):
"""Generate and store a list of exponential decay constants.
The procedure sets class data:
N (the maximum order number calculated)
taus (decay constants in flattend upper diagonal list)
ak (wavenumbers in increasing order)
index (the sorting key to reorder taus to increasing wavenumber)
alpha (the lithospheric filter values in FFTmat format)
Parameters
----------
N (int) - the maximum order number. Resulting earth parameters ak,
taus, and alpha will be size NxN when in FFTmat format.
For description of formats, see help(_list_to_fft_mat)
"""
self.N = N
#TODO Generalize to arbitrary wavelengths
wl = np.array([[6000/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000
for i in range(j, N/2+1)]
for j in range(N/2+1)])
wl = _UT2list(wl)
self.ak = 2*np.pi/np.array(wl)
# Sort by increasing order number
self.index = range(len(self.ak))
self.index.sort(key=self.ak.__getitem__)
self.ak = self.ak[self.index]
# Cathles (1975) III-21
c = np.cosh(self.ak*self.h)
s = np.sinh(self.ak*self.h)
u = self.u2/self.u1
ui = 1./u
r = 2*c*s*u + (1-u**2)*(self.ak*self.h)**2 + ((u*s)**2+c**2)
r = r/((u+ui)*s*c + self.ak*self.h*(u-ui) + (s**2+c**2))
r = 2*c*s*u + (1-u**2)*(self.ak*self.h)**2 + ((u*s)**2+c**2)
r = r/((u+ui)*s*c + self.ak*self.h*(u-ui) + (s**2+c**2))
self.taus = -2*self.u1*self.ak/self.g/self.rho*r
# Unit conversion so result is in kyrs:
# u in Pa s=kg/m s, ak in 1/km, g in m/s2, rho in g/cc
# and np.pi*1e7 s/yr
self.taus = self.taus*(1./np.pi)*1e5
# the Lithosphere filter, sorted by wave number
# factor of 1e8 is for unit conversion
self.alpha = 1.+((self.ak)**4)*self.fr23/self.g/self.rho*1e8
# Augment the decay times by the Lithosphere filter
self.taus = self.taus/self.alpha
# Turn the Lithosphere filter and taus into a matrix that matches the
# frequencey matrix from an NxN fft.
self.alpha = _list_to_fft_mat(self.alpha, self.index, self.N)
def check_k(earth):
"""Check whether different 2D k matrices are identical, useful for
debugging.
"""
N = earth.N
wl = form_wl(N/2+1)
wl = _tile_arrays(wl)
ak_wl = 2*np.pi/wl
ki = np.reshape(np.tile(
np.fft.fftfreq(N, 6000/(2*np.pi)/N), N), (N, N))
ak_fft = np.sqrt(ki**2 + ki.T**2)
ak_fft[0,0] = 2*np.pi/16000
ak_ea = _list_to_fft_mat(earth.ak, earth.index, N)
print "ak_wl and ak_fft are close: "+str(np.allclose(ak_wl, ak_fft))
print "ak_wl and ak_ea are close: "+str(np.allclose(ak_wl, ak_ea))
print "ak_fft and ak_ea are close: "+str(np.allclose(ak_fft, ak_ea))
def load(filename):
return pickle.load(open(filename, 'r'))
|
C++
|
UTF-8
| 7,279 | 3.046875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class fraction{
public:
long long int x;
long long int y=1;
fraction(int a,int b){
x=a;
y=b;
}
fraction(int c){
x=c;
y=1;
}
fraction operator + (fraction f){
long long int tempX=x*f.y+f.x*y;
long long int tempY=f.y*y;
return fraction(tempX,tempY);
};
fraction operator - (fraction f){
long long int tempX=x*f.y-f.x*y;
long long int tempY=f.y*y;
return fraction(tempX,tempY);
};
fraction operator / (fraction f){
return fraction(x*f.y,y*f.x);
};
fraction operator * (fraction f){
if(f.x==0){
return fraction(0);
}
return fraction(x*f.x,y*f.y);
};
bool operator > (fraction f){
return (double)x/y>(double)f.x/f.y;
};
bool operator < (fraction f){
return (double)x/y<(double)f.x/f.y;
};
bool operator == (double a){
return (double)x/y==a;
};
bool operator != (double a){
return !((double)x/y==a);
};
};
void sortRows(vector<vector<fraction>>& matrix,vector<vector<fraction>>& imatrix,vector<fraction>& b, int select){
for(int i=select+1;i<matrix.size();i++){
for(int j=i-1;j>=select;j--){
if(matrix[j+1][select]>matrix[j][select]){
auto temp = matrix[j];
matrix[j]=matrix[j+1];
matrix[j+1]=temp;
auto itemp = imatrix[j];
imatrix[j]=imatrix[j+1];
imatrix[j+1]=itemp;
auto btemp = b[j];
b[j]=b[j+1];
b[j+1]=btemp;
}
}
}
}
void rowOperations(vector<vector<fraction>>& matrix,vector<vector<fraction>>& imatrix,vector<fraction>& b,int startRow){
for(int i=startRow+1;i<matrix.size();i++){
fraction multi = matrix[i][startRow]/matrix[startRow][startRow];
for(int j=0;j<matrix[i].size();j++){
matrix[i][j]=matrix[i][j]-(matrix[startRow][j]*multi);
imatrix[i][j]=imatrix[i][j]-(imatrix[startRow][j]*multi);
}
b[i]=b[i]-(b[startRow]*multi);
}
}
vector<vector<fraction>> identityy(vector<vector<fraction>> matrix,vector<vector<fraction>> imatrix){
for(int i=0;i<matrix.size();i++){
for(int j=0;j<matrix.size();j++){
if(i==j){
fraction pivot=matrix[i][i];
matrix[i][j]=matrix[i][j]/pivot;
imatrix[i][j]=imatrix[i][j]/pivot;
}
}
}
fraction pivot = matrix[0][1];
for(int i=0;i<3;i++){
matrix[0][i]=matrix[0][i]-(matrix[1][i]*pivot);
imatrix[0][i]=imatrix[0][i]-(imatrix[1][i]*pivot);
}
imatrix[0][2]=imatrix[0][2]-(imatrix[2][2]*matrix[0][2]);
imatrix[1][2]=imatrix[1][2]-(imatrix[2][2]*matrix[1][2]);
return imatrix;
}
vector<vector<fraction>> identity(int n){
vector<vector<fraction>> iMatrix;
for(int i=0;i<n;i++){
vector<fraction> temp;
for(int j=0;j<n;j++){
if(i==j)
temp.push_back(fraction(1));
else
temp.push_back(fraction(0));
}
iMatrix.push_back(temp);
}
return iMatrix;
}
void assign(vector<vector<fraction>>& matrix,vector<vector<fraction>>& imatrix,vector<fraction>& b,ifstream& infile){
int size;
infile>>size;
for(int i=0;i<size;i++){
vector<fraction> v;
for(int j=0;j<size;j++){
double temp;
double bottom=1;
infile>>temp;
while((int)temp!=temp){
temp*=10;
bottom*=10;
}
v.push_back(fraction(temp,bottom));
}
double temp;
double bottom=1;
infile>>temp;
while((int)temp!=temp){
temp*=10;
bottom*=10;
}
b.push_back(fraction(temp,bottom));
matrix.push_back(v);
}
imatrix=identity(size);
}
void printMatrix(vector<vector<fraction>> matrix,ofstream& outfile){
for(int i=0;i<matrix.size();i++){
for(fraction j:matrix[i]){
outfile<<j.x/(double)j.y<<" ";
}
outfile<<endl;
}
}
vector<fraction> solve(vector<vector<fraction>> matrix,vector<fraction> b,int arbitrary){
vector<fraction> reverseSolution;
for(int i=0;i<arbitrary;i++){
reverseSolution.push_back(fraction(0));
}
for(int i=matrix.size()-arbitrary-1;i>=0;i--){
fraction sum(0);
int count=0;
if(reverseSolution.size()!=0)
for(int j=matrix.size()-1;j>i;j--){
sum=sum+(reverseSolution[count]*matrix[i][j]);
count++;
}
b[i]=b[i]-sum;
reverseSolution.push_back(b[i]/matrix[i][i]);
}
return reverseSolution;
}
void findRank(ifstream& infile,ofstream& outfile){
vector<vector<fraction>> matrix;
vector<vector<fraction>> iMatrix;
vector<fraction> b;
assign(matrix,iMatrix,b,infile);
for(int i=0;i<matrix.size();i++){
sortRows(matrix,iMatrix,b,i);
if(matrix[i][i]==0){
continue;
}
rowOperations(matrix,iMatrix,b,i);
}
int rank=matrix.size();
for(int i=0;i<matrix.size();i++){
if(matrix[i][i]==0)
rank--;
}
// if 0 arbitrary if 1 no solution if 2 unique solution
int selection;
if(rank<matrix.size()){
bool solvable=true;
int lastColumn=matrix.size()-1;
while(matrix[lastColumn][matrix.size()-1]==0){
if(b[lastColumn]!=0){
solvable= false;
break;
}
lastColumn--;
}
if(solvable){
selection=0;
}
else{
selection=1;
}
}
else{
selection=2;
}
if(selection==0){
int arbitrary=matrix.size()-rank;
vector<fraction> sol;
sol=solve(matrix,b,arbitrary);
int count=1;
outfile<<"Arbitrary variables:";
for(int i=sol.size()-1;i>=0;i--){
fraction h=sol[i];
if(h.x==0){
outfile<<"x"<<sol.size()-i<<" ";
}
}
outfile<<endl;
outfile<<"Arbitrary Solution:"<<endl;
for(int i=sol.size()-1;i>=0;i--){
fraction h=sol[i];
outfile<<"x"<<count<<"="<<h.x/(double)h.y<<" ";
count++;
}
}
else if(selection==1){
outfile<<"Inconsistent"<<" "<<"problem";
}
else{
outfile<<"Unique Solution:";
vector<fraction> sol;
sol=solve(matrix,b,0);
for(int i=sol.size()-1;i>=0;i--){
fraction h=sol[i];
outfile<<h.x/(double)h.y<<" ";
}
outfile<<endl<<"Inverted A:";
iMatrix=identityy(matrix,iMatrix);
printMatrix(matrix,outfile);
}
}
int main() {
ifstream infile1("../input1.txt");
ofstream outfile1("../output1.txt");
ifstream infile2("../input2.txt");
ofstream outfile2("../output2.txt");
ifstream infile3("../input3.txt");
ofstream outfile3("../output3.txt");
findRank(infile1,outfile1);
findRank(infile2,outfile2);
findRank(infile3,outfile3);
return 0;
}
|
C++
|
UTF-8
| 1,412 | 2.703125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#ifndef STLPLUS_WILDCARD
#define STLPLUS_WILDCARD
////////////////////////////////////////////////////////////////////////////////
// Author: Andy Rushton
// Copyright: (c) Southampton University 1999-2004
// (c) Andy Rushton 2004 onwards
// License: BSD License, see ../docs/license.html
// This is a portable interface to wildcard matching.
// The problem:
// * matches any number of characters - this is achieved by matching 1 and seeing if the remainder matches
// if not, try 2 characters and see if the remainder matches etc.
// this must be recursive, not iterative, so that multiple *s can appear in the same wildcard expression
// ? matches exactly one character so doesn't need the what-if approach
// \ escapes special characters such as *, ? and [
// [] matches exactly one character in the set - the difficulty is the set can contain ranges, e.g [a-zA-Z0-9]
// a set cannot be empty and the ] character can be included by making it the first character
////////////////////////////////////////////////////////////////////////////////
#include "./portability_fixes.hpp"
#include <string>
namespace stlplus
{
// wild = the wildcard expression
// match = the string to test against that expression
// e.g. wildcard("[a-f]*", "fred") returns true
bool wildcard(const std::string& wild, const std::string& match);
}
#endif
|
Java
|
UTF-8
| 585 | 2.21875 | 2 |
[] |
no_license
|
package org.intellij.trinkets.problemsView.problems;
import org.intellij.trinkets.problemsView.ui.TreeNodeElement;
import org.jetbrains.annotations.NotNull;
/**
* Problem.
*
* @author Alexey Efimov
*/
public interface Problem extends TreeNodeElement {
Problem[] EMPTY_PROBLEM_ARRAY = new Problem[]{};
/**
* Get problem type.
*
* @return Problem type.
*/
@NotNull
ProblemType getType();
/**
* Return fixes for this problem.
*
* @return Fixes array.
*/
@NotNull
ProblemFix[] getFixes();
}
|
JavaScript
|
UTF-8
| 540 | 2.59375 | 3 |
[] |
no_license
|
'use strict';
// Remove focus away from the hero as the user scrolls by making it darker
var $mainHeader = $('main header');
$mainHeader.css({
background: 'rgba(0, 0, 0, .5)'
});
var scrollFade = function scrollFade() {
var winheight = $(window).height();
var scrollTop = $(window).scrollTop();
var trackLength = winheight - scrollTop;
var opacity = (1 - trackLength / winheight) / 2;
$mainHeader.css({
background: 'rgba(0, 0, 0, ' + (.5 + opacity) + ')'
});
};
$(window).on('scroll', function () {
scrollFade();
});
|
Java
|
UTF-8
| 2,619 | 2.484375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.teiid.core.types.basic;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.teiid.core.CorePlugin;
import org.teiid.core.types.Transform;
import org.teiid.core.types.TransformationException;
public abstract class NumberToNumberTransform extends Transform {
private Class<?> sourceType;
private Comparable<?> min;
private Comparable<?> max;
public NumberToNumberTransform(Number min, Number max, Class<?> sourceType) {
this.sourceType = sourceType;
if (sourceType == Short.class) {
this.min = min.shortValue();
this.max = max.shortValue();
} else if (sourceType == Integer.class) {
this.min = min.intValue();
this.max = max.intValue();
} else if (sourceType == Long.class) {
this.min = min.longValue();
this.max = max.longValue();
} else if (sourceType == Float.class) {
this.min = min.floatValue();
this.max = max.floatValue();
} else if (sourceType == Double.class) {
this.min = min.doubleValue();
this.max = max.doubleValue();
} else if (sourceType == BigInteger.class) {
if (min instanceof Double || min instanceof Float) {
this.min = BigDecimal.valueOf(min.doubleValue()).toBigInteger();
this.max = BigDecimal.valueOf(max.doubleValue()).toBigInteger();
} else {
this.min = BigInteger.valueOf(min.longValue());
this.max = BigInteger.valueOf(max.longValue());
}
} else if (sourceType == BigDecimal.class) {
if (min instanceof Double || min instanceof Float) {
this.min = BigDecimal.valueOf(min.doubleValue());
this.max = BigDecimal.valueOf(max.doubleValue());
} else {
this.min = BigDecimal.valueOf(min.longValue());
this.max = BigDecimal.valueOf(max.longValue());
}
} else if (sourceType == Byte.class) {
} else {
throw new AssertionError();
}
}
@Override
public Class<?> getSourceType() {
return sourceType;
}
protected void checkValueRange(Object value)
throws TransformationException {
if (((Comparable)value).compareTo(min) < 0 || ((Comparable)value).compareTo(max) > 0) {
throw new TransformationException(CorePlugin.Event.TEIID10058, CorePlugin.Util.gs(CorePlugin.Event.TEIID10058, value, getSourceType().getSimpleName(), getTargetType().getSimpleName()));
}
}
}
|
Python
|
UTF-8
| 674 | 3.109375 | 3 |
[] |
no_license
|
from typing import List
intervals=[[1,4], [4,5], [0,1]]
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals)==0:
return intervals
addList=[]
hold=''
intervals=sorted(intervals, key=lambda x : x[0])
for i, v in enumerate(intervals):
if (i==0):
hold=v
else:
if(hold[1]>=v[0]):
hold=[hold[0], v[1]]
elif (hold[1]<v[0]):
addList.append(hold)
hold=v
addList.append(hold)
return addList
o=Solution()
y=o.merge(intervals)
print(y)
|
Markdown
|
UTF-8
| 3,804 | 3.25 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
---
layout: post
title: "markdown语法初体验"
subtitle: "学习使我快乐"
date: 2018-08-01 12:00:00
author: "Yao Shengli"
header-img: "img/post-bg-nextgen-web-pwa.jpg"
header-mask: 0.3
catalog: true
tags:
- 知识学杂
---
## markdown 语法
### 概述
***
**宗旨**
Markdown 的目标是实现「易读易写」.
可读性,无论如何,都是最重要的。一份使用 Markdown 格式撰写的文件应该可以直接以纯文本发布,并且看起来不会像是由许多标签或是格式指令所构成。Markdown 语法受到一些既有 text-to-HTML 格式的影响,包括 [Setext](http://docutils.sourceforge.net/mirror/setext.html)、[atx](http://www.aaronsw.com/2002/atx/)、[Textile](http://textism.com/tools/textile/)、[reStructuredText](http://docutils.sourceforge.net/rst.html)、[Grutatext](http://www.triptico.com/software/grutatxt.html) 和 [EtText](http://ettext.taint.org/doc/),而最大灵感来源其实是纯文本电子邮件的格式。
**兼容HTML**
例子如下,在Markdown文件里加上一段HTML表格:
<table>
<tr>
<td>name</td>
</tr>
<tr>
<td>Yao Shengli</td>
</tr>
</table>
### 区块元素
***
**段落和换行**
一个 Markdown 段落是由一个或多个连续的文本行组成,它的前后要有一个以上的空行(空行的定义是显示上看起来像是空的,便会被视为空行。比方说,若某一行只包含空格和制表符,则该行也会被视为空行)。普通段落不该用空格或制表符来缩进。
**标题**
类 Atx 形式则是在行首插入 1 到 6 个 # ,对应到标题 1 到 6 阶,例如:
# 这是 H1
## 这是 H2
###### 这是 H6
**区块引用**
Markdown 标记区块引用是使用类似 email 中用 > 的引用方式。如果你还熟悉在 email 信件中的引言部分,你就知道怎么在 Markdown 文件中建立一个区块引用,那会看起来像是你自己先断好行,然后在每行的最前面加上 > :、
>这就是区块引用
>这也是
Markdown 也允许你偷懒只在整个段落的第一行最前面加上 > :
>这样写也行
也行
>还真有意思
啊
引用的区块内也可以使用其他的 Markdown 语法,包括标题、列表、代码区块等:
> ## 这是一个标题。
>
> 1. 这是第一行列表项。
> 2. 这是第二行列表项。
>
> 给出一些例子代码:
>
> return shell_exec("echo $input | $markdown_script");
**列表**
Markdown 支持有序列表和无序列表。
* red
* green
* blue
有序列表则使用数字接着一个英文句点
1. red
2. green
3. blue
**代码区块**
要在 Markdown 中建立代码区块很简单,只要简单地缩进 4 个空格或是 1 个制表符就可以,例如,下面的输入:
这是一个普通的锻炼
这是一个代码区块
**分隔线**
你可以在一行中用三个以上的星号、减号、底线来建立一个分隔线,行内不能有其他东西。你也可以在星号或是减号中间插入空格。下面每种写法都可以建立分隔线:
* * *
***
*****
- - -
------------------
### 区段元素
***
**链接**
[链接名字](链接地址)
**强调**
**强调**
**代码**
如果要标记一小段行内代码,你可以用反引号把它包起),例如:
`printf()`
`printf()`测试
如果要在代码区段内插入反引号,你可以用多个反引号来开启和结束代码区段:
``function a(){
console.log("hellow")
}``
```javascript
function a(){
console.log("hellow")
}
```
**图片**


|
JavaScript
|
UTF-8
| 1,152 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
'use strict'
const constants = require('./constants')
const min = 0
const isNil =
(val) => typeof val === 'undefined' || val === null
const isValidInRange =
(num, max) => !isNaN(num) && num >= min && num <= max
const isValid = (val, max) => {
if (!isValidInRange(val, max)) {
throw new Error(`'${val}' must be a number between ${min} and ${max}`)
}
return true
}
const getTimestampNoMs = (date) =>
parseInt(date / constants.second, constants.radix10) % constants.uIntMax
const getNumFromPosInHexString = (hexString, start, length) =>
parseInt(hexString.substr(start, length), constants.radix16)
const getMaskedHexString = (length, num) => {
const hexString = num.toString(constants.radix16)
if (hexString.length === length) {
return hexString
}
if (hexString.length !== length) {
return constants.hexStringIntMask.substring(hexString.length, length) + hexString
}
}
const getIsoFormattedTimestampNoMs = (num) =>
new Date(num * constants.second).toISOString()
module.exports = {
isNil,
isValid,
getTimestampNoMs,
getNumFromPosInHexString,
getMaskedHexString,
getIsoFormattedTimestampNoMs
}
|
PHP
|
UTF-8
| 729 | 2.609375 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
require '../lib/mavenlink_api.php';
$mavenlinkApi = new MavenlinkApi('<oauthTokenHere>');
$workspacesJson = $mavenlinkApi->getWorkspaces();
$workspacesDecodedJson = json_decode($workspacesJson, true);
echo '<h1> Your workspaces: </h1>';
echo '<ul>';
$totalBudget = 0;
foreach ($workspacesDecodedJson[results] as $dataItem) {
$workspace = $workspacesDecodedJson[$dataItem[key]][$dataItem[id]];
echo '<li>' . $workspace[title] . '<br /> Budget: ' . $workspace[price] . '<br /><br /></li>';
$totalBudget = $totalBudget + $workspace[price_in_cents];
}
echo '</ul>';
setlocale(LC_MONETARY, 'en_US');
echo '<br /><br /><h3> Total Project Budgets: ' . money_format('%i', $totalBudget/100) . '</h3>';
?>
|
Markdown
|
UTF-8
| 1,572 | 3.015625 | 3 |
[] |
no_license
|
# Visual_tracking-based-on-CNN-and-RNN
### Motivation:
The key challenge in building a neural net is requirement of humongous training data. The next hindrance to deploy the model in embedded AI device is number of computaions,
thus demanding a lighter model. We hypothesized that training Re3 visual tracker with less number of videos should also provide an appreciable level of tracking. Our
hypothesis is backed up by the core idea of Re3, structured to learn tracking through feature level differences between consecutive frames of training videos.
### Model:
The training dataset for our project is 15 videos from imagenet video dataset. The model is implemented in Pytorch framework against the author\`s implementation in tensorflow.
Since Pytorch is easy for debugging and maintenance, this framework was chosen.
### Prerequisites:
1. python3.6
2. PyTorch
3. OpenCV 3.4.2 or greater
4. Numpy 1.16 or greater
### Result:
Model\`s behaviour of tracking animals can be seen below.

However, the model could not track a hand thus failing to generalize. Our training videos consist of animals like horse, panda,
etc.., as object of interest. It could be the reason behind model\`s behaviour on animal videos. Also, the CNN model was frozen during training.
### Future Scope:
1) Unfreeze the CNN model and see its impact on generalization.
2) Analyze the behaviour of the model with lighter CNN nets like resnet.
### Authors:
* **Goushika Janani** -[GoushikaJanani](https://github.com/GoushikaJanani)
* **Bharath C Renjith** -[cr-bharath](https://github.com/cr-bharath)
|
C++
|
UTF-8
| 550 | 2.953125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
using namespace std;
static int a[101][101] = {0};
int uniquePaths(int m, int n) {
//m为列,n为行
if(m<=0 || n<=0) return 0;
else if(m==1||n==1) return 1;
else if(m==2 && n==2) return 2;
else if((m==3 && n==2) || (m==2 && n==3)) return 3;
if(a[m][n]>0) return a[m][n];
a[m-1][n] = uniquePaths(m-1,n);
a[m][n-1] = uniquePaths(m,n-1);
a[m][n] = a[m-1][n]+a[m][n-1];
return a[m][n];
}
int main(){
cout<<uniquePaths(3,2)<<endl;
system("pause");
return 0;
}
|
Java
|
UTF-8
| 1,486 | 2.265625 | 2 |
[] |
no_license
|
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
System.out.println(LocalDateTime.now());
LoginEngine<User> userLoginEngine = new LoginEngine<>();
LoginEngine<Admin> adminLoginEngine = new LoginEngine<>();
UserCreationPanel userCreationPanel = new UserCreationPanel(userLoginEngine);
AdminCreationPanel adminCreationPanel = new AdminCreationPanel(adminLoginEngine);
LoginPanel userLoginPanel = new LoginPanel(userLoginEngine);
LoginPanel adminLoginPanel = new LoginPanel(adminLoginEngine);
loadTestAccounts(userCreationPanel);
loadTestAccounts(adminCreationPanel);
userLoginEngine.showAccounts();
adminLoginEngine.showAccounts();
// Admin admin = adminLoginPanel.login();
// System.out.println(admin);
AuctionEngine.loadTestCategories();
CategoriesBrowser.viewCategories(CategoriesBrowser.byName());
}
public static void loadTestAccounts(AccountCreationPanel creationPanel) {
creationPanel.createAccount("qwe@o2.pl", "Zaq12wsx");
creationPanel.createAccount("qwe@o2.pl", "Zaq12wsx");
creationPanel.createAccount("asd@o2.pl", "Zaq12wsx");
creationPanel.createAccount("zxc@o2.pl", "Zaq12wsx");
creationPanel.createAccount("wer@o2.pl", "Zaq12wsx");
}
}
|
Java
|
UTF-8
| 8,642 | 2.328125 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dipit_game;
import dipit_game.GameWindowJFrame;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import ExpandedGame.ExpandedGame_OnKeyPressedImpl;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xeustechnologies.jcl.JarClassLoader;
import org.xeustechnologies.jcl.JclObjectFactory;
import org.xeustechnologies.jcl.proxy.CglibProxyProvider;
import org.xeustechnologies.jcl.proxy.ProxyProviderFactory;
/**
*
* @author Arch
*/
public class DIPIT_GAME_Main {
public static final String DIPITPATH = "C:/Users/Arch/Documents/NetBeansProjects/DIPIT_GAME/build/classes";
public static World_DIPIT TheWorld;
public static PlayerBase ThePlayer;
public static GameWindowJFrame GameWindow;
static int sizex = 4;
static int sizey = 4;
public static List<String> ConsoleOuts = new ArrayList<>();
private static final List<dipit_game.events.PostWorldGenInterface> postWorldGen_listeners = new ArrayList<>();
private static List<dipit_game.events.OnKeyPressedInterface> OnKeyPressed_Listeners = new ArrayList<>();
public static void add_postWorldGen_Listener(dipit_game.events.PostWorldGenInterface toAdd) {
postWorldGen_listeners.add(toAdd);
}
public static void add_OnKeyPressed_Listener(dipit_game.events.OnKeyPressedInterface toAdd) {
OnKeyPressed_Listeners.add(toAdd);
}
public static void OnKeyPressed(java.awt.event.KeyEvent evt) {
OnKeyPressed_Listeners.stream().forEach((hl) -> {
//System.out.println(("hl(null) : " + (hl == null)));
hl.OnKeyPressed(evt);
});
}
public static void main(String[] args) {
URL main = dipit_game.DIPIT_GAME_Main.class.getResource("dipit_game.DIPIT_GAME_Main.class");
if (!"file".equalsIgnoreCase(main.getProtocol())) {
throw new IllegalStateException("Main class is not stored in a file.");
}
File path = new File(main.getPath());
System.out.println("Classpath? : " + (path.toString()));
//
LoadMods();
TheWorld = new World_DIPIT(sizex, sizey);
TheWorld.AddSolidTag("W");
// TODO code application logic here
for (int y = 0; y < sizey; y++) {
for (int x = 0; x < sizex; x++) {
TileBase aNewTile = new TileBase(x, y);
aNewTile.SetRenderCharacter("+");
TheWorld.AddTile(aNewTile);
}
}
postWorldGen_listeners.stream().forEach((hl) -> {
//System.out.println(("hl(null) : " + (hl == null)));
hl.ModifyWorldGen(TheWorld);
});
ThePlayer = new PlayerBase(0, 0, TheWorld);
GameWindow = new dipit_game.GameWindowJFrame(TheWorld, ThePlayer);
GameWindow.setVisible(true);
Iterator<String> ConsoleIterator;
ConsoleIterator = ConsoleOuts.iterator();
String output = "";
while (ConsoleIterator.hasNext()) {
output = output + "\n" + ConsoleIterator.next();
}
GameWindow.ConsoleOut.setText(output);
Debug_PrintWorldAsString();
}
public static void Debug_PrintWorldAsString() {
String print_line = "";
for (int y = 0; y < sizey; y++) {
print_line += "\n";
for (int x = 0; x < sizey; x++) {
if (ThePlayer.GetPositionX() == x && ThePlayer.GetPositionY() == y) {
print_line += "[" + ThePlayer.GetRenderCharacter() + "]";
} else {
print_line += "[" + TheWorld.GetTile(TheWorld.GetTileAtPosition(x, y)).GetRenderCharacter() + "]";
}
}
}
System.out.println(print_line);
}
private static void LoadMods() {
String referencedModlistString = "C:\\Users\\Arch\\Documents\\NetBeansProjects\\referenced" + "/modlist.txt";
String BaseModString = "C:\\Users\\Arch\\Documents\\NetBeansProjects\\referenced";
ConsoleOuts.add(referencedModlistString);
List<String> ModsToLoad = new ArrayList<>();
try {
FileReader MyReader = new FileReader(referencedModlistString);
ModsToLoad.addAll(GetModsToLoad(MyReader));
} catch (FileNotFoundException ex) {
Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, null, ex);
ConsoleOuts.add(ex.getMessage());
} catch (IOException ex) {
Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, null, ex);
}
//ConsoleOuts.addAll(MyDebugOut);
JarClassLoader jcl = new JarClassLoader();
jcl.add("ExpandedGame/");
ProxyProviderFactory.setDefaultProxyProvider(new CglibProxyProvider());
//Create a factory of castable objects/proxies
JclObjectFactory factory = JclObjectFactory.getInstance(true);
//Create and cast object of loaded class
dipit_game.DipitModBase mi = (dipit_game.DipitModBase) factory.create(jcl, "ExpandedGame.ExpandedMain");
//Object obj = factory.create(jcl, "ExpandedGame.ExpandedMain");
for (String str : ModsToLoad) {
jcl.add(BaseModString + "\\" + str);
ConsoleOuts.add(BaseModString + "\\" + str);
//factory.create(jcl, BaseModString + "\\ModLibrary.jar");
ConsoleOuts.add(">Attempting to ClassLoad [" + str + "] \n Suceeded = " + (LoadMod(BaseModString + "\\" + str)));
}
}
private static List<String> GetModsToLoad(FileReader MyReader) throws IOException {
String ModPathBuild = "";
List<String> ModsList = new ArrayList<>();
char[] readout = new char[1024];
MyReader.read(readout);
for (char c : readout) {
//System.out.println("> " + java.lang.Character.toString(c));
// System.out.println("=* " + (c == '*') );
if (c == ';') {
ConsoleOuts.add("Adding Build >" + ModPathBuild.trim());
ModsList.add(ModPathBuild.trim());
ModPathBuild = "";
} else {
ModPathBuild = ModPathBuild + java.lang.Character.toString(c);
}
}
return ModsList;
}
/**
* Loads the Mod at Binary String point [BinaryModName]. Throws exceptions,
* and continues to run the application if the mod is unable to be loaded
* for whatever reason.
*
* @param BinaryModName the Binary String name of the, [ex. MyMod.ModClass]
* .
* @return [boolean] true if the mod was loaded successfully, false if it
* failed for whatever reason.
*/
private static boolean LoadMod(String BinaryModName) {
Class<?> ModClass = null;
Method method = null;
try {
Class<?> ModClass_ = ClassLoader.getSystemClassLoader().loadClass(BinaryModName);
ModClass = ModClass_;
} catch (ClassNotFoundException ex) {
Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, "Inable to find Mod @" + BinaryModName, ex);
}
if (ModClass != null) {
//Get InitMod Method
try {
Method method_ = ModClass.getMethod("InitMod");
method = method_;
} catch (NoSuchMethodException ex) {
Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.CONFIG, "Mod @" + BinaryModName + " has not specified a [InitMod] Method!", ex);
} catch (SecurityException ex) {
Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.CONFIG, null, ex);
}
//Get Init Mod
try {
method.invoke(null, null);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
return (ModClass != null);
}
}
|
Python
|
UTF-8
| 518 | 4.5 | 4 |
[
"MIT"
] |
permissive
|
'''Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma
lista única que mantenha separados os valores pares e ímpares. No final, mostre os valores
pares e ímpares em ordem crescente'''
valores = [[], []]
n = 0
for i in range(1, 8):
n = int(input(f'Digite o valor {i}: '))
if n % 2 == 0:
valores[0].append(n)
else:
valores[1].append(n)
valores[0].sort()
valores[1].sort()
print(f'Valores pares {valores[0]}')
print(f'Valores impares {valores[1]}')
|
Java
|
UTF-8
| 5,135 | 2.21875 | 2 |
[] |
no_license
|
package milu.gui.ctrl.schema;
import java.util.ResourceBundle;
import java.sql.SQLException;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.Node;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.geometry.Orientation;
import milu.db.MyDBAbstract;
import milu.gui.view.DBView;
import milu.main.MainController;
import milu.tool.MyGUITool;
import milu.gui.ctrl.common.inf.ChangeLangInterface;
import milu.gui.ctrl.common.inf.FocusInterface;
import milu.gui.ctrl.schema.handle.SelectedItemHandlerAbstract;
import milu.gui.ctrl.schema.handle.SelectedItemHandlerFactory;
public class DBSchemaTab extends Tab
implements
FocusInterface,
GetDataInterface,
ChangeLangInterface
{
private DBView dbView = null;
// upper pane on SplitPane
private AnchorPane upperPane = new AnchorPane();
private SchemaTreeView schemaTreeView = null;
private TabPane tabPane = null;
public DBSchemaTab( DBView dbView )
{
super();
this.dbView = dbView;
this.schemaTreeView = new SchemaTreeView( this.dbView, this );
this.tabPane = new TabPane();
// no tab text & dragging doesn't work well.
// -----------------------------------------------------
// Enable tag dragging
//DraggingTabPaneSupport dragSupport = new DraggingTabPaneSupport();
//dragSupport.addSupport( this.tabPane );
this.upperPane.getChildren().add( this.schemaTreeView );
this.schemaTreeView.init();
AnchorPane.setTopAnchor( this.schemaTreeView, 0.0 );
AnchorPane.setBottomAnchor( this.schemaTreeView, 0.0 );
AnchorPane.setLeftAnchor( this.schemaTreeView, 0.0 );
AnchorPane.setRightAnchor( this.schemaTreeView, 0.0 );
SplitPane splitPane = new SplitPane();
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.getItems().addAll( this.upperPane, this.tabPane );
splitPane.setDividerPositions( 0.5f, 0.5f );
BorderPane brdPane = new BorderPane();
brdPane.setCenter( splitPane );
this.setContent( brdPane );
// set icon on Tab
this.setGraphic( MyGUITool.createImageView( 16, 16, this.dbView.getMainController().getImage("file:resources/images/schema.png") ) );
this.setAction();
this.changeLang();
this.getDataNoRefresh( null );
}
private void setAction()
{
this.selectedProperty().addListener
(
(obs,oldval,newVal)->
{
if ( newVal == false )
{
return;
}
this.setFocus();
}
);
}
/**
* set Focus on TreeView
*/
@Override
public void setFocus()
{
// https://sites.google.com/site/63rabbits3/javafx2/jfx2coding/dialogbox
// https://stackoverflow.com/questions/20049452/javafx-focusing-textfield-programmatically
// call after "new Scene"
Platform.runLater( ()->{ this.schemaTreeView.requestFocus(); System.out.println( "schemaTreeView focused."); } );
}
// GetDataInterface
@Override
public void getDataNoRefresh( Event event )
{
this.getSchemaData( event, SelectedItemHandlerAbstract.REFRESH_TYPE.NO_REFRESH );
}
// GetDataInterface
@Override
public void getDataWithRefresh( Event event )
{
this.getSchemaData( event, SelectedItemHandlerAbstract.REFRESH_TYPE.WITH_REFRESH );
}
private void getSchemaData( Event event, SelectedItemHandlerAbstract.REFRESH_TYPE refreshType )
{
MyDBAbstract myDBAbs = this.dbView.getMyDBAbstract();
try
{
SelectedItemHandlerAbstract handleAbs =
SelectedItemHandlerFactory.getInstance
(
this.schemaTreeView,
this.tabPane,
this.dbView,
myDBAbs,
refreshType
);
if ( handleAbs != null )
{
handleAbs.exec();
}
}
catch ( UnsupportedOperationException uoEx )
{
MyGUITool.showException( this.dbView.getMainController(), "conf.lang.gui.common.MyAlert", "TITLE_UNSUPPORT_ERROR", uoEx );
}
catch ( SQLException sqlEx )
{
MyGUITool.showException( this.dbView.getMainController(), "conf.lang.gui.common.MyAlert", "TITLE_EXEC_QUERY_ERROR", sqlEx );
}
catch ( Exception ex )
{
MyGUITool.showException( this.dbView.getMainController(), "conf.lang.gui.common.MyAlert", "TITLE_MISC_ERROR", ex );
}
}
/**************************************************
* Override from ChangeLangInterface
**************************************************
*/
@Override
public void changeLang()
{
MainController mainCtrl = this.dbView.getMainController();
ResourceBundle langRB = mainCtrl.getLangResource("conf.lang.gui.ctrl.schema.DBSchemaTab");
// Tab Title
Node tabGraphic = this.getGraphic();
if ( tabGraphic instanceof Label )
{
((Label)tabGraphic).setText( langRB.getString("TITLE_TAB") );
}
else
{
this.setText( langRB.getString("TITLE_TAB") );
}
this.schemaTreeView.changeLang();
this.schemaTreeView.refresh();
}
}
|
TypeScript
|
UTF-8
| 3,299 | 2.953125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
import * as cormo from 'cormo';
export function Model(options: { connection?: cormo.Connection; name?: string; description?: string } = {}) {
const c = cormo.Model({ connection: options.connection, name: options.name, description: options.description });
return (ctor: typeof cormo.BaseModel) => {
c(ctor);
};
}
interface ColumnBasicOptions {
required?: boolean;
graphql_required?: boolean;
unique?: boolean;
name?: string;
description?: string;
default_value?: string | number | (() => string | number);
}
export function Column(
options:
| ({ enum: any } & ColumnBasicOptions)
| ({ type: cormo.types.ColumnType | cormo.types.ColumnType[] } & ColumnBasicOptions),
): PropertyDecorator;
export function Column(
options: {
enum?: any;
type?: cormo.types.ColumnType | cormo.types.ColumnType[];
} & ColumnBasicOptions,
): PropertyDecorator {
let cormo_type: cormo.types.ColumnType | cormo.types.ColumnType[];
if (options.enum) {
cormo_type = cormo.types.Integer;
} else {
cormo_type = options.type!;
}
const c = cormo.Column({
default_value: options.default_value,
name: options.name,
required: options.required,
type: cormo_type,
description: options.description,
unique: options.unique,
});
return (target: object, propertyKey: string | symbol) => {
c(target, propertyKey);
};
}
interface ObjectColumnOptions {
type: any;
required?: boolean;
description?: string;
}
export function ObjectColumn(options: ObjectColumnOptions): PropertyDecorator {
const c = cormo.ObjectColumn(options.type);
return (target: object, propertyKey: string | symbol) => {
c(target, propertyKey);
};
}
interface HasManyBasicOptions {
type?: string;
foreign_key?: string;
integrity?: 'ignore' | 'nullify' | 'restrict' | 'delete';
description?: string;
}
export function HasMany(options: HasManyBasicOptions) {
const c_options = {
foreign_key: options.foreign_key,
integrity: options.integrity,
type: options.type,
};
const c = cormo.HasMany(c_options);
return (target: cormo.BaseModel, propertyKey: string) => {
c(target, propertyKey);
};
}
interface HasOneBasicOptions {
type?: string;
foreign_key?: string;
integrity?: 'ignore' | 'nullify' | 'restrict' | 'delete';
description?: string;
}
export function HasOne(options: HasOneBasicOptions) {
const c_options = {
foreign_key: options.foreign_key,
integrity: options.integrity,
type: options.type,
};
const c = cormo.HasOne(c_options);
return (target: cormo.BaseModel, propertyKey: string) => {
c(target, propertyKey);
};
}
interface BelongsToBasicOptions {
type?: string;
required?: boolean;
foreign_key?: string;
description?: string;
}
export function BelongsTo(options: BelongsToBasicOptions) {
const c_options = {
foreign_key: options.foreign_key,
required: options.required,
type: options.type,
};
const c = cormo.BelongsTo(c_options);
return (target: cormo.BaseModel, propertyKey: string) => {
c(target, propertyKey);
};
}
export function Index(columns: { [column: string]: 1 | -1 }, options?: { name?: string; unique?: boolean }) {
const c = cormo.Index(columns, options);
return (ctor: typeof cormo.BaseModel) => {
c(ctor);
};
}
|
Shell
|
UTF-8
| 1,078 | 3.1875 | 3 |
[] |
no_license
|
#!/bin/bash
open ~/Databases/Hackage.sparsebundle
sleep 5
if ! quickping hackage.haskell.org; then
exit 1
fi
simple-mirror --from="http://hackage.haskell.org" --to="/Volumes/Hackage"
index=/Volumes/Hackage/00-index.tar.gz
if [[ -f $index ]]; then
echo Installing package database from local mirror...
size=$(gzip -q -l $index | awk '{print $2}')
else
size=0
fi
echo Downloading package database from hackage.haskell.org...
mkdir -p ~/.cabal/packages/hackage.haskell.org
curl -s -o - http://hackage.haskell.org/packages/index.tar.gz \
| gzip -dc | pv \
> ~/.cabal/packages/hackage.haskell.org/00-index.tar
if [[ -f $index ]]; then
echo Installing package database from local mirror...
mkdir -p ~/.cabal/packages/mirror
gzip -dc $index | pv -s $size \
> ~/.cabal/packages/mirror/00-index.tar
fi
# sleep 5
#
# cd /Volumes/Hackage
#
# export PATH=$PATH:/usr/local/tools/hackage-server/cabal-dev/bin
#
# hackage-server run --port=9010 &
#
# sleep 300
# hackage-mirror -v --continuous mirror.cfg
|
PHP
|
UTF-8
| 786 | 2.53125 | 3 |
[] |
no_license
|
<?php
/* Service class */
namespace AppBundle\Util;
use Doctrine\ORM\Mapping as ORM;
class Utility{
const DATE_FORMAT_DATE = 'yyyy-MM-dd';
const DATE_FORMAT_DATETIME = 'yyyy-MM-dd HH:mm:ss';
const FIELD_STYLE_SMALL = 'width:250px';
const FIELD_STYLE_MEDIUM = 'width:500px';
public function filterByName($queryBuilder, $alias, $field, $value){
if(!$value['value']){
return;
}
$queryBuilder->andWhere($alias . '.name' . ' = ' . ':name' )->setParameter('name' , $value['value']->getName());
return true;
}
public function filterByUserId($queryBuilder, $alias, $field, $value){
if(!$value['value']){
return;
}
$queryBuilder->andWhere($alias . '.user_id' . ' = ' . ':user_id' )->setParameter('user_id' , $value['value']->getId());
return true;
}
}
|
Python
|
UTF-8
| 1,445 | 3.203125 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Given a directory path, search all files in the path for a given text string
within the 'word/document.xml' section of a MSWord .dotm file.
"""
__author__ = "mprodhan/yabamov/madarp"
import os
import argparse
from zipfile import ZipFile
def create_parser():
parser = argparse.ArgumentParser(description="search for a particular substring within dotm files")
parser.add_argument("--dir", default=".", help="specify the directory to search into ")
parser.add_argument('text', help="specify the text that is being searched for ")
return parser
def scan_directory(dir_name, search_text):
for root, _, files in os.walk(dir_name):
for file in files:
if file.endswith(".dotm"):
dot_m = ZipFile(os.path.join(root, file))
content = dot_m.read('word/document.xml').decode('utf-8')
if search_file(content, search_text):
print('Match found in file./dotm_file/' + file)
print(search_text)
def search_file(text, search_text):
for line in text.split('\n'):
index = line.find(search_text)
if index >= 0:
print(line[index-40:index+40])
return True
return False
def main():
parser = create_parser()
args = parser.parse_args()
print(args)
scan_directory(args.dir, args.text)
if __name__ == '__main__':
main()
|
Markdown
|
UTF-8
| 2,317 | 2.828125 | 3 |
[] |
no_license
|
# [Gulp-imagemin](https://www.npmjs.com/package/gulp-imagemin) + [Imagemin-pngquant](https://www.npmjs.com/package/imagemin-pngquant) plugins
## Описание
Плагины для оптимизации изображений
## Install
`npm install --save-dev gulp-imagemin`
`npm install --save-dev imagemin-pngquant`
## Example
***gulp-imagemin***
```js
const gulp = require('gulp');
const imagemin = require('gulp-imagemin');
gulp.task('default', () =>
gulp.src('src/images/*')
.pipe(imagemin())
.pipe(gulp.dest('dist/images'))
);
```
***imgmin-pngquant***
```js
const imagemin = require('imagemin');
const imageminPngquant = require('imagemin-pngquant');
imagemin(['images/*.png'], 'build/images', {use: [imageminPngquant()]}).then(() => {
console.log('Images optimized');
});
```
---
## Общий пример использования + plugin gulp-cache
Без использования gulp-cache
```js
var imagemin = require('gulp-imagemin'), // Подключаем библиотеку для работы с изображениями
pngquant = require('imagemin-pngquant'); // Подключаем библиотеку для работы с png
gulp.task('img', function() {
return gulp.src('app/img/**/*') // Берем все изображения из app
.pipe(imagemin({ // Сжимаем их с наилучшими настройками
interlaced: true,
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest('dist/img')); // Выгружаем на продакшен
});
```
Вместе с gulp-cache :
```js
var cache = require('gulp-cache'); // Подключаем библиотеку кеширования
gulp.task('img', function() {
return gulp.src('app/img/**/*') // Берем все изображения из app
.pipe(cache(imagemin({ // Сжимаем их с наилучшими настройками с учетом кеширования
interlaced: true,
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
})))
.pipe(gulp.dest('dist/img')); // Выгружаем на продакшен
});
```
|
Python
|
UTF-8
| 4,600 | 2.796875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
"""Auxiliary functions."""
try:
import cPickle as pickle
except ImportError:
import pickle
import re
import os
from SPARQLWrapper import SPARQLWrapper, JSON
YAGO_ENPOINT_URL = "https://linkeddata1.calcul.u-psud.fr/sparql"
RESOURCE_PREFIX = 'http://yago-knowledge.org/resource/'
def safe_mkdir(dir_name):
"""Checks if a directory exists, and if it doesn't, creates one."""
try:
os.stat(dir_name)
except OSError:
os.mkdir(dir_name)
def pickle_to_file(object_, filename):
"""Abstraction to pickle object with the same protocol always."""
with open(filename, 'wb') as file_:
pickle.dump(object_, file_, pickle.HIGHEST_PROTOCOL)
def pickle_from_file(filename):
"""Abstraction to read pickle file with the same protocol always."""
with open(filename, 'rb') as file_:
return pickle.load(file_)
def get_input_files(input_dirpath, pattern):
"""Returns the names of the files in input_dirpath that matches pattern."""
all_files = os.listdir(input_dirpath)
for filename in all_files:
if re.match(pattern, filename) and os.path.isfile(os.path.join(
input_dirpath, filename)):
yield os.path.join(input_dirpath, filename)
# TODO(mili): Is is better a pandas DataFrame
def query_sparql(query, endpoint):
"""Run a query again an SPARQL endpoint.
Returns:
A double list with only the values of each requested variable in
the query. The first row in the result contains the name of the
variables.
"""
sparql = SPARQLWrapper(endpoint)
sparql.setReturnFormat(JSON)
sparql.setQuery(query)
response = sparql.query().convert()
bindings = response['results']['bindings']
variables = response['head']['vars']
result = [variables]
for binding in bindings:
row = []
for variable in variables:
row.append(binding[variable]['value'])
result.append(row)
return result
def download_category(category_name, limit):
"""Downloads a single category and stores result in directory_name."""
query = """SELECT DISTINCT ?entity ?wikiPage WHERE {
?entity rdf:type <http://yago-knowledge.org/resource/%s> .
?entity <http://yago-knowledge.org/resource/hasWikipediaUrl> ?wikiPage
} LIMIT %s""" % (category_name, limit)
return query_sparql(query, YAGO_ENPOINT_URL)
def get_categories_from_file(category_filename):
"""Read categories and ofsets"""
with open(category_filename, 'r') as input_file:
lines = input_file.read().split('\n')
return lines
def query_subclasses(category_name, populated=True):
query = """SELECT DISTINCT ?subCategory WHERE {
?subCategory rdfs:subClassOf <%s%s> .
""" % (RESOURCE_PREFIX, category_name)
if populated:
query += """
?entity rdf:type ?subCategory .
}"""
else:
query += '}'
return query_sparql(query, YAGO_ENPOINT_URL)[1:]
def add_subcategories(category_name, graph, ancestors=[]):
"""Updates the children categories and level of category name.
"""
def add_ancestor(category_name):
graph.add_edge(ancestors[-1], category_name, path_len=len(ancestors))
response = query_subclasses(category_name)
for result in response:
child_category = result[0].replace(RESOURCE_PREFIX, '')
if 'wikicat' in child_category:
continue
add_subcategories(child_category, graph,
ancestors=ancestors + [category_name])
if category_name not in graph:
if len(ancestors):
add_ancestor(category_name)
else:
graph.add_node(category_name)
return
# We have seen the node before
if len(graph.predecessors(category_name)) == 0: # There is no ancestor yet.
if len(ancestors): # it's not the first recursive call
add_ancestor(category_name)
else: # There is a previous ancestor
added = False
for prev_ancestor in graph.predecessors(category_name):
if prev_ancestor in ancestors:
added = True
if len(ancestors) > graph.get_edge_data(
prev_ancestor, category_name)['path_len']:
# The current ancestor has a longer path
graph.remove_edge(prev_ancestor, category_name)
add_ancestor(category_name)
# The new ancestor doesn't overlap with any previous ancestor's path.
if not added and len(ancestors):
add_ancestor(category_name)
|
C++
|
UTF-8
| 2,699 | 2.65625 | 3 |
[] |
no_license
|
/*
ID: j316chuck
PROG: milk3
LANG: C++
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#include <ctime>
#include <climits>
#include <cstdlib>
const double Pi=acos(-1.0);
typedef long long LL;
#define Set(a, s) memset(a, s, sizeof (a))
#define Rd(r) freopen(r, "r", stdin)
#define Wt(w) freopen(w, "w", stdout)
using namespace std;
int A, B, C;
int amountA,amountB, amountC;
bool possible[21];
int counter =0;
class three
{
public:
int first,second, third;
};
three paths[10000];
bool checkcycle()
{
for(int i =0; i < counter; i++)
{
if(paths[i].first==amountA&&paths[i].second==amountB&&paths[i].third==amountC)
return false;
}
return true;
}
void Recursion()
{
if(amountA==0)
possible[amountC]==true;
return;
paths[counter].first=amountA;
paths[counter].second=amountB;
paths[counter].third=amountC;
if(checkcycle()==false)
return;
if(B<amountA+amountB){
amountB=B;
amountA=amountA+amountB-B;
Recursion();
}if(B>=amountA+amountB){
amountB=amountA+amountB;
amountA=0;
Recursion();
}if(C<amountC+amountA){
amountC=C;
amountA=amountA+amountC-C;
Recursion();
}if(C>=amountC+amountA){
amountC=amountC+amountA;
amountA=0;
Recursion();
}if(A<amountB+amountA){
amountA=A;
amountB=amountB+amountA-A;
Recursion();
}if(A>=amountA+amountB){
amountA=amountA+amountB;
amountB=0;
Recursion();
}if(C<amountB+amountC){
amountC=C;
amountB=amountB+amountC-C;
Recursion();
}if(C>=amountB+amountC){
amountC=amountB+amountC;
amountB=0;
Recursion();
}if(A<amountA+amountC){
amountA=A;
amountC=amountC+amountA-A;
Recursion();
}if(A>=amountA+amountC){
amountA=amountA+amountC;
amountC=0;
Recursion();
}if(B<amountB+amountC){
amountC=C;
amountB=amountB+amountC-C;
Recursion();
}if(B>=amountB+amountC){
amountB=amountB+amountC;
amountC=0;
Recursion();
}
counter++;
}
int main()
{
Rd("milk3.in");
//Wt("milk3.out");
cin>>A>>B>>C;
amountA=0;
amountB=0;
amountC=C;
Recursion();
for(int i = 0; i < C; i++)
{
if(possible[i]==true)
{
cout<<i<<endl;
}
}
}
|
Java
|
UTF-8
| 1,183 | 2.28125 | 2 |
[] |
no_license
|
package pl.skycash.zadanie_rekrutacyjne.crud_example.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import pl.skycash.zadanie_rekrutacyjne.crud_example.controller.dto.BookConvertDTO;
import pl.skycash.zadanie_rekrutacyjne.crud_example.controller.dto.BookDTO;
import pl.skycash.zadanie_rekrutacyjne.crud_example.model.Book;
import pl.skycash.zadanie_rekrutacyjne.crud_example.service.BookServiceImpl;
import java.util.List;
import java.util.Optional;
@RestController
@RequiredArgsConstructor
public class BookController {
private final BookServiceImpl bookService;
@GetMapping("/books")
public List<BookDTO> selectAllBooks(){
return BookConvertDTO.convertToDTOs(bookService.selectAllBooks());
}
@GetMapping("/books/{id}")
public Book selectBookById(@PathVariable long id){
return bookService.selectBookById(id);
}
@PostMapping("/books/add")
public Book addBook(@RequestBody Book book){
return bookService.addBook(book);
}
@DeleteMapping("/books/delete/{id}")
public void deleteBook(@PathVariable long id){
bookService.deleteBook(id);
}
}
|
C++
|
UTF-8
| 1,879 | 2.625 | 3 |
[] |
no_license
|
#include "stdafx.h"
#include "CopyFileToDir.h"
#include <fstream>
#include <string>
#include <iostream>
#include <windows.h>
//??????????????(unicode -- > ascll)
#define WCHAR_TO_CHAR(lpW_Char,lpChar) WideCharToMultiByte(CP_ACP,NULL,lpW_Char,-1,lpChar,_countof(lpChar),NULL,FALSE);
//??????????????(unicode -- > ascll)
#define CHAR_TO_WCHAR(lpChar,lpW_Char) MultiByteToWideChar(CP_ACP,NULL,lpChar,-1,lpW_Char,_countof(lpW_Char));
using namespace std;
CopyFileToDir::CopyFileToDir()
{
}
bool CopyFileToDir::ReadTXTFile_GetPath(char * PathText,char *Path)
{
//?????
ifstream in(PathText);
string filename;
string line;
//???????????
int num = 0;
if (in) // ?и????
{
while (getline(in, line)) // line?в???????е???з?
{
//???????????vector??
vecTatgetPath.push_back(line);
num++;
}
}
else // ??и????
{
cout << "no such file" << endl;
}
cout << "???????????" << num << endl;
WCHAR W_Dir[MAX_PATH];
WCHAR W_FilePath[MAX_PATH];
WCHAR W_FileName[MAX_PATH];
for (size_t i = 0; i < vecTatgetPath.size(); i++)
{
CHAR_TO_WCHAR(Path, W_Dir);
CHAR_TO_WCHAR(vecTatgetPath[i].c_str(), W_FilePath);
//??????
size_t found = vecTatgetPath[i].find_last_of("/\\");
CHAR_TO_WCHAR(vecTatgetPath[i].substr(found).c_str(), W_FileName);
lstrcat(W_Dir,W_FileName);
if (!CopyFile(W_FilePath, W_Dir, TRUE))
{
//LastError == 0x50??????????
if (GetLastError() == 0x50)
{
printf("???%ls??????????????y/n??", W_Dir);
if ('y' == getchar())
{
//??????????????????????
if (!CopyFile(W_FilePath, W_Dir, FALSE))
{
printf("???????????%d\n", GetLastError());
}
else
{
printf("????????\n");
}
}
else
{
return 0;
}
}
}
else
{
printf("%ls ????????\n", W_FileName);
}
}
return false;
}
CopyFileToDir::~CopyFileToDir()
{
}
|
PHP
|
UTF-8
| 1,923 | 2.671875 | 3 |
[] |
no_license
|
<?php
namespace App\Controllers;
use \Core\View;
use \App\Models\User;
use \App\Flash;
/**
* Signup controller
*
* PHP version 7.2
*/
class Signup extends \Core\Controller
{
/**
* Show the signup page
*
* @return void
*/
public function newAction()
{
View::renderTemplate('Signup/new.html');
}
/**
* Sign up a new user
*
* @return void
*/
public function createAction()
{
$user = new User($_POST);
$everything_OK = true;
$e_rules = "";
$e_bot = "";
$rules = isset($_POST['rules']);
if (!$rules){
$e_rules = "Potwierdź akceptację regulaminu!";
$everything_OK = false;
}
//checking reCAPTCHA
$secret = '6LfD_7wZAAAAAPmDQvgE9QJjiwT__HkfmsE88in1';
$check = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$answer = json_decode($check);
if($answer->success==false){
//$everything_OK = false;
$e_bot = "Potwierdź, że nie jesteś botem!";
}
if (($everything_OK == true) && $user->save()) {
$user_temporary = $user->authenticate($user->email, $user->password);
$user->addDefaultCategoriesToDB($user_temporary->id);
$this->redirect('/signup/success');
} else {
Flash::addMessage('Rejestracja nie powiodła się.', Flash::WARNING);
View::renderTemplate('Signup/new.html', [
'user' => $user,
'e_rules' => $e_rules,
'e_bot' => $e_bot,
'rules' => $rules
]);
}
}
/**
* Show the signup success page
*
* @return void
*/
public function successAction()
{
View::renderTemplate('Signup/success.html');
}
}
|
JavaScript
|
UTF-8
| 856 | 2.9375 | 3 |
[] |
no_license
|
function piller(){
this.pos = {}
this.height = floor(random(100, 250))
this.width = 60
this.pos.x = 600
this.pos.y = 400-this.height
this.bottom = this.pos.y
this.space = 150
this.top = this.pos.y - this.space
this.speed = 6
this.pillerbottomImage = pillerbottomImage
this.pillertopImage = pillertopImage
this.update = function(){
this.pos.x -= this.speed
}
this.draw = function(){
for(i = this.pos.y; i < this.pos.y + this.height;i+=3){
image(pillerbottomImage,this.pos.x, i, this.width);
}
image(pillertopImage,this.pos.x, this.pos.y, this.width);
for(i = 0; i+20 < this.top;i+=20){
image(pillerbottomImage,this.pos.x, i, this.width);
}
image(pillertopImage,this.pos.x,this.top - 20, this.width);
}
}
|
SQL
|
UTF-8
| 341 | 2.578125 | 3 |
[] |
no_license
|
CREATE TABLE IF NOT EXISTS Items (id INTEGER PRIMARY KEY AUTOINCREMENT, name CHAR);
CREATE TABLE IF NOT EXISTS Purchase (id INTEGER PRIMARY KEY AUTOINCREMENT, date CHAR, invoice CHAR, item CHAR, quantity INTEGER);
CREATE TABLE IF NOT EXISTS Sale (id INTEGER PRIMARY KEY AUTOINCREMENT, date CHAR, invoice CHAR, item CHAR, quantity INTEGER);
|
Ruby
|
UTF-8
| 189 | 3.625 | 4 |
[] |
no_license
|
def d n
sum = 0
(1..n/2+1).each {|x|
sum += x if n%x == 0
}
sum
end
puts d 284
s = 0
(1..10000).each {|x|
y = d(x)
s += x if x!=y && d(d(x))==x
}
puts s
|
Markdown
|
UTF-8
| 4,082 | 3.828125 | 4 |
[] |
no_license
|
```python
# random variables (no need to import random library)
# Solutions with variables converted to string
# Make sure you name the solution with part id at the end. e.g. 'solution1' will be solution for part 1.
solution1 = "4^2"
solution2 = "C(52-5,2) - C(52-5-4,2)"
solution3 = "C(52-5,2)"
solution4 = "(C(52-5,2) - C(52-5-4,2) + 4^2) / C(52-5,2)"
# Group all solutions into a list
solutions = [solution1, solution2, solution3, solution4]
```
In Texas Hold'Em, a standard 52-card deck is used. Each player is dealt two cards from the deck face down so that only the player that got the two cards can see them. After checking his two cards, a player places a bet. The dealer then puts 5 cards from the deck face up on the table, this is called the "board" or the "communal cards" because all players can see and use them. The board is layed down in 3 steps: first, the dealer puts 3 cards down (that is called "the flop") followed by two single cards, the first is called "the turn" and the second is called "the river". After the flop, the turn and the river each player can update their bet. The winner of the game is the person that can form the strongest 5-card hand from the 2 cards in their hand and any 3 of the 5 cards in the board. In previous homework you calculated the probability of getting each 5-card hand.
Here we are interested in something a bit more complex: what is the probability of a particular hand given the cards that are currently available to the player.
The outcome space in this kind of problem is the set of 7 cards the user has at his disposal after all 5 board cards have been dealt. The size of this space is \\\(|\\Omega| = C(52,7)\\\)
Suppose that \\\(A, B\\\) are events, i.e. subsets of \\\(\\Omega\\\). We will want to calculate conditional probabilities of the type \\\(P(A|B)\\\). Given that the probability of each set of seven cards is equal to \\\(1/C(52,7)\\\) we get that the conditional probability can be expressed as:
\\\[P(A|B) = \\frac{P(A \\cap B)}{P(B)} =
\\frac{\\frac{|A \\cap B|}{|\\Omega|}}{\\frac{|B|}{|\\Omega|}}
= \\frac{|A \\cap B|}{|B|} \\\]
Therefore the calculation of conditional probability (for finite sample spaces with uniform distribution) boils down to calculating the ratio between the sizes of two sets.
* Suppose you have been dealt "4\\\(\\heartsuit\\\), 5\\\(\\heartsuit\\\)".
* What is the conditional probability that you will get a straight given that you have been dealt these two cards, and that the flop is "2\\\(\\clubsuit\\\), 6\\\(\\spadesuit\\\), K\\\(\\diamondsuit\\\)"?
- Define \\\(B\\\) as the set {7-card hands that contain these 5 cards already revealed}.
- Define \\\(A\\\) as the set {7-card hands that contain a straight}.
The question is asking for \\\(P(A|B)\\\). According to the formula above we need to find \\\(|A\\cap B|\\\) and \\\(|B|\\\).
- In this case \\\(A \\cap B\\\) is the set {7-card hands that contain the 5 revealed cards AND contain a straight}. To get a straight, the remaining two cards (turn and river) must either be {7,8} or contain 3. We hence define two subsets within \\\(A \\cap B\\\):
- \\\(S_1\\\): {7-card hands that are in \\\(A \\cap B\\\) AND the remaining two cards are 7 and 8, regardless of order}.
\\\(|S_1|=\\\)
[_]
- \\\(S_2\\\): {7-card hands that are in \\\(A \\cap B\\\) AND its turn and river contain 3}.
\\\(|S_2| = \\\)
[_]
Because there is no overlap in these two subsets \\\(S_1 \\cap S_2 = \\emptyset\\\) and these two subsets cover all possible valid hands \\\(A \\cap B = S_1 \\cup S_2 \\\), by definition \\\(S_1\\\) and \\\(S_2\\\) form a _partition_ of \\\(A \\cap B\\\), and we have \\\(|A \\cap B| = |S_1| + |S_2|\\\).
- Computing \\\(|B|\\\) should be easy. 5 cards in the hand are already fixed, so we can choose any card as our turn and river from the rest 47 cards.
\\\(|B| = \\\)
[_]
- The conditional probability
\\\(P(A|B) = \\frac{P(A \\cap B)}{P(B)} = \\frac{|A\\cap B|}{|B|} = \\frac{|S_1|+|S_2|}{|B|}\\\) is
[_]
---
|
C++
|
UTF-8
| 1,099 | 2.84375 | 3 |
[] |
no_license
|
/*
* File: Alumno.h
* Author: alulab14
*
* Created on 6 de noviembre de 2015, 08:03 AM
*/
/*
* Nombre: Diego Alonso Guardia Ayala
* Codigo: 20125849
*/
#ifndef ALUMNO_H
#define ALUMNO_H
#include <cstdlib>
#include <cstring>
class Alumno {
public:
Alumno();
void SetCreditos(double creditos);
double GetCreditos() const;
void SetPromedio(double promedio);
double GetPromedio() const;
void SetSemFin(int semFin);
int GetSemFin() const;
void SetAnFin(int anFin);
int GetAnFin() const;
void SetSemIn(int semIn);
int GetSemIn() const;
void SetAnIn(int anIn);
int GetAnIn() const;
void SetNombre(char *);
void GetNombre(char *) const;
void SetCodigo(int codigo);
int GetCodigo() const;
void SetEspecialidad(char *);
void GetEspecialidad(char *) const;
private:
int codigo;
char nombre[50];
char especialidad[50];
int anIn; //Año de inicio
int semIn; //Semestre que inicio
int anFin; //Año de egresó
int semFin; //Semestre que egresó
double promedio;
double creditos;
};
#endif /* ALUMNO_H */
|
Java
|
UHC
| 1,125 | 3.28125 | 3 |
[] |
no_license
|
import java.util.Scanner;
public class BFmatch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("ؽƮ : ");
String s1 = sc.next();
System.out.print(" : ");
String s2 = sc.next();
int idx = bfMatch(s1,s2);
if(idx==-1)
System.out.println("ؽƮ ϴ.");
else {
int len=0;
for(int i=0; i<idx; i++)
len+=s1.substring(i, i+1).getBytes().length;
//substring(ġ1,ġ2) : ش ڿ ġ1~ġ2 ؽ ߶ ֱ
len+=s2.length();
System.out.println((idx+1)+"° ں ġ");
System.out.println("ؽƮ : "+s1);
System.out.printf(String.format(" : %%%ds\n", len), s2);
}
}
static int bfMatch(String txt, String pat) {
int pt = 0;//txtĿ
int pp = 0;//paternĿ
while(pt != txt.length() && pp != pat.length()) {
if(txt.charAt(pt)==pat.charAt(pp)) {
pt++;
pp++;
}else {
pt = pt-pp+1;
pp = 0;
}
}
if(pp==pat.length())//˻
return pt-pp;
return -1;
}
}
|
PHP
|
UTF-8
| 1,233 | 2.890625 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: salerat
* Date: 4/9/14
* Time: 3:20 PM
*/
namespace kaz;
require 'Kaz.php';
if(!empty($_POST)) {
$kaz = new Kaz($_POST['word']);
$resultArray = $kaz->getFlectiveClass();
}
$word = '';
if(!empty($_POST['word'])) {
$word=$_POST['word'];
}
echo '<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Генерация словоформ</title>
<link rel="stylesheet" href="css/styles.css">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<form method="POST">
Введите слово в именительном падеже (пример: адам) <input type="text" name="word" value="'.$word.'"><br>
<input type="submit" value="Сгенерировать">
</form>
';
if(!empty($resultArray)) {
echo '<table border="1">
<tr>
<td><b>Конфигурация слово образования</b></td>
<td><b>Форма слова</b></td>
</tr>';
foreach($resultArray as $res) {
echo '
<tr>
<td>'.$res['type'].'</td>
<td>'.$res['word'].'</td>
</tr>';
}
echo '</table>';
}
echo '
</body>
</html>
';
|
Java
|
UTF-8
| 1,051 | 3.71875 | 4 |
[] |
no_license
|
package com.test17;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
import com.student.Student;
public class Demo_StudentMassage {
/*
* 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按学生总分进行排名
* 1.创建键盘录入对象
* 2.依次录入5名学生信息学生信息,存储在TreeSet集合中
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
TreeSet<Student> ts=new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//按总分从高到低进行比较
int num=o2.getSum()-o1.getSum();
return num==0 ? 1 : num;
}
});
while(ts.size()<5) {
String str=sc.nextLine();
String[] sarr=str.split(","); //使用“,”分割
int chgrate=Integer.parseInt(sarr[1]);
int magrate=Integer.parseInt(sarr[2]);
int engrate=Integer.parseInt(sarr[3]);
ts.add(new Student(sarr[0],chgrate,magrate,engrate));
}
System.out.println(ts);
}
}
|
C
|
UTF-8
| 452 | 3.9375 | 4 |
[] |
no_license
|
//Program to check whether all digits in a number in ascending order or not
#include<stdio.h>
#include<math.h>
int main()
{
int j,n,d,h,flag=1;
printf("Enter a number:");
scanf("%d",&n);
d=floor(log10(n));
while(d>0)
{
j=n/(int)(pow(10,d));
n=n%(int)(pow(10,d));
h=n/(int)(pow(10,d-1));
if(j>h)
{
flag=0;
break;
}
d--;
}
if(flag)
printf("Ascending");
else
printf("not ascending");
return 0;
}
|
TypeScript
|
UTF-8
| 1,364 | 2.5625 | 3 |
[] |
no_license
|
import { Injectable } from '@angular/core';
@Injectable()
export class FavoritoService {
name = "_f";
private favoritos = [];
constructor() { }
listar(){
if(!this.favoritos || this.favoritos.length == 0){
let lista = localStorage.getItem(this.name);
this.favoritos = lista?JSON.parse(lista):[];
}
return this.favoritos;
}
removeFavorito(book){
if(this.isFavorito(book.id)){
if(this.favoritos){
var index = this.favoritos.findIndex(element => element.id == book.id );
if(index > -1){
this.favoritos.splice(index, 1);
}
let listaJSON = this.favoritos? JSON.stringify(this.favoritos): null;
localStorage[this.name] = listaJSON;
}
}
}
setFavorito(book){
if(!this.isFavorito(book.id)){
this.favoritos.push(book);
localStorage[this.name] = JSON.stringify(this.favoritos);
}
}
isFavorito(id :String){
let books = this.getFavorito(id);
return books != null && books.length > 0 ? true : false;
}
getFavorito(id :String){
return this.listar().filter(element => {
return element.id == id;
});
}
}
|
C++
|
UTF-8
| 931 | 2.921875 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
bool compare(const int &a, const int &b)
{
return a > b;
}
int main()
{
int T, m, n, i, j, k, cnt, index;
string temp, str;
vector<string> strarr;
vector<int> answerarr;
cin >> T;
for (i = 1; i <= T; i++) {
cin >> m >> n;
cin >> str;
cnt = m / 4;
for(j = 0; j < cnt; j++) {
str = str.substr(m - 1, 1) + str.substr(0, m - 1);
for (k = 0; k < 4; k++)
strarr.push_back(str.substr(k * cnt, cnt));
}
for (j = 0; j < strarr.size(); j++)
answerarr.push_back(strtol(strarr[j].c_str(), NULL, 16));
sort(answerarr.begin(), answerarr.end(), compare);
answerarr.erase(unique(answerarr.begin(), answerarr.end()), answerarr.end());
cout << "#" << i << " " << answerarr[n - 1] << endl;
strarr.erase(strarr.begin(), strarr.end());
answerarr.erase(answerarr.begin(), answerarr.end());
}
return 0;
}
|
Java
|
UTF-8
| 695 | 2.5625 | 3 |
[] |
no_license
|
package schedule;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MyListener implements ServletContextListener {
private ScheduledExecutorService scheduler;
@Override
public void contextInitialized(ServletContextEvent event) {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new MyTask(), 0, 120, TimeUnit.SECONDS);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println("shut down");
scheduler.shutdownNow();
}
}
|
PHP
|
UTF-8
| 1,884 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
namespace qtests\container;
use qing\facades\Container;
class AAA{
public $name='aaa';
}
class BBB{
public $name='bbb';
}
class CCC{
public $name='ccc';
public $aaa;
public $bbb;
}
/**
*
* @see app/config/main.php
* @author xiaowang <736523132@qq.com>
* @copyright Copyright (c) 2013 http://qingmvc.com
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
class Con01Test extends Base{
/**
*
*/
public function test(){
$res=Container::set('aaa',AAA::class);
$res=Container::set('bbb',BBB::class);
$res=Container::set('closure',function(){
return new BBB();
});
$res=Container::set('ccc',['class'=>CCC::class,'aaa'=>'aaa','bbb'=>'bbb']);
//
$aaa=Container::get('aaa');
$this->assertTrue(is_object($aaa) && $aaa instanceof AAA);
$bbb=Container::get('bbb');
$this->assertTrue(is_object($bbb) && $bbb instanceof BBB);
$func=Container::get('closure');
$this->assertTrue(is_object($func) && $func instanceof BBB);
//实例ccc依赖aaa&bbb
$ccc=Container::get('ccc');
$this->assertTrue(is_object($ccc) && $ccc instanceof CCC);
$this->assertTrue($ccc->aaa===$aaa && $ccc->bbb===$bbb);
//
//$con=Coms::get('container');
//dump(Container::getInstance());
}
/**
* 实例分类
*
* @see app/config/main.php
*/
public function testCat(){
$di=Container::get('M:Sites');
$this->assertTrue(is_object($di) && $di instanceof \main\model\Sites);
$di=Container::get('M:sites');
$this->assertTrue(is_object($di) && $di instanceof \main\model\Sites);
//
$di=Container::get('C:Index');
$this->assertTrue(is_object($di) && $di instanceof \main\controller\Index);
$di=Container::get('C:index');
$this->assertTrue(is_object($di) && $di instanceof \main\controller\Index);
}
}
?>
|
C++
|
UTF-8
| 388 | 2.5625 | 3 |
[] |
no_license
|
#pragma once
#include "AbstractMonster.hpp"
namespace patterns {
namespace abstract_factory {
class EasyMonster: public AbstractMonster
{
public:
virtual EasyMonster* clone() override {
return new EasyMonster();
}
virtual std::string text() const override {
return "Easy monster";
}
virtual ~EasyMonster() { }
};
} //abstract factory
} //patterns
|
C++
|
UTF-8
| 3,610 | 3.21875 | 3 |
[] |
no_license
|
#include "LCDHelper.h"
#include <Arduino.h>
#include <Adafruit_RGBLCDShield.h>
LCDHelper::LCDHelper(Adafruit_RGBLCDShield &lcd) {
this->lcd = &lcd;
this->color = VIOLET;
this->clearDisplay = true;
this->displayUntil = 0;
this->nextScrollTime = 0;
this->scrollIndex = 0;
}
void LCDHelper::printNext(
const char *row1,
const char *row2,
const int color,
const unsigned long displayUntil) {
this->displayUntil = displayUntil;
this->color = color;
// Just return if the text hasn't changed
if (strcmp(this->row1, row1) == 0 && strcmp(this->row2, row2) == 0) {
return;
}
strcpy(this->row1, row1);
strcpy(this->row2, row2);
this->clearDisplay = true;
}
void LCDHelper::printNextP(
const char *row1P,
const char *row2P,
const int color,
const unsigned long displayUntil) {
char row1[strlen_P(row1P) + 1];
char row2[strlen_P(row2P) + 1];
strcpy_P(this->row1, row1P);
strcpy_P(this->row2, row2P);
printNext(this->row1, this->row2, color, 0);
}
void LCDHelper::maybePrintNext(
const char *row1,
const char *row2,
const int color) {
if (millis() < displayUntil) {
return;
}
printNext(row1, row2, color, 0);
}
void LCDHelper::maybePrintNextP(
const char *row1P,
const char *row2P,
const int color) {
char row1[strlen_P(row1P) + 1];
char row2[strlen_P(row2P) + 1];
strcpy_P(row1, row1P);
strcpy_P(row2, row2P);
maybePrintNext(row1, row2, color);
}
void LCDHelper::maybeScrollRow(
char result[LCD_ROW_STR_LENGTH],
const char *row) {
const unsigned int rowLen = strlen(row);
// No scroll necessary, copy and return
if (rowLen < LCD_ROW_LENGTH) {
copy16(result, row);
return;
}
if (millis() >= this->nextScrollTime) {
this->nextScrollTime = millis() + LCD_SCROLL_DELAY_MS;
this->scrollIndex++;
// We've scrolled beyond all of the row's content plus the padding, so
// reset the pointer to 0.
if (this->scrollIndex >= rowLen + LCD_SCROLL_PADDING) {
this->scrollIndex = 0;
}
}
for (int i = 0; i < LCD_ROW_LENGTH; i++) {
unsigned int rowIndex = this->scrollIndex + i;
unsigned char c;
if (rowIndex >= rowLen) {
// This is the padding between the last char of the content and the
// start of the beginning of the content entering from the right of
// the screen.
if (rowIndex < rowLen + LCD_SCROLL_PADDING) {
c = ' ';
} else {
// This is the beginning of the content entering from the right
// of the screen.
c = row[rowIndex - rowLen - LCD_SCROLL_PADDING];
}
} else {
c = row[rowIndex];
}
result[i] = c;
}
result[LCD_ROW_LENGTH] = '\0';
}
void LCDHelper::copy16(
char dest[LCD_ROW_STR_LENGTH],
const char *src) {
strncpy(dest, src, LCD_ROW_LENGTH);
dest[min(LCD_ROW_LENGTH, strlen(src))] = '\0';
}
void LCDHelper::print() {
if (this->clearDisplay) {
lcd->clear();
// Restart scrolling
this->scrollIndex = -1;
clearDisplay = false;
}
char row[LCD_ROW_STR_LENGTH];
maybeScrollRow(row, this->row1);
lcd->setCursor(0, 0);
lcd->print(row);
maybeScrollRow(row, this->row2);
lcd->setCursor(0, 1);
lcd->print(row);
lcd->setBacklight(this->color);
}
void LCDHelper::screenOff() {
this->lcd->clear();
this->lcd->setBacklight(BLACK);
this->lcd->noDisplay();
}
void LCDHelper::screenOn() {
this->lcd->display();
}
|
C
|
ISO-8859-1
| 755 | 3.5 | 4 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<locale.h>
/*
10 - So conhecidas as notas de um determinado aluno em uma determinada disciplina
durante um semestre letivo: p1, p2, t1 e t2 com pesos respectivamente 3, 5, 1, e 1. So
conhecidos tambm o total de aulas desta disciplina e a quantidade de aulas que o aluno
assistiu. Elaborar um programa para calcular e exibir a mdia do aluno e a sua frequncia.
*/
main(){
setlocale(LC_ALL, "Portuguese");
float p1=3,p2=5,t1=1,t2=1,media;
int faulas,aulas=100;
printf("Informe o nmeros de aulas que voc frequentou: ");
scanf("%d", &faulas);
media=(p1+p2+t1+t2)/4;
system("cls");
printf("A frequencia do aluno de %d/100, e a mdia das notas %.2f",faulas,media);
}
|
Java
|
UTF-8
| 1,193 | 2.734375 | 3 |
[] |
no_license
|
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.ArrayList;
/**
* Write a description of class Obstacles here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Obstacles extends Actor implements ISubject
{
private ObstacleType obstacle = null;
IObserver gameLogic = null;
GameLogic gl = GameLogic.getGameLogicInstance();
public void attach(IObserver ob){
}
public void detach(IObserver ob){
gameLogic = null;
}
public void notifyObserver(){
notifyGameLogic();
}
public Obstacles(ObstacleType obstacle) {
this.obstacle = obstacle;
}
public ObstacleType getObstacle() {
return obstacle;
}
public void setObstacle(ObstacleType obstacle) {
this.obstacle = obstacle;
}
public void notifyGameLogic(){
if(this.getY() == 360 ){
System.out.println("IF--- Notify Obstacle class");
gl.update(this,"obstacle");
}
}
public void act() {
}
public void moveRight(){}
public void moveLeft(){}
}
|
Java
|
UTF-8
| 250 | 2.046875 | 2 |
[] |
no_license
|
package slug.soc.game.gameObjects.tiles.faction;
import java.awt.Color;
import slug.soc.game.gameObjects.tiles.GameTile;
public class TileVillage extends GameTile {
public TileVillage(Color color) {
super("village", color);
}
}
|
Java
|
UTF-8
| 2,393 | 3.875 | 4 |
[] |
no_license
|
package elementary_Data_Structures_Trees.BinaryTrees;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class BinaryTree {
public static int startIndex = 0;
public Node crateBinaryTree(int[] values, Node root, int nullNum) {
int value = values[startIndex++];
// nullNum means no child
if (value == nullNum) {
root = null;
} else {
root = new Node(value, null, null);
root.setLeftChild(crateBinaryTree(values, root.getLeftChild(),
nullNum));
root.setRightChild(crateBinaryTree(values, root.getRightChild(),
nullNum));
}
return root;
}
public void preOrderTraverse(Node root) {
if (!(root == null)) {
System.out.print(" " + root.getValue() + " ");
preOrderTraverse(root.getLeftChild());
preOrderTraverse(root.getRightChild());
}
}
public void inOrderTraverse(Node root) {
if (!(root == null)) {
inOrderTraverse(root.getLeftChild());
System.out.print(" " + root.getValue() + " ");
inOrderTraverse(root.getRightChild());
}
}
public void postOrderTraverse(Node root) {
if (!(root == null)) {
postOrderTraverse(root.getLeftChild());
postOrderTraverse(root.getRightChild());
System.out.print(" " + root.getValue() + " ");
}
}
public void breadthFirstSearch(Node root) {
if (!(root == null)) {
Queue<Node> bts_Queue = new LinkedList<Node>();
bts_Queue.add(root);
while (!bts_Queue.isEmpty()) {
Node currentNode = bts_Queue.poll();
System.out.print(" " + currentNode.getValue() + " ");
if (currentNode.getLeftChild() != null) {
bts_Queue.offer(currentNode.getLeftChild());
}
if (currentNode.getRightChild() != null) {
bts_Queue.offer(currentNode.getRightChild());
}
}
} else
System.out.print("Empty Tree");
}
public void depthFirstSearch(Node root) {
if (!(root == null)) {
Stack<Node> bts_Queue = new Stack<Node>();
bts_Queue.add(root);
while (!bts_Queue.isEmpty()) {
Node currentNode = bts_Queue.pop();
System.out.print(" " + currentNode.getValue() + " ");
if (currentNode.getRightChild() != null) {
bts_Queue.push(currentNode.getRightChild());
}
// left child will be read first
if (currentNode.getLeftChild() != null) {
bts_Queue.push(currentNode.getLeftChild());
}
}
} else
System.out.print("Empty Tree");
}
public void refresh() {
startIndex = 0;
}
}
|
Java
|
UTF-8
| 33,168 | 1.515625 | 2 |
[] |
no_license
|
package com.grgbanking.ct;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.grgbanking.ct.cach.DataCach;
import com.grgbanking.ct.database.Person;
import com.grgbanking.ct.database.PersonTableHelper;
import com.grgbanking.ct.entity.PdaCashboxInfo;
import com.grgbanking.ct.entity.PdaGuardManInfo;
import com.grgbanking.ct.entity.PdaLoginMessage;
import com.grgbanking.ct.entity.PdaNetInfo;
import com.grgbanking.ct.entity.PdaNetPersonInfo;
import com.grgbanking.ct.http.FileLoadUtils;
import com.grgbanking.ct.http.HttpPostUtils;
import com.grgbanking.ct.http.ResultInfo;
import com.grgbanking.ct.http.UICallBackDao;
import com.grgbanking.ct.page.CaptureActivity;
import com.grgbanking.ct.rfid.UfhData;
import com.grgbanking.ct.rfid.UfhData.UhfGetData;
@SuppressLint("NewApi")
public class DetailActivity extends Activity {
private Context context;
private EditText remarkEditView;
TextView positionTextView = null;
TextView branchNameTextView = null;
Button commitYesButton = null;
Button commitNoButton = null;
TextView detailTitleTextView = null;
Button connDeviceButton = null;
Button startDeviceButton = null;
TextView person1TextView = null;
TextView person2TextView = null;
ListView deviceListView;
SimpleAdapter listItemAdapter;
ArrayList<HashMap<String, Object>> listItem;
private int tty_speed = 57600;
private byte addr = (byte) 0xff;
private Timer timer;
private boolean Scanflag=false;
private static final int SCAN_INTERVAL = 10;
private boolean isCanceled = true;
private Handler mHandler;
private static final int MSG_UPDATE_LISTVIEW = 0;
private Map<String,Integer> data;
static HashMap<String, Object> boxesMap1 = null;//保存正确款箱map
static HashMap<String, Object> boxesMap2 = null;//保存错误款箱map
static PdaNetPersonInfo netPersonInfo = null;//保存网点人员
static PdaGuardManInfo guardManInfo = null;//保存押运人员
private String branchCode = null;
private String branchId = null;
private String imageUrl = null;// 上传成功后的图片URL
private String address;
private double latitude;
private double longitude;
private boolean uploadFlag = false;
private ProgressDialog pd = null;
private Person person = null;
private void showWaitDialog(String msg) {
if (pd == null) {
pd = new ProgressDialog(this);
}
pd.setCancelable(false);
pd.setMessage(msg);
pd.show();
}
private void hideWaitDialog() {
if (pd != null) {
pd.cancel();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.detail);
context = getApplicationContext();
remarkEditView = (EditText) findViewById(R.id.detail_remark);
commitNoButton = (Button) findViewById(R.id.detail_btn_commit_n);
branchNameTextView = (TextView) findViewById(R.id.detail_branch_name);
detailTitleTextView = (TextView) findViewById(R.id.detail_title_view);
connDeviceButton = (Button) findViewById(R.id.button1);
startDeviceButton = (Button) findViewById(R.id.Button01);
person1TextView = (TextView) findViewById(R.id.textView2);
person2TextView = (TextView) findViewById(R.id.textView_person2);
deviceListView = (ListView) findViewById(R.id.ListView_boxs);
// 生成动态数组,加入数据
listItem = new ArrayList<HashMap<String, Object>>();
// 生成适配器的Item和动态数组对应的元素
listItemAdapter = new SimpleAdapter(this,listItem,R.layout.boxes_list_item , new String[] { "list_img", "list_title"} , new int[] { R.id.list_boxes_img, R.id.list_boxes_title});
// 添加并且显示
deviceListView.setAdapter(listItemAdapter);
showWaitDialog("正在加载中,请稍后...");
loadDevices();
//启动RFID扫描功能刷新扫描款箱数据
flashInfo();
hideWaitDialog();
// 点击返回按钮操作内容
findViewById(R.id.detail_btn_back).setOnClickListener(click);
commitNoButton.setOnClickListener(click);
connDeviceButton.setOnClickListener(click);
startDeviceButton.setOnClickListener(click);
// 点击添加照片按钮操作内容
// findViewById(R.id.add_photo).setOnClickListener(click);
}
private void flashInfo () {
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(isCanceled) return;
switch (msg.what) {
case MSG_UPDATE_LISTVIEW:
// if(mode.equals(MainActivity.TABLE_6B)){
// data = UfhData.scanResult6b;
// }else {
// data = UfhData.scanResult6c;
// }
data = UfhData.scanResult6c;
// if(listItemAdapter == null){
// myAdapter = new MyAdapter(ScanMode.this, new ArrayList(data.keySet()));
// listView.setAdapter(myAdapter);
// }else{
// myAdapter.mList = new ArrayList(data.keySet());
// }
String person1 = person1TextView.getText().toString();
String person2 = person2TextView.getText().toString();
Iterator it = data.keySet().iterator();
while (it.hasNext()) {
String key = (String)it.next();
//判断是否是押运人员
if (key.indexOf(Constants.PRE_RFID_GUARD) != -1) {
if (person1.trim().equals("")) {
PdaLoginMessage plm = DataCach.getPdaLoginMessage();
if (plm != null) {
List<PdaGuardManInfo> guardManInfoList = plm.getGuardManInfoList();
if (guardManInfoList != null && guardManInfoList.size() > 0) {
for (PdaGuardManInfo info : guardManInfoList) {
if (info.getGuardManRFID().equals(key)) {
person1TextView.setText(info.getGuardManName());
guardManInfo = info;
break;
}
}
}
}
}
}
//判断是否是网点人员
else if (key.indexOf(Constants.PRE_RFID_BANKEMPLOYEE) != -1) {
if (person2.trim().equals("")) {
Intent intent = getIntent();
Bundle bundle = intent.getBundleExtra("bundle");
int count = bundle.getInt("count");
HashMap<String, Object> map = DataCach.taskMap.get(count+ "");
PdaNetInfo pni = (PdaNetInfo) map.get("data");
if (pni != null) {
List<PdaNetPersonInfo> netPersonInfoList = pni.getNetPersonInfoList();
if (netPersonInfoList != null && netPersonInfoList.size() > 0) {
for (PdaNetPersonInfo info : netPersonInfoList) {
if (info.getNetPersonRFID().equals(key)) {
person2TextView.setText(info.getNetPersonName());
netPersonInfo = info;
break;
}
}
// if (person2TextView.getText().toString().equals("")) {
// Toast.makeText(context, "该网点人员不是本网点人员", 5000).show();
// }
}
}
}
}
//判断是否是正确款箱RFID
else if (boxesMap1.get(key) != null) {
HashMap<String, Object> map = DataCach.boxesMap.get(key);
map.put("list_img", R.drawable.boxes_list_status_1);// 图像资源的ID
HashMap<String, Object> map1 = (HashMap<String, Object>) boxesMap1.get(key);
//记录该款箱是否已扫描 0:未扫描;1:已扫描
map1.put("status", "1");
}
//判断是否是错误款箱RFID
else if (boxesMap2.get(key) == null) {
PdaLoginMessage pdaLoginMessage = DataCach.getPdaLoginMessage();
Map<String, String> allPdaBoxsMap = pdaLoginMessage.getAllPdaBoxsMap();
if (allPdaBoxsMap.get(key) != null) {
HashMap<String, Object> map1 = new HashMap<String, Object>();
map1.put("list_img", R.drawable.boxes_list_status_3);// 图像资源的ID
map1.put("list_title",allPdaBoxsMap.get(key));
DataCach.boxesMap.put(key, map1);
boxesMap2.put(key, map1);
listItem.add(map1);
}
}
//判断是否正确扫描到全部款箱和交接人员,如果是自动停止扫描
if (boxesMap1 != null && boxesMap1.size() > 0) {
boolean right = true;
Iterator it2 = boxesMap1.keySet().iterator();
while (it2.hasNext()) {
String key2 = (String) it2.next();
HashMap<String, Object> map1 = (HashMap<String, Object>) boxesMap1.get(key2);
if (map1.get("status").equals("0")) {
right = false;
break;
}
}
if (boxesMap2 != null && boxesMap2.size() > 0) {
right = false;
}
//判断人员是否扫描
if (guardManInfo == null) {
right = false;
}
if (netPersonInfo == null) {
right = false;
}
if (right) {
String context = startDeviceButton.getText().toString();
if (context.equals("Stop")) {
startDevices ();
break;
}
}
}
}
// txNum.setText(String.valueOf(myAdapter.getCount()));
listItemAdapter.notifyDataSetChanged();
break;
default:
break;
}
super.handleMessage(msg);
}
};
}
private void connDevices () {
int result=UhfGetData.OpenUhf(tty_speed, addr, 4, 1, null);
if(result==0){
UhfGetData.GetUhfInfo();
Toast.makeText(context, "连接设备成功", Toast.LENGTH_LONG).show();
// mHandler.removeMessages(MSG_SHOW_PROPERTIES);
// mHandler.sendEmptyMessage(MSG_SHOW_PROPERTIES);
} else {
Toast.makeText(context, "连接设备失败,请关闭程序重新登录", Toast.LENGTH_LONG).show();
}
}
private void startDevices () {
if(!UfhData.isDeviceOpen()){
Toast.makeText(this, R.string.detail_title, Toast.LENGTH_LONG).show();
return;
}
if(timer == null){
// cdtion.setEnabled(false);
///////////声音开关初始化
UfhData.Set_sound(true);
UfhData.SoundFlag=false;
//////////
// if (myAdapter != null) {
// if(mode.equals(MainActivity.TABLE_6B)){
// UfhData.scanResult6b.clear();
// }else if(mode.equals(MainActivity.TABLE_6C)){
// UfhData.scanResult6c.clear();
// }
// myAdapter.mList.clear();
// myAdapter.notifyDataSetChanged();
// mHandler.removeMessages(MSG_UPDATE_LISTVIEW);
// mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW);
// }
isCanceled = false;
timer = new Timer();
//
timer.schedule(new TimerTask() {
@Override
public void run() {
if(Scanflag)return;
Scanflag=true;
// if(mode.equals(MainActivity.TABLE_6B)){
// Log.i("zhouxin", "------onclick-------6b");
// UfhData.read6b();
// }else if(mode.equals(MainActivity.TABLE_6C)){
// UfhData.read6c();
// }
Log.i("zhouxin", "------onclick-------6c");
UfhData.read6c();
mHandler.removeMessages(MSG_UPDATE_LISTVIEW);
mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW);
Scanflag=false;
}
}, 0, SCAN_INTERVAL);
startDeviceButton.setText("Stop");
}else{
cancelScan();
UfhData.Set_sound(false);
}
}
private void cancelScan(){
isCanceled = true;
// cdtion.setEnabled(true);
mHandler.removeMessages(MSG_UPDATE_LISTVIEW);
if(timer != null){
timer.cancel();
timer = null;
startDeviceButton.setText("Scan");
// if(mode.equals(MainActivity.TABLE_6B)){
// UfhData.scanResult6b.clear();
// }else if(mode.equals(MainActivity.TABLE_6C)){
// UfhData.scanResult6c.clear();
// }
UfhData.scanResult6c.clear();
// if (listItemAdapter != null) {
// listItem.clear();
// listItemAdapter.notifyDataSetChanged();
// }
// txNum.setText("0");
}
}
private void loadDevices () {
//加载数据要先把数据缓存清空
person1TextView.setText("");
person2TextView.setText("");
DataCach.boxesMap = null;
DataCach.boxesMap = new LinkedHashMap<String, HashMap<String, Object>>();
boxesMap1 = null;
boxesMap1 = new HashMap<String, Object>();
boxesMap2 = null;
boxesMap2 = new HashMap<String, Object>();
netPersonInfo = null;
guardManInfo = null;
listItem.removeAll(listItem);
Intent intent = getIntent();
Bundle bundle = intent.getBundleExtra("bundle");
int count = bundle.getInt("count");
if (DataCach.taskMap.get(count+ "") != null) {
HashMap<String, Object> map = DataCach.taskMap.get(count+ "");
PdaNetInfo pni = (PdaNetInfo) map.get("data");
detailTitleTextView.setText(pni.getBankName());
List<PdaCashboxInfo> cashBoxInfoList = pni.getCashBoxInfoList();
if (cashBoxInfoList != null && cashBoxInfoList.size() > 0) {
for (PdaCashboxInfo pci: cashBoxInfoList) {
HashMap<String, Object> map1 = new HashMap<String, Object>();
map1.put("list_img", R.drawable.boxes_list_status_2);// 图像资源的ID
map1.put("list_title", pci.getBoxSn());
//记录该款箱是否已扫描 0:未扫描;1:已扫描
map1.put("status", "0");
DataCach.boxesMap.put(pci.getRfidNum(), map1);
boxesMap1.put(pci.getRfidNum(), map1);
listItem.add(map1);
}
}
}
listItemAdapter.notifyDataSetChanged();
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
OnClickListener click = new OnClickListener() {
@Override
public void onClick(View arg0) {
String context = startDeviceButton.getText().toString();
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.detail_btn_back:
if (context.equals("Stop")) {
Toast.makeText(DetailActivity.this, "请先停止扫描", 3000).show();
} else {
backListPage();
}
break;
// case R.id.detail_btn_commit_y:
// doCommit("Y");
// break;
case R.id.detail_btn_commit_n:
// if (uploadFlag) {
// doCommit("N");
// } else {
// Toast.makeText(DetailActivity.this, "图片正在上传中,请稍等。", 5000)
// .show();
// }
if (context.equals("Stop")) {
Toast.makeText(DetailActivity.this, "请先停止扫描", 3000).show();
} else {
dialog();
}
break;
// case R.id.add_photo:
// doAddPhoto();
// break;
case R.id.button1:
//连接设备
connDevices();
break;
case R.id.Button01:
//启动设备
if (!context.equals("Stop")) {
loadDevices();
}
startDevices();
break;
default:
break;
}
}
};
protected void dialog() {
// 通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);
// // 设置Title的图标
// builder.setIcon(R.drawable.ic_launcher);
// 设置Title的内容
builder.setTitle("提示");
// 设置Content来显示一个信息
builder.setMessage("确定交接?");
// 设置一个PositiveButton
builder.setPositiveButton("取消", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
}
});
// 设置一个NegativeButton
builder.setNegativeButton("确认", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
showWaitDialog("正在提交数据...");
ResultInfo ri = this.getNetIncommitData();
if (ri.getCode().endsWith(ResultInfo.CODE_ERROR)) {
hideWaitDialog();
Toast.makeText(context, ri.getMessage(), 5000).show();
return;
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param", ri.getText()));
new HttpPostUtils(Constants.URL_NET_IN_COMMIT, params,new UICallBackDao() {
@Override
public void callBack(ResultInfo resultInfo) {
if (resultInfo.getCode().equals(ResultInfo.CODE_ERROR)) {
hideWaitDialog();
Toast.makeText(context, resultInfo.getMessage(), 5000).show();
} else {
hideWaitDialog();
Toast.makeText(context, resultInfo.getMessage(), 5000).show();
}
}
}).execute();
hideWaitDialog();
// 得到跳转到该Activity的Intent对象
Intent intent = getIntent();
Bundle bundle = intent.getBundleExtra("bundle");
int count = bundle.getInt("count");
if (DataCach.taskMap.get(count+ "") != null) {
HashMap<String, Object> map = DataCach.taskMap.get(count+ "");
map.put("list_img", R.drawable.task_1);// 图像资源的ID
map.put("list_worktime","已完成");
}
backListPage();
}
private ResultInfo getNetIncommitData() {
ResultInfo ri = new ResultInfo();
Map<String, String> dataMap = new HashMap<String, String>();
if (guardManInfo == null) {
ri.setCode(ResultInfo.CODE_ERROR);
ri.setMessage("请扫描押运人员");
return ri;
}
if (netPersonInfo == null) {
ri.setCode(ResultInfo.CODE_ERROR);
ri.setMessage("请扫描网点人员");
return ri;
}
if ((boxesMap1 == null || boxesMap1.size() == 0) && (boxesMap2 == null || boxesMap2.size() == 0)) {
ri.setCode(ResultInfo.CODE_ERROR);
ri.setMessage("请扫描款箱");
return ri;
}
//开始组装数据
PdaLoginMessage pdaLoginMessage = DataCach.getPdaLoginMessage();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dataMap.put("lineId", pdaLoginMessage.getLineId());
dataMap.put("scanningDate", format.format(new Date()));
dataMap.put("netPersonName", netPersonInfo.getNetPersonName());
dataMap.put("netPersonId", netPersonInfo.getNetPersonId());
dataMap.put("guardPersonName", guardManInfo.getGuardManName());
dataMap.put("guradPersonId", guardManInfo.getGuardManId());
dataMap.put("note", remarkEditView.getText().toString());
Intent intent = getIntent();
Bundle bundle = intent.getBundleExtra("bundle");
int count = bundle.getInt("count");
dataMap.put("scanningType", DataCach.netType);
HashMap<String, Object> map = DataCach.taskMap.get(count+ "");
PdaNetInfo pni = (PdaNetInfo) map.get("data");
dataMap.put("netId", pni.getBankId());
String rightRfidNums = "";
String missRfidNums = "";
String errorRfidNums = "";
if (boxesMap1 != null && boxesMap1.size() > 0) {
Iterator it = boxesMap1.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
HashMap<String, Object> map1 = (HashMap<String, Object>) boxesMap1.get(key);
if (map1.get("status").equals("1")) {
rightRfidNums += ";" + key;
} else {
missRfidNums += ";" + key;
}
}
if (rightRfidNums.length() > 0) {
rightRfidNums = rightRfidNums.substring(1);
}
if (missRfidNums.length() > 0) {
missRfidNums = missRfidNums.substring(1);
}
}
if (boxesMap2 != null && boxesMap2.size() > 0) {
Iterator it = boxesMap2.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
errorRfidNums += ";" + key;
}
if (errorRfidNums.length() > 0) {
errorRfidNums = errorRfidNums.substring(1);
}
}
dataMap.put("rightRfidNums", rightRfidNums);
dataMap.put("missRfidNums", missRfidNums);
dataMap.put("errorRfidNums", errorRfidNums);
if (rightRfidNums.length() > 0 && missRfidNums.length() == 0 && errorRfidNums.length() == 0) {
dataMap.put("scanStatus", Constants.NET_COMMIT_STATUS_RIGHT);
} else {
dataMap.put("scanStatus", Constants.NET_COMMIT_STATUS_ERROR);
}
JSONObject jsonObject = new JSONObject(dataMap);
String data = jsonObject.toString();
ri.setCode(ResultInfo.CODE_SUCCESS);
ri.setText(data);
return ri;
}
});
// // 设置一个NeutralButton
// builder.setNeutralButton("忽略", new DialogInterface.OnClickListener()
// {
// @Override
// public void onClick(DialogInterface dialog, int which)
// {
// Toast.makeText(DetailActivity.this, "neutral: " + which, Toast.LENGTH_SHORT).show();
// }
// });
// 显示出该对话框
builder.show();
}
void backListPage() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
void doCommit(String flag) {
if(address==null||"".equals(address)){
Toast.makeText(DetailActivity.this, "错误提示:无法获取您当前的地理位置,请返回重新扫描二维码。", 5000)
.show();
return;
}
showWaitDialog("正在处理中...");
String remark = remarkEditView.getText().toString();
String status = flag;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userid", person.getUser_id()));
params.add(new BasicNameValuePair("name", person.getUser_name()));
params.add(new BasicNameValuePair("branchId", branchId));
params.add(new BasicNameValuePair("remark", remark));
params.add(new BasicNameValuePair("status", status));
params.add(new BasicNameValuePair("imageUrl", imageUrl));
params.add(new BasicNameValuePair("longitude", longitude + ""));
params.add(new BasicNameValuePair("latitude", latitude + ""));
params.add(new BasicNameValuePair("address", address));
new HttpPostUtils(Constants.URL_SAVE_TASK, params, new UICallBackDao() {
@Override
public void callBack(ResultInfo resultInfo) {
hideWaitDialog();
if("1".equals(resultInfo.getCode())){
new AlertDialog.Builder(DetailActivity.this)
.setTitle("消息")
.setMessage("提交成功!")
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {// 设置确定按钮
@Override
// 处理确定按钮点击事件
public void onClick(DialogInterface dialog,
int which) {
backListPage();
}
}).show();
}else{
Toast.makeText(DetailActivity.this, resultInfo.getMessage(), 5*1000).show();
}
}
}).execute();
}
void doAddPhoto() {
final CharSequence[] items = { "相册", "拍照" };
AlertDialog dlg = new AlertDialog.Builder(DetailActivity.this)
.setTitle("选择照片")
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// 这里item是根据选择的方式, 在items数组里面定义了两种方式,拍照的下标为1所以就调用拍照方法
if (which == 1) {
takePhoto();
} else {
pickPhoto();
}
}
}).create();
dlg.show();
}
private static final int IMAGE_REQUEST_CODE = 0; // 选择本地图片
private static final int CAMERA_REQUEST_CODE = 1; // 拍照
private static final String IMAGE_FILE_NAME = "faceImage.jpg";
/**
* 拍照
*/
private void takePhoto() {
Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 判断存储卡是否可以用,可用进行存�?
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
.fromFile(new File(Environment
.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
}
startActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE);
}
/**
* 选择本地图片
*/
private void pickPhoto() {
Intent intentFromGallery = new Intent();
intentFromGallery.setType("image/*"); // 设置文件类型
intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
}
public String uri2filePath(Uri uri) {
String path = "";
if (DocumentsContract.isDocumentUri(this, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
new String[] { id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
path = cursor.getString(columnIndex);
}
cursor.close();
} else {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = this.getContentResolver().query(uri,
projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index);
}
return path;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case CAMERA_REQUEST_CODE:
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
Bitmap bitmap = compressImage(getSmallBitmap(Environment
.getExternalStorageDirectory()
+ "/"
+ IMAGE_FILE_NAME));
// addPhotoImageView.setImageBitmap(bitmap);
// uploadStatusTextView.setText("图片上传中...");
new FileLoadUtils(Constants.URL_FILE_UPLOAD, new File(
Environment.getExternalStorageDirectory()
+ "/faceImage1.jpg"), new UICallBackDao() {
@Override
public void callBack(ResultInfo resultInfo) {
if (resultInfo != null
&& "200".equals(resultInfo.getCode())) {
Toast.makeText(DetailActivity.this, "上传成功",
5000).show();
// uploadStatusTextView.setText("上传成功。");
// imageUrl = resultInfo.getMessage();
uploadFlag = true;
}
}
}).execute();
} else {
Toast.makeText(this, getString(R.string.sdcard_unfound),
Toast.LENGTH_SHORT).show();
}
break;
case IMAGE_REQUEST_CODE:
try {
String path = uri2filePath(data.getData());
Bitmap bitmap = compressImage(getSmallBitmap(path));
// addPhotoImageView.setImageBitmap(bitmap);
// uploadStatusTextView.setText("图片上传中...");
new FileLoadUtils(Constants.URL_FILE_UPLOAD,
new File(path), new UICallBackDao() {
@Override
public void callBack(ResultInfo resultInfo) {
if (resultInfo != null
&& "200".equals(resultInfo
.getCode())) {
Toast.makeText(DetailActivity.this,
"上传成功", 5000).show();
// uploadStatusTextView.setText("上传成功。");
imageUrl = resultInfo.getMessage();
uploadFlag = true;
}
}
}).execute();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
/**
* 图片压缩方法实现
*
* @param srcPath
* @return
*/
private Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
int hh = 800;// 这里设置高度为800f
int ww = 480;// 这里设置宽度为480f
// 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;// be=1表示不缩放
if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
be = newOpts.outWidth / ww;
} else if (w < h && h > hh) {// 如果高度高的话根据高度固定大小缩放
be = newOpts.outHeight / hh;
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;// 设置缩放比例
// 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
}
/**
* 质量压缩
*
* @param image
* @return
*/
private Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while (baos.toByteArray().length * 3 / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();// 重置baos即清空baos
options -= 10;// 每次都减少10
image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
try {
FileOutputStream out = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/faceImage1.jpg");
bitmap.compress(Bitmap.CompressFormat.PNG, 40, out);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
public void initLocation(final Context context,
final DetailActivity detailActivity) {
LocationClient locationClient = new LocationClient(context);
// 设置定位条件
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 是否打开GPS
option.setIsNeedAddress(true);
option.setLocationMode(LocationMode.Hight_Accuracy);
option.setScanSpan(0);// 设置定时定位的时间间隔。单位毫秒
option.setAddrType("all");
option.setCoorType("bd09ll");
locationClient.setLocOption(option);
// 注册位置监听器
locationClient.registerLocationListener(new BDLocationListener() {
@Override
public void onReceiveLocation(BDLocation location) {
// gpsPositionTextView = (TextView) detailActivity
// .findViewById(R.id.gps_position);
// gpsPositionTextView.setText("我的位置:" + location.getAddrStr());
address = location.getAddrStr();
latitude = location.getLatitude();
longitude = location.getLongitude();
}
});
locationClient.start();
}
/**
* 计算图片的缩放值
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
/**
* 根据路径获得突破并压缩返回bitmap用于显示
*
* @return
*/
public static Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 480, 800);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
}
|
C#
|
UTF-8
| 6,703 | 2.703125 | 3 |
[] |
no_license
|
using System.Text;
using FileServer.Core;
using Xunit;
namespace FileServer.Test
{
[Collection("Using IO")]
public class ProgramTest
{
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1000)]
[InlineData(1999)]
[InlineData(65001)]
[InlineData(9999999)]
public void Out_Of_Range_Ports(int invaildPorts)
{
var correctOutput = new StringBuilder();
correctOutput.Append("Invaild Port Detected.");
correctOutput.Append("Vaild Ports 2000 - 65000");
string[] argsHelloWorld = { "-p", invaildPorts.ToString() };
var mockPrinterOne = new MockPrinter();
var serverMadeHelloWorld = Program.MakeServer(argsHelloWorld, mockPrinterOne);
Assert.Null(serverMadeHelloWorld);
mockPrinterOne.VerifyPrint(correctOutput.ToString());
string[] args = { "-p", invaildPorts.ToString(), "-d", "C:\\" };
var mockPrinterTwo = new MockPrinter();
var serverMade = Program.MakeServer(args, mockPrinterTwo);
Assert.Null(serverMade);
mockPrinterTwo.VerifyPrint(correctOutput.ToString());
var mockPrinterThree = new MockPrinter();
string[] argsSwaped = { "-d", "C:\\", "-p", invaildPorts.ToString() };
var serverMadeSwaped = Program.MakeServer(argsSwaped, mockPrinterThree);
Assert.Null(serverMadeSwaped);
mockPrinterThree.VerifyPrint(correctOutput.ToString());
}
[Fact]
public void Make_Dirctory_Server_Correct()
{
var mockPrinter = new MockPrinter();
string[] args = { "-p", "32000", "-d", "C:\\" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.NotNull(serverMade);
}
[Fact]
public void Make_Dirctory_Server_Twice_Same_Port()
{
var mockPrinter = new MockPrinter();
var correctOutput = new StringBuilder();
string[] args = { "-p", "8765", "-d", "C:\\" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.NotNull(serverMade);
var serverMadeInvaild = Program.MakeServer(args, mockPrinter);
Assert.Null(serverMadeInvaild);
mockPrinter.VerifyPrint("Another Server is running on that port");
}
[Fact]
public void Make_Dirctory_Server_Correct_Arg_Backwords()
{
var mockPrinter = new MockPrinter();
string[] args = { "-d", "C:\\", "-p", "2020" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.NotNull(serverMade);
}
[Fact]
public void Make_Dirctory_Server_Inncorect_Correct_Not_Dir()
{
var mockPrinter = new MockPrinter();
var correctOutput = new StringBuilder();
string[] args = { "-d", "Hello", "-p", "3258" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.Null(serverMade);
mockPrinter.VerifyPrint("Not a vaild directory");
}
[Fact]
public void Make_Dirctory_Server_Inncorect_Correct_Not_Port()
{
var mockPrinter = new MockPrinter();
var correctOutput = new StringBuilder();
correctOutput.Append("Invaild Port Detected.");
correctOutput.Append("Vaild Ports 2000 - 65000");
string[] args = { "-d", "C:\\", "-p", "hello" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.Null(serverMade);
mockPrinter.VerifyPrint(correctOutput.ToString());
}
[Fact]
public void Make_Dirctory_Server_Inncorect_Correct()
{
var mockPrinter = new MockPrinter();
var correctOutput = new StringBuilder();
string[] args = { "-p", "32000", "-d", "-d" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.Null(serverMade);
mockPrinter.VerifyPrint("Not a vaild directory");
}
[Fact]
public void Make_Hello_World_Server_Correct()
{
var mockPrinter = new MockPrinter();
string[] args = { "-p", "9560" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.NotNull(serverMade);
}
[Fact]
public void Make_Hello_World_Incorrect_Correct()
{
var mockPrinter = new MockPrinter();
string[] args = { "2750", "-p" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.Null(serverMade);
}
[Fact]
public void Make_Hello_World_Incorrect_Correct_No_Port()
{
var mockPrinter = new MockPrinter();
string[] args = { "-p", "-p" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.Null(serverMade);
}
[Fact]
public void Make_Server_Inncorect_NoArgs()
{
var mockPrinter = new MockPrinter();
var correctOutput = new StringBuilder();
correctOutput.Append("Invaild Number of Arguments.\n");
correctOutput.Append("Can only be -p PORT\n");
correctOutput.Append("or -p PORT -d DIRECTORY\n");
correctOutput.Append("Examples:\n");
correctOutput.Append("Server.exe -p 8080 -d C:/\n");
correctOutput.Append("Server.exe -d C:/HelloWorld -p 5555\n");
correctOutput.Append("Server.exe -p 9999");
var args = new[] { "-s" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.Null(serverMade);
mockPrinter.VerifyPrint(correctOutput.ToString());
}
[Fact]
public void Main_Starting_Program()
{
string[] args = { };
Assert.Equal(0, Program.Main(args));
}
[Fact]
public void Test_Running_Of_Server()
{
var mockServer = new MockMainServer()
.StubAcceptingNewConn();
Program.RunServer(mockServer);
mockServer.VerifyRun();
mockServer.VerifyAcceptingNewConn();
}
[Fact]
public void Make_Log_File()
{
var mockPrinter = new MockPrinter();
string[] args = { "-p", "10560", "-l", "c:/TestLog" };
var serverMade = Program.MakeServer(args, mockPrinter);
Assert.Equal("c:/TestLog", mockPrinter.Log);
Assert.NotNull(serverMade);
}
}
}
|
JavaScript
|
UTF-8
| 1,165 | 2.96875 | 3 |
[] |
no_license
|
// a tree is a list of nodes
function find_bookmark_by_title(tree, title) {
if (!tree)
return null;
for (var i=0; i<tree.length; i++) {
var node = tree[i];
if (node.title == title)
return node;
}
// nothing at top-level, keep going
for (var i=0; i<tree.length; i++) {
var node = tree[i];
var subsearch = find_bookmark_by_title(node.children, title);
if (subsearch)
return subsearch;
}
return null;
}
var BOOKMARK_DIRECTORY = 'Firefox';
function update_bookmarks(bookmarks) {
chrome.bookmarks.getTree(function(tree) {
var bar = find_bookmark_by_title(tree, BOOKMARK_DIRECTORY);
if (bar) {
bar.children.forEach(function(bookmark) {
chrome.bookmarks.removeTree(bookmark.id);
});
} else {
// create it
var bookmarks_bar = find_bookmark_by_title(tree, 'Bookmarks Bar');
bar = chrome.bookmarks.create({
parentId: bookmarks_bar.id,
title: BOOKMARK_DIRECTORY
});
}
// add the bookmarks
bookmarks.forEach(function(one_bookmark) {
one_bookmark.parentId = bar.id;
chrome.bookmarks.create(one_bookmark);
});
});
}
|
JavaScript
|
UTF-8
| 1,997 | 2.6875 | 3 |
[] |
no_license
|
$(document).ready(function() {
jQuery.fn.exists = function(){return this.length>0;}
$(".add").click(function (event) {
event.preventDefault();
var inputitem = $('#newitem').val();
if (inputitem == '')
{
var empty_item = confirm("Item is empty, do you want to add an empty item?");
if (empty_item)
{
$("ul").append("<li><input type='checkbox' class='singlecheck'/>Item<br/><button class='remove'>Delete Item</button></li>");
}
}
else
{
$("ul").append("<li><input type='checkbox' class='singlecheck'/>"+inputitem+"<br/><button class='remove'>Delete Item</button></li>");
$('#newitem').val("");
}
$(".checkout").show();
});
$('#shopping-items').on('click', '.remove', function(){
$(this).closest("li").remove();
});
$('#shopping-items').on('click', '.checkout', function(){
event.preventDefault();
$("button").prop('disabled',true);
$("li").css("text-decoration","line-through");
$(".singlecheck").prop('checked', true);
$("li").find("img").remove();
$("#shopping-items li").append("<img class='tickmark' src='images/check-mark.jpg' alt='checked out'/>");
$(this).text('All Checked Out');
});
$('#shopping-items').on('change','.singlecheck', function() {
if ($(this).is(':checked'))
{
$(this).closest("li").find("img").remove();
$(this).closest("li").append("<img class='tickmark' src='images/check-mark.jpg' alt='checked out'/>");
$(".checkout").text('Checkout');
$("button").prop('disabled',false);
$(this).closest('li').find("button").prop('disabled',true);
$(this).closest('li').css("text-decoration","line-through");
}
else
{
console.log("not checked");
$(this).closest("li").find("img").remove();
$(".checkout").text('Checkout');
$(".checkout").prop('disabled',false);
$(".add").prop('disabled',false);
$(this).closest("li").find("button").prop('disabled',false);
$(this).closest('li').css("text-decoration","none");
}
});
});
|
Python
|
UTF-8
| 135 | 2.609375 | 3 |
[] |
no_license
|
import datetime
d={'Cumpleaños':20,'Ricardo':2002,'Fecha':datetime.date.today()}
d.setdefault('Año minimo',datetime.MINYEAR)
print(d)
|
C++
|
UTF-8
| 479 | 2.765625 | 3 |
[] |
no_license
|
#include "DataStore.h"
#include <EEPROM\src\EEPROM.h>
/*
template < class T >
DataStore<T>::DataStore(uint16_t start, uint8_t maxdata ) :
startAddres(start),
maxData(maxdata)
{
lastData = 0;
}
*/
template < class T >
void DataStore<T>::pushBack(T data) {
uint8_t length = sizeof(T);
uint8_t * p = (uint8_t *) data;
for (uint8_t i = 0; i < length; i++) {
EEPROM.write(startAddres + lastData, *p);
p++;
}
}
/*
template < class T >
DataStore<T>::~DataStore()
{
}
*/
|
Java
|
UTF-8
| 3,372 | 3.328125 | 3 |
[] |
no_license
|
package net.Programmers;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Sonf {
//곡별로 음계 전체 만들기
static String[][] pattern = new String[][]{{"C#","c"},{"D#","d"},{"F#","f"},{"G#","g"},{"A#","a"}};
public String solution(String m, String[] musicinfos) {
String answer = "(None)";
PriorityQueue<Song> queue = new PriorityQueue<>(new Comparator<Song>() {
@Override
public int compare(Song o1, Song o2) {
if(o1.time==o2.time)return o1.start-o2.start;
else return o2.time-o1.time;
}
});
for(String s: musicinfos){
String str[] = s.split(",");
int time = getTime(str[0],str[1]);
queue.offer(new Song(Integer.parseInt(str[0].replaceAll(":","")),time,str[2],getFull(time,str[3])));
}
System.out.println(queue);
while(!queue.isEmpty()){
Song current = queue.poll();
if(check(m,current))return current.name;
}
return answer;
}
//전체음계 구하기
static String getFull(int time,String scale){
StringBuilder total=new StringBuilder();
scale = removeSharp(scale);
System.out.println(time+scale);
for(int i=0;i<time;i++){
total.append(scale.charAt(i%scale.length()));
}
return total.toString();
}
//시간변환
static int getTime(String start, String end){
String startA[] = start.split(":");
String endA[] = end.split(":");
int hour = 0;
int minute= 0;
int sh = Integer.parseInt(startA[0]);
int eh = Integer.parseInt(endA[0]);
int sm =Integer.parseInt(startA[1]);
int em = Integer.parseInt(endA[1]);
if(em<sm){//분이 넘어가는 경우
minute = 60-sm+em;
eh--;
}else minute =em-sm;
if(eh<sh){//시가 넘어가는 경우, 00:00이상일 경우
hour = 23-sh;
minute = sm==0?0:60-sm;
}else hour = eh-sh;
System.out.println(hour+":"+minute);
return hour*60+minute;
}
static boolean check(String input, Song song){
input = removeSharp(input);
for(int i=0;i+input.length()<=song.scale.length();i++){
if(song.scale.substring(i,i+input.length()).equals(input))return true;
}
return false;
}
static String removeSharp(String input){
for(int i=0;i<pattern.length;i++){
input = input.replaceAll(pattern[i][0],pattern[i][1]);
}
return input;
}
class Song{
int start;
int time;
String name;
String scale;
public Song(int start,int time, String name, String scale) {
this.start = start;
this.time = time;
this.name = name;
this.scale = scale;
}
@Override
public String toString() {
return "Song{" +
"start=" + start +
", name='" + name + '\'' +
", scale='" + scale + '\'' +
'}';
}
}
public static void main(String[] args) {
System.out.println(new Sonf().solution("ABC", new String[]{"13:40,13:40,HELLO,C#DEFGAB", "20:00,14:01,WORLD,ABCDEF"}));
}
}
|
Python
|
UTF-8
| 5,118 | 2.859375 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Copyright (C) 2018 Alteryx, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import string
from IPython.display import display, Markdown
def convertObjToStr(obj):
try:
obj_str = '{}'.format(obj)
except:
obj_str = '<{}>'.format(type(obj))
return obj_str
# return a string containing a msg followed by a filepath
def fileErrorMsg(msg, filepath=None):
if filepath is None:
raise ReferenceError("No filepath provided")
return ''.join([msg, ' (', filepath, ')'])
# check if file exists. if not, throw error
def fileExists(filepath, throw_error=None, msg=None, debug=None):
# default is to not throw an error
if throw_error is None:
throw_error = False
if msg is None:
msg = 'Input data file does not exist'
# set default for debug
if debug is None:
debug = False
elif not isinstance(debug, bool):
raise TypeError('debug value must be True or False')
# if file exists, return true
if os.path.isfile(filepath):
if debug:
print(fileErrorMsg('File exists', filepath))
return True
elif os.path.isdir(filepath):
if debug:
print(fileErrorMsg('Directory exists', filepath))
return True
else:
if throw_error:
raise FileNotFoundError(fileErrorMsg(msg, filepath))
elif debug:
print(fileErrorMsg(msg, filepath))
return False
# check if a string is a valid sqlite table name
def tableNameIsValid(table_name):
if isString(table_name):
# stripped = ''.join( char for char in table_name if (char.isalnum() or char=='_'))
valid_chars = ''.join([string.ascii_letters, string.digits, '_'])
stripped = ''.join(char for char in table_name if (char in valid_chars))
if stripped != table_name:
valid = False
reason = 'invalid characters (only alphanumeric and underscores)'
elif not table_name[0].isalpha():
valid = False
reason = 'first character must be a letter'
else:
valid = True
reason = None
return valid, reason
else:
raise TypeError('table name must be a string')
# delete a file (if it exists)
def deleteFile(filepath, debug=None):
# set default for debug
if debug is None:
debug = False
elif not isinstance(debug, bool):
raise TypeError('debug value must be True or False')
# if file exists, attempt to delete it
if fileExists(filepath, throw_error=False):
try:
os.remove(filepath)
if debug:
print(fileErrorMsg("Success: file deleted", filepath))
except:
print(fileErrorMsg("Error: Unable to delete file", filepath))
raise
else:
if debug:
print(fileErrorMsg("Success: file does not exist", filepath))
def isString(var):
return isinstance(var, str)
def isDictMappingStrToStr(d):
try:
if not isinstance(d, dict):
raise TypeError('Input must be a python dict')
elif not all(isinstance(item, str) for item in d.keys()):
raise TypeError('All keys must be strings')
elif not all(isinstance(d[item], str) for item in d.keys()):
raise TypeError('All mapped values must be strings')
else:
return True
except:
print('Input: {}'.format(convertObjToStr(d)))
raise
def prepareMultilineMarkdownForDisplay(markdown):
# split each line of input markdown into items in a list
md_lines = markdown.splitlines()
# strip each line of whitespace
md_lines_stripped = list(map(lambda x: x.strip(), md_lines))
# add trailing spaces and newline char between lines when joining back together
markdown_prepared = ' \n'.join(md_lines_stripped)
# return prepared markdown
return markdown_prepared
def displayMarkdown(markdown):
# display the prepared markdown as formatted text
display(Markdown(markdown))
def convertToType(value, datatype):
try:
# special case: string to bool
if (datatype is bool) and isinstance(value,str):
if value.strip()[0].upper() in ['T', 'Y']:
return True
elif value.strip()[0].upper() in ['F', 'N']:
return False
# general case
return datatype(value)
except Exception as e:
msg = "Unable to convert {} value to data type {}: {}\n>> {}"\
.format(type(value), datatype, value, e)
print(msg)
raise
|
Python
|
UTF-8
| 854 | 2.5625 | 3 |
[] |
no_license
|
# data from:
# LIGO open science center
# www.gw-openscience.org/GW150914data/LOSC_Event_tutorial_GW150914.html
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import psd
from matplotlib import rc
data = [np.loadtxt('H-H1_LOSC_4_V2-1126259446-32.txt'),
np.loadtxt('L-L1_LOSC_4_V2-1126259446-32.txt') + 1.e-18]
label = ['Hanford', 'Livingston']
color = ['b', 'g']
fs = 4096
N = len(data[0])
plt.figure(figsize=(6.4, 6))
rc('text', usetex=True)
for (i,h) in enumerate(data):
(S,f) = psd(h, Fs=fs, NFFT=N//8)
plt.subplot(2,1,i+1)
plt.axis([20, 2000, 5e-23, 5e-18])
plt.loglog(f, np.sqrt(fs*S/2), color[i], label=label[i], lw=1)
plt.legend()
plt.ylabel(r'$\sqrt{f_{\rm c}\, S(f)}$', fontsize=14)
plt.xlabel('frequency / Hz', fontsize=14)
plt.tight_layout()
plt.savefig('fig2.eps')
plt.show()
|
Markdown
|
UTF-8
| 9,289 | 2.984375 | 3 |
[] |
no_license
|
# Introduction
Ce document a pour but de vous expliquer en 5 minutes de lecture (et 5 autres de "digestion" ;) ) tout ce que vous devez savoir sur le XML et le XPATH utilisé par le Référentiel législatif de l'AN et les données en "OpenData" qui en sont issues.
Vous en saurez assez pour comprendre tout le XML et effectuer les requêtes XPATH vous permettant d'exploiter les données de l'OpenData.
XML et XPath sont des technologies riches et si vous voulez devenir un maitre Jedi dans ces matières vous devrez vous tourner vers d'autres sources d'information en ligne.
Cela ne devrait pas être nécessaire pour exploiter l'OpenData de l'Assemnblée nationale cependant.
# XML
Le XML se présente comme un format textuel dont voici un exemple.
Ce fichier XML serra la base de tous nos exemples subséquents.
```XML
<export xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<organes>
<organe xsi:type="OrganeParlementaire_Type">
<uid>PO711218</uid>
<codeType>MISINFO</codeType>
<libelle>Formation des enseignants</libelle>
<viMoDe>
<dateDebut>2015-12-16</dateDebut>
<dateAgrement xsi:nil="true"/>
<dateFin>2016-10-05</dateFin>
</viMoDe>
<legislature>14</legislature>
<secretariat>
<secretaire xsi:nil="true"/>
<secretaire xsi:nil="true"/>
</secretariat>
</organe>
<organe xsi:type="OrganeParlementaire_Type">
<uid>PO714518</uid>
<codeType>ASSEMBLEE</codeType>
<libelle>Assemble nationale</libelle>
<viMoDe>
<dateDebut>2016-12-16</dateDebut>
<dateAgrement xsi:nil="true"/>
<dateFin>2018-10-05</dateFin>
</viMoDe>
<legislature>14</legislature>
<secretariat>
<secretaire xsi:nil="true"/>
<secretaire xsi:nil="true"/>
</secretariat>
</organe>
</organes>
<acteurs>
<acteur>
<uid>PA3445</uid>
<etatCivil>
<ident>
<nom>jean</nom>
<prenom>valjean</prenom>
</ident>
</etatCivil>
<mandats>
<mandat>
<uid>PM3455</uid>
<typeorgane>Assemblee</typeorgane>
<acteurRef>PA3445</acteurRef>
</mandat>
</mandats>
</acteur>
</acteurs>
</export>
```
## L'essentiel
### Arbre
un document XML est un arbre (il y a une "racine", unique, des "branches" et des "feuilles") de "noeuds". ces noeuds peuvent être de deux grands types : Les `Eléménts` et les `Attributs` (il y a d'autres tpes possibles mais vous ne les rencontrerez pas explicitement dans nos documents.)
## Balise
* Une balise est une chaine de charactère quelconque ('acteur', 'organe', 'ratatouille', 'poix123')
* Une balise peut être ouvrante comprise entre les symboles < et > (<acteur> <organe> etc ...) ou fermante, comprise entre les caractères < et /> (<acteur/>, <organe/>).
* Une balise peut enfin être "vide" ouvrante et fermante, comme ceci <acteur/>
* Toute balise ouvrante doit être assoiciée à une balise fermante (ou être une balise vide, ouvrante et fermante à la fois)
* Enfin, Les balises peuvent et doivent être imbriquée mais jamais se "chevaucher".
Exemple :
```xml
<racine>
<acteur><vide/></acteur>
<mandats></mandats>
</racine>
```
Mais jamais :
```xml
<racine>
<acteur>
<mandats>
</acteur>
</mandats>
</racine>
```
### élément
Un élément est la réunion d'une balise ouvrante et fermante et de tout ce qui se trouve entre.
Par exemple :
```xml
<secretariat>
<secretaire xsi:nil="true"/>
<secretaire xsi:nil="true"/>
</secretariat>
```
L'élément `secretariat` contient deux autres éléments `secretaire`
### Attribut
## Concepts "avancés"
Ces concepts sont inutiles pour comprenndre les données de l'Open Data mais vous en aurez besoin pour des usages avancés des données avec des outils sophisitiqués.
### Namespace
### schémas
# XPath
## L'essentiel
XPath est un langage de requếtage sur des documents au format XML.
C'est à dire qu'une expression XPath appliqué à un document XML retourne entre zéro et `n` noeuds (éléments ou attributs).
Une expression XPath simplement décrit le "chemin" pour accéder aux noeuds qu'elle souhaite récupérer, comme ceci :
```/export/organes/organe```
ou
```./organe```
Le résultat de l'expression XPath est l'ensemble des noeuds qui satisfont à l'expression.
La façon la plus simple d'apréhender une expression XPath est de la considérer comme un 'chemin' sélectionnant les noeuds correspondant au parcours de ce chemin depuils le point d'évaluation.
L'expression `/export/organes` limite ces noeuds aux fils de l'élément `Organes` eux même fils de la racine du document `export`.
Elle exprime ceci "retournez moi les noeuds appelés `organe`, fils d'un élément `organes` lui même fils de l'élément racine (`export`).
Les seuls noeud correspondants sont les deux éléments `organe` fils de `organes`, ce sont eux qui serront retournés, intégralement (avec leurs fils et tout leur contenu).
L'expression `./organe` retourne les noeuds `organe` fils `/` du noeud courant `.`.
En traduction pas à pas "du noeud ou vous êtes retournez moi les éléments fils de nom `organe`)
Son résultat dépend donc de l'endroit du fichier XML où elle est évaluée.
* Evaluée à la racine (`<export>`) cette expression ne retourne **rien** : Il n'y a pas d'élément `organe` fils de la racine (`<export>`).
* Evaluée sur l'élément `organes` elle retourne le même résultat que l'expression précédente :les deux éléments `organe` du document exemple qui sont bien fils directs de l'élément `organes`.
Mais peut-être voulez vous seulement le *premier* élément organe ?
```/export/organes/organe[1]```
ou le second
```/export/organes/organe[2]```
Vous pourriez aussi vouloir récupérer **tous** les éléments `organe`, peut importe où ils sont placés dans l'arborescence :
```//organe```
le symbole `//` veut dire 'n'importe où en dessous', fils direct, petit fils, petit petit fils, etc ...
## Un peu plus et ce sera assez ...
### Selecteur
Dans l'exemple ```/export/organes/organe[1]``` l'expression entre crochets ```[]``` est un selecteur.
Un sélecteur réduit le nombre de noeuds capturés par l'expression en posant une contrainte, un critère, un test sur les noeuds à cet endroit de l'expression.
Un simple nombre `n` indique de sélectionner le noeud de rang `n`, mais il est possible de construire des expressions plus puissantes.
```/export/organes/organe[uid="PO714518"]```
Sélectionne uniquement l'organe fils direct de ```/export/organes/``` possédant un fils `uid` de valeur "PO714518" si il existe.
Dans notre exemple il en existe un, le second.
```/export/organes/organe[.//dateDebut>"2016-01-01"]```
Sélectionne les organes fils de ```/export/organes/``` ayant un sous élément `dateDebut` postérieur au 1er janvier 2016.
Vous l'aurez remarqué l'expression de sélection est "enracinée" par défaut i.e. évaluée au point courant de l'expression, dans notre cas ```/export/organes/```, et nous pouvons utiliser la notation `//` pour sélectionner n'importe quel élément descendant `dateDebut` à partir ce ce point.
En l'occurence l'élément date début est en fait situé en `./viMoDe/dateDebut` et nous aurious pu écrire l'expression comme ceci :
```/export/organes/organe[./viMoDe/dateDebut > "2016-01-01"]```
L'expression 'sélecteur' peut être n'importe quelle expression XPath valide qui traduit une condition booléenne.
## Any
Le symbole `*` représente n'importe quel élément.
Ainsi l'expression :
```//*[uid="PO714518"]```
représente n'importe quel élément possédant un fils direct `uid` de valeur `PO714518`
=>un organe dans notre exemple :
```xml
<organe xsi:type="OrganeParlementaire_Type">
<uid>PO714518</uid>
<codeType>ASSEMBLEE</codeType>
...
```
```/*[uid="PO714518"]```
représente n'importe quel élément racine possédant un fils direct `uid` de valeur `PO714518`
=> aucun dans notre exemple
```//*[uid="PO714518"]```
représente n'importe quel élément racine possédant un descendant `uid` de valeur `PO714518`
=> le document racine 'export' en entier dans notre exemple
### Filtrer sur un attribut, xsi:nil ...
Enfin, pour tester la valeur d'un attribut il faut utiliser l'opérateur `@`
```//organe[@xsi:type="OrganeParlementaire_Type"]```
sélectionne tous les organes ayant un attribut xsi:type de valeur "OrganeParlementaire_Type"
=> dans notre cas les deux éléments organes répondent à ce critère.
```//*[@xsi:nil="true"]``` ...
retournera les 4 éléments `<secretaire>` **et** deux élémens `<dateAgrement>` dans notre exemple... vous devriez comprendre pourquoi à présent ;)
L'expression :
```//secretaire[@xsi:nil="true"]```
ne retournerait, elle, que les 4 éléments `<secretaire>`
# Et en Python ? lxml et co ...
|
Python
|
UTF-8
| 1,073 | 3.765625 | 4 |
[] |
no_license
|
def maxi(*l):
if len(l) == 0:
return 0
m = l[0]
for ix in range(1, len(l)):
if l[ix] > m:
m = l[ix]
return m
def mini(*l):
if len(l) == 0:
return 0
m = l[0]
for ix in range(1, len(l)):
if l[ix] < m:
m = l[ix]
return m
def media(*l):
if len(l) == 0:
return 0
suma = 0
for valor in l:
suma += valor
return suma / len(l)
funciones = {
"max": maxi,
"min": mini,
"med": media
}
def returnF(nombre):
nombre = nombre.lower()
if nombre in funciones.keys():
return funciones[nombre]
return None
# A continuación la función returnF devolverá el nombre de otra función.
print(returnF("max"))
# Si quiero que la función "max" se ejecute a través de la función "returnF" escribiré lo siguiente:
print(returnF("max")(1, 3, -1, 15, 9))
# Si quiero que la función "min" se ejecute a través de la función "returnF" escribiré lo siguiente:
print(returnF("min")(1, 3, -1, 15, 9))
# Si quiero que la función "med" se ejecute a través de la función "returnF" escribiré lo siguiente:
print(returnF("med")(1, 3, -1, 15, 9))
|
C
|
UTF-8
| 1,209 | 2.875 | 3 |
[] |
no_license
|
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include "jjp_lib.h"
int flag_18;
void fSIGSTP(int signum) {
if(flag_18==0) {
flag_18=1;
sigset_t mask;
sigfillset(&mask);
sigdelset(&mask, SIGTSTP);
printf("\n\nWaiting for:\n\tCtrl+Z - resume\n\tCtrl+C - exit\n");
sigsuspend(&mask);
}
else {
flag_18=0;
printf("\n\n");
}
}
void fSIGINT() {
printf("\n\nProgram received signal SIGINT(2). Exiting...\n\n");
exit(0);
}
int main(int argc, char** argv) {
flag_18=0;
struct sigaction sigint_action;
sigint_action.sa_handler = fSIGINT;
sigemptyset(&sigint_action.sa_mask);
sigint_action.sa_flags = 0;
signal(SIGTSTP, fSIGSTP);
sigaction(SIGINT, &sigint_action, NULL);
time_t timer;
char buffer[26];
struct tm* tm_info;
printf("\nPID:\t%d\n", getpid());
while(1) {
sleep(1);
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
puts(buffer);
}
return 0;
}
|
Java
|
UTF-8
| 342 | 2.421875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package base.components;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import base.model.Engine;
@Component("car")
public class Car {
Engine engine;
@Autowired
public void setEngine(Engine engine){
this.engine = engine;
System.out.println("car engine set");
}
}
|
Java
|
UTF-8
| 1,798 | 3.765625 | 4 |
[] |
no_license
|
package lecture11;
public class ArrayDeque<E> implements Deque<E> {
private Object[] data;
private int first, size;
public ArrayDeque(int capacity) {
this.data = new Object[capacity];
this.first = 0;
this.size = 0;
}
@Override
public void addFirst(E e) {
if (this.size == this.data.length)
this.resize(this.data.length * 2);
this.first = (this.first + this.data.length - 1) % this.data.length;
this.data[this.first] = e;
this.size++;
}
@Override
public void addLast(E e) {
if (this.size == this.data.length)
this.resize(this.data.length * 2);
int nextAvailable = (this.first + this.size) % this.data.length;
this.data[nextAvailable] = e;
this.size++;
}
@Override
public E removeFirst() {
if (this.isEmpty())
throw new IllegalStateException("Deque is empty");
E val = (E) this.data[this.first];
this.data[this.first] = null;
this.first = (this.first + 1) % this.data.length;
this.size--;
return val;
}
@Override
public E removeLast() {
if (this.isEmpty())
throw new IllegalStateException("Deque is empty");
int last = (this.first + this.size - 1) % this.data.length;
E val = (E) this.data[last];
this.data[last] = null;
this.size--;
return val;
}
@Override
public E first() {
return (E) this.data[this.first];
}
@Override
public E last() {
int last = (this.first + this.size - 1) % this.data.length;
return (E) this.data[last];
}
@Override
public int size() {
return this.size;
}
@Override
public boolean isEmpty() {
return this.size == 0;
}
private void resize(int newSize) {
Object[] larger = new Object[newSize];
for (int i = 0; i < this.size; i++) {
int j = (this.first + i) % this.data.length;
larger[i] = this.data[j];
}
this.data = larger;
this.first = 0;
}
}
|
C#
|
UTF-8
| 3,875 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
using System;
using Skybrud.Social.Sonos.Endpoints;
using Skybrud.Social.Sonos.OAuth;
namespace Skybrud.Social.Sonos {
/// <summary>
/// Class working as an entry point to the Sonos API.
/// </summary>
public class SonosService {
#region Properties
/// <summary>
/// Gets a reference to the internal OAuth client.
/// </summary>
public SonosOAuthClient Client { get; }
/// <summary>
/// Gets a reference to the <strong>groups</strong> endpoint.
/// </summary>
public SonosGroupsEndpoint Groups { get; }
/// <summary>
/// Gets a reference to the <strong>households</strong> endpoint.
/// </summary>
public SonosHouseholdsEndpoint Households { get; }
/// <summary>
/// Gets a reference to the <strong>players</strong> endpoint.
/// </summary>
public SonosPlayersEndpoint Players { get; }
#endregion
#region Constructors
private SonosService(SonosOAuthClient client) {
Client = client;
Groups = new SonosGroupsEndpoint(this);
Households = new SonosHouseholdsEndpoint(this);
Players = new SonosPlayersEndpoint(this);
}
#endregion
#region Static methods
/// <summary>
/// Initialize a new service instance from the specified OAuth <paramref name="client"/>.
/// </summary>
/// <param name="client">The OAuth client.</param>
/// <returns>The created instance of <see cref="SonosService" />.</returns>
public static SonosService CreateFromOAuthClient(SonosOAuthClient client) {
if (client == null) throw new ArgumentNullException(nameof(client));
return new SonosService(client);
}
/// <summary>
/// Initializes a new service instance from the specifie OAuth 2 <paramref name="accessToken"/>.
/// </summary>
/// <param name="accessToken">The access token.</param>
/// <returns>The created instance of <see cref="SonosService" />.</returns>
public static SonosService CreateFromAccessToken(string accessToken) {
if (String.IsNullOrWhiteSpace(accessToken)) throw new ArgumentNullException(nameof(accessToken));
return new SonosService(new SonosOAuthClient(accessToken));
}
///// <summary>
///// Initializes a new instance based on the specified <paramref name="refreshToken"/>.
///// </summary>
///// <param name="clientId">The client ID.</param>
///// <param name="clientSecret">The client secret.</param>
///// <param name="refreshToken">The refresh token of the user.</param>
///// <returns>The created instance of <see cref="Skybrud.Social.Sonos.SonosService" />.</returns>
//public static SonosService CreateFromRefreshToken(string clientId, string clientSecret, string refreshToken) {
// if (String.IsNullOrWhiteSpace(clientId)) throw new ArgumentNullException(nameof(clientId));
// if (String.IsNullOrWhiteSpace(clientSecret)) throw new ArgumentNullException(nameof(clientSecret));
// if (String.IsNullOrWhiteSpace(refreshToken)) throw new ArgumentNullException(nameof(refreshToken));
// // Initialize a new OAuth client
// SonosOAuthClient client = new SonosOAuthClient(clientId, clientSecret);
// // Get an access token from the refresh token.
// SonosTokenResponse response = client.GetAccessTokenFromRefreshToken(refreshToken);
// // Update the OAuth client with the access token
// client.AccessToken = response.Body.AccessToken;
// // Initialize a new service instance
// return new SonosService(client);
//}
#endregion
}
}
|
Python
|
UTF-8
| 341 | 2.71875 | 3 |
[] |
no_license
|
class Solution:
def isHappy(self, n: int) -> bool:
ht = dict()
while n:
if 1 in ht:
return True
if n in ht:
return False
ht[n] = 0
tmp = 0
while n:
tmp += (n%10) ** 2
n //= 10
n = tmp
|
Java
|
UTF-8
| 2,456 | 1.820313 | 2 |
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright © 2012-2014 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.tephra.persist;
import co.cask.tephra.TxConstants;
import co.cask.tephra.metrics.TxMetricsCollector;
import co.cask.tephra.snapshot.SnapshotCodecProvider;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
/**
* Tests persistence of transaction snapshots and write-ahead logs to HDFS storage, using the
* {@link HDFSTransactionStateStorage} and {@link HDFSTransactionLog} implementations.
*/
public class HDFSTransactionStateStorageTest extends AbstractTransactionStateStorageTest {
@ClassRule
public static TemporaryFolder tmpFolder = new TemporaryFolder();
private static MiniDFSCluster dfsCluster;
private static Configuration conf;
@BeforeClass
public static void setupBeforeClass() throws Exception {
Configuration hConf = new Configuration();
hConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, tmpFolder.newFolder().getAbsolutePath());
dfsCluster = new MiniDFSCluster.Builder(hConf).numDataNodes(1).build();
conf = new Configuration(dfsCluster.getFileSystem().getConf());
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
dfsCluster.shutdown();
}
@Override
protected Configuration getConfiguration(String testName) throws IOException {
// tests should use the current user for HDFS
conf.unset(TxConstants.Manager.CFG_TX_HDFS_USER);
conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath());
return conf;
}
@Override
protected AbstractTransactionStateStorage getStorage(Configuration conf) {
return new HDFSTransactionStateStorage(conf, new SnapshotCodecProvider(conf), new TxMetricsCollector());
}
}
|
C
|
ISO-8859-1
| 1,805 | 2.765625 | 3 |
[] |
no_license
|
/*
* Projeto: Teclado e Display 1
* Arquivo: App.c
* Autor: JABNeto
* Data: 10/02/2016
*/
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include "Base_1.h"
#include "Oscilador.h"
//Prottipos das funes -----------------------------
void Timer0_Inicializacao (void);
void Timer0_Recarga (void);
//Alocao de memria para o mdulo-------------------
Ulong Contador;
struct
{
Uchar Temporizador100ms;
union
{
Uchar Valor;
struct
{
Uchar Contador:1;
};
}EventosDe100ms;
}TMR0_Eventos;
//Funes do mdulo ----------------------------------
int main(int argc, char** argv)
{
Oscilador_Inicializacao();
Display_InicializaVarredura();
Timer0_Inicializacao();
Contador = 0;
Varredura.Opcoes.OmiteZeros = _SIM;
Varredura.Opcoes.ExibePonto5 = _SIM;
Display_ExibeNumero(Contador);
INTCONbits.GIEH = 1;
while(1)
{
if(TMR0_Eventos.EventosDe100ms.Contador == 1)
{
TMR0_Eventos.EventosDe100ms.Contador = 0;
if (++Contador == 10000) Contador = 0;
Display_ExibeNumero(Contador);
}
}
return (EXIT_SUCCESS);
}
/* Interrupt_High
* Atendimento das interrupes de alta prioridade
*/
void interrupt high_priority Interrupt_High(void)
{
if ((INTCONbits.TMR0IE == 1) &&
(INTCONbits.TMR0IF == 1))
{
Timer0_Recarga();
if(--TMR0_Eventos.Temporizador100ms == 0)
{
TMR0_Eventos.Temporizador100ms = 100;
TMR0_Eventos.EventosDe100ms.Valor = 0xFF;
}
//Funes do usurio -------------------------
Display_ExecutaVarredura();
}
}
|
Python
|
UTF-8
| 570 | 3.234375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
import time
import math
import numpy as np
x = [i for i in xrange(1000 * 1000)]
start = time.clock()
for i, t in enumerate(x):
x[i] = math.sin(t)
print "math.sin:", time.clock() - start
x = [i for i in xrange(1000 * 1000)]
x = np.array(x)
start = time.clock()
np.sin(x, x)
print "numpy.sin:", time.clock() - start
x = np.arange(1, 4)
y = np.arange(2, 5)
print np.add(x, y)
print np.subtract(y, x)
print np.multiply(x, y)
print np.divide(y, x)
print np.true_divide(y, x)
print np.floor_divide(y, x)
|
Python
|
UTF-8
| 804 | 2.59375 | 3 |
[] |
no_license
|
# connect
# close
# dinh nghia class db
# co self , nam, usr., host, db_password, 4 thong so
# """"db_host = localhost
# db_user = root
# db_name = cdcol
# db_password = root
# """
import MySQLdb
import ConfigLoader
class Database(object):
"""docstring for Database"""
def __init__(self, host, user, db, password):
self.host = raw_input("Nhap Ten host :")
self.user = raw_input("Nhap Ten User :")
self.db = raw_input("Nhap Ten Database :")
self.password = raw_input("Nhap Password :")
def connect():
con = MySQLdb.connect(self.host,self.user,self.db,self.password)
cur = con.cursor() # dung con tro de lam viec vs DB
cur.execute("SELECT VERSION()")
row = cursor.fetchall()
print "server version",row[0]
cursor.close()
con.close()
if __name__ == '__main__':
main()
|
Java
|
UTF-8
| 2,027 | 2.875 | 3 |
[] |
no_license
|
package com.finago.interview.fileProcessor;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javax.xml.parsers.ParserConfigurationException;
import com.finago.interview.task.Constants;
/**
*
* @author Ajay Naik File Processor Usage : This class will validate the xml
* with xsd , read xml if the validation is successful move all xml to
* archive location and delete all pdf
*/
public class FileProcessor {
/**
* This class will validate the xml with xsd read xml if the validation is
* successful. if validation is successfull perform the logic as given if
* validation is not successful move the files to error location
*
*
* @throws ParserConfigurationException
*/
/**
*
* Main method method to process the xml
*
* @param xmlString
* @throws ParserConfigurationException
*/
public static void process(String xmlString) throws ParserConfigurationException {
if (FileUtility.fileExists(xmlString)) {
if (new XMLValidator().validate(xmlString, Constants.XSDFILEPATH)) {
System.out.println("validation is successful and Processing File start " + xmlString);
XMLReader.readANDProcessXML(xmlString);
System.out.println("validation is successful and Processing File end " + xmlString);
} else {
try {
if (FileUtility.fileExists(xmlString)) {
System.out.println(
xmlString + " validation is un-successful and moving the file to error location ");
Files.move(Paths.get(xmlString),
Paths.get(Constants.XMLERRORFOLDER + Paths.get(xmlString).getFileName().toString()),
StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Processing fail for xml "+ xmlString);
e.printStackTrace();
}
}
}else {
System.out.println(xmlString + " File doesn't exists");
}
}
}
|
Python
|
UTF-8
| 385 | 3.9375 | 4 |
[] |
no_license
|
#Multi line printing versions
#You can print with defining it into variable then print variable
message = """This message will
span several
lines."""
print(message)
#Or you can write you multi line printing into directly print function
print("""This message will span
several lines
of the text.""")
# Different String versions
print('This is a string.')
print("""And so is this.""")
|
Java
|
UTF-8
| 6,933 | 2.234375 | 2 |
[] |
no_license
|
package com.ravisravan.capstone.UI;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import com.ravisravan.capstone.R;
import com.ravisravan.capstone.UI.adapters.RemindersAdapter;
import com.ravisravan.capstone.data.ReminderContract;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link AllEventsFragment.Callback} interface
* to handle interaction events.
*/
public class AllEventsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private final int REMINDERS_LOADER = 200;
private RecyclerView recyclerview_reminders;
private RemindersAdapter mRemindersAdapter;
private Callback mListener;
public AllEventsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_all_events, container, false);
recyclerview_reminders = (RecyclerView) rootview.findViewById(R.id.recyclerview_reminders);
//TODO: configure the spancount in integers and use
recyclerview_reminders.setLayoutManager(new GridLayoutManager(getActivity(), 1));
View emptyView = rootview.findViewById(R.id.recyclerview_reminders_empty);
mRemindersAdapter = new RemindersAdapter(getActivity(), emptyView,
new RemindersAdapter.ReminderAdapterOnClickHandler() {
@Override
public void onClick(Long id, RemindersAdapter.ReminderViewHolder vh) {
((Callback) getActivity())
.onItemSelected(ReminderContract.Reminders.buildReminderUri(id), vh);
}
});
recyclerview_reminders.setAdapter(mRemindersAdapter);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerview_reminders.setHasFixedSize(true);
return rootview;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// we hold for transition here just in case the activity
// needs to be recreated. In a standard return transition,
// this doesn't actually make a difference.
//TODO: transitions
// if (mHoldForTransition) {
// getActivity().supportPostponeEnterTransition();
// }
getLoaderManager().initLoader(REMINDERS_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Callback) {
mListener = (Callback) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//1 is active 0 is inactive
return new CursorLoader(getActivity(), ReminderContract.Reminders.CONTENT_URI, null,
ReminderContract.Reminders.COLUMN_STATE + " = ?", new String[]{"1"},
ReminderContract.Reminders.COLUMN_CREATED_DATE);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mRemindersAdapter.swapCursor(data);
recyclerview_reminders.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
// Since we know we're going to get items, we keep the listener around until
// we see Children.
recyclerview_reminders.getViewTreeObserver().removeOnPreDrawListener(this);
if (recyclerview_reminders.getChildCount() > 0) {
int position = 0;
// if (position == RecyclerView.NO_POSITION &&
// -1 != mInitialSelectedMessage) {
// Cursor data = mMessagesAdapter.getCursor();
// int count = data.getCount();
// int messageColumn = data.getColumnIndex(ReminderContract.MessageLkpTable._ID);
// for (int i = 0; i < count; i++) {
// data.moveToPosition(i);
// if (data.getLong(messageColumn) == mInitialSelectedMessage) {
// position = i;
// break;
// }
// }
// }
//if (position == RecyclerView.NO_POSITION) position = 0;
// If we don't need to restart the loader, and there's a desired position to restore
// to, do so now.
recyclerview_reminders.smoothScrollToPosition(position);
RecyclerView.ViewHolder vh = recyclerview_reminders.findViewHolderForAdapterPosition(position);
// if (null != vh) {
// mRemindersAdapter.selectView(vh);
// }
return true;
} else {
}
return false;
}
});
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mRemindersAdapter.swapCursor(null);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface Callback {
/**
* ViewReminder for when an item has been selected.
*/
public void onItemSelected(Uri uri, RemindersAdapter.ReminderViewHolder vh);
}
}
|
Markdown
|
UTF-8
| 5,800 | 2.578125 | 3 |
[] |
no_license
|
# circos-utilities
Utility scripts for working with Circos.
# The scripts
* UCSC_chrom_sizes_2_circos_karyotype.py
> UCSC chrom.sizes files --> karyotype.tab file for use in Circos
Takes a URL for a UCSC `chrom.sizes` file and makes a `karyotype.tab` file from it for use with Circos.
Verified compatible with both Python 2.7 and Python 3.6.
Written to run from command line or pasted/loaded/imported inside a Jupyter notebook cell.
The main ways to run the script are demonstrated in the notebook [`demo UCSC_chrom_sizes_2_circos_karyotype script.ipynb`](https://github.com/fomightez/sequencework/blob/master/circos-utilities/demo%20UCSC_chrom_sizes_2_circos_karyotype%20script.ipynb) that is included in this repository. (That notebook can be viewed in a nicer rendering [here](https://nbviewer.jupyter.org/github/fomightez/sequencework/blob/master/circos-utilities/demo%20UCSC_chrom_sizes_2_circos_karyotype%20script.ipynb).)
To determine the URL to feed the script, google `YOUR_ORGANISM genome UCSC chrom.sizes`, where you replace `YOUR_ORGANISM` with your organism name and then adapt the path you see in the best match to be something similar to
`http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes` -or-
`http://hgdownload.cse.ucsc.edu/goldenPath/canFam2/bigZips/canFam2.chrom.sizes`.
You can get an idea of what is available by exploring the top section [here](http://hgdownload.cse.ucsc.edu/downloads.html); clicking on the arrows creates drop-down lists reveal many genomes for each category.
Importantly, this script is intended for organisms without cytogenetic bands, such as dog, cow, yeast, etc..
(For organisms with cytogenetic band data: Acquiring the cytogenetic bands information is described [here](http://circos.ca/tutorials/lessons/ideograms/karyotypes/), about halfway down
the page where it says, "obtain the karyotype structure from...".
Unfortunately, it seems the output to which one is directed to by those instructions is not
directly useful in Circos(?). Fortunately, though as described [here](http://circos.ca/documentation/tutorials/quick_start/hello_world/), "Circos ships with several predefined karyotype files for common sequence
assemblies: human, mouse, rat, and drosophila. These files are located in
data/karyotype within the Circos distribution." And also included there is a script for converting the cytogenetic band data to karyotype, see [here](http://circos.ca/documentation/tutorials/quick_start/hello_world/) and [here](https://groups.google.com/d/msg/circos-data-visualization/B55NlByQ6jY/nKWGSPsXCwAJ).)
Example call to run script from command line:
```
python UCSC_chrom_sizes_2_circos_karyotype.py http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes
```
(Alternatively, upload the script to a Jupyter environment and use `%run UCSC_chrom_sizes_2_circos_karyotype.py http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes` in a Python-backed notebook to run the example.)
Example input from http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes :
```
chrIV 1531933
chrXV 1091291
chrVII 1090940
chrXII 1078177
chrXVI 948066
chrXIII 924431
chrII 813184
chrXIV 784333
chrX 745751
chrXI 666816
chrV 576874
chrVIII 562643
chrIX 439888
chrIII 316620
chrVI 270161
chrI 230218
chrM 85779
```
Example output sent to file (tab-separated):
```
chr - Sc-chrIV chrIV 0 1531933 black
chr - Sc-chrXV chrXV 0 1091291 black
chr - Sc-chrVII chrVII 0 1090940 black
chr - Sc-chrXII chrXII 0 1078177 black
chr - Sc-chrXVI chrXVI 0 948066 black
chr - Sc-chrXIII chrXIII 0 924431 black
chr - Sc-chrII chrII 0 813184 black
chr - Sc-chrXIV chrXIV 0 784333 black
chr - Sc-chrX chrX 0 745751 black
chr - Sc-chrXI chrXI 0 666816 black
chr - Sc-chrV chrV 0 576874 black
chr - Sc-chrVIII chrVIII 0 562643 black
chr - Sc-chrIX chrIX 0 439888 black
chr - Sc-chrIII chrIII 0 316620 black
chr - Sc-chrVI chrVI 0 270161 black
chr - Sc-chrI chrI 0 230218 black
chr - Sc-chrM chrM 0 85779 black
```
#### For running in a Jupyter notebook:
To use this script after pasting or loading into a cell in a Jupyter notebook, in the next cell define the URL and then call the main function similar to below:
```
url = "http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes"
species_code = "Ys"
UCSC_chrom_sizes_2_circos_karyotype(url, species_code)
```
-or-
```
UCSC_chrom_sizes_2_circos_karyotype(url)
```
Without supplying a second argument, a species code will be extracted automatically and used.
Note that `url` is actually not needed if you are using the yeast one because that specific one is hardcoded in script as default.
In fact, because I hardcoded in defaults, just `main()` will indeed work for yeast after script pasted in or loaded into a cell.
See [here](https://nbviewer.jupyter.org/github/fomightez/sequencework/blob/master/circos-utilities/demo%20UCSC_chrom_sizes_2_circos_karyotype%20script.ipynb) for a notebook demonstrating use within a Jupyter notebook.
Related
-------
- [circos-binder](https://github.com/fomightez/circos-binder) - for running Circos in your browser without need for downloads, installations, or maintenance.
- [gos: (epi)genomic visualization in python](https://gosling-lang.github.io/gos/) looks to circos-like images, see that page in the link for representative examples in the image at the top. [The Example Gallery](https://gosling-lang.github.io/gos/gallery/index.html) has a link to a Circos-style example under the 'Others' heading; it includes code [here](https://gosling-lang.github.io/gos/gallery/circos.html).
|
Java
|
UTF-8
| 11,306 | 3.046875 | 3 |
[] |
no_license
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* in this class we design the interface of our calculator.
*
* @author Mahdi Hejarti 9723100
* @since 2020.04.23
*/
public class View {
private JFrame calFrame;
private JPanel standardMode;
private JPanel scientificMode;
private JButton[] buttons1;
private JButton[] buttons2;
private JTextArea display1;
private JTextArea display2;
private Controller controller;
/**
* constructor of View class
*/
public View() {
Handler handler = new Handler();
controller = new Controller();
// create main frame
calFrame = new JFrame();
designCalculatorFrame();
// add a tab to frame to change mode
JTabbedPane modeTabbedPane = new JTabbedPane();
calFrame.setContentPane(modeTabbedPane);
// add a panel to tabbedPane for standard mode
standardMode = new JPanel();
standardMode.setLayout(new BorderLayout(5, 5));
modeTabbedPane.add("Standard View", standardMode);
// add a panel to tabbedPane for scientific mode
scientificMode = new JPanel();
scientificMode.setLayout(new BorderLayout(5, 5));
modeTabbedPane.add("Scientific View", scientificMode);
// create keys and add them to panels
buttons1 = new JButton[20];
AddStandardKey(buttons1);
buttons2 = new JButton[30];
AddScientificKey(buttons2);
// add action listener to buttons
for (JButton button : buttons2) {
button.addActionListener(handler);
button.addKeyListener(new KeyLis());
}
// add display part to panels
addFirstDisplay();
addSecondDisplay();
// create menu bar
JMenuBar menuBar = new JMenuBar();
// create file menu
JMenu mainMenu = new JMenu("Menu");
mainMenu.setMnemonic('N');
// create exit item
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.ALT_MASK));
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
System.exit(0);
}
});
// create copy item
JMenuItem copyItem = new JMenuItem("Copy");
copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
copyItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
controller.setCopiedText(display2, display1);
}
});
// create about item
JMenuItem aboutItem = new JMenuItem("About");
aboutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
JOptionPane.showMessageDialog(null,
"Mahdi Hejrati \n9723100 \n",
"About",
JOptionPane.INFORMATION_MESSAGE);
}
});
// add menu
mainMenu.add(exitItem);
mainMenu.add(copyItem);
mainMenu.add(aboutItem);
menuBar.add(mainMenu);
calFrame.setJMenuBar(menuBar);
calFrame.addKeyListener(new KeyLis());
calFrame.requestFocusInWindow();
calFrame.setFocusable(true);
}
/**
* design the main frame
*/
public void designCalculatorFrame() {
calFrame.setTitle("My Calculator");
calFrame.setSize(430, 550);
calFrame.setLocation(600, 230);
calFrame.setMinimumSize(new Dimension(380, 350));
calFrame.setResizable(true);
calFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* create keys and add them to the center part of standardMode panel
*/
public void AddStandardKey(JButton[] buttons) {
JPanel standardKeyboardPanel = new JPanel();
standardKeyboardPanel.setLayout(new GridLayout(5, 4));
standardMode.add(standardKeyboardPanel, BorderLayout.CENTER);
String[] buttonText = {"%", "CE", "C", "/", "7", "8", "9", "*", "4", "5", "6", "-", "1", "2", "3", "+", "( )", "0", ".", "="};
// add properties to buttons
for (int i = 0; i < 20; i++) {
buttons[i] = new JButton();
buttons[i].setText(buttonText[i]);
buttons[i].setBackground(new Color(50, 50, 50));
buttons[i].setForeground(Color.white);
buttons[i].setOpaque(true);
buttons[i].setToolTipText(buttonText[i]);
buttons[i].setFont(buttons[i].getFont().deriveFont(16f));
standardKeyboardPanel.add(buttons[i]);
}
}
/**
* create keys and add them to the center part of scientificMode panel
*/
public void AddScientificKey(JButton[] buttons) {
JPanel scientificKeyboardPanel = new JPanel();
scientificKeyboardPanel.setLayout(new GridLayout(5, 6));
scientificMode.add(scientificKeyboardPanel, BorderLayout.CENTER);
String[] buttonText = {"PI", "%", "CE", "C", "/", "sin", "e", "7", "8", "9", "*", "tan", "^", "4", "5", "6", "-", "log", "!", "1", "2", "3", "+", "exp", "(", ")", "0", ".", "=", "shift"};
// add properties to buttons
for (int i = 0; i < 30; i++) {
buttons[i] = new JButton();
buttons[i].setText(buttonText[i]);
buttons[i].setBackground(new Color(50, 50, 50));
buttons[i].setForeground(Color.white);
buttons[i].setOpaque(true);
buttons[i].setToolTipText(buttonText[i]);
buttons[i].setFont(buttons[i].getFont().deriveFont(16f));
scientificKeyboardPanel.add(buttons[i]);
}
}
/**
* creat display part and add it to north part of standardMode panel
*/
public void addFirstDisplay() {
display1 = new JTextArea();
makeDisplay(display1);
JScrollPane scrollPane = new JScrollPane(display1);
scrollPane.setPreferredSize(new Dimension(100, 90));
standardMode.add(scrollPane, BorderLayout.NORTH);
}
/**
* creat display part and add it to north part of scientificMode panel
*/
public void addSecondDisplay() {
display2 = new JTextArea();
makeDisplay(display2);
JScrollPane scrollPane = new JScrollPane(display2);
scrollPane.setPreferredSize(new Dimension(100, 90));
scientificMode.add(scrollPane, BorderLayout.NORTH);
}
/**
* add properties to display
* @param display
*/
void makeDisplay(JTextArea display) {
display.setEditable(false);
display.setForeground(Color.white);
display.setBackground(new Color(100, 100, 100));
display.setFont(display.getFont().deriveFont(19f));
display.setToolTipText("text area to show operations");
}
/**
* set the frame visible to show
*/
public void setVisible() {
calFrame.setVisible(true);
}
/**
* inner class of button handler
*/
private class Handler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 29; i++)
if (e.getSource().equals(buttons2[i])) {
controller.clickButton(buttons2[i], i, display2);
}
if (e.getSource().equals(buttons2[29])) {
controller.shift(buttons2);
}
}
}
/**
* inner class of key handler
*/
private class KeyLis extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_7:
case KeyEvent.VK_NUMPAD7:
controller.clickButton(buttons2[7], 7, display2);
break;
case KeyEvent.VK_8:
case KeyEvent.VK_NUMPAD8:
controller.clickButton(buttons2[8], 8, display2);
break;
case KeyEvent.VK_9:
case KeyEvent.VK_NUMPAD9:
controller.clickButton(buttons2[9], 9, display2);
break;
case KeyEvent.VK_4:
case KeyEvent.VK_NUMPAD4:
controller.clickButton(buttons2[13], 13, display2);
break;
case KeyEvent.VK_5:
case KeyEvent.VK_NUMPAD5:
controller.clickButton(buttons2[14], 14, display2);
break;
case KeyEvent.VK_6:
case KeyEvent.VK_NUMPAD6:
controller.clickButton(buttons2[15], 15, display2);
break;
case KeyEvent.VK_1:
case KeyEvent.VK_NUMPAD1:
controller.clickButton(buttons2[19], 19, display2);
break;
case KeyEvent.VK_2:
case KeyEvent.VK_NUMPAD2:
controller.clickButton(buttons2[20], 20, display2);
break;
case KeyEvent.VK_3:
case KeyEvent.VK_NUMPAD3:
controller.clickButton(buttons2[21], 21, display2);
break;
case KeyEvent.VK_0:
case KeyEvent.VK_NUMPAD0:
controller.clickButton(buttons2[26], 26, display2);
break;
case KeyEvent.VK_R:
controller.clickButton(buttons2[1], 1, display2);
break;
case KeyEvent.VK_D:
controller.clickButton(buttons2[4], 4, display2);
break;
case KeyEvent.VK_M:
controller.clickButton(buttons2[10], 10, display2);
break;
case KeyEvent.VK_S:
controller.clickButton(buttons2[16], 16, display2);
break;
case KeyEvent.VK_P:
controller.clickButton(buttons2[22], 22, display2);
break;
case KeyEvent.VK_ENTER:
controller.clickButton(buttons2[28], 28, display2);
break;
case KeyEvent.VK_BACK_SPACE:
controller.clickButton(buttons2[3], 3, display2);
break;
case KeyEvent.VK_I:
controller.clickButton(buttons2[5], 5, display2);
break;
case KeyEvent.VK_T:
controller.clickButton(buttons2[11], 11, display2);
break;
case KeyEvent.VK_H:
controller.shift(buttons2);
break;
}
}
}
}
|
C++
|
UTF-8
| 2,179 | 3.015625 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <conio.h>
using namespace std;
template <typename T>
void prove(T a);
void fill_array(int** ary, const int N, const int M);
void solution(int** ary, const int N, const int M);
int main()
{
setlocale(LC_CTYPE, "rus");
srand(time(NULL));
int n, m, sum = 0;
cout << "Введите n: "; cin >> n; prove(n);
cout << "Введите m: "; cin >> m; prove(m);
int** matrix = new int* [n];
for (int i = 0; i < n; i++)
matrix[i] = new int[m];
fill_array(matrix, n, m);
solution(matrix, n, m);
cout << endl;
for (int i = 0; i < n; i++)
delete[] matrix[i];
delete[] matrix;
system("pause");
return 0;
}
template <typename T>
void prove(T a)
{
while (cin.fail())
{
cin.clear();
cin.ignore(INT16_MAX, '\t');
cout << "Error\nВведите другое значение";
cin >> a;
}
}
void fill_array(int** ary, const int N, const int M)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
cout << "array[" << i + 1 << "][" << j + 1 << "] = ";
cin >> ary[i][j];
}
cout << endl;
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
printf("%5i", ary[i][j]);
}
cout << endl;
}
}
void solution(int** ary, const int N, const int M)
{
bool col = true, row = true, p = true;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
col = true, row = true;
for (int i1 = 0; i1 < N; i1++)
if (ary[i][j] < ary[i1][j])
col = false;
for (int j1 = 0; j1 < M; j1++)
if (ary[i][j] > ary[i][j1])
row = false;
if (row && col)
{
cout << '[' << i + 1 << "][" << j + 1 << ']' << '\t';
p = false;
}
col = true, row = true;
for (int i1 = 0; i1 < N; i1++)
if (ary[i][j] > ary[i1][j])
col = false;
for (int j1 = 0; j1 < M; j1++)
if (ary[i][j] < ary[i][j1])
row = false;
if (row && col)
{
cout << '[' << i + 1 << "][" << j + 1 << ']' << '\t' << endl;
p = false;
}
}
}
if (p)
cout << "\nТаких элемениов нет\n";
}
|
JavaScript
|
UTF-8
| 1,574 | 3.578125 | 4 |
[] |
no_license
|
// PLEASE DON'T change function name
module.exports = function makeExchange(currency) {
// Your code goes here!
// Return an object containing the minimum number of coins needed to make change
currency = +currency;
let remainderH = 0, remainderQ = 0, remainderD = 0, remainderN = 0, remainderP = 0;
let answer = {};
if (currency > 10000){
answer = {error: "You are rich, my friend! We don't have so much coins for exchange"};
} else if(currency <= 0){
answer = {};
} else{
answer['H'] = Math.floor(currency / 50);
if (answer['H'] > 0){
remainderH = currency - (answer['H'] * 50);
} else{
remainderH = currency;
delete answer['H'];
}
answer['Q'] = Math.floor(remainderH / 25);
if (answer['Q'] > 0){
remainderQ = remainderH - (answer['Q'] * 25);
} else{
remainderQ = remainderH;
delete answer['Q'];
}
answer['D'] = Math.floor(remainderQ / 10);
if (answer['D'] > 0){
remainderD = remainderQ - (answer['D'] * 10);
} else{
remainderD = remainderQ;
delete answer['D'];
}
answer['N'] = Math.floor(remainderD / 5);
if (answer['N'] > 0){
remainderN = remainderD - (answer['N'] * 5);
} else{
remainderN = remainderD;
delete answer['N'];
}
if (remainderN > 0){
answer['P'] = remainderN;
}
}
return answer;
}
|
Java
|
UTF-8
| 210 | 1.882813 | 2 |
[] |
no_license
|
package base;
import org.openqa.selenium.WebElement;
public class PageElement {
private WebElement webElement;
private String elementType;
private String elementName;
int elementTimeout;
}
|
Markdown
|
UTF-8
| 424 | 2.703125 | 3 |
[] |
no_license
|
Thank You for looking at my resume! If Markdown isn't your thing you can find links to other formats of the resume below:
- [PDF](https://github.com/justgage/resume/raw/master/resume-in-many-formats/GageKPetersonsResume.pdf)
- [Website (HTML)](http://justgage.github.io/resume/)
- [Markdown](https://github.com/justgage/resume/blob/master/resume-in-many-formats/GageKPetersonsResume.md) (without comments at the top)
***
|
Python
|
UTF-8
| 1,563 | 3.3125 | 3 |
[] |
no_license
|
from itertools import cycle
from player import Player
from poker import Poker
"""
def bet_loop(poker):
stay = poker.players
fold = set()
pool = cycle(stay)
for p in pool:
"""
if __name__ == "__main__":
p1 = Player('P1', 1000)
p2 = Player('P2', 1000)
p3 = Player('P3', 1000)
poker = Poker()
while True:
poker.start_game()
poker.register_player(p1)
poker.register_player(p2)
poker.register_player(p3)
poker.deliver()
print(p1)
print(p2)
print(p3)
#bet_loop(poker)
for i, p in enumerate(poker.players):
if i == 0:
poker.get_money(p.bet(50))
elif i == 1:
poker.get_money(p.bet(100))
#print([str(p) for p in poker.players])
poker.fold_player(p2)
poker.reveal_card()
poker.reveal_card()
poker.reveal_card()
poker.reveal_card()
poker.reveal_card()
print('Table: {} / {}'.format([str(c) for c in poker.table_cards], poker.table_money))
win, score = poker.winner()
print('Winner: ' + win.name + ' with ' + score)
print([str(p) for p in poker.players])
control = input('Press any key to continue or q to quit:')
if control.lower() == 'q':
break
#poker.unregister_player(p1)
#poker.unregister_player(p2)
#poker.unregister_player(p3)
#print(poker.players)
|
Rust
|
UTF-8
| 7,755 | 3.71875 | 4 |
[
"BSD-2-Clause"
] |
permissive
|
pub mod huffman {
use std::boxed::Box;
use std::cmp::Ordering;
use std::collections::*;
/// Node is a binary tree data structure.
/// It will be used by huffman compression algorithm
#[derive(Clone, PartialEq, Eq, Ord, std::fmt::Debug)]
struct Node {
letter: char,
freq: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl PartialOrd for Node {
fn partial_cmp(self: &Node, other: &Node) -> Option<Ordering> {
let cmp = self.freq.cmp(&other.freq);
Some(cmp.reverse()) // For min heap
}
}
impl Node {
/// A convinence function to create a leaf node, i.e a node with no children
fn new(letter: char, freq: i32) -> Node {
Node {
letter,
freq,
left: None,
right: None,
}
}
}
///
/// Count the frequency of chars, return a vector of node.
///
/// Each node contains the character and corresponding frequency
/// > Note: Algotithm is based on sorting
///
fn freq_count(text: std::str::Chars) -> Vec<Node> {
let mut freq_vec = Vec::new();
let mut chars: Vec<char> = text.collect();
chars.sort();
let mut freq = 0;
let mut prev: char = *chars.first().expect("Input cannot be empty");
for c in chars {
if c == prev {
freq += 1;
} else {
freq_vec.push(Node::new(prev, freq));
freq = 1;
prev = c;
}
}
freq_vec.push(Node::new(prev, freq));
return freq_vec;
}
/// Create huffman encoding using huffman algorithm
/// ## Input:
/// Frequency vector: A vector of Nodes containing character frequency
/// (Use the freq_count function)
/// ## Output:
/// Root node of Huffman Tree of type Option<Box<Node>>
/// # Algorithm
/// - While priority_queue contains atleast 2 nodes:
/// - Choose two minimum elements and combine them
/// - Insert combined value back to tree
/// - Return tree
///
fn construct_huffman_tree(freq: Vec<Node>) -> Node {
let mut pq = BinaryHeap::new();
for node in freq {
pq.push(node);
}
while pq.len() > 1 {
let (a, b) = (pq.pop().unwrap(), pq.pop().unwrap());
let new_node = Node {
letter: '\0',
freq: a.freq + b.freq,
left: Option::from(Box::from(a)),
right: Option::from(Box::from(b)),
};
pq.push(new_node);
}
pq.pop().unwrap()
}
/// Convert huffman tree to a hashmap with key as char and value as encoding
/// E.g key = 'a', value = '1000'
fn to_hashmap(node: &Node) -> HashMap<char, String> {
let mut hm = HashMap::new();
// Huffman tree is complete binary tree, a node will have either 0 or 2 children, 1 is not possible
if node.left.is_none() {
hm.insert(node.letter, "0".to_string());
return hm;
}
fn encode(hm: &mut HashMap<char, String>, node: &Node, encoding: String) {
if node.left.is_none() {
hm.insert(node.letter, encoding);
} else {
let left_path = String::from(&encoding) + "0";
let right_path = String::from(&encoding) + "1";
if let Some(left) = &node.left {
encode(hm, &left, left_path);
}
if let Some(right) = &node.right {
encode(hm, &right, right_path);
}
}
};
encode(&mut hm, &node, "".to_string());
return hm;
}
/// Convert huffman node to string of chars using post-order traversal
fn to_string(huffman_node: &Node) -> String {
let mut output = String::new();
fn post_order(node: &Node, output_str: &mut String) {
if let Some(left) = &node.left {
post_order(left.as_ref(), output_str);
}
if let Some(right) = &node.right {
post_order(right.as_ref(), output_str);
}
output_str.push(node.letter);
}
post_order(huffman_node, &mut output);
return output;
}
/// Convert huffman tree to vector of bytes
///
/// First element is length of tree
///
/// There are only 100 or so printable characters
/// based on python's string.printable
/// So worst case tree size is 2N-1 = 199
/// So a unsigned char will suffice for length of tree
///
/// Following elements are charectars in post-order traversal of tree
fn embed_tree(huffman_node: &Node) -> Vec<u8> {
let mut compressed_data = to_string(huffman_node).into_bytes();
compressed_data.insert(0, compressed_data.len() as u8); // Append length
return compressed_data;
}
/// Simply maps input characters to their corresponding encoding and return as byte array
///
/// The first element is padding, (Number of zeroes appended for last encoding), as encoding might not fit into 8 bits
fn compress_data(text: &String, huffman_node: &Node) -> Vec<u8> {
let mut byte_stream: Vec<u8> = Vec::new();
let (mut byte, mut count) = (0, 0);
let huffman_map = to_hashmap(huffman_node);
for c in text.chars() {
let encoding = huffman_map.get(&c).unwrap();
for e in encoding.bytes() {
let bit: bool = (e - '0' as u8) != 0;
byte = byte << 1 | (bit as u8);
count = (count + 1) % 8;
if count == 0 {
byte_stream.push(byte);
byte = 0;
}
}
}
if count != 0 {
let padding: u8 = 8 - count;
byte <<= padding;
byte_stream.push(byte);
byte_stream.insert(0, padding);
} else {
byte_stream.insert(0, 0);
}
return byte_stream;
}
/// Compression using huffman's algorithm
/// # Data Format
/// First byte (n): Length of post-order traversal of huffman tree
///
/// Following n bytes contain post-order traversal
///
/// Padding byte (p): Padding for final byte
///
/// All remaining bytes are data
pub fn compress(text: &String) -> Vec<u8> {
let frequency = freq_count(text.chars());
let huffman_tree = construct_huffman_tree(frequency);
let mut compressed_data = Vec::from(embed_tree(&huffman_tree));
compressed_data.extend(compress_data(text, &huffman_tree));
return compressed_data;
}
fn construct_tree_from_postorder(postorder: &[u8]) -> Node {
// parent left right
// Assuming input does not contain null
let mut stack = Vec::new();
for c in postorder {
if *c == 0 as u8 {
let (left, right) = (
stack.pop().expect("Input contains Null byte"),
stack.pop().expect("Input contains Null byte"),
);
stack.push(Node {
letter: '\0',
freq: 0,
left: Option::from(Box::from(right)),
right: Option::from(Box::from(left)),
});
} else {
stack.push(Node {
letter: *c as char,
freq: 0,
left: None,
right: None,
});
}
}
return stack.pop().unwrap();
}
fn decompress_data(data: &[u8], tree: &Node) -> String {
let padding = *data.first().expect("Data empty");
let data = &data[1..]; // Remove first element which stores number of padded bits
let mut bit_stream = Vec::new();
let mut tmp = tree;
let mut output = String::new();
for character in data.iter() {
let mut character = *character;
for _ in 0..8 {
let bit: bool = (character >> 7 & 1) != 0;
character <<= 1;
bit_stream.push(bit);
}
}
bit_stream.resize(bit_stream.len() - padding as usize, false); // Remove padding bits
if tree.left.is_none() {
// Huffman tree is complete binary tree, a node will have either 0 or 2 children, 1 is not possible
for _ in 0..bit_stream.len() {
output.push(tree.letter);
}
return output;
}
for &bit in &bit_stream {
if tmp.left.is_none() {
output.push(tmp.letter);
tmp = tree;
}
let right: &Node = tmp.right.as_ref().unwrap().as_ref();
let left: &Node = tmp.left.as_ref().unwrap().as_ref();
tmp = if bit { right } else { left };
}
if tmp != tree {
output.push(tmp.letter);
}
return output;
}
pub fn decompress(data: &Vec<u8>) -> String {
let post_order_length = *data.first().expect("Data cannot be empty") as usize;
let post_order = &data[1..=post_order_length];
let huffman_tree = construct_tree_from_postorder(post_order);
let data = &data[post_order_length + 1..];
decompress_data(data, &huffman_tree)
}
}
|
C++
|
UTF-8
| 3,069 | 2.71875 | 3 |
[] |
no_license
|
#include "receiver.h"
#include <iostream>
Receiver::Receiver(QWidget *parent) : QWidget(parent)
{
}
void Receiver::receiveValueHW1(int i)
{
if(scoreHW1 != i){
scoreHW1 = i;
double t = this->recalculate();
emit signalValue(t);
//emit two signals? or maybe emit calculated value?
}
}
void Receiver::receiveValueHW2(int i){
if(scoreHW2 != i){
scoreHW2 = i;
double t = this->recalculate();
emit signalValue(t);
//emit two signals? or maybe emit calculated value?
}
}
void Receiver::receiveValueHW3(int i){
if(scoreHW3 != i){
scoreHW3 = i;
double t = this->recalculate();
emit signalValue(t);
//emit two signals? or maybe emit calculated value?
}
}
void Receiver::receiveValueHW4(int i){
if(scoreHW4 != i){
scoreHW4 = i;
double t = this->recalculate();
emit signalValue(t);
//emit two signals? or maybe emit calculated value?
}
}
void Receiver::receiveValueHW5(int i){
if(scoreHW5 != i){
scoreHW5 = i;
double t = this->recalculate();
emit signalValue(t);
//emit two signals? or maybe emit calculated value?
}
}
void Receiver::receiveValueHW6(int i){
if(scoreHW6 != i){
scoreHW6 = i;
double t = this->recalculate();
emit signalValue(t);
//emit two signals? or maybe emit calculated value?
}
}
void Receiver::receiveValueHW7(int i){
if(scoreHW7 != i){
scoreHW7 = i;
double t = this->recalculate();
emit signalValue(t);
//emit two signals? or maybe emit calculated value?
}
}
void Receiver::receiveValueHW8(int i){
if(scoreHW8 != i){
scoreHW8 = i;
double t = this->recalculate();
emit signalValue(t);
//emit two signals? or maybe emit calculated value?
}
}
void Receiver::receiveValueMID1(int i){
if(scoreMID1 != i){
scoreMID1 = i;
double t = this->recalculate();
emit signalValue(t);
//emit two signals? or maybe emit calculated value?
}
}
void Receiver::receiveValueMID2(int i){
if(scoreMID2 != i){
scoreMID2 = i;
double t = this->recalculate();
emit signalValue(t);
//emit two signals? or maybe emit calculated value?
}
}
void Receiver::receiveValueFIN(int i){
if(scoreFIN != i){
scoreFIN = i;
double t = this->recalculate();
emit signalValue(t);
}
}
double Receiver::recalculate()
{
double temp1 = ((scoreHW1 + scoreHW2 + scoreHW3 + scoreHW4 + scoreHW5 + scoreHW6 + scoreHW7 + scoreHW8) / 800. * 25.) + (scoreMID1) / 100. * 20. + (scoreMID2) / 100. * 20. + (scoreFIN) / 100. * 35.;
double temp2 = (scoreHW1 + scoreHW2 + scoreHW3 + scoreHW4 + scoreHW5 + scoreHW6 + scoreHW7 + scoreHW8) / 800. * 25. + fmax(scoreMID1,scoreMID2) / 100. * 30. + (scoreFIN) / 100. * 44.;
score = fmax(temp1,temp2);
return score;
}
|
JavaScript
|
UTF-8
| 442 | 3.1875 | 3 |
[] |
no_license
|
export const format = (seconds) => {
if (isNaN(seconds)) return '...';
const minutes = Math.floor(seconds / 60);
seconds = Math.floor(seconds % 60);
if (seconds < 10) seconds = '0' + seconds;
return `${minutes}:${seconds}`;
}
export const timeToMiliSeconds = (time) => {
if (time === null || time === undefined) return '...';
const [min, sec] = time.split(':');
const milliseconds = (+min * 60) + +sec + 1;
return milliseconds
}
|
Python
|
UTF-8
| 1,057 | 3.15625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 5 10:08:31 2018
@author: Tim
"""
#1. Board, Marble, 1D, Pitch/Roll
from sense_hat import SenseHat
sense = SenseHat()
b = (0,0,0)
w = (255,255,255)
board = [[b,b,b,b,b,b,b,b],
[b,b,b,b,b,b,b,b],
[b,b,b,b,b,b,b,b],
[b,b,b,b,b,b,b,b],
[b,b,b,b,b,b,b,b],
[b,b,b,b,b,b,b,b],
[b,b,b,b,b,b,b,b],
[b,b,b,b,b,b,b,b]]
y = 2
x = 2
board[y][x] = w
board_1D = sum(board,[])
sense.set_pixels(board_1D)
def move_marble(pitch, roll, x, y):
new_x = x
new_y = y
if 1 < pitch <179 and x !=0:
new_x -= 1
elif 179 < pitch < 359 and x!= 7:
new_x += 1
if 1 < roll <179 and x !=7:
new_x += 1
elif 179 < roll < 359 and x!= 0:
new_x -= 1
return new_x, new_y
while True:
pitch = sense.get_orientation()['pitch']
roll = sense.get_orientation()['roll']
board[y][x] = b
x,y = move_marble(pitch,roll,x,y)
board[y][x] = w
sense.set_pixels(sum(board,[]))
sleep(0.05)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.