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
|
---|---|---|---|---|---|---|---|
SQL
|
UTF-8
| 408 | 3.015625 | 3 |
[] |
no_license
|
DROP TABLE IF EXISTS `address_book`;
CREATE TABLE `address_book` (
`id` int(11) AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`birthday` DATE NOT NULL,
`sex` tinyint NOT NULL,
`tel` varchar(32) NOT NULL,
`zip` varchar(8) NOT NULL,
`address` varchar(255) NOT NULL,
`is_used` tinyint NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY (`name`,`tel`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
Python
|
UTF-8
| 733 | 3.875 | 4 |
[] |
no_license
|
# %%
# Conjunto não garante a ordem da inserção, não é indexado e não aceita repetição
a = {1, 2, 3}
print(type(a))
# a[0]
a = set('coddddd3r')
print(type(a))
print(a)
print('3' in a, 4 not in a)
{1, 2, 3} == {3, 2, 1, 3}
# operacoes
c1 = {1, 2}
c2 = {2, 3}
print(c1.union(c2)) # union() -> união de dois conjuntos gerando um novo conjunto
print(c1.intersection(c2)) # intersection() -> intersecção de dois conjuntos gerando um novo conjunto
c1.update(c2) # update() -> altera o conjunto c1 adicionando o c2
print(c1)
print(c2 <= c1) # leitura -> c2 é subconjunto de c1
print(c1 >= c2) # leitura -> c1 é superconjunto de c2
print({1, 2, 3} - {2}) # diferença entre os conjuntos
print(c1 - c2)
c1 -= {2}
print(c1)
|
Java
|
UTF-8
| 493 | 2.09375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package nc.bs.lxt.pub;
import java.util.HashMap;
import nc.bs.pub.formulaparse.FormulaParse;
import nc.vo.pub.formulaset.FormulaParseFather;
public class NCBSTool {
static public Object[][] getValueByFormula(String[] formula, HashMap<String, Object> vars) {
FormulaParseFather f = new FormulaParse();
for (String key : vars.keySet())
f.addVariable(key ,vars.get(key));
f.setExpressArray(formula);
Object[][] results = f.getValueSArray();
return results;
}
}
|
Python
|
UTF-8
| 2,753 | 3.34375 | 3 |
[] |
no_license
|
from Account import saved_username
from Account import saved_password
account_existence = input("Hello,do you have an account? ")
if account_existence.lower() not in "yesno":
print("Please type Yes if you agree or No if you do not agree next time!")
if account_existence.lower() == "no":
account_m_process = input("Do you want to make an account? ")
if account_m_process.lower() in "no":
print("Got it!")
elif account_m_process.lower() in "yes":
print("Please enter your new username and password: ")
saved_username = input("Username: ")
saved_password = input("Password: ")
Account_file = open("Account.py", "w")
Account_file.write("saved_username = " "\"" + saved_username + "\"" "\n" "saved_password = " "\"" + saved_password + "\"")
Account_file.close()
print("Congratulations on the birth of your new account!")
elif account_m_process.lower() in "no":
print("Ok!")
elif account_m_process.lower() not in "yesno":
print("Please type Yes if you agree or No if you do not agree next time!")
elif account_existence.lower() in "yes" and account_existence.lower() not in "es":
print("Please enter your username and password: ")
username = input("Username: ")
password = input("Password: ")
if username == saved_username and password == saved_password:
print("Welcome back " + saved_username + "!")
elif password == saved_password and not username == saved_username:
account_username_trying = input("Wrong username,try again? ")
if account_username_trying.lower() in "yes":
tries_username = 5
while tries_username > 0:
username = input("Username: ")
tries_username -= 1
if username == saved_username:
print("Welcome back!")
elif username != saved_username and not tries_username == 1:
print("Wrong username!")
elif tries_username == 1:
print("Last chance!")
elif username == saved_username and not password == saved_password:
account_password_trying = input("Wrong password,try again? ")
if account_password_trying.lower() in "yes":
tries_password = 5
while tries_password > 0:
password = input("Password: ")
tries_password -= 1
if password == saved_password:
print("Welcome back!")
elif password != saved_password and not tries_password == 1:
print("Wrong password!")
elif tries_password == 1:
print("Last chance!")
else:
print("No account exists with the info! ")
|
Swift
|
UTF-8
| 1,768 | 2.609375 | 3 |
[] |
no_license
|
//
// TabBarViewController.swift
// TheCodeChallange
//
// Created by Saurav Dutta on 11/08/20.
// Copyright © 2020 Saurav Dutta. All rights reserved.
//
import UIKit
class TabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.viewControllers = self.setAllViewControllers()
self.setLayoutAndDesign()
}
// MARK: - Set VCs to TabBar
//In-Short :This method returns all VC associated with the Tab Bar.
// Added by: Saurav Dutta
// Added on: 11/08/20
func setAllViewControllers() ->[UIViewController]{
let vcHome = setVcForTabBar(SDViewController(title: "Home"),"Home")
let vcSearch = setVcForTabBar(SearchMainViewController(title: "Search"),"Search")
let vcMarket = setVcForTabBar(SDViewController(title: "Market"),"Market")
let vcUsers = setVcForTabBar(SDViewController(title: "Users"),"Users")
let vcReserach = setVcForTabBar(SDViewController(title: "Research"),"Research")
return [vcHome,vcSearch,vcMarket,vcUsers,vcReserach]
}
func setVcForTabBar(_ vc:UIViewController,_ imgNamed:String = "") -> UIViewController{
let vc = SDNavController(rootViewController: vc)
vc.view.backgroundColor = UIColor.white
vc.tabBarItem = UITabBarItem(title: "", image: UIImage(named: imgNamed), selectedImage: UIImage(named: imgNamed))
return vc
}
// MARK: - Design & Appearance
// In-Short :These methods are responsible to setup the design and appearance of this Tab Bar by setting up colors.
// Added by: Saurav Dutta
// Added on: 11/08/20
func setLayoutAndDesign(){
self.tabBar.barTintColor = UIColor.white
self.tabBar.tintColor = APP_PRIMARY_COLOR
}
}
|
TypeScript
|
UTF-8
| 12,753 | 2.75 | 3 |
[
"Apache-2.0"
] |
permissive
|
import {isNotNil} from "@w11k/rx-ninja";
import {filter} from "rxjs/operators";
import {createAsyncPromise, createTestFacade, createTestMount} from "../testing";
import {collect} from "../testing/test-utils-internal";
import {Commands, CommandsInvoker} from "./commands";
import {enableTyduxDevelopmentMode} from "./development";
import {Facade} from "./Facade";
import {untilNoBufferedStateChanges} from "./utils";
describe("Commands", () => {
beforeEach(() => enableTyduxDevelopmentMode());
it("CommandsInvoker", () => {
class TestCommands extends Commands<{ n1: number }> {
mut1() {
this.state.n1++;
}
}
const ci = new CommandsInvoker(new TestCommands());
const newState = ci.invoke({n1: 1}, c => c.mut1());
expect(newState).toEqual({n1: 2});
});
it("methods can assign state properties", async () => {
class TestCommands extends Commands<{ n1: number }> {
mut1() {
this.state.n1 = 1;
}
}
const facade = createTestFacade(new TestCommands(), {n1: 0});
facade.commands.mut1();
expect(facade.state).toEqual({n1: 1});
});
it("methods can assign state properties successively", async () => {
class State {
list1?: number[];
list2: number[] = [];
}
class TestCommands extends Commands<State> {
mut1() {
this.state.list1 = [1];
}
mut2() {
this.state.list2 = [2];
}
}
class TestFacade extends Facade<TestCommands> {
action1() {
this.commands.mut1();
}
action2() {
this.commands.mut2();
}
}
const facade = new TestFacade(createTestMount(new State()), new TestCommands(), undefined);
facade.select(s => s.list1)
.pipe(
filter(s => isNotNil(s))
)
.subscribe(() => {
facade.action2();
});
facade.action1();
await untilNoBufferedStateChanges(facade);
expect(facade.state.list1).toEqual([1]);
expect(facade.state.list2).toEqual([2]);
});
it("methods can assign a new state", async () => {
class TestCommands extends Commands<{ n1: number }> {
mut1() {
this.state = {
n1: 99
};
}
}
class TestFacade extends Facade<TestCommands> {
action() {
this.commands.mut1();
}
}
const facade = new TestFacade(createTestMount({n1: 0}), new TestCommands(), undefined);
facade.action();
await untilNoBufferedStateChanges(facade);
expect(facade.state).toEqual({n1: 99});
});
it("can change the state deeply", () => {
class TestCommands extends Commands<{ n1: number[] }> {
mut1() {
this.state.n1.push(3);
}
}
class TestFacade extends Facade<TestCommands> {
action() {
this.commands.mut1();
}
}
const facade = new TestFacade(createTestMount({n1: [1, 2]}), new TestCommands(), undefined);
facade.action();
expect(facade.state).toEqual({n1: [1, 2, 3]});
});
it("nested methods are merged", async () => {
class TestCommands extends Commands<{ n1: string }> {
mod1() {
this.state.n1 += "1";
this.mod2();
this.mod3();
}
mod2() {
this.state.n1 += "2";
}
mod3() {
this.state.n1 += "3";
}
}
class TestStore extends Facade<TestCommands> {
action1() {
this.commands.mod1();
}
}
const facade = new TestStore(createTestMount({n1: ""}), new TestCommands(), undefined);
const collected = collect(facade.select(s => s.n1));
facade.action1();
await untilNoBufferedStateChanges(facade);
collected.assert("", "123");
});
it("state changes are only persistent if the Commands did not throw an exception", () => {
class TestCommands extends Commands<any> {
mut1() {
this.state.count = 1;
if (this.state.count > 0) {
throw new Error("");
}
this.state.count = 2;
}
}
class TestFacade extends Facade<TestCommands> {
action() {
this.commands.mut1();
}
}
const facade = new TestFacade(createTestMount({a: 0}), new TestCommands(), undefined);
expect(() => facade.action()).toThrow();
expect(facade.state.a).toEqual(0);
});
it("Commands must not have instance members", () => {
class TestCommands extends Commands<any> {
// noinspection JSUnusedGlobalSymbols
abc = 1;
}
class TestFacade extends Facade<TestCommands> {
}
expect(
() => new TestFacade(createTestMount({}), new TestCommands(), undefined)
).toThrow();
});
it("Commands must not create instance members", () => {
class TestCommands extends Commands<any> {
mut() {
(this as any).abc = 1;
}
}
class TestFacade extends Facade<TestCommands> {
action() {
expect(() => this.commands.mut()).toThrow();
}
}
const facade = new TestFacade(createTestMount({}), new TestCommands(), undefined);
facade.action();
});
it("methods are pulled to the instance", () => {
class TestCommands extends Commands<any> {
mut() {
this.state.val = 1;
}
}
class TestFacade extends Facade<TestCommands> {
mut = this.commands.mut;
}
const facade = new TestFacade(createTestMount(), new TestCommands(), {});
facade.mut();
expect(facade.state.val).toEqual(1);
});
});
describe("Commands - sanity tests", function () {
beforeEach(() => enableTyduxDevelopmentMode());
it("can not access the state asynchronously", function (done) {
class TestCommands extends Commands<{ n1: number }> {
mut() {
setTimeout(() => {
expect(() => this.state).toThrow();
done();
}, 0);
}
}
class TestFacade extends Facade<TestCommands> {
action() {
this.commands.mut();
}
}
const facade = new TestFacade(createTestMount({n1: 0}), new TestCommands(), undefined);
facade.action();
});
it("can not modify the state asynchronously by keeping a reference to a nested state property", function (done) {
class TestCommands extends Commands<{ root: { child: number[] } }> {
mut() {
const child = this.state.root.child;
setTimeout(() => {
expect(() => child.push(3)).toThrow();
done();
}, 0);
}
}
class TestFacade extends Facade<TestCommands> {
action() {
this.commands.mut();
}
}
const state = {root: {child: [1, 2]}};
const facade = new TestFacade(createTestMount(state), new TestCommands(), undefined);
facade.action();
});
it("can not replace the state asynchronously", function (done) {
class TestCommands extends Commands<{ n1: number }> {
mut() {
setTimeout(() => {
expect(() => this.state = {n1: 99}).toThrow();
done();
}, 0);
}
}
class TestFacade extends Facade<TestCommands> {
action() {
this.commands.mut();
}
}
const facade = new TestFacade(createTestMount({n1: 0}), new TestCommands(), undefined);
facade.action();
});
it("can not change the state in asynchronous promise callbacks", function (done) {
class TestCommands extends Commands<{ n1: number }> {
mut1() {
createAsyncPromise(1).then(val => {
expect(() => this.state.n1 = val).toThrow();
done();
});
}
}
class TestFacade extends Facade<TestCommands> {
action() {
this.commands.mut1();
}
}
const facade = new TestFacade(createTestMount({n1: 0}), new TestCommands(), undefined);
facade.action();
});
it("can not access other members asynchronously", function (done) {
class TestCommands extends Commands<{ n1: number }> {
mut1() {
setTimeout(() => {
expect(() => this.mut2()).toThrow();
done();
}, 0);
}
mut2() {
// empty
}
}
class TestFacade extends Facade<TestCommands> {
action() {
this.commands.mut1();
}
}
const facade = new TestFacade(createTestMount({n1: 0}), new TestCommands(), undefined);
facade.action();
});
it("can not access other members in an asynchronous promise resolve", function (done) {
class TestCommands extends Commands<{ n1: number }> {
mut1() {
createAsyncPromise(1)
.then(() => {
this.mut2();
})
.catch((e: Error) => {
expect(e.message).toMatch(/.*Illegal access.*this.*/);
done();
});
}
mut2() {
console.log(3);
this.state.n1 = -99;
}
}
class TestFacade extends Facade<TestCommands> {
action() {
this.commands.mut1();
}
}
const facade = new TestFacade(createTestMount({n1: 0}), new TestCommands(), undefined);
facade.action();
});
it("must not return a value", function () {
class TestCommands extends Commands<any> {
mod1() {
return 1;
}
}
class TestFacade extends Facade<TestCommands> {
action() {
expect(() => this.commands.mod1()).toThrow();
}
}
const facade = new TestFacade(createTestMount({}), new TestCommands(), undefined);
facade.action();
});
it("commands can change state more than once", () => {
class TestCommands extends Commands<{ numbers: number[], foo: Record<string, number> }> {
addNumberInNumbers(n: number) {
this.state.numbers.push(n);
}
addNumbersToFoo(numbers: number[]) {
numbers.forEach(n => {
this.state.foo[`${n}`] = n;
});
}
}
class TestFacade extends Facade<TestCommands> {
action() {
this.commands.addNumbersToFoo([1, 2, 3]);
this.commands.addNumberInNumbers(1);
}
}
const facade = new TestFacade(createTestMount({numbers: [], foo: {}} as any), new TestCommands(), undefined);
facade.action();
expect(facade.state).toEqual({
foo: {
"1": 1,
"2": 2,
"3": 3
},
numbers: [1]
});
});
it("todo example", () => {
class TestCommands extends Commands<{ todos: { name: string, isDone: boolean }[] }> {
toggleTodo(name: string) {
const todo = this.state.todos.find(it => it.name === name);
todo!.isDone = !todo!.isDone;
}
}
class TestFacade extends Facade<TestCommands> {
toggleFoo() {
this.commands.toggleTodo("foo");
}
}
const facade = new TestFacade(createTestMount({todos: [{name: "foo", isDone: false}]} as any), new TestCommands(), undefined);
facade.toggleFoo();
expect(facade.state.todos[0].isDone).toBe(true);
facade.toggleFoo();
expect(facade.state.todos[0].isDone).toBe(false);
});
});
|
Python
|
UTF-8
| 325 | 3.703125 | 4 |
[] |
no_license
|
cost = float (input ("Bonjour, S'il vous plait,mettez le prix de votre déjeuner"))
tip = cost*0.18
tax = 0.25*cost
print ("Vos allez payer por le tip le combien de " "%.2f" % tip, "$" )
print ("Vos allez payer por le tax le combien de " "%.2f" % tax, "$" )
print ("Le prix total est : " "%.2f" % (tip + cost + tax), "$" )
|
Java
|
UTF-8
| 593 | 1.773438 | 2 |
[] |
no_license
|
package com.serious.business.common;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
private static final String BUNDLE_NAME = "com.serious.business.common.messages";
static {
reloadMessages();
}
public static void reloadMessages() {
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
public static String message_child_name;
public static String message_button_up;
public static String message_button_down;
public static String message_button_edit;
public static String message_button_add;
public static String message_button_remove;
}
|
Java
|
UTF-8
| 9,549 | 2.21875 | 2 |
[] |
no_license
|
package school.view;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.ResourceBundle;
import entite.Groupes;
import entite.Salles;
import entite.Sessions;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import school.MainApp;
public class ControlerSecretaire implements Initializable {
@FXML private Pane paneAcc;
@FXML private SplitPane paneSessions;
@FXML private TableView<Sessions> SessionView;
@FXML private TableColumn<Sessions,String> ColDateFin;
@FXML private TableColumn<Sessions,String> colDateDebut;
@FXML private TableColumn<Sessions,String> colNom;
@FXML private TableColumn<Sessions,String> colId;
@FXML private TableColumn<Sessions,String> colSalle;
@FXML private Button btnSupp;
@FXML private Button btnModif;
@FXML private Button btnRecherche;
@FXML private TextField inName;
@FXML private DatePicker inDebutPicker;
@FXML private DatePicker inFinPicker;
@FXML private ComboBox<Salles> cbSalle;
@FXML private ComboBox<Groupes> cbGroupe;
@FXML private Button btnAjouter;
//panel Groupe
@FXML private SplitPane paneGroupes;
@FXML private Button btnAjouter2;
@FXML private Button btnModifier2;
@FXML private Button btnSupp2;
@FXML private Button btnRetour2;
@FXML private ComboBox cbGroupe2;
@FXML private TextField txtMatiere2;
@FXML private TableView<Groupes> GroupesView;
@FXML private TableColumn<Groupes,String> GroupesId;
@FXML private TableColumn<Groupes,String> GroupesMatiere;
@FXML private TableColumn<Groupes,String> GroupesNom;
private String nom;
private String prenom;
private String num;
ObservableList<Sessions> SessionsData = FXCollections.observableArrayList();
ObservableList<Groupes> GroupesData = FXCollections.observableArrayList();
private Calendar h = Calendar.getInstance();
private MainApp mainApp;
//
public void init(MainApp mainAp, String name,String prename , String numero) {
this.setMainApp(mainAp);
this.setNom(name);
this.setPrenom(prename);
this.setNum(numero);
cbSalle.getItems().addAll(mainApp.getFct().selectAllNameSalle());
cbGroupe.getItems().addAll(mainApp.getFct().selectAllNameGroupe());
cbGroupe2.getItems().addAll(mainApp.getFct().selectAllNameGroupe());
}//
public ControlerSecretaire(){
}
@FXML public void initialize(URL location, ResourceBundle resources){
colId.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getIdSession()+"") );
colNom.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getLibelSession()) );
colDateDebut.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getDateDebutSession().get(h.YEAR) +"-"+ cellData.getValue().getDateDebutSession().get(h.MONTH)+"-"+ cellData.getValue().getDateDebutSession().get(h.DAY_OF_MONTH)));
ColDateFin.setCellValueFactory(cellData -> new SimpleObjectProperty(cellData.getValue().getDateFinSession().get(h.YEAR) +"-"+ cellData.getValue().getDateFinSession().get(h.MONTH)+"-"+ cellData.getValue().getDateFinSession().get(h.DAY_OF_MONTH)));
colSalle.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getSalle() ));
SessionView.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> MajInput(newValue));
GroupesId.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getIdGroupe()+""));
GroupesMatiere.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getIdMatiere()+""));
GroupesNom.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getLibelGroupe()));
GroupesView.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> MajInput(newValue));
}
//****** PANEL ACC
public void GestionSessions() {
paneAcc.setVisible(false);
SessionView.getSelectionModel().clearSelection();
SessionsData.clear();
SessionsData.addAll(mainApp.getFct().allSessions());
SessionView.setItems(SessionsData);
paneSessions.setVisible(true);
}
public void GestionGroupes() {
paneAcc.setVisible(false);
GroupesView.getSelectionModel().clearSelection();
GroupesData.clear();
GroupesData.addAll(mainApp.getFct().selectAllNameGroupe());
GroupesView.setItems(GroupesData);
paneGroupes.setVisible(true);
}
/*
PANEL SESSIONS
*/
/**
* Lorsqu'un items du tableau est selectionnez permet de mettre a jours les textfields
*/
public void MajInput(Sessions s) {
if( s!=null) {
h = s.getDateDebutSession();
LocalDate hh = LocalDate.of(h.get(h.YEAR), h.get(h.MONTH), h.get(h.DAY_OF_MONTH));
inDebutPicker.setValue(hh);
h = s.getDateFinSession();
LocalDate hh2 = LocalDate.of(h.get(h.YEAR), h.get(h.MONTH), h.get(h.DAY_OF_MONTH));
inFinPicker.setValue(hh2);
cbSalle.getSelectionModel().select(mainApp.getFct().selectSalleById(s.getSalle()));
cbGroupe.getSelectionModel().select(mainApp.getFct().selectGroupeById(s.getIdGroupe()));
inName.setText(s.getLibelSession());
}
}
public void backAcc() {
paneAcc.setVisible(true);
paneSessions.setVisible(false);
}
public void handleRecherche() {
SessionView.getSelectionModel().clearSelection();
SessionsData.clear();
SessionsData.addAll(mainApp.getFct().selectSessionName(inName.getText()));
SessionView.setItems(SessionsData);
}
public void handleModif() {
Sessions s = SessionView.getSelectionModel().getSelectedItem();
System.out.println(s.toString());
mainApp.getFct().updateSessions(s.getIdSession(),inName.getText(),cbSalle.getSelectionModel().getSelectedItem().getIdSalle(),inDebutPicker.getValue(),inFinPicker.getValue());
SessionView.getSelectionModel().clearSelection();
SessionsData.clear();
SessionsData.addAll(mainApp.getFct().allSessions());
SessionView.setItems(SessionsData);
}
public void handleSupp() {
mainApp.getFct().suppSessions(SessionView.getSelectionModel().getSelectedItem().getIdSession()+"");
SessionView.getSelectionModel().clearSelection();
SessionsData.clear();
SessionsData.addAll(mainApp.getFct().allSessions());
SessionView.setItems(SessionsData);
}
public void handleAjouter() {
mainApp.getFct().addSessions(((Salles) cbSalle.getSelectionModel().getSelectedItem()).getIdSalle(), ((Groupes) cbGroupe.getSelectionModel().getSelectedItem()).getIdGroupe(),inName.getText(),inDebutPicker.getValue(),inFinPicker.getValue());
SessionView.getSelectionModel().clearSelection();
SessionsData.clear();
SessionsData.addAll(mainApp.getFct().allSessions());
SessionView.setItems(SessionsData);
}
/**
Panel des groupes.
**/
public void backAcc2() {
paneAcc.setVisible(true);
paneGroupes.setVisible(false);
}
public void MajInput(Groupes s) {
if( s!=null) {
txtMatiere2.setText(s.getIdMatiere()+"");
cbGroupe2.getSelectionModel().select(mainApp.getFct().selectGroupeById(s.getIdGroupe()));
}
}
public void handleModif2() {
Groupes g = new Groupes();
g.setIdMatiere(Integer.valueOf(txtMatiere2.getText()));
g.setLibelGroupe(((Groupes) cbGroupe2.getValue()).getLibelGroupe());
mainApp.getFct().updateGroupe(g);
SessionView.getSelectionModel().clearSelection();
SessionsData.clear();
SessionsData.addAll(mainApp.getFct().allSessions());
SessionView.setItems(SessionsData);
}
public void handleSupp2() {
mainApp.getFct().deleteGroupe(GroupesView.getSelectionModel().getSelectedItem());
GroupesView.getSelectionModel().clearSelection();
GroupesData.clear();
GroupesData.addAll(mainApp.getFct().selectAllNameGroupe());
GroupesView.setItems(GroupesData);
}
public void handleAjouter2() {
Groupes g = new Groupes();
g.setIdMatiere(Integer.valueOf(txtMatiere2.getText()));
g.setLibelGroupe(((Groupes) cbGroupe2.getValue()).getLibelGroupe());
mainApp.getFct().addGroupe(g);
SessionView.getSelectionModel().clearSelection();
SessionsData.clear();
SessionsData.addAll(mainApp.getFct().allSessions());
SessionView.setItems(SessionsData);
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public MainApp getMainApp() {
return mainApp;
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
}
}
|
C++
|
UTF-8
| 2,759 | 3.203125 | 3 |
[] |
no_license
|
#include "network.h"
#include "random.h"
#include <algorithm>
#include <stdexcept>
struct greater
{
template<class T>
bool operator()(T const &a, T const &b) const
{
return a > b;
}
};
void Network::resize(const size_t& size)
{
values.resize(size);
RandomNumbers rn;
rn.normal(values);
}
bool Network::add_link(const size_t& a, const size_t& b)
{
if (a < values.size() and b < values.size() and a != b and !is_pair_in_links(std::pair<size_t, size_t>(a,b)))
{
links.emplace(a,b);
links.emplace(b,a);
return true;
}
return false;
}
size_t Network::random_connect(const double& mean_deg)
{
links.clear();
size_t size = values.size();
std::vector<size_t> deg_n_values(size, 0); // stores the deg(n) values for each node
std::vector<size_t> actual_connections_nb(size, 0); // stores the nb of connections that each node has yet
RandomNumbers rn;
rn.poisson(deg_n_values, mean_deg);
for (size_t i(0); i < size; ++i)
{
if (deg_n_values[i] >= size-1)
{
deg_n_values[i] = size-1;
}
while (actual_connections_nb[i] < deg_n_values[i])
{
int index(rn.uniform_int(i, size-1));
if (actual_connections_nb[index] < deg_n_values[index] and add_link(i, size_t(index)))
{
actual_connections_nb[i] += 1;
actual_connections_nb[index] += 1;
}
else
{
size_t j(i+1);
while ((actual_connections_nb[j] >= deg_n_values[j] or !add_link(i, j)) and j < size)
{
++j;
}
if (j == size)
{
deg_n_values[i] = actual_connections_nb[i];
}
else
{
actual_connections_nb[i] += 1;
actual_connections_nb[j] += 1;
}
}
}
}
return links.size();
}
size_t Network::set_values(const std::vector<double>& new_vect)
{
size_t n(std::min(values.size(), new_vect.size()));
for (size_t i(0); i < n; ++i)
{
values[i] = new_vect[i];
}
return n;
}
size_t Network::size() const
{
return values.size();
}
size_t Network::degree(const size_t& n) const
{
return links.count(n);
}
double Network::value(const size_t & n) const
{
if (n >= values.size())
{
throw std::out_of_range("n greater than values.size()");
}
return values[n];
}
std::vector<double> Network::sorted_values() const
{
std::vector<double> sorted_values(values);
std::sort(sorted_values.begin(), sorted_values.end(), greater());
return sorted_values;
}
std::vector<size_t> Network::neighbors(const size_t& n) const
{
std::vector<size_t> neighbors;
for (auto I : links)
{
if (I.first == n)
{
neighbors.push_back(I.second);
}
}
return neighbors;
}
bool Network::is_pair_in_links(const std::pair<size_t, size_t>& my_pair)
{
for (const auto& I : links)
{
if (I.first == my_pair.first and I.second == my_pair.second)
{
return true;
}
}
return false;
}
|
Markdown
|
UTF-8
| 3,316 | 3.71875 | 4 |
[] |
no_license
|
# sequencia-maxima
### Objetivo do algoritmo: Identificar sequência crescente de maior soma.
Escreva um programa que leia um inteiro n >= 2 e uma sequência de n números inteiros e imprima um segmento crescente de dois elementos desta sequência, cuja a soma seja a máxima.
O algoritmo deverá receber um ou mais números inteiros, o primeiro será a quantidade de números na sequência e os seguintes serão o valor de cada número.
### Objetivos do exercicio:
- A partir do código base dentro de **exercicio.py**, você deverá validar o que já está escrito, realizando as modificações necessárias para a execução correta do algoritmo.
- Desenvolver a capacidade de detectar os casos de teste de um algoritmo
### Entrada
- Número inteiro X igual ou maior que 2.
- Números inteiros Yn (quantidade de números definida pelo valor da variável X).
### Saída
- String contendo sequência crescente de maior soma, string "sem sequencia crescente" ou string "entrada invalida".
### Observações
**Obs1.:** Caso o algoritmo não encontre o segmento crescente de dois elementos consecutivos da sequência, cuja soma seja máxima, o algoritmo deve informar “sem sequencia crescente” e caso identifique alguma entrada inválida deve informar “entrada invalida”.
**Obs2.:** Não usar as funções mínimo e máximo.
### Exemplos
| Entrada | Saida |
| ------ | ------ |
| 12-1-15-2-4-7-20-19-26-3-14-40-25 | "14, 40" |
| 3-1-5-6 | "5, 6" |
| 0 | "entrada invalida" |
| 3-6-5-1 | "sem sequencia crescente" |
### Instruções gerais
- Escreva seu código dentro do arquivo **exercicio.py**
- Escreva os casos de teste do algoritmo dentro do arquivo **casosDeTeste.py**
- Dentro do arquivo **exercicio.py** existe um código que resolve parcialmente o problema. Vocé deverá validar o que está escrito, realizando as modificações necessárias para a execução correta do algoritmo.
- Dentro do arquivo **casosDeTeste.py** existe uma estrutura no formato: { "X-Y1-Y2": "saida" }, onde X, Y1 e Y2 são as entradas já descritas e devem ser separadas por hífen. Você deverá inserir seus casos de teste nele. Por exemplo, {"3-1-5-6" : "5, 6"} significa que as entradas serão **X = 3**, **Y1 = 1**, **Y2 = 5** e **Y3 = 6** e a saida será **"5, 6"**. Para inserir um novo caso de teste como, por exemplo,{"0" : "entrada invalida"}, basta inserir uma virgula e adicionar os novos dados, como no exemplo abaixo:
```sh
{"3-1-5-6" : "5, 6",
"0" : "entrada invalida"}
```
- Após a codificação do algoritmo não esqueça de **commitar as mudanças** clicando no botão commit **changes**.
- Dentro do arquivo **exercicio.py** existem duas variáveis: **n** e **sequencia** que representam **X** e **Yn** respectivamente. Ou seja, você deverá usa-las como entradas do seu algoritmo. Note, que esse algoritmo não recebe as entradas através do ``` input()``` e sim através de ``` sys.argv[1]``` e ``` sys.argv[i+2]```. Para a codificação do algoritmo na sua máquina, você poderá ``` input()``` normalmente, mas não se esqueça de altera-lo para ``` sys.argv[1]``` e ``` sys.argv[i+2]``` no momento de submeter seu código.
- Em hipótese alguma você deverá alterar o código do arquivo exercicio_test.py, caso seja detectada alguma alteração, sua resolução será desconsiderada.
|
TypeScript
|
UTF-8
| 2,278 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
import { Message } from "./dtos";
import { resolve } from "dns";
export type Res = (resData: unknown) => void;
type ListenHandler = (data: unknown | undefined, res: Res) => void;
interface Listener {
eventType: string;
handler: ListenHandler;
}
export interface PendingMessage {
type: string;
resolver: (value: unknown) => void;
}
export interface ClientChannel {
send<T = unknown>(payload: Message<T>): Promise<T>;
}
export interface ServerChannel {
listen(eventType: string, handler: ListenHandler): void;
}
export class Channel implements ClientChannel, ServerChannel {
private store: Worker;
private msgQueue: PendingMessage[] = [];
private self: (WorkerGlobalScope & typeof globalThis) | undefined;
private listeners: Listener[] = [];
constructor(store: Worker, self?: WorkerGlobalScope & typeof globalThis) {
this.store = store;
this.self = self;
if (this.store) {
this.store.onmessage = this.onMessage as any;
}
if (this.self) {
this.self.addEventListener("message", (e: MessageEvent) =>
this.onWebWorkerMessage(e.data)
);
}
}
private unlock(targetType: string, data: unknown) {
const pos = this.msgQueue.findIndex(
({ type }: PendingMessage) => type === targetType
);
this.msgQueue[pos].resolver(data);
this.msgQueue.splice(pos, 1);
}
private onMessage = (e: MessageEvent) => {
const { type, data } = e.data as Message<unknown>;
this.unlock(type, data);
};
private onWebWorkerMessage(msg: Message<unknown>) {
const listener: Listener | undefined = this.listeners.find(
({ eventType }: Listener) => eventType === msg.type
);
if (listener) {
listener.handler(msg.data, (resData: unknown) => {
this.self.postMessage({ type: msg.type, data: resData });
});
}
}
send<R, T = unknown>(payload: Message<T>): Promise<R> {
return new Promise(resolve => {
this.store.postMessage(payload);
this.msgQueue.push({
type: payload.type,
resolver: resolve
});
});
}
listen(eventType: string, handler: ListenHandler) {
if (!this.self) {
throw new Error("The self is required!");
}
this.listeners.push({
eventType,
handler
});
}
}
|
Java
|
UTF-8
| 1,156 | 2.625 | 3 |
[] |
no_license
|
package ASM;
import ASM.inst.Inst;
import java.io.PrintStream;
import java.util.ArrayList;
public class ASMBlock {
public ArrayList<Inst> inst = new ArrayList<>();
public String id;
public int cnt = 1; // number of registers
public ASMBlock(String _id) {
id = _id;
}
public void print(PrintStream prt) {
prt.println("\t.globl\t" + id);
prt.println("\t.type\t" + id + ", @function");
prt.println(id + ":");
int size = 4 * (cnt + 2);
if (size<2048) prt.println("\taddi\tsp,sp,-" + String.valueOf(size));
else
{
prt.println("\tli s1, -"+size);
prt.println("\tadd sp, sp, s1");
}
prt.println("\tsw\tra,0(sp)");
inst.forEach(x -> x.print(prt));
prt.println(".Return_" + id + ":");
prt.println("\tlw\tra,0(sp)");
if (size<2048) prt.println("\taddi\tsp, sp, "+String.valueOf(size));
else
{
prt.println("\tli s1, "+size);
prt.println("\tadd sp, sp, s1");
}
prt.println("\tjr\tra");
prt.println("\t.size\t" + id + ", .-" + id);
}
}
|
PHP
|
UTF-8
| 3,312 | 2.578125 | 3 |
[] |
no_license
|
<?php
class Cimej extends Kawal
{
#***************************************************************************************
public function __construct()
{
parent::__construct();
Kebenaran::kawalKeluar();
}
public function index()
{
$this->papar->baca('cimej/index');
}
function cari()
{ //echo '<br>Anda berada di class Cimej extends Kawal:cari()<br>';
//echo '<pre>'; print_r($_POST) . '</pre>';
//$_POST[id] => Array ( [ssm] => 188561 atau [nama] => sharp manu)
$myJadual = dpt_senarai('kawalan_tahunan');
$this->papar->cariNama = array();
# cari id berasaskan newss/ssm/sidap/nama
$id['ssm'] = isset($_POST['id']['ssm']) ? $_POST['id']['ssm'] : null;
$id['nama'] = isset($_POST['id']['nama']) ? $_POST['id']['nama'] : null;
if (!empty($id['ssm']))
{
//echo "POST[id][ssm]:" . $_POST['id']['ssm'];
$cariMedan = 'sidap'; # cari dalam medan apa
$cariID = $id['ssm']; # benda yang dicari
$this->papar->carian='ssm:' . $cariID;
# mula cari $cariID dalam $myJadual
foreach ($myJadual as $key => $myTable)
{# mula ulang table
# senarai nama medan
$medan = ($myTable=='sse10_kawal') ?
'sidap,newss,nama' : 'sidap,nama';
$this->papar->cariNama[$myTable] =
$this->tanya->cariMedan($myTable, $medan, $cariMedan, $cariID);
}# tamat ulang table
}
elseif (!empty($id['nama']))
{
//echo "POST[id][nama]:" . $_POST['id']['nama'];
$cariMedan = 'nama'; # cari dalam medan apa
$cariID = $id['nama']; # benda yang dicari
$this->papar->carian='nama:' . $cariID;
# mula cari $cariID dalam $myJadual
foreach ($myJadual as $key => $myTable)
{# mula ulang table
# senarai nama medan
$medan = ($myTable=='sse10_kawal') ?
'sidap,newss,nama' : 'sidap,nama';
$this->papar->cariNama[$myTable] =
$this->tanya->cariMedan($myTable, $medan, $cariMedan, $cariID);
}# tamat ulang table
}
else
{
$this->papar->carian = null;
}
# semak data
//echo '<pre>$this->papar->cariNama:'; print_r($this->papar->cariNama) . '</pre>';
# paparkan ke fail cimej/cari.php
$this->papar->baca('cimej/cari', 0);
}
function imej($cari = 'ssm', $cariID = null)
{
//echo '<br>Anda berada di class CImej extends Kawal:imej($cari)<br>';
//echo '<pre>$cari->' . print_r($cari, 1) . '</pre>';
//echo '<pre>$id->' . print_r($cariID, 1) . '</pre>';
$myJadual = dpt_senarai('kawalan_tahunan'); // dapatkan senarai jadual
if (!empty($cariID))
{
# mula cari $cariID dalam $myJadual
foreach ($myJadual as $key => $myTable)
{# mula ulang table
$cariMedan = in_array($myTable,
array('sse10_kawal','alamat_newss_2013')) ?
'newss' : 'sidap';
$medan = in_array($myTable,
array('sse10_kawal','alamat_newss_2013')) ?
'sidap,newss,nama' : 'sidap,nama';
$this->papar->kesID[$myTable] =
$this->tanya->cariSemuaMedan($myTable, $medan, $cariMedan, $cariID);
}# tamat ulang table
$this->papar->carian = $cariMedan;
}
else
{
$this->papar->carian='[tiada id diisi]';
}
# semak data
//echo '<pre>$this->papar->kesID:'; print_r($this->papar->kesID) . '</pre>';
# paparkan ke fail cimej/imej.php
$this->papar->baca('cimej/imej', 0);
}
#***************************************************************************************
}
|
C#
|
UTF-8
| 741 | 2.8125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Challenge_Wed_1
{
class Essay
{
public string Title { get; set; }
public string Thesis { get; set; }
public string AuthorName { get; set; }
public int NumOfParagraphs { get; set; }
public string References { get; set; }
public Essay()
{
}
public Essay(string title, string thesis, string name, int numParagraphs, string citations)
{
Title = title;
Thesis = thesis;
AuthorName = name;
NumOfParagraphs = numParagraphs;
References = citations;
}
}
}
|
Java
|
UTF-8
| 2,012 | 2.140625 | 2 |
[] |
no_license
|
package ph.txtdis.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import ph.txtdis.domain.EdmsInvoice;
import ph.txtdis.domain.EdmsTruck;
import ph.txtdis.dto.Keyed;
import ph.txtdis.dto.Truck;
import ph.txtdis.repository.EdmsTruckRepository;
import static ph.txtdis.util.Code.addZeroes;
import static ph.txtdis.util.DateTimeUtils.to24HourTimestampText;
import static ph.txtdis.util.DateTimeUtils.toZonedDateTimeFrom24HourTimestamp;
@Service("truckService")
public class EdmsTruckServiceImpl //
extends AbstractCreateNameListService<EdmsTruckRepository, EdmsTruck, Truck> //
implements EdmsTruckService {
@Value("${client.user}")
private String username;
@Value("${client.truck}")
private String description;
@Value("${prefix.truck}")
private String truckPrefix;
@Override
public EdmsTruck findEntityByPlateNo(String no) {
return no == null || no.isEmpty() ? null : //
repository.findByNameIgnoreCase(no);
}
@Override
public Long getId(EdmsInvoice i) {
EdmsTruck e = truck(i);
return e == null ? null : e.getId();
}
private EdmsTruck truck(EdmsInvoice i) {
return i == null ? null : repository.findByCodeIgnoreCase(i.getTruckCode());
}
@Override
protected EdmsTruck toEntity(Truck t) {
EdmsTruck e = new EdmsTruck();
e.setCode(getCode(t));
e.setName(t.getName());
e.setDescription(getDescription());
e.setCreatedBy(username);
e.setCreatedOn(to24HourTimestampText(t.getCreatedOn()));
e.setModifiedBy("");
e.setModifiedOn("");
return e;
}
@Override
public String getCode(Keyed<Long> r) {
return r == null || r.getId() == null ? "" : truckPrefix + addZeroes(2, r.getId().toString());
}
@Override
public String getDescription() {
return description;
}
@Override
protected Truck toModel(EdmsTruck e) {
Truck t = new Truck();
t.setName(e.getName());
t.setCreatedBy(e.getCreatedBy());
t.setCreatedOn(toZonedDateTimeFrom24HourTimestamp(e.getCreatedOn()));
return t;
}
}
|
Markdown
|
UTF-8
| 12,429 | 2.765625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
# VPC Service Controls
This module offers a unified interface to manage VPC Service Controls [Access Policy](https://cloud.google.com/access-context-manager/docs/create-access-policy), [Access Levels](https://cloud.google.com/access-context-manager/docs/manage-access-levels), and [Service Perimeters](https://cloud.google.com/vpc-service-controls/docs/service-perimeters).
Given the complexity of the underlying resources, the module intentionally mimics their interfaces to make it easier to map their documentation onto its variables, and reduce the internal complexity. The tradeoff is some verbosity, and a very complex type for the `service_perimeters_regular` variable (while [optional type attributes](https://www.terraform.io/language/expressions/type-constraints#experimental-optional-object-type-attributes) are still an experiment).
If you are using [Application Default Credentials](https://cloud.google.com/sdk/gcloud/reference/auth/application-default) with Terraform and run into permissions issues, make sure to check out the recommended provider configuration in the [VPC SC resources documentation](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/access_context_manager_access_level).
## Examples
### Access policy
By default, the module is configured to use an existing policy, passed in by name in the `access_policy` variable:
```hcl
module "test" {
source = "./fabric/modules/vpc-sc"
access_policy = "12345678"
}
# tftest modules=0 resources=0
```
If you need the module to create the policy for you, use the `access_policy_create` variable, and set `access_policy` to `null`:
```hcl
module "test" {
source = "./fabric/modules/vpc-sc"
access_policy = null
access_policy_create = {
parent = "organizations/123456"
title = "vpcsc-policy"
}
}
# tftest modules=1 resources=1
```
### Access levels
As highlighted above, the `access_levels` type replicates the underlying resource structure.
```hcl
module "test" {
source = "./fabric/modules/vpc-sc"
access_policy = "12345678"
access_levels = {
a1 = {
combining_function = null
conditions = [{
members = ["user:user1@example.com"], ip_subnetworks = null,
negate = null, regions = null, required_access_levels = null
}]
}
a2 = {
combining_function = "OR"
conditions = [{
regions = ["IT", "FR"], ip_subnetworks = null,
members = null, negate = null, required_access_levels = null
},{
ip_subnetworks = ["101.101.101.0/24"], members = null,
negate = null, regions = null, required_access_levels = null
}]
}
}
}
# tftest modules=1 resources=2
```
### Service perimeters
Bridge and regular service perimeters use two separate variables, as bridge perimeters only accept a limited number of arguments, and can leverage a much simpler interface.
The regular perimeters variable exposes all the complexity of the underlying resource, use [its documentation](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/access_context_manager_service_perimeter) as a reference about the possible values and configurations.
If you need to refer to access levels created by the same module in regular service perimeters, you can either use the module's outputs in the provided variables, or the key used to identify the relevant access level. The example below shows how to do this in practice.
/*
Resources for both perimeters have a `lifecycle` block that ignores changes to `spec` and `status` resources (projects), to allow using the additive resource `google_access_context_manager_service_perimeter_resource` at project creation. If this is not needed, the `lifecycle` blocks can be safely commented in the code.
*/
#### Bridge type
```hcl
module "test" {
source = "./fabric/modules/vpc-sc"
access_policy = "12345678"
service_perimeters_bridge = {
b1 = {
status_resources = ["projects/111110", "projects/111111"]
spec_resources = null
use_explicit_dry_run_spec = false
}
b2 = {
status_resources = null
spec_resources = ["projects/222220", "projects/222221"]
use_explicit_dry_run_spec = true
}
}
}
# tftest modules=1 resources=2
```
#### Regular type
```hcl
module "test" {
source = "./fabric/modules/vpc-sc"
access_policy = "12345678"
access_levels = {
a1 = {
combining_function = null
conditions = [{
members = ["user:user1@example.com"], ip_subnetworks = null,
negate = null, regions = null, required_access_levels = null
}]
}
a2 = {
combining_function = null
conditions = [{
members = ["user:user2@example.com"], ip_subnetworks = null,
negate = null, regions = null, required_access_levels = null
}]
}
}
service_perimeters_regular = {
r1 = {
spec = null
status = {
access_levels = [module.test.access_level_names["a1"], "a2"]
resources = ["projects/11111", "projects/111111"]
restricted_services = ["storage.googleapis.com"]
# example: allow writing to external GCS bucket
egress_policies = [
{
egress_from = {
identity_type = null
identities = [
"serviceAccount:foo@myproject.iam.gserviceaccount.com"
]
}
egress_to = {
operations = [{
method_selectors = ["*"], service_name = "storage.googleapis.com"
}]
resources = ["projects/123456789"]
}
}
]
# example: allow management from external automation SA
ingress_policies = [
{
ingress_from = {
identities = [
"serviceAccount:test-tf@myproject.iam.gserviceaccount.com",
],
source_access_levels = ["*"], identity_type = null, source_resources = null
}
ingress_to = {
operations = [{ method_selectors = [], service_name = "*" }]
resources = ["*"]
}
}
]
vpc_accessible_services = {
allowed_services = ["storage.googleapis.com"]
enable_restriction = true
}
}
use_explicit_dry_run_spec = false
}
}
}
# tftest modules=1 resources=3
```
## Notes
- To remove an access level, first remove the binding between perimeter and the access level in `status` and/or `spec` without removing the access level itself. Once you have run `terraform apply`, you'll then be able to remove the access level and run `terraform apply` again.
## TODO
- [ ] implement support for the `google_access_context_manager_gcp_user_access_binding` resource
<!-- BEGIN TFDOC -->
## Variables
| name | description | type | required | default |
|---|---|:---:|:---:|:---:|
| [access_policy](variables.tf#L55) | Access Policy name, leave null to use auto-created one. | <code>string</code> | ✓ | |
| [access_levels](variables.tf#L17) | Map of access levels in name => [conditions] format. | <code title="map(object({ combining_function = string conditions = list(object({ ip_subnetworks = list(string) members = list(string) negate = bool regions = list(string) required_access_levels = list(string) })) }))">map(object({…}))</code> | | <code>{}</code> |
| [access_policy_create](variables.tf#L60) | Access Policy configuration, fill in to create. Parent is in 'organizations/123456' format. | <code title="object({ parent = string title = string })">object({…})</code> | | <code>null</code> |
| [service_perimeters_bridge](variables.tf#L69) | Bridge service perimeters. | <code title="map(object({ spec_resources = list(string) status_resources = list(string) use_explicit_dry_run_spec = bool }))">map(object({…}))</code> | | <code>{}</code> |
| [service_perimeters_regular](variables.tf#L79) | Regular service perimeters. | <code title="map(object({ spec = object({ access_levels = list(string) resources = list(string) restricted_services = list(string) egress_policies = list(object({ egress_from = object({ identity_type = string identities = list(string) }) egress_to = object({ operations = list(object({ method_selectors = list(string) service_name = string })) resources = list(string) }) })) ingress_policies = list(object({ ingress_from = object({ identity_type = string identities = list(string) source_access_levels = list(string) source_resources = list(string) }) ingress_to = object({ operations = list(object({ method_selectors = list(string) service_name = string })) resources = list(string) }) })) vpc_accessible_services = object({ allowed_services = list(string) enable_restriction = bool }) }) status = object({ access_levels = list(string) resources = list(string) restricted_services = list(string) egress_policies = list(object({ egress_from = object({ identity_type = string identities = list(string) }) egress_to = object({ operations = list(object({ method_selectors = list(string) service_name = string })) resources = list(string) }) })) ingress_policies = list(object({ ingress_from = object({ identity_type = string identities = list(string) source_access_levels = list(string) source_resources = list(string) }) ingress_to = object({ operations = list(object({ method_selectors = list(string) service_name = string })) resources = list(string) }) })) vpc_accessible_services = object({ allowed_services = list(string) enable_restriction = bool }) }) use_explicit_dry_run_spec = bool }))">map(object({…}))</code> | | <code>{}</code> |
## Outputs
| name | description | sensitive |
|---|---|:---:|
| [access_level_names](outputs.tf#L17) | Access level resources. | |
| [access_levels](outputs.tf#L25) | Access level resources. | |
| [access_policy](outputs.tf#L30) | Access policy resource, if autocreated. | |
| [access_policy_name](outputs.tf#L35) | Access policy name. | |
| [service_perimeters_bridge](outputs.tf#L40) | Bridge service perimeter resources. | |
| [service_perimeters_regular](outputs.tf#L45) | Regular service perimeter resources. | |
<!-- END TFDOC -->
|
Python
|
UTF-8
| 1,194 | 3.84375 | 4 |
[] |
no_license
|
"""
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example:
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]
"""
class Solution:
"""
思路: BFS
首先将所有 = 0 的 cell 入队,然后通过 BFS 的方法动态的更新当前已经入队的 cell 周围 = 1 的 cell 的值
"""
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
from collections import deque
m, n = len(mat), len(mat[0])
dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)]
dq = deque([])
visited = [[False] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if mat[i][j] == 0:
visited[i][j] = True
dq.append((i, j))
while dq:
x, y = dq.popleft()
for dx, dy in dirs:
r, c = x + dx, y + dy
if 0 <= r < m and 0 <= c < n and not visited[r][c]:
mat[r][c] = mat[x][y] + 1
visited[r][c] = True
dq.append((r, c))
return mat
|
Python
|
UTF-8
| 6,940 | 2.5625 | 3 |
[] |
no_license
|
#! /usr/bin/env python3
# encoding: utf-8
""" Internationalization for Russian
This module considers dictionary of
pairs of variants of books of Bible abbreviations
with its number in MyBible format, function for preprocessing references from text materials to the common format,
and some text for internationalization.
"""
import regex as re
db_info_description_title = "Пособие по изучению Библии в Субботней школе церкви Христиан адвентистов седьмого дня"
db_info_description_version_adult = "для взрослых"
db_info_description_version_youth = "для молодёжи"
db_info_description_list_of_quarterly_themes = "Список тем кварталов:"
db_info_description_from_author = """Для отправки замечаний и пожеланий по модулю воспользуйтесь сервисом по адресу <a href="https://github.com/Juzujka/SDA_SS_to_MyBible/issues">https://github.com/Juzujka/SDA_SS_to_MyBible/issues </a>. Благодарности, благословения, предложения о помощи и сотрудничестве присылайте на juzujka@gmail.com."""
db_info_description_origin_text = """created by Egor Ibragimov, juzujka@gmail.com\nthe text is taken from sabbath-school.adventech.io"""
db_info_description_lesson = "урок"
db_info_description_day = "день"
def ref_tag_preprocess(inp_tag_text):
"""adopting references in lessons in Russian"""
# some words in references
#TODO: fix "see also"
inp_tag_text = inp_tag_text.replace("see also", " ")
# long book name for Song of Solomon
inp_tag_text = re.sub(r'((?<=[0-9])+[а-д])', '', inp_tag_text)
inp_tag_text = re.sub(r'((?<=[0-9])+\s[а-д])', '', inp_tag_text)
inp_tag_text = inp_tag_text.replace("Иисуса Навина", "Навина")
inp_tag_text = inp_tag_text.replace("Песнь Песней", "Песн.")
inp_tag_text = inp_tag_text.replace("Песни Песней", "Песн.")
inp_tag_text = inp_tag_text.replace("Плач Иеремии", "Плач")
inp_tag_text = inp_tag_text.replace("К римлянам", "Рим.")
inp_tag_text = inp_tag_text.replace("к римлянам", "Рим.")
inp_tag_text = inp_tag_text.replace("к ефесянам", "Ефесянам")
inp_tag_text = inp_tag_text.replace("Псалмы", "Псалом")
inp_tag_text = inp_tag_text.replace("псалмы", "Псалом")
inp_tag_text = inp_tag_text.replace("Евангелие от", "")
inp_tag_text = inp_tag_text.replace("от Марка", "Марка")
inp_tag_text = inp_tag_text.replace("от Матфея", "Матфея")
inp_tag_text = inp_tag_text.replace("от Луки", "Луки")
inp_tag_text = inp_tag_text.replace("от Иоанна", "Иоанна")
inp_tag_text = inp_tag_text.replace("Послание", "")
inp_tag_text = inp_tag_text.replace("к евреям", "Евреям")
inp_tag_text = inp_tag_text.replace("Стихи", "")
inp_tag_text = inp_tag_text.replace("главы", "")
inp_tag_text = inp_tag_text.replace("Главы", "")
inp_tag_text = inp_tag_text.replace("и далее", "")
inp_tag_text = inp_tag_text.replace(" и ", "; ")
inp_tag_text = inp_tag_text.replace("–", "-")
inp_tag_text = inp_tag_text.replace("'", "’")
return inp_tag_text
#TODO: check this, dict replaced with { for avoiding a warning
book_index_to_MyBible = dict([\
#book_index_to_MyBible = {[\
('Быт',10),\
('Бытие',10),\
('Исх',20),\
('Исход',20),\
('Лев',30),\
('Левит',30),\
('Чис',40),\
('Числ',40),\
('Числа',40),\
('Втор',50),\
('Второзаконие',50),\
('Нав',60),\
('Навина',60),\
('Суд',70),\
('Судей',70),\
('Руфь',80),\
('Руф',80),\
('1Цар',90),\
('1Царств',90),\
('2Цар',100),\
('2Царств',100),\
('3Цар',110),\
('3Царств',110),\
('4Цар',120),\
('4Царств',120),\
('Иудф',180),\
('1Пар',130),\
('1Паралипоменон',130),\
('2Пар',140),\
('2Паралипоменон',140),\
('Ездр',150),\
('Езд',150),\
('Ездра',150),\
('Ездры',150),\
('Неем',160),\
('Неемии',160),\
('Неемия',160),\
('2Езд',165),\
('Тов',170),\
('Есф',190),\
('Есфирь',190),\
('Иов',220),\
('Иова',220),\
('Пс',230),\
('Псалом',230),\
('Псалтирь',230),\
('Прит',240),\
('Притч',240),\
('Притчи',240),\
('Еккл',250),\
('Песн',260),\
('Песней',260),\
('Прем',270),\
('Сир',280),\
('Ис',290),\
('Исаии',290),\
('Исаия',290),\
('Иер',300),\
('Иеремии',300),\
('Иеремия',300),\
('Плач',310),\
('Посл',315),\
('Вар',320),\
('Иез',330),\
('Иезекииля',330),\
('Иезекииль',330),\
('Дан',340),\
('Даниила',340),\
('Даниил',340),\
('Ос',350),\
('Осии',350),\
('Иоил',360),\
('Иоиля',360),\
('Ам',370),\
('Амоса',370),\
('Авд',380),\
('Ион',390),\
('Ионы',390),\
('Иона',390),\
('Мих',400),\
('Михея',400),\
('Михей',400),\
('Наум',410),\
('Авв',420),\
('Аввакума',420),\
('Соф',430),\
('Софонии',430),\
('Софония',430),\
('Агг',440),\
('Аггея',440),\
('Аггей',440),\
('Зах',450),\
('Захарии',450),\
('Захария',450),\
('Мал',460),\
('Малахии',460),\
('Малахия',460),\
('1Мак',462),\
('2Мак',464),\
('3Мак',466),\
('3Езд',468),\
('Мат',470),\
('Матфея',470),\
('Мф',470),\
('Мар',480),\
('Марка',480),\
('Мк',480),\
('Лук',490),\
('Луки',490),\
('Luke',490),\
('Лк',490),\
('Ин',500),\
('Иоанна',500),\
('Деян',510),\
('Деяния',510),\
('Иак',660),\
('Иакова',660),\
('1Пет',670),\
('1Петр',670),\
('1Петра',670),\
('2Пет',680),\
('2Петр',680),\
('2Петра',680),\
('1Ин',690),\
('1Иоанна',690),\
('2Ин',700),\
('2Иоанна',700),\
('3Ин',710),\
('3Иоанна',710),\
('Иуд',720),\
('Иуды',720),\
('Рим',520),\
('Римлянам',520),\
('1Кор',530),\
('1Коринфянам',530),\
('2Кор',540),\
('2Коринфянам',540),\
('Гал',550),\
('Галатам',550),\
('Еф',560),\
('Ефесянам',560),\
('Флп',570),\
('Филиппийцам',570),\
('Филиппийцам',570),\
('Фил',570),\
('Кол',580),\
('Колоссянам',580),\
('1Фес',590),\
('1Фессалоникийцам',590),\
('2Фес',600),\
('2Фессалоникийцам',600),\
('1Тим',610),\
('1Тимофею',610),\
('2Тим',620),\
('2Тимофею',620),\
('Тит',630),\
('Титу',630),\
('Флм',640),\
('Филимону',640),\
('Евр',650),\
('Евреям',650),\
('Откр',730),\
('Отк',730),\
('Откровение',730),\
('Лаод',780),\
('Мол',790),\
])
#]}
|
Java
|
UTF-8
| 11,550 | 1.703125 | 2 |
[
"OGL-UK-3.0"
] |
permissive
|
package uk.gov.caz.whitelist.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static uk.gov.caz.correlationid.Constants.X_CORRELATION_ID_HEADER;
import static uk.gov.caz.whitelist.controller.WhitelistController.BASE_PATH;
import static uk.gov.caz.whitelist.controller.WhitelistController.X_MODIFIER_EMAIL_HEADER;
import static uk.gov.caz.whitelist.controller.WhitelistController.X_MODIFIER_ID_HEADER;
import static uk.gov.caz.whitelist.model.CategoryType.EARLY_ADOPTER;
import static uk.gov.caz.whitelist.model.CategoryType.EXEMPTION;
import static uk.gov.caz.whitelist.model.CategoryType.NON_UK_VEHICLE;
import static uk.gov.caz.whitelist.model.CategoryType.OTHER;
import static uk.gov.caz.whitelist.model.CategoryType.PROBLEMATIC_VRN;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.UUID;
import java.util.stream.Stream;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import uk.gov.caz.whitelist.annotation.MockedMvcIntegrationTest;
import uk.gov.caz.whitelist.dto.WhitelistedVehicleRequestDto;
import uk.gov.caz.whitelist.model.CategoryType;
import uk.gov.caz.whitelist.model.WhitelistVehicle;
import uk.gov.caz.whitelist.repository.WhitelistVehiclePostgresRepository;
import uk.gov.caz.whitelist.service.WhitelistService;
@MockedMvcIntegrationTest
@Sql(scripts = {"classpath:data/sql/clear-whitelist-vehicles-data.sql",
"classpath:data/sql/whitelist-vehicles-data.sql"}, executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "classpath:data/sql/clear-whitelist-vehicles-data.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public class WhitelistControllerTestIT {
private static final String SOME_CORRELATION_ID = "63be7528-7efd-4f31-ae68-11a6b709ff1c";
private static final String SOME_MODIFIER_ID = "a6ce833d-1798-434d-88a9-d7ac6452fbc6";
private static final String SOME_MODIFIER_EMAIL = RandomStringUtils.randomAlphabetic(10);
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private WhitelistVehiclePostgresRepository whitelistVehiclePostgresRepository;
@Autowired
private WhitelistService whitelistService;
@Test
public void shouldReturnWhitelistedVehicleDetailsWithAddedTimestamp() throws Exception {
mockMvc.perform(get(BASE_PATH + "/CAS310")
.accept(MediaType.APPLICATION_JSON)
.header(X_CORRELATION_ID_HEADER, SOME_CORRELATION_ID))
.andExpect(status().isOk())
.andExpect(jsonPath("$.vrn", is("CAS310")))
.andExpect(jsonPath("$.reasonUpdated", is("reasonUpdated")))
.andExpect(jsonPath("$.addedTimestamp", is("2020-12-22 13:40:21")))
.andExpect(jsonPath("$.category", is("Other")))
.andExpect(jsonPath("$.email", is("test@gov.uk")))
.andExpect(jsonPath("$.uploaderId", is("2c01df02-da8d-4d92-ad24-7c20bf6617e7")));
}
@Test
public void shouldReturnWhitelistedVehicleDetailsWithoutAddedTimestamp() throws Exception {
mockMvc.perform(get(BASE_PATH + "/EB12QMD")
.accept(MediaType.APPLICATION_JSON)
.header(X_CORRELATION_ID_HEADER, SOME_CORRELATION_ID))
.andExpect(status().isOk())
.andExpect(jsonPath("$.vrn", is("EB12QMD")))
.andExpect(jsonPath("$.reasonUpdated", is("reasonUpdated")))
.andExpect(jsonPath("$.addedTimestamp", nullValue()))
.andExpect(jsonPath("$.category", is("Other")))
.andExpect(jsonPath("$.email", is("test@gov.uk")))
.andExpect(jsonPath("$.uploaderId", is("2c01df02-da8d-4d92-ad24-7c20bf6617e7")));
}
@Test
public void shouldRemoveWhitelistedVehicleAndReturnItsDetails() throws Exception {
WhitelistVehicle vehicle = addVehicle();
mockMvc.perform(delete(BASE_PATH + "/" + vehicle.getVrn())
.accept(MediaType.APPLICATION_JSON)
.header(X_CORRELATION_ID_HEADER, SOME_CORRELATION_ID)
.header(X_MODIFIER_ID_HEADER, SOME_MODIFIER_ID)
.header(X_MODIFIER_EMAIL_HEADER, SOME_MODIFIER_EMAIL))
.andExpect(status().isOk())
.andExpect(jsonPath("$.vrn", is(vehicle.getVrn())))
.andExpect(jsonPath("$.reasonUpdated", is(vehicle.getReasonUpdated())))
.andExpect(jsonPath("$.category", is(vehicle.getCategory())))
.andExpect(jsonPath("$.email", is(vehicle.getUploaderEmail())))
.andExpect(jsonPath("$.uploaderId", is(vehicle.getUploaderId().toString())));
assertThat(whitelistService.findBy(vehicle.getVrn())).isEmpty();
}
@Test
public void shouldReturn404IfVehicleDoesntExist() throws Exception {
String vrn = "doesntexist";
mockMvc.perform(delete(BASE_PATH + "/" + vrn)
.accept(MediaType.APPLICATION_JSON)
.header(X_CORRELATION_ID_HEADER, SOME_CORRELATION_ID)
.header(X_MODIFIER_ID_HEADER, SOME_MODIFIER_ID)
.header(X_MODIFIER_EMAIL_HEADER, SOME_MODIFIER_EMAIL))
.andExpect(status().isNotFound());
assertThat(whitelistService.findBy(vrn)).isEmpty();
}
@Test
public void shouldReturnNotFound() throws Exception {
mockMvc.perform(get(BASE_PATH + "/CAS311")
.accept(MediaType.APPLICATION_JSON)
.header(X_CORRELATION_ID_HEADER, SOME_CORRELATION_ID))
.andExpect(status().isNotFound());
}
@Test
public void whenCalledWithoutModifierEmailHeaderShouldNotAcceptRequest400() throws Exception {
String vrn = RandomStringUtils.randomAlphabetic(10);
mockMvc.perform(delete(BASE_PATH + "/" + vrn)
.accept(MediaType.APPLICATION_JSON)
.header(X_CORRELATION_ID_HEADER, SOME_CORRELATION_ID)
.header(X_MODIFIER_ID_HEADER, SOME_MODIFIER_ID))
.andExpect(status().isBadRequest())
;
}
@ParameterizedTest
@MethodSource("vrnsTypeCategoriesAndManufacturers")
public void shouldSaveWhitelistedVehicleAndReturnDetails(String vrn,
CategoryType categoryType, String manufacturer) throws Exception {
mockMvc.perform(post(BASE_PATH)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(createPayload(vrn, categoryType, manufacturer))
.header(X_CORRELATION_ID_HEADER, SOME_CORRELATION_ID))
.andExpect(status().isCreated())
.andDo(MockMvcResultHandlers.print())
.andExpect(jsonPath("$.vrn", is(vrn)))
.andExpect(jsonPath("$.reasonUpdated", is("Reason")))
.andExpect(jsonPath("$.manufacturer", is(manufacturer)))
.andExpect(jsonPath("$.category", is(categoryType.getCategory())))
.andExpect(jsonPath("$.uploaderId", is("4490996d-eb18-4c41-ac50-299cf7defbcb")))
.andExpect(jsonPath("$.email", is("test@gov.uk")));
whenSaveWhitelistVehicle(vrn)
.thenWhitelistVehicleFromDB()
.hasCategory(categoryType.getCategory())
.hasManufacturer(manufacturer)
.hasEmail("test@gov.uk")
.isExempt(categoryType.isExempt())
.isCompliant(categoryType.isCompliant());
}
@SneakyThrows
private String createPayload(String vrn, CategoryType categoryType, String manufacturer) {
return objectMapper
.writeValueAsString(createWhitelistedVehicleRequestDto(vrn, categoryType, manufacturer));
}
private WhitelistVehicle addVehicle() {
return whitelistService.save(WhitelistVehicle.builder()
.reasonUpdated("Reason")
.manufacturer("Manufacturer")
.category("Category")
.vrn("CAS311")
.uploaderId(UUID.randomUUID())
.uploaderEmail(UUID.randomUUID() + "@gov.uk")
.compliant(true)
.exempt(false)
.build());
}
private WhitelistedVehicleRequestDto createWhitelistedVehicleRequestDto(String vrn,
CategoryType categoryType, String manufacturer) {
return WhitelistedVehicleRequestDto.builder()
.vrn(vrn)
.manufacturer(manufacturer)
.category(categoryType.getCategory())
.reasonUpdated("Reason")
.uploaderId(UUID.fromString("4490996d-eb18-4c41-ac50-299cf7defbcb"))
.email("test@gov.uk")
.build();
}
private static Stream<Arguments> vrnsTypeCategoriesAndManufacturers() {
return Stream.of(
Arguments.of("CAS331", EARLY_ADOPTER, "Manu1"),
Arguments.of("CAS332", NON_UK_VEHICLE, "Manu2"),
Arguments.of("CAS333", PROBLEMATIC_VRN, null),
Arguments.of("CAS334", EXEMPTION, null),
Arguments.of("CAS335", OTHER, "Manu3")
);
}
private WhitelistVehicleAssertion whenSaveWhitelistVehicle(String vrn) {
return WhitelistVehicleAssertion
.whenSaveWhitelistVehicle(vrn, whitelistVehiclePostgresRepository);
}
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
private static class WhitelistVehicleAssertion {
private final String vrn;
private final WhitelistVehiclePostgresRepository whitelistVehiclePostgresRepository;
private String category;
private String manufacturer;
private String email;
private boolean exempt;
private boolean compliant;
static WhitelistVehicleAssertion whenSaveWhitelistVehicle(String vrn,
WhitelistVehiclePostgresRepository whitelistVehiclePostgresRepository) {
return new WhitelistVehicleAssertion(vrn, whitelistVehiclePostgresRepository);
}
public WhitelistVehicleAssertion thenWhitelistVehicleFromDB() {
WhitelistVehicle whitelistVehicle = whitelistVehiclePostgresRepository.findOneByVrn(vrn)
.get();
this.category = whitelistVehicle.getCategory();
this.manufacturer = whitelistVehicle.getManufacturer().orElse(null);
this.email = whitelistVehicle.getUploaderEmail();
this.exempt = whitelistVehicle.isExempt();
this.compliant = whitelistVehicle.isCompliant();
return this;
}
public WhitelistVehicleAssertion hasCategory(String category) {
assertThat(this.category).isEqualTo(category);
return this;
}
public WhitelistVehicleAssertion hasManufacturer(String manufacturer) {
assertThat(this.manufacturer).isEqualTo(manufacturer);
return this;
}
public WhitelistVehicleAssertion hasEmail(String email) {
assertThat(this.email).isEqualTo(email);
return this;
}
public WhitelistVehicleAssertion isExempt(boolean exempt) {
assertThat(this.exempt).isEqualTo(exempt);
return this;
}
public WhitelistVehicleAssertion isCompliant(boolean compliant) {
assertThat(this.compliant).isEqualTo(compliant);
return this;
}
}
}
|
C++
|
UTF-8
| 291 | 2.625 | 3 |
[] |
no_license
|
#include"condition.h"
inline void Condition::Wait(Mutex* mutex) {
pthread_cond_wait(&condition_, &mutex_->pthread_mutex_);
}
inline void Condition::Signal(){
pthread_cond_signal(&condition_);
}
inline void Condition::BroadCast() {
pthread_cond_broadcast(&condition_);
}
|
Java
|
UTF-8
| 2,744 | 1.734375 | 2 |
[] |
no_license
|
package iih.ci.ord.ems.d;
import xap.mw.core.data.*;
import xap.mw.coreitf.d.*;
import java.math.BigDecimal;
/**
* 医疗单环境信息DTO DTO数据
*
*/
public class UIEmsEnvDTO extends BaseDTO {
private static final long serialVersionUID = 1L;
/**
* 所属集团
* @return String
*/
public String getId_grp() {
return ((String) getAttrVal("Id_grp"));
}
/**
* 所属集团
* @param Id_grp
*/
public void setId_grp(String Id_grp) {
setAttrVal("Id_grp", Id_grp);
}
/**
* 所属组织
* @return String
*/
public String getId_org() {
return ((String) getAttrVal("Id_org"));
}
/**
* 所属组织
* @param Id_org
*/
public void setId_org(String Id_org) {
setAttrVal("Id_org", Id_org);
}
/**
* 开立科室
* @return String
*/
public String getId_dep_or() {
return ((String) getAttrVal("Id_dep_or"));
}
/**
* 开立科室
* @param Id_dep_or
*/
public void setId_dep_or(String Id_dep_or) {
setAttrVal("Id_dep_or", Id_dep_or);
}
/**
* 开立医生
* @return String
*/
public String getId_emp_or() {
return ((String) getAttrVal("Id_emp_or"));
}
/**
* 开立医生
* @param Id_emp_or
*/
public void setId_emp_or(String Id_emp_or) {
setAttrVal("Id_emp_or", Id_emp_or);
}
/**
* 医疗单应用场景
* @return Integer
*/
public Integer getEmsappmode() {
return ((Integer) getAttrVal("Emsappmode"));
}
/**
* 医疗单应用场景
* @param Emsappmode
*/
public void setEmsappmode(Integer Emsappmode) {
setAttrVal("Emsappmode", Emsappmode);
}
/**
* 患者
* @return String
*/
public String getId_pat() {
return ((String) getAttrVal("Id_pat"));
}
/**
* 患者
* @param Id_pat
*/
public void setId_pat(String Id_pat) {
setAttrVal("Id_pat", Id_pat);
}
/**
* 就诊
* @return String
*/
public String getId_en() {
return ((String) getAttrVal("Id_en"));
}
/**
* 就诊
* @param Id_en
*/
public void setId_en(String Id_en) {
setAttrVal("Id_en", Id_en);
}
/**
* 就诊类型
* @return String
*/
public String getCode_entp() {
return ((String) getAttrVal("Code_entp"));
}
/**
* 就诊类型
* @param Code_entp
*/
public void setCode_entp(String Code_entp) {
setAttrVal("Code_entp", Code_entp);
}
/**
* 医保信息
* @return String
*/
public String getId_hp() {
return ((String) getAttrVal("Id_hp"));
}
/**
* 医保信息
* @param Id_hp
*/
public void setId_hp(String Id_hp) {
setAttrVal("Id_hp", Id_hp);
}
/**
* 就诊类型id
* @return String
*/
public String getId_entp() {
return ((String) getAttrVal("Id_entp"));
}
/**
* 就诊类型id
* @param Id_entp
*/
public void setId_entp(String Id_entp) {
setAttrVal("Id_entp", Id_entp);
}
}
|
Shell
|
UTF-8
| 9,724 | 3.078125 | 3 |
[] |
no_license
|
#!/bin/bash
#mysql主从设置,master设置,centos6
#mysql 5.7.23
#环境设置:u 不存在的变量报错;e 发生错误退出;pipefail 管道有错退出
set -euo pipefail
START_TIME=`date +%s`
#########要更改变的变量#######
IP=`ifconfig|sed -n '/inet addr/s/^[^:]*:\([0-9.]\{7,15\}\) .*/\1/p'|head -1`
###MYSQL版本
MYSQL_VERSION="5.7.23"
MAJOR=`echo "${MYSQL_VERSION}"|awk '{print substr('${MYSQL_VERSION}',1,3)}'`
#MYSQL登录信息,新安装则更改为此密码;为了安全,用户名应不为root
MYSQL_USER="chenzl"
MYSQL_PASS='fokefZk7ch6$RnOD'
###MYSQL参数
MYSQL_CNF="/etc/my.cnf"
###版本改动的配置
###MYSQL新装参数
PORT="3306"
USER="mysql"
BASE_DIR="/usr"
DIR_PRE="/cache1/mysql";
DATA_DIR="${DIR_PRE}/data"
SOCKET="${DIR_PRE}/mysql.sock"
LOG_ERROR="${DIR_PRE}/mysql_error.err"
PID_FILE="${DIR_PRE}/mysqld.pid"
SLOW_DIR="${DIR_PRE}/slowlog"
###MYSQL新装参数,不新装则可更改的参数
LOG_BIN="${DIR_PRE}/binlog"
RELAY_LOG="${DIR_PRE}/relaybinlog"
###BINLOG参数
###IP后两位
SERVER_ID=`echo "${IP}"|awk -F "." '{print $3$4}'`
###BINLOG保留天数
EXPIRE_DAYS=5
###组提交参数:延迟可以让多个事务在用一时刻提交;等待延迟提交的最大事务数
GROUP_DELAY=1000000
GROUP_COUNT=20
###SLAVE参数
WORKERS=16
###INNODE参数
###data的路径,分布在多盘
DATA_FILE_PATH="ibdata1:200M;/cache1/mysql/data/ibdata2:12M:autoextend"
TMP_FILE_PATH="/cache1/mysql/data/ibtmp1:12M:autoextend:max:50G"
###innodb缓存空间,不超过内存的2/3
POOL_SIZE=6G
###innodb写log的缓存,上限4G
LOG_SIZE=256M
###对于io的能力预估,hdd为200,hdd+raid0为400,ssd为20000
IO_CAP=200
##双1设置
###多少个BINLOG时刷磁盘,0为由系统决定;1最安全;100 性能
SYNC_BINLOG=0
###innodb刷新模式,1最安全也最慢,0代表mysql崩溃可能导致丢失事务,2代表linux崩溃,一般建议2
FLUSH_TRX=2
###是否禁用密码策略:off 禁用
MYSQL_PASS_POLICY="off"
#slow_log目录不存,则新建
if [ ! -d ${SLOW_DIR} ];then
mkdir -p ${SLOW_DIR}
fi
###下载地址
DOWN_URL=""
if [ -n "${DOWN_URL}" ]; then
SERVER_URL="${DOWN_URL}/mysql/mysql-community-server-${MYSQL_VERSION}-1.el6.x86_64.rpm"
CLIENT_URL="${DOWN_URL}/mysql/mysql-community-client-${MYSQL_VERSION}-1.el6.x86_64.rpm"
DEVEL_URL="${DOWN_URL}/mysql/mysql-community-devel-${MYSQL_VERSION}-1.el6.x86_64.rpm"
LIB_URL="${DOWN_URL}/mysql/mysql-community-libs-${MYSQL_VERSION}-1.el6.x86_64.rpm"
COMMON_URL="${DOWN_URL}/mysql/mysql-community-common-${MYSQL_VERSION}-1.el6.x86_64.rpm"
COMPAT_URL="${DOWN_URL}/mysql/mysql-community-libs-compat-${MYSQL_VERSION}-1.el6.x86_64.rpm"
XTRABACK24_URL="${DOWN_URL}/percona-xtrabackup-24-2.4.1-1.el6.x86_64.rpm"
XTRABACK22_URL="${DOWN_URL}/percona-xtrabackup-2.2.9-5067.el6.x86_64.rpm"
XTRABACK16_URL="${DOWN_URL}/xtrabackup-1.6.7-356.rhel6.x86_64.rpm"
LIBEV_URL="${DOWN_URL}/libev-4.03-3.el6.x86_64.rpm"
else
SITE_URL="http://mirrors.ustc.edu.cn/mysql-ftp/Downloads/MySQL-$MAJOR"
PERCONA_URL="https://www.percona.com/downloads/XtraBackup"
SERVER_URL="${SITE_URL}/mysql-community-server-${MYSQL_VERSION}-1.el6.x86_64.rpm"
CLIENT_URL="${SITE_URL}/mysql-community-client-${MYSQL_VERSION}-1.el6.x86_64.rpm"
DEVEL_URL="${SITE_URL}/mysql-community-devel-${MYSQL_VERSION}-1.el6.x86_64.rpm"
LIB_URL="${SITE_URL}/mysql-community-libs-${MYSQL_VERSION}-1.el6.x86_64.rpm"
COMMON_URL="${SITE_URL}/mysql-community-common-${MYSQL_VERSION}-1.el6.x86_64.rpm"
COMPAT_URL="${SITE_URL}/mysql-community-libs-compat-${MYSQL_VERSION}-1.el6.x86_64.rpm"
XTRABACK24_URL="${PERCONA_URL}/Percona-XtraBackup-2.4.12/binary/redhat/6/x86_64/percona-xtrabackup-24-2.4.12-1.el6.x86_64.rpm"
XTRABACK22_URL="${PERCONA_URL}/XtraBackup-2.2.9/binary/redhat/6/x86_64/percona-xtrabackup-2.2.9-5067.el6.x86_64.rpm"
XTRABACK16_URL="${PERCONA_URL}/XtraBackup-1.6.7/RPM/rhel6/x86_64/xtrabackup-1.6.7-356.rhel6.x86_64.rpm"
LIBEV_URL="http://dl.fedoraproject.org/pub/epel/6/x86_64/Packages/l/libev-4.03-3.el6.x86_64.rpm"
fi
##############################
#新建binlog
if [ ! -d ${LOG_BIN} ];then
mkdir -p ${LOG_BIN}
fi
#slave新建relaylog
if [ ! -d ${RELAY_LOG} ];then
mkdir -p ${RELAY_LOG}
fi
echo "==========MYSQL安装=========="
###下载
cd /var/tmp
if [ ! -f "mysql-community-server-${MYSQL_VERSION}-1.el6.x86_64.rpm" ]; then
wget ${SERVER_URL}
wget ${CLIENT_URL}
wget ${DEVEL_URL}
wget ${LIB_URL}
wget ${COMMON_URL}
wget ${COMPAT_URL}
fi
###安装numactl
if [ ! -f "/usr/bin/numactl" ]; then
yum -y install numactl
fi
###设置账号
grep "mysql" /etc/passwd && ISSET="true" || ISSET="false"
if [ "$ISSET" == "false" ]; then
groupadd mysql
useradd -M -s /sbin/nologin -g mysql mysql
fi
###安装
if [ ! -f "/usr/sbin/mysqld" ]; then
rpm -Uvh --replacefiles mysql-community*
fi
###创建DIR_PRE
if [ ! -d "${DIR_PRE}" ]; then
mkdir -p ${DIR_PRE}
chown -R $USER:$USER ${DIR_PRE}
fi
###创建LOG_ERROR
if [ -f "${LOG_ERROR}" ]; then
rm -f "${LOG_ERROR}"
fi
touch "${LOG_ERROR}"
chown -R $USER:$USER ${DIR_PRE}
###新建datadir
if [ ! -d ${DATA_DIR} ];then
mkdir -p ${DATA_DIR}
chown -R $USER:$USER ${DIR_PRE}
else
rm -rf ${DATA_DIR}/*
chown -R $USER:$USER ${DIR_PRE}
fi
###关闭selinux,否则mysql创建文件夹报没权限
echo "#########关闭selinux#######"
grep 'SELINUX=disabled' /etc/selinux/config && ISSET="true" || ISSET="false"
if [ "$ISSET" == "false" ]; then
echo "#########关闭selinux#########"
sed -i 's;SELINUX=enforcing;SELINUX=disabled;' /etc/selinux/config
setenforce 0
else
echo "#########selinux 已关闭#########"
fi
#清理默认文件
set +e
rm -f /root/.mysql_secret
rm -rf /var/lib/mysql
rm -f /root/.mysql_history
rm -f /etc/my.cnf.rpmnew
rm -f /var/log/mysqld.log
set -e
echo "==========设置master的MY.CNF=========="
cat > ${MYSQL_CNF} <<EOF
[client]
port=$PORT
[mysql]
socket=$SOCKET
default-character-set = utf8
no_auto_rehash
[mysqld]
user = $USER
port=$PORT
basedir=${BASE_DIR}
datadir=${DATA_DIR}
socket=$SOCKET
log-error=${LOG_ERROR}
pid-file=${PID_FILE}
slow_query_log=1
long_query_time=3
slow_query_log_file=${SLOW_DIR}/slow_query.log
default_password_lifetime=0
server_id=${SERVER_ID}
log-bin=${LOG_BIN}/mysql-bin
expire_logs_days=${EXPIRE_DAYS}
binlog_format=ROW
sync_binlog=${SYNC_BINLOG}
binlog-row-image=minimal
binlog_group_commit_sync_delay=1000
binlog_group_commit_sync_no_delay_count=20
relay_log=${RELAY_LOG}/mysql-relay-bin
slave-parallel-type=LOGICAL_CLOCK
slave-parallel-workers=${WORKERS}
master_info_repository=TABLE
relay_log_info_repository=TABLE
relay_log_recovery=ON
gtid_mode=on
enforce_gtid_consistency=on
#log-slave-updates=1
skip-character-set-client-handshake
wait_timeout=1800
interactive_timeout=1800
character-set-server = utf8
collation-server = utf8_general_ci
symbolic-links=0
explicit_defaults_for_timestamp=1
max_connections=1000
max_connect_errors = 30
skip_external_locking
#skip_name_resolve
read_only=0
event_scheduler=0
query_cache_type=1
query_cache_size=64M
default-storage-engine=INNODB
innodb_large_prefix=1
innodb_strict_mode=1
innodb_file_per_table=1
innodb_buffer_pool_size=${POOL_SIZE}
innodb_io_capacity=${IO_CAP}
innodb_flush_neighbors=1
innodb_log_file_size=${LOG_SIZE}
innodb_flush_log_at_trx_commit=${FLUSH_TRX}
innodb_stats_on_metadata=0
innodb_data_home_dir=
innodb_data_file_path=${DATA_FILE_PATH}
innodb_temp_data_file_path =${TMP_FILE_PATH}
transaction_isolation=READ-COMMITTED
key_buffer_size=256M
max_allowed_packet=16M
sort_buffer_size=2M
read_buffer_size=2M
read_rnd_buffer_size=2M
join_buffer_size=2M
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
tmp_table_size=128M
max_heap_table_size=128M
group_concat_max_len=64K
table_open_cache=2048
thread_cache_size=1024
character_set_server=utf8
log_bin_trust_function_creators=1
open_files_limit=60000
lower_case_table_names=1
secure_file_priv=
[mysqld_multi]
mysqld=/usr/bin/mysqld_safe
mysqladmin=/usr/bin/mysqladmin
[mysqldump]
quick
[myisamchk]
key_buffer_size = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M
[mysqlhotcopy]
interactive-timeout
[mysqld_safe]
pid-file=${PID_FILE}
EOF
echo "==========启动,更改默认密码=========="
set +e
service mysqld start
TEM_PASS=`sed '/A temporary password/!d;s/.*: //' ${LOG_ERROR}`
echo "初始密码是:"${TEM_PASS}
###初始修改root密码
echo "mysql -uroot -P${PORT} -p"${TEM_PASS}" --connect-expired-password -e \"SET PASSWORD = PASSWORD('"${MYSQL_PASS}"');\""
mysql -uroot -P${PORT} -p"${TEM_PASS}" --connect-expired-password -e "SET PASSWORD = PASSWORD('"${MYSQL_PASS}"');"
###设置密码不过期
echo "mysql -uroot -P${PORT} -p"${MYSQL_PASS}" --connect-expired-password -e \"update mysql.user set password_expired='N' where user='root';\""
mysql -uroot -P${PORT} -p"${MYSQL_PASS}" --connect-expired-password -e "update mysql.user set password_expired='N' where user='root';"
###修改root用户名
if [ "${MYSQL_USER}" != "root" ]; then
echo "mysql -uroot -P${PORT} -p'${MYSQL_PASS}' --connect-expired-password -e \"UPDATE mysql.user set user='"${MYSQL_USER}"' where user='root';flush privileges;\""
mysql -uroot -P${PORT} -p"${MYSQL_PASS}" --connect-expired-password -e "UPDATE mysql.user set user='"${MYSQL_USER}"' where user='root';flush privileges;"
fi
set -e
if [ "${MYSQL_PASS_POLICY}" == "off" ]; then
echo "==========关闭密码策略=========="
sed -i "/default_password_lifetime/a\validate_password=off" ${MYSQL_CNF}
service mysqld restart
fi
echo "==========mysql安装完成=========="
echo "=====运行时间为====="
END_TIME=`date +%s`
dif=$[ END_TIME - START_TIME ]
echo $dif "秒"
|
Python
|
UTF-8
| 1,560 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""
File options.
"""
import imp
import os
import shutil
import sys
from fabric.api import runs_once
@runs_once
def _clear_dir(dir_name):
"""
Remove an entire directory tree.
"""
if os.path.isdir(dir_name):
shutil.rmtree(dir_name)
def _clear_file(file_name):
"""
Remove an entire directory tree.
"""
if os.path.exists(file_name):
os.remove(file_name)
def _ensure_dir(dir_name):
"""
Ensure that a directory exists.
"""
if not os.path.exists(dir_name):
os.makedirs(dir_name)
def _import(module_name, dir_name):
"""
Load python module from file system without reloading.
Raises ImportError if not found.
"""
# assign module a name that's not likely to conflict
safe_name = 'confab.data.' + module_name
# check if module is already loaded
existing = sys.modules.get(safe_name)
if existing:
return existing
# try to load module
module_info = imp.find_module(module_name, [dir_name])
module = imp.load_module(safe_name, *module_info)
return module
def _import_string(module_name, content):
"""
Load python module from an in-memory string without reloading.
"""
# assign module a name that's not likely to conflict
safe_name = 'confab.data.' + module_name
# check if module is already loaded
existing = sys.modules.get(safe_name)
if existing:
return existing
# try to load module
module = imp.new_module(safe_name)
exec content in module.__dict__
return module
|
Markdown
|
UTF-8
| 1,355 | 2.71875 | 3 |
[] |
no_license
|
<style>
r { color: Red }
o { color: Orange }
g { color: Green }
</style>
# Target
1. Command resolution
- ~~which Command was passed, default Command~~ - <g>Done</g>
- ~~Command parameters verification~~ - <g>Done</g>
1. User connect
- ~~before executing any commands the user should set username~~ - <g>Done</g>
1. Create/Join rooms
- ~~create room - check if the name is available~~ - <g>Done</g>
- ~~join room - the user can be in more rooms~~ - <g>Done</g>
- ~~leave room~~ - <g>Done</g>
- ~~broadcast when another user joins the room~~ - <g>Done</g>
- ~~get list with active users in the room~~ - <g>Done</g>
- ~~nice-to-have - broadcast when user quits to all the rooms he was in~~ <g>Done</g>
1. Post to room
- ~~by default to the current room~~ - <g>Done</g>
- if used command /post _room_ - send to the specified room - <span style="color:red">Not done, the user should switch with /room </span>.
1. Store information in database
- ~~adapter classes for the different DBs - the should have the same set of default methods so they can be changed without changing anything in the code~~ - <g>Done</g>
- ~~store rooms messages in the database~~ - <g>Done</g>
1. Start server parameters handling
- argparse
- ~~config file~~ - <g>Done</g>
# Optional
1. Executables
2. Web client
|
Python
|
UTF-8
| 720 | 2.75 | 3 |
[] |
no_license
|
"""Wrapper around sensor input for the robot"""
import ev3dev.ev3 as ev3
import Colors
# The reflectivity sensor
_LEFT = ev3.ColorSensor('in2')
# The color sensor
_RIGHT = ev3.ColorSensor('in4')
_ULTRA_SONIC = ev3.UltrasonicSensor('in1')
if not _LEFT.connected:
raise AssertionError('Left sensor not connected')
if not _RIGHT.connected:
raise AssertionError('Right sensor not connected')
_LEFT.mode = 'COL-REFLECT'
_RIGHT.mode = 'COL-COLOR'
def read_color():
"""Convert colors sensor output into members of the Colors Enum"""
return Colors(_RIGHT.value()+1)
def sonar_poll():
"""Read the sonar sensor"""
return _ULTRA_SONIC.distance_centimeters
def read_reflect():
return _LEFT.value()
|
Markdown
|
UTF-8
| 6,487 | 3.5625 | 4 |
[] |
no_license
|
# 399. Evaluate Division(M)
[399. 除法求值](https://leetcode-cn.com/problems/evaluate-division/)
## 题目描述(中等)
给出方程式 `A / B = k`, 其中 A 和 B 均为代表字符串的变量, k 是一个浮点型数字。根据已知方程式求解问题,并返回计算结果。如果结果不存在,则返回 -1.0。
示例 :
```
给定 a / b = 2.0, b / c = 3.0
问题: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
返回 [6.0, 0.5, -1.0, 1.0, -1.0 ]
输入为: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries(方程式,方程式结果,问题方程式), 其中 equations.size() == values.size(),即方程式的长度与方程式结果长度相等(程式与结果一一对应),并且结果值均为正数。以上为方程式的描述。 返回vector<double>类型。
基于上述例子,输入如下:
equations(方程式) = [ ["a", "b"], ["b", "c"] ],
values(方程式结果) = [2.0, 3.0],
queries(问题方程式) = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
```
输入总是有效的。你可以假设除法运算中不会出现除数为0的情况,且不存在任何矛盾的结果。
## 思路
构建图
- DFS遍历
- BFS遍历
- Floyd
- 并查集
## 解决方法
### DFS遍历
```java
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
Map<String, Map<String, Double>> graph = buildGraph(equations, values);
double[] result = new double[queries.size()];
for (int i = 0; i < queries.size(); i++) {
Double r = dfsQuery(graph, queries.get(i).get(0), queries.get(i).get(1), new HashSet<>());
result[i] = r != null ? r : -1.0;
}
return result;
}
public Map<String, Map<String, Double>> buildGraph(List<List<String>> equations, double[] values) {
Map<String, Map<String, Double>> graph = new HashMap<>();
int n = equations.size();
for (int i = 0; i < n; i++) {
String x = equations.get(i).get(0);
String y = equations.get(i).get(1);
double value = values[i];
if (!graph.containsKey(x)) {
graph.put(x, new HashMap<>());
}
graph.get(x).put(y, value);
if (!graph.containsKey(y)) {
graph.put(y, new HashMap<>());
}
graph.get(y).put(x, 1 / value);
}
return graph;
}
public Double dfsQuery(Map<String, Map<String, Double>> graph, String a, String b, Set<String> visited) {
if (!graph.containsKey(a)) {
return null;
}
Map<String, Double> adjMap = graph.get(a);
if (adjMap.containsKey(b)) {
return graph.get(a).get(b);
}
visited.add(a);
for (String adj : adjMap.keySet()) {
if (visited.contains(adj)) {
continue;
}
Double r = dfsQuery(graph, adj, b, visited);
if (r != null) {
return adjMap.get(adj) * r;
}
}
visited.remove(a);
return null;
}
```
### BFS
```java
public double[] calcEquation1(List<List<String>> equations, double[] values, List<List<String>> queries) {
Map<String, Map<String, Double>> graph = buildGraph(equations, values);
double[] result = new double[queries.size()];
for (int i = 0; i < queries.size(); i++) {
Double r = bfsQuery(graph, queries.get(i).get(0), queries.get(i).get(1));
result[i] = r != null ? r : -1.0;
}
return result;
}
public Double bfsQuery(Map<String, Map<String, Double>> graph, String a, String b) {
if (!graph.containsKey(a)) {
return null;
}
Queue<Pair<String, Double>> queue = new LinkedList<>();
queue.add(new Pair<>(a, 1.0));
Set<String> visited = new HashSet<>();
visited.add(a);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Pair<String, Double> pair = queue.poll();
if (b.equals(pair.getKey())) {
return pair.getValue();
}
Map<String, Double> adjMap = graph.get(pair.getKey());
for (String adj : adjMap.keySet()) {
if (visited.contains(adj)) {
continue;
}
queue.add(new Pair<>(adj, pair.getValue() * adjMap.get(adj)));
visited.add(adj);
}
}
}
return null;
}
```
### Floyd
```java
public double[] calcEquation2(List<List<String>> equations, double[] values, List<List<String>> queries) {
Map<String, Map<String, Double>> graph = buildGraph(equations, values);
double[] result = new double[queries.size()];
Map<String, Integer> indexMap = new HashMap<>();
int index = 0;
for (String node : graph.keySet()) {
indexMap.put(node, index++);
}
Double[][] floydValues = floyd(graph, indexMap);
for (int i = 0; i < queries.size(); i++) {
String x = queries.get(i).get(0);
String y = queries.get(i).get(1);
if (indexMap.containsKey(x) && indexMap.containsKey(y)) {
Double f = floydValues[indexMap.get(x)][indexMap.get(y)];
result[i] = f != null ? f : -1.0;
} else {
result[i] = -1.0;
}
}
return result;
}
public Double[][] floyd(Map<String, Map<String, Double>> graph, Map<String, Integer> indexMap) {
int n = graph.size();
Double[][] values = new Double[n][n];
for (String a : graph.keySet()) {
for (String b : graph.get(a).keySet()) {
values[indexMap.get(a)][indexMap.get(b)] = graph.get(a).get(b);
}
}
for (int i = 0; i < n; i++) {
values[i][i] = 1.0;
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
if (values[i][j] == null && values[i][k] != null && values[k][j] != null) {
values[i][j] = values[i][k] * values[k][j];
}
}
}
}
return values;
}
```
### 并查集
|
Ruby
|
UTF-8
| 444 | 3.5625 | 4 |
[] |
no_license
|
class House
def initialize(color, number_of_bedrooms)
self.color = color
self.number_of_bedrooms = number_of_bedrooms
end
def fire_alarm
puts 'STOP DROP AND ROLL'
end
attr_accessor:color
attr_accessor:number_of_bedrooms
end
class Bathroom < House
def flush_toliet
puts 'FLUSHHHH!'
end
attr_accessor:shower
attr_accessor:bath
attr_accessor:tiling
end
my_house = House.new('white', 3)
puts my_house
my_house.fire_alarm
|
Java
|
UTF-8
| 587 | 2.125 | 2 |
[] |
no_license
|
package controllers;
import models.Device;
import models.LogItem;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.logItemsViews.indexView;
import java.util.List;
/**
* Created by Luuk on 26/01/15.
*/
public class LogItems extends Controller {
public static Result index() {
List<LogItem> logItems = LogItem.find.all();
return ok(indexView.render(logItems));
}
public static Result delete(Long id) {
Device device = Device.find.byId(id);
device.delete();
return redirect(routes.LogItems.index());
}
}
|
Markdown
|
UTF-8
| 5,748 | 2.578125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|

---
## The Lumpy Ci40 application
The Lumpy Ci40 is part of bigger project called "Weather Station". Using code from this repository you will be able to handle various sensor clicks inserted into your Ci40 board. Values measured by those clicks will be sent to Creator Device Server.
## Environment for Weather Station project
The complete IoT Environment is builded with following components:
* LWM2M cloud server
* Ci40 application which allows usage of clicks in mirkroBUS sockets.
* Contiki based applications build for clicker platform:
* [Temperature sensor](https://github.com/CreatorKit/temperature-sensor)
* a mobile application to present Weather measurements.
## Ci40 application specific dependencies
This application uses the [Awa LightweightM2M](https://github.com/FlowM2M/AwaLWM2M) implementation of the OMA Lightweight M2M protocol to provide a secure and standards compliant device management solution without the need for an intimate knowledge of M2M protocols. Additionnaly MikroE Clicks support is done through [LetMeCreate library](https://github.com/CreatorDev/LetMeCreate).
## Integration with openWrt
It's assumed that you have build envriroment for ci40 openWrt described [here](https://github.com/CreatorKit/build) and this is located in folder `work`. So structure inside will be:
work/
build/
constrained-os/
dist/
packages/
Clone this repository into `work/packages`, after this operation structure will look:
work/
build/
constrained-os/
dist/
packages/
weather-station-gateway
Now copy folder from `packages/weather-station-gateway/feeds` into `work/dist/openwrt/openwrt-ckt-feeds`.
Then execute commands:
cd work/dist/openwrt
./scripts/feeds update
./script/feeds update weather-station-gateway
./script/feeds install weather-station-gateway
make menuconfig
in menuconfig please press `/` and type `weather-station-gateway` one occurrence will appear. Mark it with `<*>` and do save of config.
In terminal type `make` to build openwrt image with this application. After uploading to ci40 edit file located in `/etc/init.d/weather_station_initd` and put proper switch arguments related to clicks which you put into mikroBus port.
## Setup for execution - development
While Lumpy uses Awa Client Deamon to communicate with Cloud LWM2M server it requires few things to be done before project will run. First of all you need to go to CreatorKit console and create certificate which will be used to make secure connection. If you havent done this earlier, you will find usefull informations on [ Creator Device Server](https://docs.creatordev.io/deviceserver/) page. Then you have to provide IPSO object definitions, to do so please run `clientObjectsDefine.sh` shript from `scripts` folder (make sure Awa client deamon is working!). And here you go!
Wait! No! Put some clicks into Ci40 mikroBUS, and then you can execute Lumpy with one of following options:
| Switch | Description |
|---------------|----------|
|-1, --click1 | Type of click installed in microBUS slot 1 (default:none)|
|-2, --click2 | Type of click installed in microBUS slot 2 (default:none)|
|-s, --sleep | Delay between measurements in seconds. (default: 60s)|
|-v, --logLevel | Debug level from 1 to 5 (default:info): fatal(1), error(2), warning(3), info(4), debug(5) and max(>5)|
|-h, --help | prints help|
Please refer to section 'Supprted clicks' to obtain argument values for switch --click1 and --click2. If one of slots is empty you can skip proper switch or set it's value to `none`.
## Supported clicks
From wide range of [MikroE clicks](http://www.mikroe.com/index.php?url=store/click/) in this project you can use:
| Click | Argument |
|--------------------- |----------|
| [Air Quality](http://www.mikroe.com/click/air-quality/) | air |
| [Carbon monoxide](http://www.mikroe.com/click/co/) | co |
| [Thermo3](http://www.mikroe.com/click/thermo3/) | thermo3 |
| [Thunder](http://www.mikroe.com/click/thunder/) | thunder |
| [Weather](http://www.mikroe.com/click/weather/) | weather |
## License
Copyright (c) 2016, Imagination Technologies Limited and/or its affiliated group companies.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----
|
C#
|
UTF-8
| 4,817 | 2.609375 | 3 |
[] |
no_license
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NearLosslessPredictiveCoder.Contracts.Predictors;
using NearLosslessPredictiveCoder.Entities;
using NearLosslessPredictiveCoder.PredictionAlgorithms;
namespace NearLosslessPredictiveCoder.UnitTests
{
[TestClass]
public class BasePredictionAlgorithmUnitTests
{
private BasePredictionAlgorithm basePredictionAlgorithm;
private Mock<IPredictor> predictorMock;
private Mock<IPredictor> firstRowPredictorMock;
private Mock<IPredictor> firstColumnPredictorMock;
private int acceptedError = 2;
private int range = 16;
private int[,] matrix = new int[,]
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
[TestInitialize]
public void Setup()
{
predictorMock = new Mock<IPredictor>();
firstRowPredictorMock = new Mock<IPredictor>();
firstColumnPredictorMock = new Mock<IPredictor>();
var predictorSettings = new PredictorSettings
{
Predictor = predictorMock.Object,
AcceptedError = acceptedError,
Range = range
};
basePredictionAlgorithm = new BasePredictionAlgorithm(predictorSettings)
{
firstRowPredictor = firstRowPredictorMock.Object,
firstColumnPredictor = firstColumnPredictorMock.Object
};
}
[TestMethod]
public void TestThatWhenPredictorIsHalfRangeInitializePredictorsSetsFirstRowAndColumnPredictorsToBeTheSame()
{
basePredictionAlgorithm.predictorSettings.Predictor = new Predictors.HalfRange(range);
basePredictionAlgorithm.InitializePredictors();
Assert.AreEqual(basePredictionAlgorithm.predictor, basePredictionAlgorithm.firstRowPredictor);
Assert.AreEqual(basePredictionAlgorithm.predictor, basePredictionAlgorithm.firstColumnPredictor);
}
[TestMethod]
public void TestThatWhenPredictorIsNotHalfRangeInitializePredictorsSetsFirstRowPredictorIsPredictorA()
{
basePredictionAlgorithm.predictorSettings.Predictor = new Predictors.Predictor4();
basePredictionAlgorithm.InitializePredictors();
Assert.AreEqual(typeof(Predictors.A), basePredictionAlgorithm.firstRowPredictor.GetType());
}
[TestMethod]
public void TestThatWhenPredictorIsNotHalfRangeInitializePredictorsSetsFirstColumnPredictorIsPredictorB()
{
basePredictionAlgorithm.predictorSettings.Predictor = new Predictors.Predictor4();
basePredictionAlgorithm.InitializePredictors();
Assert.AreEqual(typeof(Predictors.B), basePredictionAlgorithm.firstColumnPredictor.GetType());
}
[TestMethod]
public void TestThatWhenOnFirstCellGetPredictionReturnsHalfRange()
{
var result = basePredictionAlgorithm.GetPrediction(0, 0, matrix);
Assert.AreEqual(range/2, result);
}
[TestMethod]
public void TestThatWhenOnFirstRowGetPredictionCallsFirstRowPredictorPredictOnce()
{
basePredictionAlgorithm.GetPrediction(0, 2, matrix);
firstRowPredictorMock.Verify(x => x.Predict(matrix[0, 1], It.IsAny<int>(), It.IsAny<int>()), Times.Once);
}
[TestMethod]
public void TestThatWhenOnFirstColumnGetPredictionCallsFirstColumnPredictorPredictOnce()
{
basePredictionAlgorithm.GetPrediction(2, 0, matrix);
firstColumnPredictorMock.Verify(x => x.Predict(It.IsAny<int>(), matrix[1, 0], It.IsAny<int>()), Times.Once);
}
[TestMethod]
public void TestThatGetPredictionCallsPredictorPredictOnce()
{
basePredictionAlgorithm.GetPrediction(1, 2, matrix);
predictorMock.Verify(x => x.Predict(matrix[1, 1], matrix[0, 2], matrix[0, 1]), Times.Once);
}
[TestMethod]
public void TestThatWhenValueIsLowerThan0NormalizeValueReturns0()
{
var result = basePredictionAlgorithm.NormalizeValue(-1);
Assert.AreEqual(0, result);
}
[TestMethod]
public void TestThatWhenValueIsGreaterThanMaxValueInRangeNormalizeValueReturnsMaxValue()
{
var result = basePredictionAlgorithm.NormalizeValue(range + 1);
Assert.AreEqual(range - 1, result);
}
[TestMethod]
public void TestThatWhenValueIsInRangeNormalizeValueReturnsValue()
{
var value = range / 2;
var result = basePredictionAlgorithm.NormalizeValue(value);
Assert.AreEqual(value, result);
}
}
}
|
Java
|
UTF-8
| 350 | 2.875 | 3 |
[] |
no_license
|
import java.util.Calendar;
public class TimeInMilli {
public static void main(String[] args) {
long timeInMill=Calendar.getInstance().getTimeInMillis();
System.out.println("TimeInMilli.main() timeinmili="+timeInMill);
String strLong=String.valueOf(timeInMill);
System.out.println(strLong +" length="+strLong.length());
}
}
|
Markdown
|
UTF-8
| 179,716 | 3.65625 | 4 |
[] |
no_license
|
# 함수(function)
<center>
<img src="./images/03/func.png", alt="func.png">
</center>
## 들어가기전에
> 직사각형의 둘레와 면적을 구하는 코드를 작성해주세요.
```python
height = 30
width = 20
```
---
```
예시 출력)
직사각형 둘레: 100, 면적: 600입니다.
```
```python
height = 30
width = 20
# 아래에 코드를 작성하세요.
perimeter = (height+width)*2
area = height*width
print(f'직사각형 둘레: {perimeter}, 면적: {area}입니다.')
```
직사각형 둘레: 100, 면적: 600입니다.
* 앞서 작성한 코드에서 매번 사각형의 둘레와 면적을 구하기 위해서는 변수에 값을 바꾸거나 코드를 복사 붙여넣기 해야합니다.
* 코드가 많아질수록 문제가 발생할 확률이 높아지며, 유지 보수하기도 힘들어진다.
<center>
<img src="./images/03/emc2.png", alt="programming principle">
</center>
<center>
<img src="./images/03/principle.png", alt="programming principle">
</center>
## 함수의 선언과 호출
```python
def func(parameter1, parameter2):
code line1
code line2
return value
```
* 함수 선언은 `def`로 시작하여 `:`으로 끝나고, 다음은 `4spaces 들여쓰기`로 코드 블록을 만듭니다.
* 함수는 `매개변수(parameter)`를 넘겨줄 수도 있습니다.
* 함수는 동작후에 `return`을 통해 결과값을 전달 할 수도 있습니다. (`return` 값이 없으면, None을 반환합니다.)
* 함수는 호출을 `func(val1, val2)`와 같이 합니다.
```python
# 위의 사각형 면적을 반환 코드를 함수로 아래에 작성해보세요
def rectangle(height,width):
perimeter = (height+width)*2
area = height*width
return f'직사각형 둘레: {perimeter}, 면적: {area}입니다.'
print(rectangle(20,20)) # 출력 되는것
rectangle(20,50) # 출력이 아니라 반환값 보여주는것
```
직사각형 둘레: 80, 면적: 400입니다.
'직사각형 둘레: 140, 면적: 1000입니다.'
```python
def rectangle(height,width):
perimeter = (height+width)*2
area = height*width
return perimeter, area
a,c = rectangle(20,30)
print(a,c)
```
100 600
<center>
<img src="./images/03/func_des.png", alt="function descrpition">
</center>
<center>
<img src="./images/03/function_ex.png", alt="function_example">
</center>
```python
# 우리가 활용하는 print문도 파이썬에 지정된 함수입니다.
# 아래에서 'hi'는 parameter이고 출력을 하게 됩니다.
print('hi')
```
<center>
<img src="./images/03/built_in.png", alt="built_in">
</center>
[출처: python 공식문서](https://docs.python.org/3/library/functions.html)
```python
# 내장함수 목록을 직접 볼 수도 있습니다.
dir(__builtins__)
```
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BlockingIOError',
'BrokenPipeError',
'BufferError',
'BytesWarning',
'ChildProcessError',
'ConnectionAbortedError',
'ConnectionError',
'ConnectionRefusedError',
'ConnectionResetError',
'DeprecationWarning',
'EOFError',
'Ellipsis',
'EnvironmentError',
'Exception',
'False',
'FileExistsError',
'FileNotFoundError',
'FloatingPointError',
'FutureWarning',
'GeneratorExit',
'IOError',
'ImportError',
'ImportWarning',
'IndentationError',
'IndexError',
'InterruptedError',
'IsADirectoryError',
'KeyError',
'KeyboardInterrupt',
'LookupError',
'MemoryError',
'ModuleNotFoundError',
'NameError',
'None',
'NotADirectoryError',
'NotImplemented',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'PermissionError',
'ProcessLookupError',
'RecursionError',
'ReferenceError',
'ResourceWarning',
'RuntimeError',
'RuntimeWarning',
'StopAsyncIteration',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
'TabError',
'TimeoutError',
'True',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'WindowsError',
'ZeroDivisionError',
'__IPYTHON__',
'__build_class__',
'__debug__',
'__doc__',
'__import__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'abs',
'all',
'any',
'ascii',
'bin',
'bool',
'breakpoint',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'compile',
'complex',
'copyright',
'credits',
'delattr',
'dict',
'dir',
'display',
'divmod',
'enumerate',
'eval',
'exec',
'filter',
'float',
'format',
'frozenset',
'get_ipython',
'getattr',
'globals',
'hasattr',
'hash',
'help',
'hex',
'id',
'input',
'int',
'isinstance',
'issubclass',
'iter',
'len',
'license',
'list',
'locals',
'map',
'max',
'memoryview',
'min',
'next',
'object',
'oct',
'open',
'ord',
'pow',
'print',
'property',
'range',
'repr',
'reversed',
'round',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'vars',
'zip']
## 함수를 만들어봅시다.
> 아래의 코드와 동일한 `my_max`함수를 만들어주세요.
>
> 정수를 두개 받아서, 큰 값을 출력합니다.
```python
max(1, 5)
```
---
```
예상 출력)
5가 더 큽니다
```
```python
# max(1, 5)를 호출 해봅시다.
max(1, 5)
```
5
```python
# 여기에 my_max 함수를 만들어주세요.
def my_max (num1,num2):
if num1 > num2:
print(num1)
else:
print(num2)
```
```python
# 그리고 호출 해봅시다.
a = 'w'
e = 'e'
my_max (a,e)
```
w
```python
def my_max (num1,num2):
return num1 if num1 > num2 else num2
```
```python
my_max(1000,300)
```
1000
# 함수의 return
앞서 설명한 것과 마찬가지로 함수는 반환되는 값이 있으며, 이는 어떠한 종류의 객체여도 상관없습니다.
단, 오직 한 개의 객체만 반환됩니다.
함수가 return 되거나 종료되면, 함수를 호출한 곳으로 돌아갑니다.
## 함수를 정의하고 값을 반환해봅시다.
> 함수는 모든 객체를 리턴할 수 있습니다.
>
> 리스트 두개를 받아 각각 더한 결과를 비교하여 값이 큰 리스트를 반환합니다.
```python
my_list_max([10, 3], [5, 9])
```
---
```
예상 출력)
[5, 9]
```
```python
def my_func(a,b):
return a, b
```
```python
my_func(1,'2') # 숫자와 문자 두 개를 반활하는 것처럼 보이지만, 실제로는 tuple이다. 즉 하나의 객체!
```
(1, '2')
```python
type(my_func(1,'2'))
```
tuple
```python
# 여기에 my_list_max 함수를 만들어주세요.
def my_list_max (list1,list2):
# if sum(list1) > sum(list2):
# return list1
# else:
# return list2
return list1 if sum(list1) > sum(list2) else list2
a = [1,2]
b = [2,3]
c = my_list_max(a,b)
print(c)
c
```
[2, 3]
[2, 3]
# 함수의 인수
함수는 `인자(parameter)`를 넘겨줄 수 있습니다.
인수(arguments) --> 함수 호출시
func (a,b)에서 a와 b
인자(parameter) --> 함수 정의
def func (a,b)에서 a와 b
## 위치 인수
함수는 기본적으로 인수를 위치로 판단합니다.
```python
# 알고 있는 수학 공식의 함수를 하나만 만들어보세요.
```
<center>
<img src="./images/03/func_ex_01.png", alt="function example 02">
</center>
```python
def my_sub(a,b):
return a-b
```
```python
my_sub(1,3)
```
-2
```python
my_sub(3,1)
```
2
```python
my_sub(1)
```
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-67-fce120493363> in <module>
----> 1 my_sub(1)
TypeError: my_sub() missing 1 required positional argument: 'b'
```python
my_sub()
```
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-68-078ed5892caf> in <module>
----> 1 my_sub()
TypeError: my_sub() missing 2 required positional arguments: 'a' and 'b'
## 기본 값(Default Argument Values)
함수가 호출될 때, 인자를 지정하지 않아도 기본 값을 설정할 수 있습니다.
**활용법**
```python
def func(p1=v1):
return p1
```
### 기본 값 활용 예제
> 이름을 받아서 다음과 같이 인사하는 함수 greeting을 만들어보세요. 이름이 길동이면, "길동, 안녕?" 이름이 없으면 "익명, 안녕?" 으로 출력해주세요.
```python
# 아래에 greeting 함수를 만들어보세요.
def greeting(name='익명'):
print(f'{name}, 안녕')
```
```python
greeting('명')
```
명, 안녕
* 기본 인자 값이 설정되어 있더라도 기존의 함수와 동일하게 호출 가능합니다.
<center>
<img src="./images/03/func_ex_02.png", alt="function example 02">
</center>
* 호출시 인자가 없으면 기본 인자 값이 활용됩니다.
<center>
<img src="./images/03/func_ex_03.png", alt="function example 03">
</center>
* 단, 기본 매개변수 이후에 기본 값이 없는 매개변수를 사용할 수는 없습니다.
```python
# 오류를 확인해봅시다.
def greetin(name = '익명', age):
print(f'{name}은 {age}살')
```
File "<ipython-input-72-6c176d32295f>", line 2
def greetin(name = '익명', age):
^
SyntaxError: non-default argument follows default argument
```python
# 수정해 봅시다.
def greeting(age, name = '익명'):
print(f'{name}은 {age}살')
```
```python
greeting(1000,'둘리')
```
둘리은 1000살
## 키워드 인자(Keyword Arguments)
키워드 인자는 직접적으로 변수의 이름으로 특정 인자를 전달할 수 있습니다.
```python
# 키워드 인자 예시
print('123', end='\t')
print('123', end='\t')
```
123 123
* 단 아래와 같이 활용할 수는 없습니다. 키워드 인자를 활용한 뒤에 위치 인자를 활용할 수는 없습니다.
```python
# 확인 해봅시다.
print(end=',', '123' )
```
File "<ipython-input-86-34c7e09c63ff>", line 3
print(end='\t', '123' )
^
SyntaxError: positional argument follows keyword argument
우리가 주로 활용하는 `print()` 함수는 [파이썬 표준 라이브러리의 내장함수](https://docs.python.org/ko/3.6/library/functions.html) 중 하나이며, 다음과 같이 구성되어 있다.
<br>
<br>
<center>
<img src="./images/03/print.png", alt="print">
</center>
```python
# print 함수를 활용 해봅시다.
print('안녕','하세요',sep='/',end='끝!')
```
안녕/하세요끝!
## 가변 인자 리스트
앞서 설명한 `print()`처럼 정해지지 않은 임의의 숫자의 인자를 받기 위해서는 가변인자를 활용합니다.
가변인자는 `tuple` 형태로 처리가 되며, `*`로 표현합니다.
**활용법**
```python
def func(*args):
```
```python
# 가변 인자 예시 (print문은 *obejcts를 통해 임의의 숫자의 인자를 모두 처리합니다.)
print('hi','안녕','hello', '곤니치와')
```
hi 안녕 hello 곤니치와
```python
# args는 tuple!
def my_fuc(*args):
print(type(args))
```
```python
my_fuc(1,2,3)
```
<class 'tuple'>
### 가변인자 리스트를 사용해봅시다.
> 정수를 여러 개 받아서 가장 큰 값을 반환(return)하는 `my_max()`을 만들어주세요.
```python
my_max(10, 20, 30, 50)
```
---
```
예시출력)
50
```
```python
max(1, 2, 3, 4)
```
```python
# 아래에 코드를 작성해주세요.
def my_max(*num):
for i in range(len(num)):
# if num[i] > num[i-1]:
# max1 = num[i]
max1 = num[i] if num[i] > num[i-1] else num[i-1]
return max1
```
```python
# 함수를 호출 해보세요.
my_max(1,2,3,4,6,3,10,3)
```
10
```python
# 다른 풀이
def my_max(*nums):
max_value = nums[0]
#하나씩 반복하면서, 큰 값을 기록한다.
for num in nums:
# 만약에 큰 값보다 지금 값이 더 크면, 값을 바꾼다.
if num > max_value:
max_vlaue = num
# 반복문 끝나면 반환한다.
return max_value
```
```python
my_max(100,2,4)
```
100
## 정의되지 않은 인자들 처리하기
정의되지 않은 인자들은 `dict` 형태로 처리가 되며, `**`로 표현합니다.
주로 `kwagrs`라는 이름을 사용하며, `**kwargs`를 통해 인자를 받아 처리할 수 있습니다.
**활용법**
```python
def func(**kwargs):
```
우리가 dictionary를 만들 때 사용할 수 있는 `dict()` 함수는 [파이썬 표준 라이브러리의 내장함수](https://docs.python.org/ko/3.6/library/functions.html) 중 하나이며, 다음과 같이 구성되어 있다.
<br>
<br>
<center>
<img src="./images/03/dict.png", alt="dictionary">
</center>
```python
# 딕셔너리 생성 함수 예시
dict(사과='apple', 바나나='banana', 고양이='cat')
```
{'사과': 'apple', '바나나': 'banana', '고양이': 'cat'}
```python
def my_func(**kwargs):
print(type(kwargs))
print(kwargs)
```
```python
my_func(사과='apple')
```
<class 'dict'>
{'사과': 'apple'}
### 정의되지 않은 인자를 처리해봅시다.
> `my_dict()` 함수를 만들어 실제로 dictionary 모습으로 출력 함수를 만들어보세요.
>
>
```
예시 출력)
한국어: 안녕, 영어: hi
```
```python
def my_dict(**kwargs):
result = []
for k,v in kwargs.items():
result.append(f'{k} : {v}')
print(result)
print(type(result))
print(', '.join(result))
my_dict(사과=1,w=2)
```
['사과 : 1', 'w : 2']
<class 'list'>
사과 : 1, w : 2
```python
# 사실은 dict()는 출력이 아니라 딕셔너리를 리턴(반환)합니다.
# 리턴하는 my_fake_dict를 만들어주세요.
def my_fake_dict(**kwargs):
print(kwargs)
return kwargs
```
```python
my_fake_dict(한국어='안녕', 영어='hi')
```
{'한국어': '안녕', '영어': 'hi'}
{'한국어': '안녕', '영어': 'hi'}
## dictionary를 인자로 넘기기(unpacking arguments list)
`**dict`를 통해 함수에 인자를 넘길 수 있습니다.
```python
my_dict = {'한국어':'안녕', '영어':'hi'}
my_fake_dict(**my_dict)
```
{'한국어': '안녕', '영어': 'hi'}
{'한국어': '안녕', '영어': 'hi'}
### 회원가입 검증 예제
> 회원가입 로직을 검증하는 코드를 작성 해봅시다.
* signup 함수는 `username`, `password`, `password_confirmation`을 인자로 받습니다.
* `password`가 8자리 이상인지 확인을 합니다.
* `password`와 `password_confirmation`이 일치하는지 확인을 합니다.
```python
my_account = {
'username': '홍길동',
'password': '1q2w3e4r',
'password_confirmation': '1q2we4r'
}
```
```python
# signup 함수를 작성 해주세요.
def signup(username, password, password_confirmation):
if 8 <= len(password):
if password == password_confirmation:
return True
else:
return False
else:
return False
```
```python
# signup 함수를 my_account를 넘겨 확인 해보세요.
signup(**my_account)
```
False
```python
signup(username='홍길동', password='1q2w4r', password_confirmation='1q2w3er')
```
False
```python
signup('홍길동', '1q2w3e4r', '1q2w3e4r')
```
True
```python
signup('홍길동', password='1q2w3e4r', password_confirmation='1q2w3e4r')
```
True
```python
signup(password='1q2w3e4r', password_confirmation='1q2w3e4r', username='홍길동')
```
True
```python
signup(password='1q2w3e4r', '1q2w3e4r', '홍길동')
```
File "<ipython-input-255-8cbd7ad9089c>", line 1
signup(password='1q2w3e4r', '1q2w3e4r', '홍길동')
^
SyntaxError: positional argument follows keyword argument
### URL 편하게 만들기
> url 패턴을 만들어 문자열을 반환하는 `my_url` 함수를 만들어봅시다.
>
> 영진위에서 제공하는 일별 박스오피스 API 서비스는 다음과 같은 방식으로 요청을 받습니다.
```
기본 요청 URL : http://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?
```
* key : 발급받은 키값(abc)
* targetDt : yyyymmdd
* itemPerPage : 1 ~ 10 **기본 10**
```
예시)
my_url(key='abc', targetDt='yyyymmdd')
api = {
'key': 'abc',
'targetDt': 'yyyymmdd'
}
my_url(**api)
예시 출력)
'http://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?itemPerPage=10&key=abc&targetDt=yyyymmdd&'
```
```python
# 여기에 코드를 작성해주세요.
def my_url(key, targetDt, itemPerPage=10):
base_url = '?'
base_url += f'itemPerPage={itemPerPage}&key={key}&targetDt={targetDt}&'
return base_url
```
```python
api = {
'key': 'abc',
'targetDt': 'yyyymmdd'
}
my_url(**api)
```
'?itemPerPage=10&key=abc&targetDt=yyyymmdd&'
```python
def my_url_2(itemPerPage=10, **kwargs):
base_url = '?'
base_url += f'itemPerPage={itemPerPage}&'
for key, value in kwargs.items():
base_url += f'{key}={value}&'
return base_url
```
```python
api = {
'key': 'abc',
'targetDt': 'yyyymmdd'
}
my_url_2(**api)
```
'?itemPerPage=10&key=abc&targetDt=yyyymmdd&'
### URL 검증하기
> 이제 우리는 만들어진 요청 보내기전에 URL을 검증해야합니다.
>
> 앞선 설명을 참고하여 검증 로직을 구현하고 문자열을 반환하세요.
```
> 아래의 두가지 상황만 만들도록 하겠습니다. <
key, targetDt가 없으면, '필수 요청변수가 누락되었습니다.'
itemPerPage의 범위가 1~10을 넘어가면, '1~10까지의 값을 넣어주세요.'
```
```python
# 여기에 코드를 작성해주세요
def my_url_2(itemPerPage=10, **kwargs):
# key, targetDt 있는지 확인
if 'key' not in kwargs.keys() or 'targetDt' not in kwargs.keys():
return '필수 요청 변수가 누락되었습니다.'
if int(itemPerPage) not in range(1,11):
return '1~10까지의 값을 넣어주세요'
# itemPerPage 있는지 확인
base_url = '?'
base_url += f'itemPerPage={itemPerPage}&'
for key, value in kwargs.items():
base_url += f'{key}={value}&'
return base_url
```
```python
my_url_2(10,key='안녕', targetDt='20190717')
```
'?itemPerPage=10&key=안녕&targetDt=20190717&'
## 이름공간 및 스코프(Scope)
파이썬에서 사용되는 이름들은 이름공간(namespce)에 저장되어 있습니다.
그리고, LEGB Rule을 가지고 있습니다.
변수에서 값을 찾을 때 아래와 같은 순서대로 이름을 찾아나갑니다.
* `L`ocal scope: 정의된 함수
* `E`nclosed scope: 상위 함수
* `G`lobal scope: 함수 밖의 변수 혹은 import된 모듈
* `B`uilt-in scope: 파이썬안에 내장되어 있는 함수 또는 속성
```python
# 따라서 첫시간에 내장함수의 식별자를 사용할 수 없었던 예제에서 오류가 생기는 이유를 확인할 수 있습니다.
print(str(4))
str = 4
print(str(4))
```
4
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-210-8c23451a07ab> in <module>
2 print(str(4))
3 str = 4
----> 4 print(str(4))
TypeError: 'int' object is not callable
* `str()` 코드가 실행되면
* str을 Global scope에서 먼저 찾아서 `str = 4`를 가져오고,
* 이는 함수가 아니라 변수이기 때문에 `not callable`하다라는 오류를 내뱉게 됩니다.
* 우리가 원하는 `str()`은 Built-in scope에 있기 때문입니다.
```python
del str
```
```python
# print(a)에 무엇이 출력되는지 확인해보세요.
a = 1
def localscope(a):
print(a)
localscope(3)
print(a)
```
3
1
```python
# 전역 변수를 바꿀 수 있을까요?
global_num = 3
def localscope2():
global_num = 5
print(f'global_num이 {global_num}으로 설정됨')
print(global_num)
localscope2()
print(global_num)
```
3
global_num이 5으로 설정됨
3
```python
def localscope3():
yyh = 'yyh'
print(yyh)
return None
localscope3()
print(yyh)
```
yyh
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-220-6d0bb0956aa1> in <module>
5
6 localscope3()
----> 7 print(yyh)
NameError: name 'yyh' is not defined
```python
for yyh in range(5):
print(yyh)
print(yyh)
```
0
1
2
3
4
4
```python
# 굳이 전역에 있는 변수를 바꾸고 싶다면, 아래와 같이 선언할 수 있습니다.
global_num = 5
def localscope3():
global global_num
global_num = 3
print('local에서 설정', global_num)
print(global_num)
localscope3()
print(global_num)
```
5
local에서 설정 3
3
```python
# 만약 로컬 스코프에서 내가 글로벌 값을 쓰고 싶다면,
global_num = 5
def localscope4(g):
print(g)
localscope4(global_num)
```
5
```python
# 만약 로컬 스코프에 있는 값을 내가 글로벌 값으로 쓰고 싶다면, 리턴을 해라
def localscope5():
global_num = 6
return global_num
global_num = localscope5()
print(global_num)
```
6
이름공간은 각자의 수명주기가 있습니다.
* built-in scope : 파이썬이 실행된 이후부터 끝까지
* Global scope : 모듈이 호출된 시점 이후 혹은 이름 선언된 이후부터 끝까지
* Local/Enclosed scope : 함수가 실행된 시점 이후부터 리턴할때 까지
# 재귀 함수(recursive function)
재귀 함수는 함수 내부에서 자기 자신을 호출 하는 함수를 뜻한다.
## 팩토리얼 계산
> `팩토리얼(factorial)`을 계산하는 함수 `fact(n)`를 작성해봅시다.
>
> n은 1보다 큰 정수라고 가정하고, 팩토리얼을 계산한 값을 반환합니다.
$$
\displaystyle n! = \prod_{ k = 1 }^{ n }{ k }
$$
$$
\displaystyle n! = 1*2*3*...*(n-1)*n
$$
---
```
예시 출력)
120
```
```python
# 아래에 코드를 작성해주세요.
def fact(n):
result = 1
for i in range(1,n+1):
result = result*i
return result
```
```python
fact(5)
```
120
## 재귀를 이용한 팩토리얼 계산
```
1! = 1
2! = 1 * 2 = 1! * 2
3! = 1 * 2 * 3 = 2! * 3
```
```python
# 아래에 코드를 작성해주세요.
def factorial(n):
if n > 1:
return n*factorial(n-1)
return n
```
```python
factorial(5)
```
120
```python
def factorial(n):
if n <= 1:
return n
else:
return n * factorial(n-1)
```
```python
factorial(5)
```
120
## 반복문과 재귀함수
```
factorial(3)
3 * factorail(2)
3 * 2 * factorial(1)
3 * 2 * 1
3 * 2
6
```
* 두 코드 모두 원리는 같다!
```
반복문 코드:
n이 1보다 큰 경우 반복문을 돌며, n은 1씩 감소한다.
마지막에 n이 1이면 더 이상 반복문을 돌지 않는다.
재귀 함수 코드:
재귀 함수를 호출하며, n은 1씩 감소한다.
마지막에 n이 1이면 더 이상 추가 함수를 호출을 하지 않는다.
```
* 재귀 함수는 기본적으로 같은 문제이지만 점점 범위가 줄어드는 문제를 풀게 된다.
* 재귀함수를 작성시에는 반드시, `base case`가 존재 하여야 한다.
* `base case`는 점점 범위가 줄어들어 반복되지 않는 최종적으로 도달하는 곳이다.
재귀를 이용한 팩토리얼 계산에서의 base case는 n이 1일때, 함수가 아닌 정수 반환하는 것이다.
* 자기 자신을 호출하는 재귀함수는 알고리즘 구현시 많이 사용된다.
* 코드가 더 직관적이고 이해하기 쉬운 경우가 있음. (하지만, 만들기는 어려움)
* [Python Tutor](https://goo.gl/k1hQYz)에 보면, 함수가 호출될 때마다 메모리 공간에 쌓이는 것을 볼 수 있다.
* 이 경우, 메모리 스택이 넘치거나(Stack overflow) 프로그램 실행 속도가 늘어지는 단점이 생긴다.
* 파이썬에서는 이를 방지하기 위해 1,000번이 넘어가게 되면 더이상 함수를 호출하지 않고, 종료된다.
```python
# 여기에서 오류를 확인 해봅시다.
def my_func(n):
return my_func(n)
my_func(3)
```
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-54-291a72a7713d> in <module>
2 def my_func(n):
3 return my_func(n)
----> 4 my_func(3)
<ipython-input-54-291a72a7713d> in my_func(n)
1 # 여기에서 오류를 확인 해봅시다.
2 def my_func(n):
----> 3 return my_func(n)
4 my_func(3)
... last 1 frames repeated, from the frame below ...
<ipython-input-54-291a72a7713d> in my_func(n)
1 # 여기에서 오류를 확인 해봅시다.
2 def my_func(n):
----> 3 return my_func(n)
4 my_func(3)
RecursionError: maximum recursion depth exceeded
## 피보나치 수열
> 피보나치 수열은 다음과 같은 점화식이 있다.
>
> 피보나치 값을 리턴하는 두가지 방식의 코드를 모두 작성해보자.
$$
\displaystyle F_0 = F_1 = 1
$$
$$
F_n=F_{n-1}+F_{n-2}\qquad(n\in\{2,3,4,\dots\})
$$
1) `fib(n)` : 재귀함수
2) `fib_loop(n)` : 반복문 활용한 함수
---
```
예시 입력)
fib(10)
예시 호출)
89
```
```python
# 재귀를 이용한 코드를 작성해주세요.
def fib(n):
if n < 2:
return 1
elif n >= 2:
return fib(n-1)+fib(n-2)
```
```python
fib(4)
```
5
```python
# 반복문을 이용한 코드를 작성해주세요.
def fib_loop(n):
a = [1,1]
for i in range(n-1):
a.append(a[-1]+a[-2])
return print(a)
```
```python
fib_loop(10)
```
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
```python
def fib_loop2(n):
x = 1
y = 1
z = 2
temp = 2
if n == 1 or n == 0:
return 1
else:
for i in range(1,n):
z = x + y
temp = z
x = y
y = temp
print(z)
return z
```
```python
fib_loop2(10)
```
2
3
5
8
13
21
34
55
89
89
```python
def fib_loop3(n):
# 초기값 두개 설정
first, last = 1,1
# 정해진 횟수를 반복
for i in range(n-1):
# first에는 last주고
# last에는 first+last 준다.
first, last = last, first + last
# tmp = first
# first = last
# last = temp + last
return last
```
```python
fib_loop3(10)
```
89
## 반복문과 재귀 함수의 차이
```python
# 큰 숫자를 재귀로 짜여진 fib()함수의 인자로 넘겨보세요.
fib(1000)
```
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-197-e0067ea06e01> in <module>
1 # 큰 숫자를 재귀로 짜여진 fib()함수의 인자로 넘겨보세요.
----> 2 fib(1000)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
<ipython-input-82-ae55755feb50> in fib(n)
4 return 1
5 elif n >= 2:
----> 6 return fib(n-1)+fib(n-2)
KeyboardInterrupt:
```python
# 100배 되는 숫자를 반복문으로 짜여진 fib_loop()인자로 넘겨보세요.
fib_loop3(1000)
```
70330367711422815821835254877183549770181269836358732742604905087154537118196933579742249494562611733487750449241765991088186363265450223647106012053374121273867339111198139373125598767690091902245245323403501
#### 속도의 차이를 느껴보자
###### for문이 더 빠른데 왜 재귀씀? (https://kldp.org/node/134556)
- 알고리즘 자체가 재귀적인 표현이 자연스러운 경우
- 재귀 호출은 '변수 사용'을 줄여줄 수 있다.
## 실습문제 - 하노이의 탑
> 다음은 하노이의 탑이다.
>
> 하노이의 탑을 풀이하는 해법(한쪽 탑의 원판을 다른 탑으로 모두 옮기는 법을 출력하는 함수를 만드세요.
>
> 참고링크 : https://ko.khanacademy.org/computing/computer-science/algorithms/towers-of-hanoi/a/towers-of-hanoi
<br>
<br>
<center>
<img src="./images/03/hanoi.gif", alt="">
</center>
1. 한 번에 한개의 층만을 다른 기둥으로 옮길 수 있다
2. 옮기려는 기둥에는 아무것도 없거나 옮기려는 층보다 큰 층이 있을 경우에만 옮길 수 있다
3. 옮기려는 기둥에 옮기려는 층보다 작은 층이 이미 있을 경우 그 기둥으로 옮길 수 없다.
4. 가능한 적은 회수로 전체 탑을 다른 기둥으로 옮긴다.
```python
# 아래에 코드를 작성해주세요.
def hanoi(n,start,tmp,end):
if n :
hanoi(n-1,start,end,tmp)
print(f'{n}번째 원판을, {start}->{end}')
hanoi(n-1,tmp,start,end)
```
```python
hanoi(4,'a','b','c')
```
1번째 원판을, a->b
2번째 원판을, a->c
1번째 원판을, b->c
3번째 원판을, a->b
1번째 원판을, c->a
2번째 원판을, c->b
1번째 원판을, a->b
4번째 원판을, a->c
1번째 원판을, b->c
2번째 원판을, b->a
1번째 원판을, c->a
3번째 원판을, b->c
1번째 원판을, a->b
2번째 원판을, a->c
1번째 원판을, b->c
|
Java
|
UTF-8
| 2,685 | 1.78125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2018 Martynas Sateika
*
* 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 lt.martynassateika.idea.codeigniter.view;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.php.lang.PhpLangUtil;
import com.jetbrains.php.lang.psi.elements.ConstantReference;
import com.jetbrains.php.lang.psi.elements.MethodReference;
import com.jetbrains.php.lang.psi.elements.Statement;
import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor;
import lt.martynassateika.idea.codeigniter.CodeIgniterProjectSettings;
import lt.martynassateika.idea.codeigniter.inspection.CodeIgniterInspection;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
/**
* @author martynas.sateika
* @since 0.2.0
*/
public class CodeIgniterReturnedViewNotUsedInspection extends CodeIgniterInspection {
@Nls
@NotNull
@Override
public String getDisplayName() {
return "Returned view data not used";
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder problemsHolder, boolean b) {
return new PhpElementVisitor() {
@Override
public void visitPhpConstantReference(ConstantReference reference) {
Project project = reference.getProject();
if (CodeIgniterProjectSettings.getInstance(project).isEnabled()) {
if (PhpLangUtil.isTrue(reference)) {
if (CiViewUtil.isArgumentOfLoadView(reference, 2)) {
if (isBareStatement(reference)) {
problemsHolder.registerProblem(reference, "Returned view data not used");
}
}
}
}
}
};
}
/**
* @param reference constant reference
* @return true if the method reference ('$this->load') is at the start of a statement
*/
private static boolean isBareStatement(ConstantReference reference) {
MethodReference methodReference = PsiTreeUtil.getParentOfType(reference, MethodReference.class);
return methodReference != null && methodReference.getParent() instanceof Statement;
}
}
|
Markdown
|
UTF-8
| 11,574 | 2.734375 | 3 |
[] |
no_license
|
Background
----------
Using devices such as *Jawbone Up*, *Nike FuelBand*, and *Fitbit* it is
now possible to collect a large amount of data about personal activity
relatively inexpensively. These type of devices are part of the
quantified self movement - a group of enthusiasts who take measurements
about themselves regularly to improve their health, to find patterns in
their behavior, or because they are tech geeks. One thing that people
regularly do is quantify how *much* of a particular activity they do,
but they rarely quantify *how well they do it*. In this project, your
goal will be to use data from accelerometers on the belt, forearm, arm,
and dumbell of 6 participants. They were asked to perform barbell lifts
correctly and incorrectly in 5 different ways. More information is
available from the website here:
<http://web.archive.org/web/20161224072740/http:/groupware.les.inf.puc-rio.br/har>
(see the section on the Weight Lifting Exercise Dataset).
Executive Summary
-----------------
In this course project, I will use machine learning to predict the
manner in which the participants did the exercise. I will perform data
cleaning, partitioning, and variable selection. Then I will use the
`classe` variable in the sub-training set to build three prediction
models. I will then select the best model, based on accuracy, out of
sample error, and calculation efficiency. In summary, I have selected my
best model that's using **Random Forests** because of its accuracy and
less computationally exhaustive.
Load Dependencies
-----------------
library(caret); library(ggplot2)
library(rpart); library(rpart.plot)
library(knitr); library(randomForest)
Load Train and Test Sets
------------------------
training <- read.csv("https://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv", na.strings = c("NA", "#DIV/0!", ""))
testing <- read.csv("https://d396qusza40orc.cloudfront.net/predmachlearn/pml-testing.csv", na.strings = c("NA", "#DIV/0!", ""))
Data Partitioning
-----------------
set.seed(123)
inSubTrain <- createDataPartition(training$classe, p = 3/4, list = F)
subTrain <- training[inSubTrain,]
subTest <- training[-inSubTrain,] # Validation data set
dim(subTrain); dim(subTest)
## [1] 14718 160
## [1] 4904 160
Data Pre-Processing and Feature Selection
-----------------------------------------
Exclude variables with NA values exceeding 50% of the total rows of the
subTrain data set
na_percent <- sapply(subTrain, function(x) sum(length(which(is.na(x))))/length(x))
exclTable <- data.frame(na_percent)
exclTable["NAabove50pct"] <- exclTable$na_percent > 0.5
Exclude non-predictor variables (columns 1-7)
exclTable["nonpredictor"] <- F; exclTable$nonpredictor[1:7] <- T
Exclude variables with Zero- and Near Zero-Variance
exclTable["nzv"] <- nearZeroVar(subTrain, saveMetrics = T)$nzv
exclTable["exclude"] <- exclTable$NAabove50pct | exclTable$nonpredictor | exclTable$nzv
Apply variable exclusion to all data sets
subTrain <- subTrain[,-(which(exclTable$exclude))]
subTest <- subTest[,-(which(exclTable$exclude))]
testing <- testing[,-(which(exclTable$exclude))]
Model Fits and Prediction
-------------------------
In this section, I will be using three prediction model fits and then
select the best model, based on accuracy, out of sample error, and
calculation efficiency.
**1. Using Decision Trees** The result of this model is easy to
interpret but without proper cross-validation, the model can be
over-fitted especially with large number of variables such as our train
data here.
set.seed(123)
begtime <- Sys.time()
modFit1 <- rpart(classe ~ ., data = subTrain, method = "class")
endtime <- Sys.time()
duration <- endtime - begtime
pred1 <- predict(modFit1, subTest, type = "class")
confmat1 <- confusionMatrix(pred1, subTest$classe)
table1 <- confmat1$table
par(mfrow = c(1,2))
plot(confmat1$table, col = c("salmon", "orange", "grey80", "skyblue", "lightgreen"),
main = "Fig 1. Confusion Matrix", sub = "(Using Decision Trees)", cex = 0.8)
prp(modFit1, box.palette = "auto", main = paste("Decision Tree Model"))

<table>
<caption>Table 1. Confusion Matrix (Decision Tree): Accuracy = 0.7486 ; Error = 0.2514 ; Model Fit Process Time = 3.55 seconds</caption>
<thead>
<tr class="header">
<th></th>
<th align="right">A</th>
<th align="right">B</th>
<th align="right">C</th>
<th align="right">D</th>
<th align="right">E</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>A</td>
<td align="right">1237</td>
<td align="right">131</td>
<td align="right">16</td>
<td align="right">44</td>
<td align="right">15</td>
</tr>
<tr class="even">
<td>B</td>
<td align="right">45</td>
<td align="right">598</td>
<td align="right">72</td>
<td align="right">67</td>
<td align="right">71</td>
</tr>
<tr class="odd">
<td>C</td>
<td align="right">39</td>
<td align="right">102</td>
<td align="right">683</td>
<td align="right">134</td>
<td align="right">115</td>
</tr>
<tr class="even">
<td>D</td>
<td align="right">51</td>
<td align="right">64</td>
<td align="right">65</td>
<td align="right">499</td>
<td align="right">46</td>
</tr>
<tr class="odd">
<td>E</td>
<td align="right">23</td>
<td align="right">54</td>
<td align="right">19</td>
<td align="right">60</td>
<td align="right">654</td>
</tr>
</tbody>
</table>
**2. Using Random Forests** Because random forest algorithm
automatically bootstrap by default, we can expect a better model
accuracy.
set.seed(123)
modFit2 <- randomForest(classe ~ ., data = subTrain, ntree = 500)
pred2 <- predict(modFit2, subTest, type = "class")
confmat2 <- confusionMatrix(pred2, subTest$classe)
table2 <- confmat2$table
par(mfrow = c(1,2))
plot(confmat2$table, col = c("salmon", "orange", "grey80", "skyblue", "lightgreen"),
main = "Fig 2.1. Confusion Matrix", sub = "(Using Random Forests, ntree = 500)", cex = 0.8)
plot(modFit2, main = "Random Forests Model"); abline(v = 100, col = "red")

Notice that in **Fig2.1**, considerably good accuracy can already be
achieved at `ntrees = 100`, so I re-modelled (shown in **Fig2.2**) and
got a fairly faster computation time and achieved the same accuracy.
set.seed(123)
begtime <- Sys.time()
modFit2 <- randomForest(classe ~ ., data = subTrain, ntree = 100)
endtime <- Sys.time()
duration <- endtime - begtime
pred2 <- predict(modFit2, subTest, type = "class")
confmat2 <- confusionMatrix(pred2, subTest$classe)
table2 <- confmat2$table
par(mfrow = c(1,2))
plot(confmat2$table, col = c("salmon", "orange", "grey80", "skyblue", "lightgreen"),
main = "Fig 2.2. Confusion Matrix", sub = "(Using Random Forests, ntree = 100)", cex = 0.8)
plot(modFit2, main = "Random Forests Model")

<table>
<caption>Table 2. Confusion Matrix (Random Forests): Accuracy = 0.9953 ; Error = 0.0047 ; Model Fit Process Time = 14.45 seconds</caption>
<thead>
<tr class="header">
<th></th>
<th align="right">A</th>
<th align="right">B</th>
<th align="right">C</th>
<th align="right">D</th>
<th align="right">E</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>A</td>
<td align="right">1394</td>
<td align="right">1</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="even">
<td>B</td>
<td align="right">1</td>
<td align="right">946</td>
<td align="right">6</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="odd">
<td>C</td>
<td align="right">0</td>
<td align="right">2</td>
<td align="right">848</td>
<td align="right">8</td>
<td align="right">0</td>
</tr>
<tr class="even">
<td>D</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">1</td>
<td align="right">793</td>
<td align="right">1</td>
</tr>
<tr class="odd">
<td>E</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">3</td>
<td align="right">900</td>
</tr>
</tbody>
</table>
**3. Using Generalized Boosted Model** To check whether it is still
possible to optimize the processing speed in the random forest model
`modFit2`, let's apply tree boosting methods with repeated cross
validation `repeatedcv` as computational nuance. With 5 folds of
test/training splits, and repeats = 1.
set.seed(123)
begtime <- Sys.time()
fitCtrl <- trainControl(method = "repeatedcv", number = 5, repeats = 1)
modFit3 <- train(classe ~ ., data = subTrain, method = "gbm",
trControl = fitCtrl, verbose = F)
endtime <- Sys.time()
duration <- endtime - begtime
pred3 <- predict(modFit3, subTest)
confmat3 <- confusionMatrix(pred3, subTest$classe)
table3 <- confmat3$table
par(mfrow = c(1,2))
plot(confmat3$table, col = c("salmon", "orange", "grey80", "skyblue", "lightgreen"),
main = "Fig 3.1. Confusion Matrix", sub = "(Using Generalized Boosted Model)", cex = 0.8)
par(mfrow = c(1,1))

plot(modFit3,
main = "Fig 3.2. Generalized Boosted Model")

<table>
<caption>Table 3. Confusion Matrix (GBM): Accuracy = 0.9625 ; Error = 0.0375 ; Model Fit Process Time = 8.28 seconds</caption>
<thead>
<tr class="header">
<th></th>
<th align="right">A</th>
<th align="right">B</th>
<th align="right">C</th>
<th align="right">D</th>
<th align="right">E</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>A</td>
<td align="right">1374</td>
<td align="right">34</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">3</td>
</tr>
<tr class="even">
<td>B</td>
<td align="right">11</td>
<td align="right">894</td>
<td align="right">30</td>
<td align="right">3</td>
<td align="right">9</td>
</tr>
<tr class="odd">
<td>C</td>
<td align="right">5</td>
<td align="right">17</td>
<td align="right">812</td>
<td align="right">28</td>
<td align="right">2</td>
</tr>
<tr class="even">
<td>D</td>
<td align="right">4</td>
<td align="right">3</td>
<td align="right">12</td>
<td align="right">765</td>
<td align="right">12</td>
</tr>
<tr class="odd">
<td>E</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">8</td>
<td align="right">875</td>
</tr>
</tbody>
</table>
Conclusion
----------
I have chosen the superior model that's using **Random Forests
`ntrees = 100`** because of its better accuracy (compared to `modFit1`
and `modFit3`). `modFit3` is faster but sacrifices about **3%**
accuracy. So I used **Random Forests** `modFit2` in order to predict on
the Test Data in the next section. Applying this model achieved 100%
prediction accuracy in the Course Project Prediction quiz.
Predicting on the Test Data
---------------------------
Here are the answers to the Course Project Prediction quiz.
data.frame(Answers = predict(modFit2, testing, type = "class"))
## Answers
## 1 B
## 2 A
## 3 B
## 4 A
## 5 A
## 6 E
## 7 D
## 8 B
## 9 A
## 10 A
## 11 B
## 12 C
## 13 B
## 14 A
## 15 E
## 16 E
## 17 A
## 18 B
## 19 B
## 20 B
|
Java
|
UTF-8
| 1,945 | 3.625 | 4 |
[] |
no_license
|
package com.cyanflxy.leetcode._1;
import com.cyanflxy.leetcode.help.TreeNode;
import java.util.ArrayList;
import java.util.List;
/**
* https://leetcode.com/problems/path-sum-ii/description/
* <p>
* Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
* <p>
* Note: A leaf is a node with no children.
* <p>
* Example:
* <p>
* Given the below binary tree and sum = 22,
* <pre>
* 5
* / \
* 4 8
* / / \
* 11 13 4
* / \ / \
* 7 2 5 1
* </pre>
* Return:
* <pre>
* [
* [5,4,11,2],
* [5,8,4,5]
* ]
* </pre>
* <p>
* Created by cyanflxy on 2018/8/24.
*/
public class _113_Path_Sum_II {
public static void main(String... args) {
test();
}
private static void test() {
_113_Path_Sum_II object = new _113_Path_Sum_II();
System.out.println(object.pathSum(
TreeNode.create(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1),
22));
}
/**
* 采用 创建-合并 的方式,总体上创建List实例过多,不如先加再减的方式速度更快。
*/
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
if (root.left == null && root.right == null) {
if (root.val == sum) {
List<Integer> value = new ArrayList<>();
value.add(sum);
result.add(value);
}
return result;
}
if (root.left != null) {
result.addAll(pathSum(root.left, sum - root.val));
}
if (root.right != null) {
result.addAll(pathSum(root.right, sum - root.val));
}
for (List<Integer> list : result) {
list.add(0, root.val);
}
return result;
}
}
|
Markdown
|
UTF-8
| 763 | 2.578125 | 3 |
[] |
no_license
|
---
actions: 1
layout: block
level: 4
prerequisites: "source de mise \xE0 mal, alignement mauvais"
rarity: C
source: ??
summary: '-'
title: "Injection n\xE9crotique"
titleEN: Necrotic Infusion
traits:
- general
---
<p>Vous injectez de l’énergie négative dans votre mort‑vivant pour augmenter la puissance de ses attaques. Si la prochaine action que vous effectuez consiste à lancer une mise à mal pour restaurer les points de vie d’un unique mort‑vivant, celui‑ci inflige ensuite 1d6 dégâts négatifs supplémentaires avec ses armes de corps à corps et ses attaques à mains nues jusqu’à la fin de son prochain tour. Si le sort mise à mal est de niveau 5 au moins, les dégâts passent à 2d6, ou à 3d6 s’il est de niveau 8 au moins.</p>
|
C++
|
UTF-8
| 717 | 3.328125 | 3 |
[] |
no_license
|
#include "Coord2.h"
#include "CoordException.h"
Coord2::Coord2()
: x(0)
, y(0)
{
//
}
Coord2::Coord2(int x, int y)
: x(x)
, y(y)
{
if(x < 0 || y < 0) {
throw CoordException(x, y, "Values must be greater or equal to zero");
}
}
std::ostream& operator<<(std::ostream& stream, Coord2 coord) {
stream << "(" << coord.x << ", " << coord.y << ")";
return stream;
}
bool operator<(const Coord2& lhs, const Coord2& rhs) {
return lhs.x < rhs.x && lhs.y < rhs.y;
}
bool operator<=(const Coord2& lhs, const Coord2& rhs) {
return lhs.x <= rhs.x && lhs.y <= rhs.y;
}
bool operator==(const Coord2& lhs, const Coord2& rhs) {
return lhs.x == rhs.x && lhs.y == rhs.y;
}
|
Markdown
|
UTF-8
| 1,239 | 2.9375 | 3 |
[] |
no_license
|
* 模板定义中,模板的参数列表不能为空!
* 每个类型参数必须以`typename/class`开头,应优先使用`typename`关键字
* 模板接受非类型参数,要求必须是const expression,以便在编译时(模板实例化)执行替换
* 模板代码的生成发生在使用模板时!
* 类模板不能进行类型参数推断!
* 类模板外定义的成员函数必须以类模板开头!且类作用域操作符前要加模板参数(不是模板,而是模板的实例)
* 类模板中的成员函数只有在被使用时才进行实例化!
* 模板类作用域内部可以省略模板参数
* 通过`typename`显式说明一个标识符是类型名而不是变量名
* 新标准下,函数模板和类模板都可以有默认参数,有默认值的形参的右边所有形参也必须有默认值
* 使用类模板参数的默认值,也必须写`<>`,类模板不能进行自动推导
* 不同编译单元使用相同的模板参数使用模板会导致模板实例化多次
* 函数模板的类型推导会忽略top level const
* 函数模板的类型推导:如果参数不是引用类型,那么数组被转为首元素指针,函数被转为该类型函数的指针
* trail return type
|
Java
|
UTF-8
| 1,018 | 2.40625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package projeto.Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import projeto.Domain.Funcionario;
import projeto.Repository.FuncionarioRepository;
@Service
public class FuncionarioService {
@Autowired
FuncionarioRepository repository;
public Funcionario addFuncionario(Funcionario funcionario) {
return repository.insert(funcionario);
}
public Funcionario atualizaFuncionario(Funcionario funcionario) {
if (repository.existsById(funcionario.getId())) {
repository.save(funcionario);
return funcionario;
}
return null;
}
public Funcionario getById(String id)
{
return repository.findById(id).get();
}
public void deletaFuncionario(String id) throws Exception{
if (repository.existsById(id)) {
repository.deleteById(id);
}else{
throw new Exception("Não foi apagado!! ID errado ou não existe");
}
}
public List<Funcionario> ReadAll() {
return repository.findAll();
}
}
|
C++
|
UTF-8
| 519 | 3 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main () {
int days;
cin >> days;
int logs;
int current;
int total = 0;
for (int x = 0; x < days; x++) {
total = 0;
cin >> logs;
for (int i = 0; i < logs; i++) {
cin >> current;
total += current;
}
if (total == 0) {
cout << "Weekend" << endl;
} else {
cout << "Day " << x + 1 << ": " << total << endl;
}
}
}
|
Java
|
UTF-8
| 1,403 | 2.875 | 3 |
[] |
no_license
|
package cuoi_ky;
public class Diem {
public double x, y, z;
public Diem() {
}
public Diem(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double khoangCach(Diem g) {
return Math.pow((x - g.x), 2) + Math.pow(y - g.y, 2) + Math.pow(z - g.z, 2);
}
public boolean isThangDung(Diem g) {
return x == g.x && y == g.y;
}
public boolean isThuocTrongHinhHop(HinhHop hh) {
if (this.x >= hh.toaDo.get(0).x && this.y >= hh.toaDo.get(0).y && this.z >= hh.toaDo.get(0).z
&& Math.pow(this.x - hh.toaDo.get(0).x, 2) < hh.width
&& Math.pow(this.y - hh.toaDo.get(0).y, 2) < hh.length
&& Math.pow(this.z - hh.toaDo.get(0).z, 2) < hh.height) {
return true;
}
return false;
}
public boolean isThuocMatPhangHinhHop(HinhHop hh) {
if ((Math.pow(this.x - hh.toaDo.get(0).x, 2) == hh.width
|| this.x - hh.toaDo.get(0).x == 0 || Math.pow(this.y - hh.toaDo.get(0).y, 2) == hh.length
|| this.y - hh.toaDo.get(0).y == 0 || Math.pow(this.z - hh.toaDo.get(0).z, 2) == hh.height
|| this.z - hh.toaDo.get(0).z == 0) && this.z <= hh.toaDo.get(4).z && this.x <= hh.toaDo.get(2).x && this.y <= hh.toaDo.get(2).y) {
return true;
}
return false;
}
}
|
Ruby
|
UTF-8
| 1,460 | 2.65625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
# frozen_string_literal: true
require_relative '../support/test_case'
module DEBUGGER__
class ListTest < TestCase
def program
<<~RUBY
1| p 1
2| p 2
3| p 3
4| p 4
5| p 5
6| p 6
7| p 7
8| p 8
9| p 9
10| p 10
11| p 11
12| p 12
13| p 13
14| p 14
15| p 15
16| p 16
17| p 17
18| p 18
19| p 19
20| p 20
21| p 21
22| p 22
23| p 23
24| p 24
25| p 25
26| p 26
27| p 27
28| p 28
29| p 29
30| p 30
RUBY
end
def test_list_only_lists_part_of_the_program
debug_code(program) do
type 'list'
assert_line_text(/p 1/)
assert_line_text(/p 10/)
assert_no_line_text(/p 11/)
type 'q!'
end
end
def test_list_only_lists_after_the_given_line
debug_code(program) do
type 'list 11'
assert_no_line_text(/p 10/)
assert_line_text(/p 11/)
type 'q!'
end
end
def test_list_continues_automatically
debug_code(program) do
type 'list'
assert_line_text(/p 10/)
assert_no_line_text(/p 11/)
type ""
assert_line_text(/p 20/)
assert_no_line_text(/p 10/)
assert_no_line_text(/p 21/)
type ""
assert_line_text(/p 30/)
assert_no_line_text(/p 20/)
type 'q!'
end
end
end
end
|
Shell
|
UTF-8
| 1,207 | 3.46875 | 3 |
[] |
no_license
|
#!/bin/bash
##Author : Ravi Tomar ###
### Description :used to show list of flow on jenkins ####
#### dated 01/07/2020 #####
getNifiParameter(){
echo 'fetching nifi parameters from aws'
echo 'Fetching registry_url'
registry_url=`aws ssm get-parameter --name "/a2i/stage/nifi/nifiregistryurl" --with-decryption --profile stage --output text --query Parameter.Value`
echo 'Fetching cli path'
cli=`aws ssm get-parameter --name "/a2i/infra/nifi_toolkit/clipath" --with-decryption --profile stage --output text --query Parameter.Value`
}
createBucketflow(){
buckets=$($cli registry list-buckets -u ${registry_url} -ot json)
filename="/data/extralibs/nifi"
bucket_names=$(echo "$buckets" | jq -r '.[].name')
for bucket_name in ${bucket_names[@]}
do
bucket_id=$(echo "$buckets" | jq -r '.[] | select(.name == '\"$bucket_name\"' ) | .identifier')
bucket_flows=$($cli registry list-flows -b ${bucket_id} -u $registry_url -ot json)
echo "$bucket_flows" | jq -r '.[].name' > $filename/$bucket_name.txt
if [ $? -eq 0 ]
then
echo "$bucket_name's file created and populated with flow names"
fi
done
}
getNifiParameter
createBucketflow
|
Java
|
UTF-8
| 8,110 | 3.109375 | 3 |
[] |
no_license
|
package hcimodify.test1;
import android.util.Log;
public class window {
public int[] window(int [][] RGB, int x0, int y0){ //input is RGB image in 3D array format and the point on the image that the user touches (x0,y0)
int windowcols = RGB.length;
int windowrows = RGB[0].length;
int x1 = x0 - (windowcols / 10);
int y1 = y0 - (windowrows / 10); //makes initial window using the user input point as the center of the window
int x2 = x0 + (windowcols / 10);
int y2 = y0 + (windowrows / 10);
int left = 1, right = 1, top = 1, bottom = 1;
int count=0;
int countx1=0;
while(left > 0 && right > 0 && top > 0 && bottom > 0){ //if there are very salient points along every edge, expand every edge of the new RGB image
x1 = x1 - 10;
y1 = y1 - 10;
x2 = x2 + 10;
y2 = y2 + 10;
if(x1 < 0){ //make sure left edge isn't expanded past left edge of original RGB image
x1 = 0;
break;
}
else{}
if(x2 > windowcols-1){
x2 = windowcols-1;
break;
}
else{}
if(y1 < 0){
y1 = 0;
break;
}
else{}
if(y2 > windowrows-1){
y2 = windowrows-1;
break;
}
else{}
Log.v ("x1",""+x1);
Log.v ("y1",""+y1);
Log.v ("x2",""+x2);
Log.v ("y2",""+y2);
augwindow aug1 = new augwindow();
int[][] newRGB = aug1.augwindow( RGB, x1, y1, x2, y2 );
sal sal0 = new sal();
double[][] saliencymap = sal0.sal(newRGB);
tobinary bin = new tobinary();
int[][] binary = bin.tobinary(saliencymap, 0.5);
edgecheck edgecheck0 = new edgecheck();
int[] edges = edgecheck0.edgecheck(binary);
left = edges[0];
right = edges[1];
top = edges[2];
bottom = edges[3];
count++;
Log.v("LRTB", ""+left+"+"+""+right+"+"+""+top+"+"+""+bottom);
Log.v("count", ""+count);
}
int left1=0;
while(left > 0){ //if very salient points along left edge then expand left edge
x1 = x1 - 10;
if(x1 < 0){ //make sure left edge isn't expanded past left edge of original RGB image
x1 = 1;
countx1++;
Log.v("countx1", ""+countx1);
break;
}
else{}
augwindow aug1 = new augwindow(); //use augwindow to get new RGB image from new top left and bottom right points
int[][] newRGB = aug1.augwindow( RGB, x1, y1, x2, y2 );
sal sal0 = new sal(); //use sal to get saliency map from new RGB image
double[][] saliencymap = sal0.sal(newRGB);
tobinary bin = new tobinary(); //use tobinary to get binary image from saliency map
int[][] binary = bin.tobinary(saliencymap, 0.5);
edgecheck edgecheck0 = new edgecheck(); //use edgecheck to check edges of binary images for very salient points
int[] edges = edgecheck0.edgecheck(binary);
left = edges[0];
right = edges[1]; //update edges array with amounts of salient points around each edge
top = edges[2];
bottom = edges[3];
left1++;
Log.v("left1",""+left1);
}
int right1=0;
while(right > 0){
x2 = x2 + 10;
if(x2 > windowcols-1){
x2 = windowcols-1;
break;
}
else{}
augwindow aug1 = new augwindow();
int[][] newRGB = aug1.augwindow( RGB, x1, y1, x2, y2 );
sal sal0 = new sal();
double[][] saliencymap = sal0.sal(newRGB);
tobinary bin = new tobinary();
int[][] binary = bin.tobinary(saliencymap, 0.5);
edgecheck edgecheck0 = new edgecheck();
int[] edges = edgecheck0.edgecheck(binary);
left = edges[0];
right = edges[1];
top = edges[2];
bottom = edges[3];
right1++;
Log.v("right1",""+right1);
}
int top1=0;
while(top > 0){
y1 = y1 - 10;
if(y1 < 0){
y1 = 1;
break;
}
else{}
augwindow aug1 = new augwindow();
int[][] newRGB = aug1.augwindow( RGB, x1, y1, x2, y2 );
sal sal0 = new sal();
double[][] saliencymap = sal0.sal(newRGB);
tobinary bin = new tobinary();
int[][] binary = bin.tobinary(saliencymap, 0.5);
edgecheck edgecheck0 = new edgecheck();
int[] edges = edgecheck0.edgecheck(binary);
left = edges[0];
right = edges[1];
top = edges[2];
bottom = edges[3];
top1++;
Log.v("top1",""+top1);
}
int bottom1=0;
while(bottom > 0){
y2 = y2 + 10;
if(y2 > windowrows-1){
y2 = windowrows-1;
break;
}
else{}
augwindow aug1 = new augwindow();
int[][] newRGB = aug1.augwindow( RGB, x1, y1, x2, y2 );
sal sal0 = new sal();
double[][] saliencymap = sal0.sal(newRGB);
tobinary bin = new tobinary();
int[][] binary = bin.tobinary(saliencymap, 0.5);
edgecheck edgecheck0 = new edgecheck();
int[] edges = edgecheck0.edgecheck(binary);
left = edges[0];
right = edges[1];
top = edges[2];
bottom = edges[3];
bottom1++;
Log.v("bottom1",""+bottom1);
}
int left2=0;
while((left > 0)&(left2<15)){
if (left2<20){
x1 = x1 - 10;
if(x1 < 0){
x1 = 1;
break;
}
else{}
augwindow aug1 = new augwindow();
int[][] newRGB = aug1.augwindow( RGB, x1, y1, x2, y2 );
sal sal0 = new sal();
double[][] saliencymap = sal0.sal(newRGB);
tobinary bin = new tobinary();
int[][] binary = bin.tobinary(saliencymap, 0.5);
edgecheck edgecheck0 = new edgecheck();
int[] edges = edgecheck0.edgecheck(binary);
left = edges[0];
right = edges[1];
top = edges[2];
bottom = edges[3];
left2++;
Log.v("left2",""+left2);
}
else{break;}
}
int right2=0;
while((right > 0)&(right2<10)){
x2 = x2 + 10;
if(x2 > windowcols-1){
x2 = windowcols-1;
break;
}
else{}
augwindow aug1 = new augwindow();
int[][] newRGB = aug1.augwindow( RGB, x1, y1, x2, y2 );
sal sal0 = new sal();
double[][] saliencymap = sal0.sal(newRGB);
tobinary bin = new tobinary();
int[][] binary = bin.tobinary(saliencymap, 0.5);
edgecheck edgecheck0 = new edgecheck();
int[] edges = edgecheck0.edgecheck(binary);
left = edges[0];
right = edges[1];
top = edges[2];
bottom = edges[3];
right2++;
Log.v("right2", ""+right2);
}
int top2=0;
while((top > 0)&(top2<10)){
y1 = y1 - 10;
if(y1 < 0){
y1 = 1;
break;
}
else{}
augwindow aug1 = new augwindow();
int[][] newRGB = aug1.augwindow( RGB, x1, y1, x2, y2 );
sal sal0 = new sal();
double[][] saliencymap = sal0.sal(newRGB);
tobinary bin = new tobinary();
int[][] binary = bin.tobinary(saliencymap, 0.5);
edgecheck edgecheck0 = new edgecheck();
int[] edges = edgecheck0.edgecheck(binary);
left = edges[0];
right = edges[1];
top = edges[2];
bottom = edges[3];
top2++;
Log.v("top2", ""+top2);
}
int bottom2=0;
while((bottom > 0)&(bottom2<10)){
y2 = y2 + 10;
if(y2 > windowrows-1){
y2 = windowrows-1;
break;
}
else{}
augwindow aug1 = new augwindow();
int[][] newRGB = aug1.augwindow( RGB, x1, y1, x2, y2 );
sal sal0 = new sal();
double[][] saliencymap = sal0.sal(newRGB);
tobinary bin = new tobinary();
int[][] binary = bin.tobinary(saliencymap, 0.5);
edgecheck edgecheck0 = new edgecheck();
int[] edges = edgecheck0.edgecheck(binary);
left = edges[0];
right = edges[1];
top = edges[2];
bottom = edges[3];
bottom2++;
Log.v("bottom2", ""+bottom2);
}//*/
int[] windowpoints = new int[4];
windowpoints[0] = x1;
windowpoints[1] = y1; //put final top left and bottom right x,y window points into array
windowpoints[2] = x2;
windowpoints[3] = y2;
return (windowpoints);
}
}
|
SQL
|
UTF-8
| 976 | 3.609375 | 4 |
[
"Apache-2.0"
] |
permissive
|
CREATE OR REPLACE VIEW "public"."view_users_stats" AS
SELECT users.id,
users.type,
users.created_at,
CASE
WHEN (users.type = 'ti') THEN tis.departement_code
WHEN (users.type = 'individuel') THEN mandataires.departement_code
WHEN (users.type = 'prepose') THEN mandataires.departement_code
WHEN (users.type = 'service') THEN services.departement_code
WHEN (users.type = 'direction' AND direction.type = 'departemental') THEN direction.departement_code
ELSE NULL::character varying
END AS departement_code
FROM users
LEFT JOIN magistrat ON magistrat.user_id = users.id
LEFT JOIN tis ON magistrat.ti_id = tis.id
LEFT JOIN mandataires ON mandataires.user_id = users.id
LEFT JOIN service_members ON service_members.user_id = users.id
LEFT JOIN services ON service_members.service_id = services.id
LEFT JOIN direction ON direction.user_id = users.id
;
|
PHP
|
UTF-8
| 11,123 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
<?php
class Mesa_model extends CI_Model {
public function insertar($idUsuario,$idVotacion)
{
$sinProblemas = true;
$datos = array(
'Id_Usuario' => $idUsuario,
'Id_Votacion' => $idVotacion
);
$this->db->insert('mesa_electoral',$datos);
}
//Devuelve el listado de votaciones de las que se encarga un miembro de la mesa electoral.
public function getVotaciones($id) {
$consulta = $this->db->get_where('mesa_electoral', array('Id_Usuario' => $id));
$votaciones = $this->noFinalizadas($consulta->result());
return $votaciones;
}
//Devuelve un subarray de votaciones con aquellas que no están finalizadas.
private function noFinalizadas($votaciones) {
$votacionesOK = array();
foreach($votaciones as $votacion) {
$consulta = $this->db->get_where('votacion', array('Id' => $votacion->Id_Votacion, 'Finalizada' => 0));
if ($consulta->num_rows() != 0) array_push($votacionesOK, $consulta->result()[0]);
}
return $votacionesOK;
}
//Establece a true la decisión de abrir la urna de un usuario concreto para una votación concreta.
public function abreUrna($usuario, $votacion) {
$this->db->where('Id_Usuario', $usuario);
$this->db->where('Id_Votacion', $votacion);
$this->db->update('mesa_electoral', array('seAbre' => 1));
}
//Comprueba si una urna se puede cerrar.
public function cierraUrna($usuario, $idVotacion) {
$this->db->where('Id_Usuario', $usuario);
$this->db->where('Id_Votacion', $idVotacion);
$this->db->update('mesa_electoral', array('seCierra' => 1));
}
//Devuelve el número de decisiones de apertura para una votación concreta.
public function getNApertura($votacion) {
$consulta = $this->db->get_where('mesa_electoral', array('Id_Votacion' => $votacion, 'seAbre' => 1));
return $consulta->num_rows();
}
//Devuelve un array con los nombres de usuario que quieren abrir una urna.
public function getNamesApertura($idVotacion) {
$consulta = $this->db->get_where('mesa_electoral', array('Id_Votacion' => $idVotacion, 'seAbre' => 1));
$arrayNames = array();
foreach($consulta->result() as $result) {
$consulta2 = $this->db->get_where('usuario', array('Id' => $result->Id_Usuario));
array_push($arrayNames, $consulta2->result()[0]->NombreUsuario);
}
return $arrayNames;
}
//Devuelve un array con los nombres de usuario que quieren cerrar una urna.
public function getNamesCierre($idVotacion) {
$consulta = $this->db->get_where('mesa_electoral', array('Id_Votacion' => $idVotacion, 'seCierra' => 1));
$arrayNames = array();
foreach($consulta->result() as $result) {
$consulta2 = $this->db->get_where('usuario', array('Id' => $result->Id_Usuario));
array_push($arrayNames, $consulta2->result()[0]->NombreUsuario);
}
return $arrayNames;
}
//Comprueba si un miembro electoral quiere abrir una votación concreta.
public function getQuiereAbrir($username, $votacion) {
$consulta = $this->db->get_where('mesa_electoral', array('Id_Votacion' => $votacion, 'Id_Usuario' => $username, 'seAbre' => 1));
return ($consulta->num_rows() == 1);
}
//Comprueba si un miembro electoral quiere cerrar una votación concreta.
public function getQuiereCerrar($username, $votacion) {
$consulta = $this->db->get_where('mesa_electoral', array('Id_Votacion' => $votacion, 'Id_Usuario' => $username, 'seCierra' => 1));
return ($consulta->num_rows() == 1);
}
//Devuelve el número de decisiones de cierre para una votación concreta.
public function getNCierre($votacion) {
$consulta = $this->db->get_where('mesa_electoral', array('Id_Votacion' => $votacion, 'seCierra' => 1));
return $consulta->num_rows();
}
//Comprueba si existe algún recuento para la votación.
public function checkVotos($idVotacion) {
/*$consulta = $this->db->get_where('votacion_voto', array('Id_Votacion' => $idVotacion));
$rows = $consulta->result();
if(!empty($rows))
{
$consulta2 = $this->db->get_where('recuento', array('Id_Votacion' => $rows[0]->Id_Voto));
return ($consulta2->num_rows()>=1);
}*/
$consulta = $this->db->get_where('recuento', array('Id_Votacion' => $idVotacion));
return ($consulta->num_rows()>=1);
}
//Devuelve las opciones de voto de una votacion.
public function getOptions($idVotacion) {
$consulta = $this->db->get_where('votacion_voto', array('Id_Votacion' => $idVotacion));
$result = array('Id' => array(), 'Nombre' => array());
foreach($consulta->result() as $row) {
if ($row->Id_Voto != 1) array_push($result['Id'], $row->Id_Voto); //Se consideran todas las opciones a excepción de No votado.
}
foreach($result['Id'] as $id) {
$consulta = $this->db->get_where('voto', array('Id' => $id));
array_push($result['Nombre'], $consulta->result()[0]->Nombre);
}
return $result;
}
//Devuelve un recuento de un voto en concreto en una votación concreta, eliminando dichos votos del registro.
public function volcadoVotos($idVotacion, $idVoto) { //ACTUALMENTE EN DESUSO.
$usuario_votacion = $this->db->get_where('usuario_votacion', array('Id_Votacion' => $idVotacion));
$cont = 0;
foreach ($usuario_votacion->result() as $row) {
if (password_verify($idVoto, $row->Id_Voto) == true) {
$cont++;
$this->db->delete('usuario_votacion', array('Id_Votacion' => $row->Id_Votacion, 'Id_Usuario' => $row->Id_Usuario));
}
}
return $cont;
}
//Inserta los resultados de una votación en la tabla recuento.
public function insertVotos($idVotacion, $arrayIdVoto, $arrayNumVotos) { //ACTUALMENTE EN DESUSO.
for($it=0; $it<count($arrayIdVoto); $it++) {
$this->db->insert('recuento', array('Id_Votacion' => $idVotacion, 'Id_Voto' => $arrayIdVoto[$it], 'Num_Votos' => $arrayNumVotos[$it]));
//$sql = "INSERT INTO recuento (Id_Votacion,Id_Voto,Num_Votos) VALUES (" . $idVotacion . "," . $arrayIdVoto[$it] . "," . $arrayNumVotos[$it] . ") ON DUPLICATE KEY UPDATE Id_Votacion=Id_Votacion, Id_Voto=Id_Voto";
//$this->db->update('recuento', array('Id_Votacion' => $idVotacion, 'Id_Voto' => $arrayIdVoto[$it], 'Num_Votos' => $arrayNumVotos[$it]));
//$this->db->query($sql);
}
}
//Devuelve la cantidad de un voto concreto para una votacion.
public function getNVotos($idVotacion, $idVoto, $idGrupo = "") {
if ($idGrupo == "") {
$consulta = $this->db->get_where('recuento', array('Id_Votacion' => $idVotacion, 'Id_Voto' => $idVoto));
$total = 0;
foreach($consulta->result() as $row)
$total += $row->Num_Votos;
return $total;
} else {
$consulta = $this->db->get_where('recuento', array('Id_Votacion' => $idVotacion, 'Id_Voto' => $idVoto, 'Id_Grupo' => $idGrupo));
return $consulta->result()[0]->Num_Votos;
}
}
//Devuelve el quorum (%) requerido en una votacion.
public function getQuorum($idVotacion) {
$consulta = $this->db->get_where('votacion', array('Id' => $idVotacion));
return $consulta->result()[0]->Quorum;
}
//Devuelve el tamaño del censo de la votacion indicada.
public function getCenso($idVotacion) {
$consulta = $this->db->get_where('censo', array('Id_Votacion' => $idVotacion));
if ($consulta->num_rows() == 0) return 200;
else return $consulta->num_rows();
}
//Devuelve toda la información necesaria para que se muestre el recuento.
public function getFullVotoData($idVotacion) {
$votos = $this->getOptions($idVotacion);
$aGrupoPonderacion = $this->getGroupData($idVotacion);
$contVotos = array();
foreach($votos['Nombre'] as $opcion)
array_push($contVotos, array($opcion => array()));
$totalVotos = 0;
$abstenciones = $this->getNVotos($idVotacion, 1, 4);
$itVoto = 0;
$itGrupo = 0;
foreach($votos['Id'] as $idVoto) {
foreach($aGrupoPonderacion['Id'] as $idGrupo) {
$nVotos = $this->getNVotos($idVotacion, $idVoto, $idGrupo);
$contVotos[$votos['Nombre'][$itVoto]][$aGrupoPonderacion['Grupo'][$itGrupo]] = $nVotos;
$totalVotos = $totalVotos + $nVotos;
$itGrupo++;
}
$itVoto++;
$itGrupo = 0;
}
$result = array('opciones' => $votos['Nombre'], //Nombres de los votos.
'grupos' => $aGrupoPonderacion['Grupo'], //Nombres de los grupos.
'matrizVotos' => $contVotos, //Matriz con el total de votos. El primer [] tiene las opciones de voto en el mismo orden que $opciones. El segundo [] no es nominal, y tiene la cantidad de votos para el grupo i, en el mismo orden que $grupos.
'totalVotos' => $totalVotos, //Suma total de votos.
'abstenciones' => $abstenciones, //Cantidad de personas del censo que no han votado.
'quorum' => $this->getQuorum($idVotacion), //Quorum de la votacion (0-1).
'censo' => $this->getCenso($idVotacion), //Tamaño del censo.
'titulo' => $this->getVotacionTitle($idVotacion),
'descripcion' => $this->getVotacionDescription($idVotacion),
'votacion' => $idVotacion); //Id de la votacion actual.
return $result;
}
//Devuelve el titulo de una votacion.
private function getVotacionTitle($idVotacion) {
$consulta = $this->db->get_where('votacion', array('Id' => $idVotacion));
return $consulta->row()->Titulo;
}
//Devuelve la descripcion de una votacion.
private function getVotacionDescription($idVotacion) {
$consulta = $this->db->get_where('votacion', array('Id' => $idVotacion));
return $consulta->row()->Descripcion;
}
//Devuelve un array compuesto de un array de Nombre de grupo y un array de Ponderacion, correspondientes a la votacion dada.
private function getGroupData($idVotacion) {
$consulta = $this->db->get_where('ponderaciones', array('Id_Votacion' => $idVotacion));
$arrayGlobal = array('Id' => array(), 'Grupo' => array(), 'Ponderacion' => array());
foreach($consulta->result() as $row) {
$consulta2 = $this->db->get_where('grupo', array('Id' => $row->Id_Grupo));
array_push($arrayGlobal['Id'], $consulta2->result()[0]->Id);
array_push($arrayGlobal['Grupo'], $consulta2->result()[0]->Nombre);
array_push($arrayGlobal['Ponderacion'], $row->Valor);
}
return $arrayGlobal;
}
//Establece como finalizada una votación.
public function setFinalizada($idVotacion) {
$this->db->where('Id', $idVotacion);
$this->db->update('votacion', array('Finalizada' => 1));
}
//Establece como inválida una votación.
public function setInvalida($idVotacion) {
$this->db->where('Id', $idVotacion);
$this->db->update('votacion', array('Finalizada' => 1, 'Invalida' => 1));
}
//Comprueba si una votación está finalizada.
public function isFinished($idVotacion) {
$consulta = $this->db->get_where('votacion', array('Id' => $idVotacion));
return ($consulta->result()[0]->Finalizada == 1);
}
public function eliminarMiembroFromVotacion($idMiembro,$idVotacion)
{
$query = $this->db->query("DELETE FROM mesa_electoral WHERE Id_Votacion = '$idVotacion' AND Id_Usuario = '$idMiembro'");
}
public function getMesa($idVotacion)
{
$query = $this->db->get_where('mesa_electoral', array('Id_Votacion' => $idVotacion));
return $query->result();
}
public function deleteMesa($idVotacion)
{
$query = $this->db->query("DELETE FROM mesa_electoral WHERE Id_Votacion = '$idVotacion'");
//return $query->result();
}
}
?>
|
Swift
|
UTF-8
| 3,045 | 2.578125 | 3 |
[] |
no_license
|
//
// SearchUserController.swift
// HundredDays
//
// Created by Vinicius Nadin on 17/04/17.
// Copyright © 2017 Vinicius Nadin. All rights reserved.
//
import UIKit
class SearchUserController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
// MARK : - Properties
var users : [UserProfile]!
override var canBecomeFirstResponder: Bool {
return true
}
// MARK : - Outlets
@IBOutlet weak var userNameTextField: UITextField!
@IBOutlet weak var usersTableView: UITableView!
@IBOutlet weak var searchUserTextField: UITextField!
// MARK : - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.users = [UserProfile]()
self.usersTableView.delegate = self
self.usersTableView.dataSource = self
self.searchUserTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK : - View Actions
@IBAction func searchUser(_ sender: UIButton) {
self.resignFirstResponder()
if !(self.userNameTextField.text?.isEmpty)! {
UserProfile.searchUser(name: self.userNameTextField.text!) { (users) in
self.users = users
self.usersTableView.reloadData()
}
}
}
@IBAction func clearSearchs(_ sender: UIBarButtonItem) {
self.users = [UserProfile]()
self.usersTableView.reloadData()
}
// MARK : - View Methods
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("SearchUserCell", owner: self, options: nil)?.first as! SearchUserCell
let user = self.users[indexPath.row]
cell.user = user
cell.setupCellLabels()
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.users.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.becomeFirstResponder()
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyBoard.instantiateViewController(withIdentifier: "userProfileController") as! UserProfileController
let cell = tableView.cellForRow(at: indexPath) as! SearchUserCell!
viewController.user = cell?.user
self.navigationController?.pushViewController(viewController, animated: true)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 51
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
self.searchUser(UIButton())
return true
}
override func viewWillAppear(_ animated: Bool) {
self.usersTableView.reloadData()
}
}
|
Python
|
UTF-8
| 869 | 2.796875 | 3 |
[] |
no_license
|
from sklearn.neighbors import KNeighborsClassifier
from .TrainingData import TrainingData
import logging
logger = logging.getLogger("KNN")
class KNN():
def __init__(self, ug_chords):
training_inputs, training_outputs = TrainingData.getTrainingData(ug_chords)
self.training_inputs = training_inputs
self.training_outputs = training_outputs
self.knn_classifier = KNeighborsClassifier(n_neighbors=1)
logger.error('####################################################### in KNN init')
logger.error(self.training_inputs)
self.knn_classifier.fit(training_inputs, training_outputs)
logger.error('####################################################### finished training')
def get_classification(self, input):
knn_predictions = self.knn_classifier.predict(input)
return knn_predictions
|
Java
|
UTF-8
| 1,599 | 2.34375 | 2 |
[] |
no_license
|
package org.granchi.mythicgm.client.sucesos;
import org.granchi.mythicgm.client.ComponenteEscenaView;
import org.granchi.mythicgm.client.recursos.Cadenas;
import org.granchi.mythicgm.modelo.EventoAleatorio;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.HTML;
/**
* Panel que muestra un evento aleatorio.
*/
public class EventoAleatorioView extends ComponenteEscenaView<EventoAleatorio> {
private static final Cadenas cadenas = GWT.create(Cadenas.class);
/**
* Constructor.
*
* @param evento evento aleatorio
*/
public EventoAleatorioView(EventoAleatorio evento) {
super(evento);
}
@Override
protected void addComponentes() {
addStyleName("eventoAleatorio");
StringBuffer html = new StringBuffer();
html.append("<b><i>");
html.append(cadenas.eventoAleatorio());
html.append("</i></b><br/><b>");
html.append(cadenas.foco());
html.append("</b><br/>");
html.append("<i>(");
html.append(componente.getTiradaFoco());
html.append(")</i> ");
html.append(EventoAleatorio.DESC_FOCO[componente.getFoco().ordinal()]);
if (componente.getObjetoFoco() != null) {
html.append(": ");
html.append(componente.getObjetoFoco());
}
html.append("<br/><b>");
html.append(cadenas.significado());
html.append("</b><br/>");
html.append("<i>(");
html.append(componente.getTiradaAccion());
html.append(")</i> ");
html.append(componente.getAccion());
html.append(" + <i>(");
html.append(componente.getTiradaObjeto());
html.append(")</i> ");
html.append(componente.getObjeto());
add(new HTML(html.toString()));
}
}
|
Java
|
UTF-8
| 758 | 3.40625 | 3 |
[] |
no_license
|
package com.soumyadeep.string;
public class StringAndStringBufferPerformance {
public static void concatWithString() {
String s1="soumyadeep";
for(int i=0; i<10000; i++) {
s1=s1+"soumyadeep";
}
}
public static void concatWithStringBuilder() {
StringBuffer sb= new StringBuffer();
sb.append("soumyadeep");
for(int i=0; i<10000; i++) {
sb.append("soumyadeep");
}
}
public static void main(String[] args) {
long start=System.currentTimeMillis();
concatWithString();
System.out.println("Time taken with string: "+(System.currentTimeMillis()-start)+"ms");
start=System.currentTimeMillis();
concatWithStringBuilder();
System.out.println("Time taken with string buffer: "+(System.currentTimeMillis()-start)+"ms");
}
}
|
JavaScript
|
UTF-8
| 1,220 | 2.9375 | 3 |
[] |
no_license
|
/**
* Invia una richiesta GET verso la risora checkUsername.do che fa capo alla servlet CheckUsername
* E' atteso un messaggio di risposta dal server con questa forma
*
* <notification>
* <errorOccurred>false</errorOccurred>
* <message>Some text</message>
* <details>Some details</details>
* </notification>
*
* Il messaggio viene utilizzato per notificare la validità o meno dello username.
*
* DIPENDENZE: questo file dipende dallo script AjaxCallTemplate.js
*
* @param usernameInputField
*/
function checkUsername(usernameInputField) {
ajaxCallGet("checkUsername.do", "username=" + usernameInputField.value, responseHandler);
}
/*
* Funzione di callback per gestire il messaggio XML di risposta, Questa volta la notifica
* non viene visualizzata in modo "standard" ma si manifesta come campo non valido.
*
* TODO - completa
*
* @param responseXML
* @returns
*/
function responseHandler(responseText, responseXML) {
var errorOccurred = responseXML.getElementsByTagName("errorOccurred")[0].innerHTML;
if(errorOccurred == "true") {
alert("Username duplicato");
// Username duplicato
//document.getElementById("username").valid = "false";
//alert("Username duplicato");
}
}
|
Ruby
|
UTF-8
| 1,576 | 3.546875 | 4 |
[] |
no_license
|
class Award
attr_accessor :name, :expires_in, :quality
def initialize(name, expires_in, quality)
@name = name
@expires_in = expires_in
@quality = quality
end
def max (a,b)
a>b ? a : b
end
def min (a,b)
a>b ? b : a
end
def update_expiration
@expires_in -= 1
end
def update_quality
if @name != 'Blue Distinction Plus'
update_expiration
end
if @name === 'NORMAL ITEM'
update_quality_normal
elsif @name === 'Blue First'
update_quality_blue_first
elsif @name === 'Blue Compare'
update_quality_blue_compare
elsif @name == 'Blue Star'
update_quality_blue_star
end
end
def update_quality_normal
@quality = max(@quality - 1, 0)
if @expires_in < 0
@quality = max(@quality - 1, 0)
end
end
def update_quality_blue_first
if @quality < 50
@quality += 1
if @expires_in < 0
@quality = min(quality + 1, 50)
end
end
end
def update_quality_blue_compare
if @quality < 50
@quality += 1
if @expires_in < 11
@quality += 1
end
if @expires_in < 6
@quality += 1
end
end
if @expires_in < 0
@quality = 0
end
end
def update_quality_blue_star
@quality = max(@quality - 2, 0)
if @expires_in < 0
@quality = max(@quality - 2, 0)
end
end
end
|
Python
|
UTF-8
| 468 | 3.171875 | 3 |
[] |
no_license
|
import psycopg2
from config import config
# read connection parameters
params = config()
# connect to the PostgreSQL server
print("Connecting to the PostgreSQL database...")
con = psycopg2.connect(**params)
print("Database opened successfully")
# create a cursor
cur = con.cursor()
# run commands using execute
cur.execute("SELECT title from film LIMIT 10")
rows = cur.fetchall()
for row in rows:
print(row)
# close the connection
print("Done")
con.close()
|
SQL
|
UTF-8
| 379 | 3.859375 | 4 |
[] |
no_license
|
drop view if exists q9h;
create view q9h
as
select l.country as country, count(distinct b.style) as num
from beers b join brewers bs on b.brewer = bs.id
join locations l on bs.location = l.id
join beerstyles bty on b.style = bty.id
group by l.country
;
drop view if exists q9;
create view q9
as
select country, num as nstyles
from q9h
where num = (select max(num) from q9h)
;
|
C++
|
UTF-8
| 847 | 3.328125 | 3 |
[] |
no_license
|
class Solution {
public:
void wiggleSort(vector<int> & arr) {
int n = arr.size();
if (n < 2) return;
// Here we taek care of i - 1 and i + 1 when we are at ith Index.
// -- we need to form : /\ at distance of 2 indexs
for (int i = 1; i < n; i = i + 2) {
if (arr[i - 1] > arr[i])
swap(arr[i - 1], arr[i]);
// We perform this Operation, if we are allowed to do so
if (i + 1 < n && arr[i + 1] > arr[i])
swap(arr[i + 1], arr[i]);
}
}
};
class Solution {
public:
void wiggleSort(vector<int>& nums)
{
sort(nums.begin(), nums.end());
int N =nums.size();
for (int i = 1; i < N - 1; i = i + 2){
swap(nums[i], nums[i+1]);
}
}
};
|
SQL
|
UTF-8
| 1,441 | 2.78125 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.8.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: May 16, 2019 at 05:59 PM
-- Server version: 5.7.24
-- PHP Version: 7.3.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `cpt211`
--
CREATE DATABASE IF NOT EXISTS `cpt211` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `cpt211`;
-- --------------------------------------------------------
--
-- Table structure for table `admin`
--
DROP TABLE IF EXISTS `admin`;
CREATE TABLE IF NOT EXISTS `admin` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(30) NOT NULL,
`pass` varchar(30) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `admin`
--
INSERT INTO `admin` (`Id`, `user`, `pass`) VALUES
(12, 'syafiq', 'abc1234'),
(14, 'bad', '1234'),
(15, 'aziz', '1234'),
(16, 'furqan', '12345');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
JavaScript
|
UTF-8
| 2,464 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
function buscaAgendamentos(){
$.ajax({
//Tipo de envio POST ou GET
type: "POST",
dataType: "text",
data: {
action: "buscar"
},
url: "../controller/AvaliacaoController.php",
//Se der tudo ok no envio...
success: function (dados) {
var json = $.parseJSON(dados);
//Carregando a grid
var grid = "";
for (var i = 0; i < json.length; i++) {
var agendamento = json[i];
grid = grid + "<tr>";
grid = grid + "<td>" + agendamento.dtAgendamento + "</td>";
grid = grid + "<td>" + agendamento.hrInicial + "</td>";
grid = grid + "<td>" + agendamento.hrFinal + "</td>";
grid = grid + "<td>" + agendamento.nmUsuario + "</td>";
grid = grid + "<td>" + agendamento.nmAnimal + "</td>";
grid = grid + "<td style='width: 75px'; href='javascript:void(0);' onClick='aprovarAgendamento(" + agendamento.cdAgendamento + ")'><a style='color:green;'>Aprovar</a></td>";
grid = grid + "<td style='width: 75px'; href='javascript:void(0);' onClick='reprovarAgendamento(" + agendamento.cdAgendamento + ")'><a style='color:red;'>Reprovar</a></td>";
grid = grid + "</tr>";
}
$("#tbAvaliacaoAgendamento").html(grid);
}
});
};
function aprovarAgendamento(cdAgendamento)
{
$.ajax({
//Tipo de envio POST ou GET
type: "POST",
dataType: "text",
data: {
agendamento: cdAgendamento,
action: "aprovaragendamento"
},
url: "../controller/AvaliacaoController.php",
//Se der tudo ok no envio...
success: function (dados) {
jbkrAlert.sucesso('Agendamentos', 'Agendamento aprovado com sucesso!');
buscaAgendamentos();
}
});
}
function reprovarAgendamento(cdAgendamento)
{
$.ajax({
//Tipo de envio POST ou GET
type: "POST",
dataType: "text",
data: {
agendamento: cdAgendamento,
action: "reprovaragendamento"
},
url: "../controller/AvaliacaoController.php",
//Se der tudo ok no envio...
success: function (dados) {
jbkrAlert.sucesso('Agendamentos', 'Agendamento reprovado com sucesso!');
buscaAgendamentos();
}
});
}
|
PHP
|
UTF-8
| 3,142 | 2.609375 | 3 |
[] |
no_license
|
<?php
namespace app\addons\card\plat\controllers;
use app\addons\card\plat\controllers\PlatController;
use Yii;
use app\vendor\org\FileUpload;
/**
* Default controller for the `plat` module
*/
class DefaultController extends PlatController
{
/**
* Renders the index view for the module
* @return string
*/
public $layout = "layout1";
public function beforeAction($action)
{
$currentaction = $action->id;
$novalidactions = ['upload'];
if(in_array($currentaction,$novalidactions)) {
$action->controller->enableCsrfValidation = false;
}
parent::beforeAction($action);
return true;
}
public function actionIndex()
{
return $this->render('index');
}
public function actionHomepage()
{
//首页
return $this->render('homepage');
}
public function actionCreate_card()
{
//发卡
return $this->render('create_card');
}
public function actionCard_list()
{
//发布的卡
return $this->render('card_list');
}
public function actionCreate_ticket()
{
//发券
return $this->render('create_ticket');
}
public function actionTicket_list()
{
//发布的券
return $this->render('ticket_list');
}
public function actionCard_varify()
{
//卡券核销
return $this->render('card_varify');
}
public function actionReceived_record()
{
//领卡记录
return $this->render('received_record');
}
public function actionLogout()
{
//退出登录
$session = Yii::$app->session;
unset($session['user']);
$this->redirect('index.php?r=publics/default/login');
}
public function actionTest()
{
$session = Yii::$app->session;
echo $session['user']['uid'];
}
public function actionUpload()
{
//文件上传
if(Yii::$app->session['img']){
unlink(Yii::$app->session['img']);
$session = Yii::$app->session;
$session->remove('img');
}
$up = new FileUpload();
//设置属性(上传的位置、大小、类型、设置文件名是否要随机生成)
$path = "./images/";
$up->set("path",$path);
$up->set("maxsize",2000000); //kb
$up->set("allowtype",array("gif","png","jpg","jpeg"));//可以是"doc"、"docx"、"xls"、"xlsx"、"csv"和"txt"等文件,注意设置其文件大小
$up->set("israndname",true);//true:由系统命名;false:保留原文件名
//使用对象中的upload方法,上传文件,方法需要传一个上传表单的名字name:upload_file
//如果成功返回true,失败返回false
if($up->upload("upload_file")){
$session = Yii::$app->session;
session_set_cookie_params(120);
$session['img'] = $path.$up->getFileName();
echo $path.$up->getFileName();
die;
}else{
echo $up->getErrorMsg();
die;
}
}
}
|
Python
|
UTF-8
| 449 | 2.59375 | 3 |
[] |
no_license
|
import numpy as np
x0=np.ones(10)
x1=np.array([64.3,99.6,145.45,63.75,135.46,92.85,86.97,144.76,59.3,116.03])
x2=np.array([2,3,4,2,3,4,2,4,1,3])
y=np.array([62.55,82.42,132.62,73.31,131.05,86.57,85.49,127.44,55.25,104.84])
X=np.concatenate((x0,x1,x2),axis=0)
X=X.reshape(3,10)
X1=np.mat(X)
X1=X1.T
X=np.array(X1)
Y=y.reshape(10,1)
X=np.mat(X)
Y=np.mat(Y)
W=(((X.T)*X).I)*(X.T)*Y
print(X)
print(Y)
print(W)
print("W的shape属性结果是:",W.shape)
|
Markdown
|
UTF-8
| 2,055 | 3.53125 | 4 |
[] |
no_license
|
title: 内存栅栏(Memory Barrier)和volatile
date: 2015-11-06 23:32:06
tags: [java,并发]
---
内存栅栏是指本地或者工作内存到主存间的拷贝动作。在程序运行过程中。所有变更会先在线程的寄存器或本地cache中完成,然后才会拷贝到主存以跨越内存栅栏。理解内存栅栏先看下面代码:
{% codeblock lang:java %}
public class RaceCondition{
private static boolean done;
public static void main(final String[] args) throws InterruptedException{
new Thread(
public void run(){
int i = 0;
while(!done){ i++ ; }
System.out.println("Done!");
}
).start();
System.out.println("OS:" + System.getProperty("os.name"));
Thread.sleep(2000);
done = true;
System.out.println("flag done set to true");
}
}
{% endcodeblock %}
如果在win7上运行
java RaceCondition
可能输出以下结果:
>OS: Windows 7<br>
flag done set to true<br>
Done!
而在Mac上运行同样命令,则可能是:
> OS: Mac OS X<br>
flag done set to true<br>
这是由于windows平台执行java 命令默认是以server模式,而Mac下默认是以client模式运行。
在server模式下,JIT编译器会对代码新线程里的while循环进行优化,新线程会从寄存器或本地cache中读取done的拷贝值,而不会去速度相对较慢的内存里读取。由于以上原因,主线程中对于done的变更在新线程中不可见。
为解决这个问题,可以使用**volatile**关键字,其作用是告知JIT编译器改变量可能被某个线程更改,不要对其进行优化。volatile可使对变量的每次读写都忽略本地cache直接对内存操作,但正是这样会使得每次访问变量都要跨越内存栅栏导致程序性能下降。
由于每个线程对volatile字段的访问都是独立处理的,所以volatile关键字无法保证读写操作的原子性,为解决这个问题,可以使用**synchronized**关键字标注的setter和getter方法,synchronized可使同步区块内跨越内存栅栏。
|
C
|
UTF-8
| 378 | 4.21875 | 4 |
[] |
no_license
|
// Fazer um programa em C leia um número inteiro positivo N e informe se o número é divisível por 3 e 6.
#include <stdio.h>
int main()
{
int n;
scanf("%i", &n);
if (n<0)
{
printf("O NUMERO DEVE SER MAIOR OU IGUAL A ZERO");
} else if ( n%3 == 0 && n%6 == 0) {
printf("SIM");
} else {
printf("NAO");
}
return 0;
}
|
Rust
|
UTF-8
| 13,478 | 2.84375 | 3 |
[] |
no_license
|
// https://atcoder.jp/contests/code-festival-2018-final-open/tasks/code_festival_2018_final_f
//
#![allow(unused_imports)]
use std::io::*;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;
macro_rules! input {
(source = $s:expr, $($r:tt)*) => {
let mut iter = $s.split_whitespace();
input_inner!{iter, $($r)*}
};
($($r:tt)*) => {
let s = {
use std::io::Read;
let mut s = String::new();
std::io::stdin().read_to_string(&mut s).unwrap();
s
};
let mut iter = s.split_whitespace();
input_inner!{iter, $($r)*}
};
}
macro_rules! input_inner {
($iter:expr) => {};
($iter:expr, ) => {};
($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
let $var = read_value!($iter, $t);
input_inner!{$iter $($r)*}
};
}
macro_rules! read_value {
($iter:expr, ( $($t:tt),* )) => {
( $(read_value!($iter, $t)),* )
};
($iter:expr, [ $t:tt ; $len:expr ]) => {
(0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
};
($iter:expr, chars) => {
read_value!($iter, String).chars().collect::<Vec<char>>()
};
($iter:expr, usize1) => {
read_value!($iter, usize) - 1
};
($iter:expr, $t:ty) => {
$iter.next().unwrap().parse::<$t>().expect("Parse error")
};
}
#[allow(unused_macros)]
macro_rules! dvec {
($t:expr ; $len:expr) => {
vec![$t; $len]
};
($t:expr ; $len:expr, $($rest:expr),*) => {
vec![dvec!($t; $($rest),*); $len]
};
}
#[allow(unused_macros)]
macro_rules! debug {
($($a:expr),*) => {
println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
}
}
use std::rc::Rc;
type Merger<T> = Rc<Fn(T, T) -> T>;
struct SegmentTree<T> {
n: usize,
default: T,
bottom_offset: usize,
data: Vec<T>,
merger: Merger<T>
}
impl<T: Copy> SegmentTree<T> {
fn new(n: usize, initial: T, merger: Merger<T>) -> Self {
let z = (8u32 * std::mem::size_of::<usize>() as u32) - n.leading_zeros();
let size = (1<<z) as usize;
SegmentTree { n: size*2, default: initial, bottom_offset: size, data: vec![initial; size*2], merger: merger }
}
fn get(&self, i: usize) -> T {
let mut ret = self.default;
let mut idx = i + self.bottom_offset;
while idx >= 1 {
ret = (self.merger)(ret, self.data[idx]);
idx /= 2;
}
ret
}
fn set(&mut self, i: usize, value: T) {
self.data[self.bottom_offset+i] = value;
}
/// Apply given value to [i, j).
fn apply_range(&mut self, i: usize, j: usize, value: T) {
let m = self.bottom_offset;
self.range(i, j, value, 1, 0, m);
}
fn range(&mut self, i: usize, j: usize, value: T, idx: usize, begin: usize, end: usize) {
if end <= i || j <= begin {
return;
} else if i <= begin && end <= j {
self.data[idx] = (self.merger)(self.data[idx], value);
return;
}
let center = (begin+end)/2;
self.range(i, j, value, idx*2, begin, center);
self.range(i, j, value, idx*2+1, center, end);
}
fn merge(&mut self, i: usize, j: usize) -> T {
(self.merger)(self.data[i], self.data[j])
}
}
/// Fenwick tree.
struct FenwickTree<T> {
data: Vec<T>
}
impl<T: Copy + Default + std::ops::Add + std::ops::AddAssign + std::ops::Sub> FenwickTree<T> {
fn new(n: usize, initial: T) -> Self {
FenwickTree { data: vec![initial; n+1] }
}
/// Computes sum value of ([0, i)).
fn sum(&self, i: usize) -> T {
let mut idx = i as i64;
let mut ret = T::default();
while idx > 0 {
ret += self.data[idx as usize];
idx -= idx & (-idx);
}
ret
}
/// Adds value x into i-th position.
fn add(&mut self, i: usize, x: T) {
let mut idx = (i + 1) as i64;
while idx < self.data.len() as i64 {
self.data[idx as usize] += x;
idx += idx & (-idx);
}
}
fn range(&self, r: std::ops::Range<usize>) -> <T as std::ops::Sub>::Output {
self.sum(r.end) - self.sum(r.start)
}
}
// ====
#[derive(Debug, Clone)]
struct Treap<T> {
total: usize,
root: Link<T>
}
impl<T: Ord + Copy + Debug> Treap<T> {
fn new() -> Self {
Treap {
total: 0,
root: None
}
}
fn push(&mut self, v: T) -> bool {
if self.contains(v) {
return false;
}
let u = self.root.take();
self.root = Node::push(u, v);
self.total += 1;
true
}
fn remove(&mut self, v: T) -> bool {
let r = Node::remove(&mut self.root, v);
if r { self.total -= 1; }
r
}
fn len(&self) -> usize {
self.total
}
fn min(&self) -> Option<T> {
Node::min(&self.root)
}
fn max(&self) -> Option<T> {
Node::max(&self.root)
}
fn contains(&self, value: T) -> bool {
Node::contains(&self.root, value)
}
fn peek_less(&self, value: T) -> Option<T> {
Node::peek_less(&self.root, value)
}
fn peek_greater(&self, value: T) -> Option<T> {
Node::peek_greater(&self.root, value)
}
}
struct XorShift {
x: i64,
y: i64,
z: i64,
w: i64
}
impl XorShift {
fn rotate(&mut self) {
let t = self.x ^ (self.x << 11);
self.x = self.y;
self.y = self.z;
self.z = self.w;
self.w = (self.w ^ (self.w >> 19)) ^ (t ^ (t >> 8));
}
fn next_i64(&mut self) -> i64 {
self.rotate();
self.w
}
}
static mut RAND: XorShift = XorShift {
x: 123456789i64,
y: 362436069i64,
z: 521288629i64,
w: 88675123i64
};
fn generate_next() -> i64 {
let x;
unsafe {
x = RAND.next_i64();
}
x
}
type Link<T> = Option<Box<Node<T>>>;
#[derive(Debug, Clone)]
struct Node<T> {
value: T,
size: usize,
priority: i64,
left: Link<T>,
right: Link<T>,
}
impl<T: Ord + Copy + Debug> Node<T> {
fn new(value: T) -> Self {
Node {
value: value,
size: 1,
priority: generate_next(),
left: None,
right: None
}
}
fn sz(node: &Link<T>) -> usize {
match node.as_ref() { // TODO: Remove as_ref() after upgrading above 1.26
None => 0,
Some(x) => x.size
}
}
fn merge(left: Link<T>, right: Link<T>) -> Link<T> {
match (left, right) {
(None, None) => None,
(None, x) => x,
(x, None) => x,
(Some(l), Some(r)) => {
if l.priority < r.priority {
let mut l = l;
l.right = Self::merge(l.right.take(), Some(r));
Some(l)
} else {
let mut r = r;
r.left = Self::merge(Some(l), r.left.take());
Some(r)
}
}
}
}
fn min(now: &Link<T>) -> Option<T> {
match now.as_ref() { // TODO: Remove as_ref() after upgrading above 1.26
None => None,
Some(x) => {
match x.left.as_ref() { // TODO: Remove as_ref() after upgrading above 1.26
None => Some(x.value),
Some(_) => Self::min(&x.left)
}
}
}
}
fn max(now: &Link<T>) -> Option<T> {
match now.as_ref() { // TODO: Remove as_ref() after upgrading above 1.26
None => None,
Some(x) => {
match x.right.as_ref() { // TODO: Remove as_ref() after upgrading above 1.26
None => Some(x.value),
Some(_) => Self::max(&x.right)
}
}
}
}
fn contains(now: &Link<T>, value: T) -> bool {
match now.as_ref() { // TODO: Remove as_ref() after upgrading above 1.26
None => false,
Some(x) => {
match value.cmp(&x.value) {
Ordering::Less => Self::contains(&x.left, value),
Ordering::Equal => true,
Ordering::Greater => Self::contains(&x.right, value)
}
}
}
}
fn peek_less(now: &Link<T>, value: T) -> Option<T> {
match now.as_ref() { // TODO: Remove as_ref() after upgrading above 1.26
None => None,
Some(x) => {
match value.cmp(&x.value) {
Ordering::Less | Ordering::Equal => {
Self::peek_less(&x.left, value)
},
Ordering::Greater => {
let w = Self::peek_less(&x.right, value);
if w == None {
Some(x.value)
} else {
Some(max(w.unwrap(), x.value))
}
}
}
}
}
}
fn peek_greater(now: &Link<T>, value: T) -> Option<T> {
match now.as_ref() { // TODO: Remove as_ref() after upgrading above 1.26
None => None,
Some(x) => {
match value.cmp(&x.value) {
Ordering::Greater | Ordering::Equal => {
Self::peek_greater(&x.right, value)
},
Ordering::Less => {
let w = Self::peek_greater(&x.left, value);
if w == None {
Some(x.value)
} else {
Some(min(w.unwrap(), x.value))
}
}
}
}
}
}
fn split_at(now: Link<T>, k: usize) -> (Link<T>, Link<T>) {
match now {
None => (None, None),
Some(x) => {
let mut x = x;
let lsz = Self::sz(&x.left);
if k <= lsz {
let (nl, nr) = Self::split_at(x.left.take(), k);
x.left = nr;
(nl, Some(x))
} else {
let (nl, nr) = Self::split_at(x.right.take(), k-1-lsz);
x.right = nl;
(Some(x), nr)
}
},
}
}
fn split_by(now: Link<T>, v: T) -> (Link<T>, Link<T>) {
match now {
None => (None, None),
Some(x) => {
let mut x = x;
if v <= x.value {
let (nl, nr) = Self::split_by(x.left.take(), v);
x.left = nr;
(nl, Some(x))
} else {
let (nl, nr) = Self::split_by(x.right.take(), v);
x.right = nl;
(Some(x), nr)
}
},
}
}
fn push(now: Link<T>, new_value: T) -> Link<T> {
let new_node = Some(Box::new(Node::new(new_value)));
let (left, right) = Self::split_by(now, new_value);
Self::merge(Self::merge(left, new_node), right)
}
fn remove(now: &mut Link<T>, target_value: T) -> bool {
let mut both_none = false;
let w = match now.as_mut() { // TODO: Remove as_mut() after upgrading above 1.26
None => false,
Some(x) => {
if target_value < x.value {
Self::remove(&mut x.left, target_value)
} else if x.value < target_value {
Self::remove(&mut x.right, target_value)
} else {
let new_link = Self::merge(x.left.take(), x.right.take());
if let Some(node) = new_link {
*x = node;
} else {
both_none = true;
}
true
}
}
};
if both_none {
now.take();
}
w
}
}
// ====
const INF: i64 = 1e18 as i64;
fn main() {
input! {
n: usize, k: usize,
meals: [(i32, i64); n]
};
// let mut seg = SegmentTree::new(k+2*n, 0i64, Rc::new(|i, j| i + j));
// let mut fen = FenwickTree::new(k+2*n, 0i64);
let mut ram = Treap::new();
let mut res = Treap::new();
for i in 0..k {
let pv = i as i32;
ram.push((INF, -pv-1));
}
let mut total = 0;
for ((kind, value), idx) in meals.into_iter().zip(0..n) {
let idx = idx as i32;
total += value;
if kind == 0 {
ram.push((value, idx));
if res.len() >= 1 {
let best = res.max().unwrap();
res.remove(best);
} else {
let ram_cancel = ram.min().unwrap();
ram.remove(ram_cancel);
total -= ram_cancel.0;
}
} else {
res.push((value, idx));
if ram.len() >= 1 {
let best = ram.max().unwrap();
ram.remove(best);
} else {
let res_cancel = res.min().unwrap();
res.remove(res_cancel);
total -= res_cancel.0;
}
}
}
println!("{}", total);
}
|
SQL
|
UTF-8
| 4,253 | 3.609375 | 4 |
[] |
no_license
|
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema TimeCard
-- -----------------------------------------------------
DROP DATABASE IF EXISTS `TimeCard`;
-- -----------------------------------------------------
-- Schema TimeCard
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `TimeCard` DEFAULT CHARACTER SET utf8 ;
USE `TimeCard` ;
-- -----------------------------------------------------
-- Table `TimeCard`.`role`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `TimeCard`.`role` (
`RoleId` INT NOT NULL AUTO_INCREMENT,
`RoleDesc` NVARCHAR(255) NOT NULL,
PRIMARY KEY (`RoleId`),
UNIQUE INDEX `RoleId_UNIQUE` (`RoleId` ASC) VISIBLE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `TimeCard`.`user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `TimeCard`.`user` (
`UserId` INT NOT NULL AUTO_INCREMENT,
`Fname` NVARCHAR(255) NOT NULL,
`Lname` NVARCHAR(255) NOT NULL,
`UserName` NVARCHAR(255) NOT NULL,
`UserPassword` NVARCHAR(255) NOT NULL,
`RoleId` INT NOT NULL,
PRIMARY KEY (`UserId`),
UNIQUE INDEX `UserId_UNIQUE` (`UserId` ASC) VISIBLE,
INDEX `fk_user_role1_idx` (`RoleId` ASC) VISIBLE,
CONSTRAINT `fk_user_role1`
FOREIGN KEY (`RoleId`)
REFERENCES `TimeCard`.`role` (`RoleId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `TimeCard`.`status`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `TimeCard`.`status` (
`StatusId` INT NOT NULL AUTO_INCREMENT,
`StatusDesc` NVARCHAR(255) NOT NULL,
UNIQUE INDEX `StatusId_UNIQUE` (`StatusId` ASC) VISIBLE,
PRIMARY KEY (`StatusId`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `TimeCard`.`timesheet`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `TimeCard`.`timesheet` (
`TimeSheetId` INT NOT NULL AUTO_INCREMENT,
`MondayHours` FLOAT NULL,
`TuesdayHours` FLOAT NULL,
`WednesdayHours` FLOAT NULL,
`ThursdayHours` FLOAT NULL,
`FridayHours` FLOAT NULL,
`SaturdayHours` FLOAT NULL,
`SundayHours` FLOAT NULL,
`WeekEndingAt` DATE NOT NULL,
`UserId` INT NOT NULL,
`StatusId` INT NOT NULL,
PRIMARY KEY (`TimeSheetId`),
UNIQUE INDEX `TimeSheetId_UNIQUE` (`TimeSheetId` ASC) VISIBLE,
INDEX `fk_timesheet_user_idx` (`UserId` ASC) VISIBLE,
INDEX `fk_timesheet_status1_idx` (`StatusId` ASC) VISIBLE,
CONSTRAINT `fk_timesheet_user`
FOREIGN KEY (`UserId`)
REFERENCES `TimeCard`.`user` (`UserId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_timesheet_status1`
FOREIGN KEY (`StatusId`)
REFERENCES `TimeCard`.`status` (`StatusId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
INSERT INTO `Role` (`RoleDesc`) VALUES (N'Employee');
INSERT INTO `Role` (`RoleDesc`) VALUES (N'Manager');
INSERT INTO `Status` (`StatusDesc`) VALUES (N'Saved');
INSERT INTO `Status` (`StatusDesc`) VALUES (N'Submitted');
INSERT INTO `Status` (`StatusDesc`) VALUES (N'Approved');
INSERT INTO `Status` (`StatusDesc`) VALUES (N'Denied');
-- Populate User table
INSERT INTO `User` (`Fname`,`Lname`,`UserName`,`UserPassword`,`RoleId`) VALUES (N'Andrew','Tan','AndrewTan','AndrewPassword','1');
INSERT INTO `User` (`Fname`,`Lname`,`UserName`,`UserPassword`,`RoleId`) VALUES (N'Patrick','Walsh','PatrickWalsh','PatrickWalshPassword','2');
-- Populate Time Sheet table
INSERT INTO `TimeSheet` (`MondayHours`,`TuesdayHours`,`WednesdayHours`,`ThursdayHours`,`FridayHours`,`SaturdayHours`,`SundayHours`,`WeekEndingAt`,`StatusId`,`UserId`) VALUES (N'40','40','40','40','40','0','0','2019-11-10','1','1');
|
Java
|
UTF-8
| 2,201 | 1.96875 | 2 |
[] |
no_license
|
package com.example.cuma.tinder.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.cuma.tinder.R;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
public class deneme extends AppCompatActivity implements RewardedVideoAdListener{
private RewardedVideoAd mRewardedVideoAd;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deneme);
button=findViewById(R.id.oynat);
MobileAds.initialize(this, "ca-app-pub-7740710689946524~4712663337");
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
deneme();
}
public void deneme(){
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
else
{
Toast.makeText(deneme.this,"olmadı",Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onRewardedVideoAdLoaded() {
}
@Override
public void onRewardedVideoAdOpened() {
}
@Override
public void onRewardedVideoStarted() {
}
@Override
public void onRewardedVideoAdClosed() {
}
@Override
public void onRewarded(RewardItem rewardItem) {
}
@Override
public void onRewardedVideoAdLeftApplication() {
}
@Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
@Override
public void onRewardedVideoCompleted() {
}
}
|
Java
|
WINDOWS-1252
| 642 | 1.929688 | 2 |
[] |
no_license
|
package com.my;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
@ContextConfiguration(locations = { "/application-context.xml"})
public class UserMapperTest extends AbstractJUnit4SpringContextTests{
@Autowired
public UserMapper userMapper;
@Test
public void testGetUser(){
Assert.assertNotNull(userMapper.getUser(1L));
Assert.assertEquals(userMapper.getUser(1L).getRealName(), "");
}
}
|
Python
|
UTF-8
| 1,695 | 2.765625 | 3 |
[] |
no_license
|
# pip install sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, backref
Base = declarative_base()
class Department(Base):
__tablename__ = 'departments'
idDepartment = Column(Integer, primary_key=True)
DepartmentCity = Column(String)
CountOfWorkers = Column(Integer)
def __repr__(self):
return f'Id: {self.idDepartment} City: {self.DepartmentCity}'
class Client(Base):
__tablename__ = 'clients'
idClient = Column(Integer, primary_key=True)
FirstName = Column(String)
LastName = Column(String)
Education = Column(String)
Passport = Column(String)
City = Column(String)
Age = Column(Integer)
department_id = Column(Integer,
ForeignKey('departments.idDepartment'))
department = relationship('Department',
backref=backref('clients',
order_by=idClient))
def __repr__(self):
return f'Name: {self.FirstName} Surname: {self.LastName}'
class Application(Base):
__tablename__ = 'applications'
idApplication = Column(Integer, primary_key=True)
Sum = Column(Integer)
CreditState = Column(String)
Currency = Column(String)
client_id = Column(Integer,
ForeignKey('clients.idClient'))
client = relationship('Client',
backref=backref('applications',
order_by=Sum))
def __repr__(self):
return f'Id: {self.idApplication} Sum: {self.Sum} ClientId: {self.client_id}'
|
JavaScript
|
UTF-8
| 931 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
import React, { useState, useEffect } from "react";
import Card from "../components/Card/Card";
import API from '../utils/API'
import styled from 'styled-components';
const Container = styled.div`
margin: 1rem auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
`;
const Title = styled.div`
color: #F0F0F0;
font-size: 3rem;
margin-bottom: 2rem;
`;
function Favorites() {
const [favorites, setFavorites] = useState([]);
const getFavorites = () => {
API.getFavorites()
.then(res => {
// console.log(res.data);
setFavorites(res.data.reverse());
})
.catch(err => console.log(err));
};
useEffect(() => {
getFavorites();
}, []);
return (
<Container>
<Title>Favorites</Title>
{ favorites.map((item, index) => (
<Card quote={ item } key={ index }/>
))}
</Container>
)
}
export default Favorites
|
PHP
|
UTF-8
| 727 | 3.109375 | 3 |
[] |
no_license
|
<?php
// $my_db_handle = new PDO(
// 'mysql:host=localhost;dbname=world', // connection string
// 'dev', //username
// '' //password
// );
// $pdo_connection = new PDO(
// 'mysql:dbname=test;host=localhost;charset=utf8', // connection information
// 'root', // username
// 'rootroot' // password
// );
$servername = "localhost";
$username = "root";
$password = "rootroot";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
|
JavaScript
|
UTF-8
| 1,038 | 4.125 | 4 |
[] |
no_license
|
'use strict'
//funciones
// las funciones son un grupo de ordenes agrupado con un numbre concreto,
// en una funcion vamos a tener un conjunto de reglas/funciones/variables, es decir, cosas
// que se van a ejecutar. Podemos usar una funcion tantas veces como querramos
// esta funcion se va a ejecutar cuando se le invoque.
// una funcion es una agrupacion reutilizable de un conjunto de instrucciones
// Defino la funcion
function calculadora(numero1,numero2){
//conjunto de instrucciones
console.log("hola soy la calculadora!");
console.log("Si, soy yo");
console.log("suma: "+(numero1+numero2));
console.log("resta: "+(numero1-numero2));
console.log("multiplicacion: "+(numero1*numero2));
console.log("division: "+(numero1/numero2));
console.log("________---------_________")
// return "hola soy el return calculadora!";
}
//llamo o invoco a la funcion
// var resultado = calculadora(12,4)
for(var i= 1; i<=10;i++){
console.log(i)
calculadora(i,8)
}
|
Java
|
UTF-8
| 1,030 | 1.648438 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.xiaomi.mone.tpc.controller;
import com.xiaomi.mone.tpc.aop.ArgCheck;
import com.xiaomi.mone.tpc.common.param.NodeOrgQryParam;
import com.xiaomi.mone.tpc.common.vo.OrgInfoVo;
import com.xiaomi.mone.tpc.common.vo.PageDataVo;
import com.xiaomi.mone.tpc.common.vo.ResultVo;
import com.xiaomi.mone.tpc.node.NodeOrgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @project: mi-tpc
* @author: zgf1
* @date: 2022/3/3 19:41
*/
@Slf4j
@RestController
@RequestMapping(value = "/backend/org")
public class NodeOrgController {
@Autowired
private NodeOrgService nodeOrgService;
@ArgCheck
@RequestMapping(value = "/list")
public ResultVo<PageDataVo<OrgInfoVo>> list(@RequestBody NodeOrgQryParam param) {
return nodeOrgService.list(param);
}
}
|
Java
|
UTF-8
| 1,043 | 2.703125 | 3 |
[] |
no_license
|
package generic;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class Excel {
public static String getData(String xl_path, String sheet, int row, int column)
{
String v="";
Workbook wb;
try {
wb=WorkbookFactory.create(new FileInputStream(xl_path));
v=wb.getSheet(sheet).getRow(row).getCell(column).toString();
}catch(Exception e)
{
}
return v;
}
public static int rowCount(String xl_path, String sheet)
{
int row_count=0;
Workbook wb;
try {
wb=WorkbookFactory.create(new FileInputStream(xl_path));
row_count=wb.getSheet(sheet).getLastRowNum();
} catch (Exception e) {
}
return row_count;
}
public static int coloumnCount(String xl_path, String sheet, int row)
{
int column_Count=0;
Workbook wb;
try {
wb=WorkbookFactory.create(new FileInputStream(xl_path));
column_Count=wb.getSheet(sheet).getRow(row).getLastCellNum();
} catch (Exception e) {
}
return column_Count;
}
}
|
C#
|
UTF-8
| 634 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mko
{
public class ExceptionHelper
{
public static string FlattenExceptionMessages(Exception ex)
{
if (ex != null)
{
string msg = ex.Message;
Exception inner = ex.InnerException;
while (inner != null)
{
msg += "\n" + inner.GetType().Name + ": " + inner.Message;
inner = inner.InnerException;
}
return msg;
} return "";
}
}
}
|
Python
|
UTF-8
| 10,960 | 2.53125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
# Copyright (c) 2015, Scott J Maddox. All rights reserved.
# Use of this source code is governed by the BSD-3-Clause
# license that can be found in the LICENSE file.
import sys
import StringIO
# System and cell definitions/configurations
from .system_config import systems
# Calculte measure_wait
def generate_sto(targets,
bf_var="bf",
num_temps=4,
num_shutterings=3,
num_samples=3,
temp_tolerance=0.2,
update_time=10):
'''
Generates an AMBER source turn on (STO) recipe that uses the Newton iteration
method, assuming an Arrhenius relationship, to find the cell temperature that
provides a desired beam equivalent pressure (BEP).
Basic operation:
1. Ramp to initial guess temperature.
2. Measure the BEP several times and take the average.
3. Calculate a new temperature guess using the last measurement and the
activation energy for the cell (defined by the user).
4. Ramp to the new guessed temperature.
5. Repeat steps 2-4 as many times as desired.
'''
old_stdout = sys.stdout
sys.stdout = StringIO.StringIO()
measure_wait = update_time * 2.5
# Define variables
print "! *** Define Variables ***"
print "! *** Note: if you change Tguess, you should fix the ramp up time"
for target in targets:
print "eval %s=%.3E" % (target.BEP_var, target.BEP)
print "eval %s=%.1f" % (target.Tguess_var, target.Tguess)
print "eval %s=%.1f" % (target.Tmin_var, target.Tguess - 50)
print "eval %s=%.1f" % (target.Tmax_var, target.Tguess + 50)
print "eval %s=%.2f" % (target.Ea_var, target.cell.Ea)
if target.cell.diff is not None:
print "eval %s=%.1f" % (target.Tdiff_var, target.cell.diff)
print ""
# Define structures (AKA subroutines)
print "! *** Define structures ***"
shutters = [target.cell.shutter for target in targets]
comma_separated_shutters = ','.join(shutters)
print "structure (pregetter)"
print " repeat 5"
print " open %s" % comma_separated_shutters
print " wait 30"
print " close %s" % comma_separated_shutters
print " wait 30"
print " er"
print "es"
print ""
for target in targets:
print "structure (getter_%s)" % (target.cell.id)
print " repeat 3"
print " open %s" % target.cell.shutter
print " wait 10"
print " close %s" % target.cell.shutter
print " wait 10"
print " er"
print "es"
print ""
for target in targets:
print "structure (ramp_%s)" % (target.cell.id)
print " eval low = step(%s-%s)" % (target.Tmin_var, target.T_var)
print " eval high = step(%s-%s)" % (target.T_var, target.Tmax_var)
print " eval %s = %s*(1-low)+%s*low" % (target.T_var, target.T_var,
target.Tmin_var)
print " eval %s = %s*(1-high)+%s*high" % (target.T_var, target.T_var,
target.Tmax_var)
print " t %s=%s" % (target.cell.primary, target.T_var)
print "es"
print ""
for target in targets:
print "structure (wait_%s)" % (target.cell.id)
print " waituntil ( %s-%.1f < %s < %s+%.1f ) 30" % (target.T_var,
temp_tolerance,
target.cell.primary,
target.T_var,
temp_tolerance)
if target.cell.dual:
print " waituntil ( %s+%s-%.1f < %s < %s+%s+%.1f ) 30" % (
target.T_var,
target.Tdiff_var,
temp_tolerance,
target.cell.secondary,
target.T_var,
target.Tdiff_var,
temp_tolerance)
print " wait 00:02:00"
print "es"
print ""
# Write flux log headers
print "! *** Write flux log headers ***"
for target in targets:
print 'writefile (%sFluxes; "#Cell=%s")' % (target.cell.id, target.cell.id)
print 'writefile (%sFluxes; "#T\tBG\tP\tBEP")' % (target.cell.id)
print ""
# Ramp to initial temperature
print "! *** Ramp to initial temperature ***"
print "comment (Ramp to initial temperature)"
# calculate the ramp times for each cell
ramptimes = [int((target.Tguess - target.cell.idle)
/ target.cell.ramprate * 60)
for target in targets]
ramptimes_and_targets = zip(ramptimes, targets)
ramptimes_and_targets.sort(reverse=True) # sort in place
for i in xrange(len(ramptimes_and_targets) - 1):
ramptime, target = ramptimes_and_targets[i]
next_ramptime, next_target = ramptimes_and_targets[i + 1]
waittime = ramptime - next_ramptime
print "! %s takes %d sec to ramp up" % (target.cell.id, ramptime)
print "eval %s=%s" % (target.T_var, target.Tguess_var)
print "ramp_%s" % (target.cell.id)
print "wait %d" % (waittime)
ramptime, target = ramptimes_and_targets[-1]
waittime = ramptime
print "! %s takes %d sec to ramp up" % (target.cell.id, ramptime)
print "eval %s=%s" % (target.T_var, target.Tguess_var)
print "ramp_%s" % (target.cell.id)
print "wait %d" % (ramptime)
print "! stabilize for an hour"
print "wait 01:00:00"
print ""
# Initial getter
print "! *** Initial getter ***"
print "comment (Initial getter)"
print "pregetter"
print ""
# Wait to stabilize, measure the BEP 5 times, then start ramping to the
# next temperature while doing the same for the next cell
def take_measurement(target, i):
id = target.cell.id
BEP_acc = "%s_BEP_%d_acc" % (id, i) # BEP accumulator
BEP_avg = "%s_BEP_%d_avg" % (id, i) # BEP average
print "! *** %s stabilizing %d ***" % (id, i)
print "comment (%s stabilizing %d )" % (id, i)
print "wait_%s" % (id)
print "getter_%s" % (id)
print "eval %s_%d=%s" % (target.T_var, i, target.T_var)
print "eval %s=0" % BEP_acc # initialize the BEP accumulator
print ""
# Measure the BEP num_shutterings times, and write the values to the
# flux log
for j in xrange(1, num_shutterings + 1):
print "! *** %s measurement %d - %d ***" % (id, i, j)
print "comment (%s measurement %d - %d)" % (id, i, j)
T = target.T_var
print "open %s" % target.cell.shutter
for k in xrange(1, num_samples + 1):
if k == 1:
print "wait %d" % measure_wait
else:
print "wait %d" % update_time
P = "%s_P_%d_%d_%d" % (id, i, j, k)
print "eval %s=%s" % (P, bf_var)
print "close %s" % target.cell.shutter
for k in xrange(1, num_samples + 1):
if k == 1:
print "wait %d" % measure_wait
else:
print "wait %d" % update_time
P = "%s_P_%d_%d_%d" % (id, i, j, k)
BG = "%s_BG_%d_%d_%d" % (id, i, j, k)
BEP = "%s_BEP_%d_%d_%d" % (id, i, j, k)
print "eval %s=%s" % (BG, bf_var)
print "eval %s=%s-%s" % (BEP, P, BG)
print "eval %s=%s+%s" % (BEP_acc, BEP_acc, BEP)
print "writefile (%sFluxes; %s, %s, %s, %s)" % (id, T, BG, P, BEP)
print ""
# Calculate the average
print "! *** %s calculate average BEP %d ***" % (id, i)
print "comment (%s calculate average BEP %d)" % (id, i)
print "eval %s=%s/%d/%d" % (BEP_avg, BEP_acc, num_shutterings,
num_samples)
print ""
# def calculate_Ea(target, i):
# id = target.cell.id
# Ts = ["%s_%d" % (target.T_var, j) for j in xrange(1, i + 1)]
# BEPs = ["%s_BEP_%d_avg" % (id, j) for j in xrange(1, i + 1)]
# csTs = ','.join(Ts)
# csBEPs = ','.join(BEPs)
# print "! *** %s calculate Ea %d ***" % (id, i)
# print "comment (%s calculate Ea %d)" % (id, i)
# print "fitexp (%s;%s;Amp,Ea_%d)" % (csTs, csBEPs, i)
# print ""
# def calculate_median(target, i):
# id = target.cell.id
# for j in range(1, num_temps + 1):
# for k in range(1, j) + range(j, num_temps + 1):
# jBEP = "%s_BEP_%d_%d" % (id, i, j)
# kBEP = "%s_BEP_%d_%d" % (id, i, k)
# # 1 (True) if jBEP > kBEP:
# print "eval bool_%s_BEP_%d_%d_gt_%d=st(%s-%s)" % (id, i, j, k,
# jBEP, kBEP)
# print "eval bool_%s_%d_is_median=st(" % (id, i)
def calculate_guess(target, i):
id = target.cell.id
# Calculate a new Amp from the most resent data point
T = "%s_%d" % (target.T_var, i)
BEP = "%s_BEP_%d_avg" % (id, i) # BEP average
print "! *** %s calculate guess %d ***" % (id, i + 1)
print "comment (%s calculate guess %d)" % (id, i + 1)
print "eval Amp_%d=%s*exp(%s/(8.617385E-5*(%s+273.15)))" % (i, BEP,
target.Ea_var,
T)
# Calculate a new Tguess from Ea and the new Amp
print "eval %s=-%s/(8.617385E-5*ln(%s/Amp_%d))-273.15" % (
target.Tguess_var,
target.Ea_var,
target.BEP_var, i)
print ""
# start looping through the iterations:
# 1. measure
# 2. calculate new guess
# 3. ramp to guess
for i in xrange(1, num_temps + 1):
for target in targets:
id = target.cell.id
# measure
take_measurement(target, i)
calculate_guess(target, i)
# ramp to Tguess
print "! *** %s ramp to guess %d ***" % (id, i + 1)
print "comment (%s ramp to guess %d)" % (id, i + 1)
print "eval %s=%s" % (target.T_var, target.Tguess_var)
print "ramp_%s" % (target.cell.id)
print ""
result = sys.stdout.getvalue()
sys.stdout = old_stdout
return result
|
JavaScript
|
UTF-8
| 6,462 | 3.296875 | 3 |
[] |
no_license
|
/**
* The table dimentions.
* @constant
* @type int
*/
const TABLE_H_OFFSET = 0;
const TABLE_V_OFFSET = 0;
const TABLE_WIDTH = 5;
const TABLE_HEIGHT= 5;
const DEBUG = true;
/* ==================== ROBOT ==================== */
/**
* @class
*
*
* <p>The ROBOT class represents toy robot moving on a square tabletop</p>
*
*
* <p> The origin (0,0) can be considered to be the SOUTH WEST most corner.
* The first valid command to the robot is a PLACE command, aXer that, any
* sequence of commands may be issued, in any order, including another PLACE command.
* The application should discard all commands in the sequence until a valid PLACE command has been executed.
</p>
*/
/**
* The facing directions.
* @constant
* @type int
*/
const FACING_NORTH = 0;
const FACING_EAST = 1;
const FACING_SOUTH = 2;
const FACING_WEST = 3;
const TABLE_DIRECTIONS = [ 'NORTH' , 'EAST' , 'SOUTH','WEST' ];
class Robot {
constructor () {
this._x = 0;
this._y = 0;
this._f = 0;
}
set X (x) {
if(x < TABLE_H_OFFSET || x >= TABLE_H_OFFSET + TABLE_WIDTH)
return this.ignore("X = " + x) ;
this._x = x;
}
get X () { return this._x; }
set Y (y) {
if(y < TABLE_V_OFFSET || y >= TABLE_V_OFFSET + TABLE_HEIGHT)
return this.ignore("Y = " + y) ;
this._y = y;
}
get Y () { return this._y; }
set F (f) {
if(f < FACING_NORTH || f > FACING_WEST)
return this.ignore("Wrong direction: " + f) ;
this._f = f;
}
get F() {return this._f;}
get Facing() {return TABLE_DIRECTIONS[this._f];}
ignore (error) {
throw 'Invalid placement: ' + error;
return -1;
}
}
/* ==================== ROBOT Controller ==================== */
/**
* @class
*
*
* <p>The ROBOT Controller class controls robot movement</p>
*
*
* <p> PLACE will put the toy robot on the table in position X,Y and facing NORTH,SOUTH, EAST or WEST.
* MOVE will move the toy robot one unit forward in the direction it is currently facing.
* LEFT and RIGHT will rotate the robot 90 degrees in the specified direction without changing the position of the robot.
* REPORT will announce the X,Y and F of the robot. This can be in any form, but standard output is sufficient</p>
*/
class RobotController {
constructor (robot) {
this.robot = robot;
}
Place(x,y,f)
{
var placement = {x: this.robot.X , y: this.robot.Y ,f: this.robot.F };
try
{
this.robot.X = x;
this.robot.Y = y;
this.robot.F = f ;
} catch (err)
{
//rollback
this.robot.X = placement.x;
this.robot.Y = placement.y;
this.robot.F = placement.f ;
Logger.log(err, 1);
return -1;
}
return 0 ;
}
LEFT() { this.robot.F = (this.robot.F == FACING_NORTH)? FACING_WEST: this.robot.F -1; }
RIGHT() { this.robot.F = (this.robot.F == FACING_WEST)? FACING_NORTH: this.robot.F + 1; };
Move()
{
switch(this.robot.F) {
case FACING_NORTH:
return this.Place(this.robot.X, this.robot.Y + 1, this.robot.F) ;
break;
case FACING_EAST:
return this.Place(this.robot.X + 1, this.robot.Y , this.robot.F) ;
break;
case FACING_SOUTH:
return this.Place(this.robot.X, this.robot.Y -1, this.robot.F) ;
break;
case FACING_WEST:
return this.Place(this.robot.X- 1 , this.robot.Y , this.robot.F) ;
break;
default:
}
}
Report() { return (this.robot.X +","+ this.robot.Y +","+ this.robot.Facing).toString(); }
}
/*
* The Input Commands.
* @constant
* @type string
*/
const COMMAND_PLACE = "PLACE";
const COMMAND_LEFT = "LEFT";
const COMMAND_RIGHT = "RIGHT";
const COMMAND_MOVE = "MOVE";
const COMMAND_REPORT = "REPORT";
/* ==================== Command Parser ==================== */
/**
* @class
* <p>Command Parser</p>
*/
class CommandParser
{
constructor ( ) {
this.validPlacement = false;
}
parseText(commands_text, controller)
{
var lines = commands_text.split('\n');
var commands = [];
for(var i =0; i < lines.length; i ++) //Prepare commands
{
var command = lines[i].trim();
if(command.length ==0)
continue;
commands.push(command);
}
for( i =0; i < commands.length; i ++) //parse commands
{
var result = this.parseCommand(commands[i], controller);
if(result!== 0)
{
Logger.log(result, 1);//Error
}
}
};
parseCommand(command_text, controller)
{
var args = command_text.replace(/,/g,' ').split(' ');
for(var i=0; i<args.length; i++)
{
var command = args[0];
switch(command)
{
case COMMAND_PLACE :
if(args.length <4 )
return "command: " +command_text + ". Insufficient arguments : " + command ;
var x = parseInt(args[1]);
if(isNaN(x))
return "command: " +command_text + ". Invalid X position : " + args[1] ;
var y = parseInt(args[2]);
if(isNaN(y))
return "command: " +command_text+ ". Invalid Y position : " + args[2] ;
var f = TABLE_DIRECTIONS.indexOf(args[3]);
if(f==-1 )
return "command: " +command_text + ". Invalid direction : " + args[3] ;
if (controller.Place(x,y, f) == 0)
{
this.validPlacement = true;
return 0;
}
return -1;
break;
case COMMAND_LEFT : if(this.validPlacement ) controller.LEFT(); break;
case COMMAND_RIGHT : if(this.validPlacement ) controller.RIGHT(); break;
case COMMAND_MOVE : if(this.validPlacement ) return controller.Move() ; break;
case COMMAND_REPORT: if(this.validPlacement ) Logger.log (controller.Report()); break;
default:
return "Invalid argument : " + command ;
}
}
return 0;
};
}
//* ==================== Logger ==================== */
/**
* @class
* <p>Logger</p>
*/
class Logger {
constructor ( ) { }
log( message, message_type)
{
if( message_type ==0 || message_type == null || message_type == undefined) //LOG
console.log(message);
if(message_type == 1 )//Error
console.error(message);
};
}
exports.Robot = Robot;
exports.RobotController = RobotController;
exports.CommandParser = CommandParser;
exports.Logger = Logger;
exports.FACING_NORTH = FACING_NORTH;
exports.FACING_EAST = FACING_EAST ;
exports.FACING_SOUTH = FACING_SOUTH;
exports.FACING_WEST = FACING_WEST ;
|
Python
|
UTF-8
| 142 | 3.15625 | 3 |
[] |
no_license
|
favorieten = ["Foster The People"]
favorieten.append("Tristam")
favorieten[1] = "Braken"
print(favorieten)
"['Foster The People', 'Braken']"
|
C++
|
UTF-8
| 2,480 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
//
// 2019-12-12, jjuiddong
// udp/ip server sample
// udp server is only receive module
//
#include "pch.h"
#include "../Protocol/Src/basic_Protocol.h"
#include "../Protocol/Src/basic_ProtocolData.h"
#include "../Protocol/Src/basic_ProtocolHandler.h"
using namespace std;
bool g_isLoop = true;
bool g_print = false;
class cPacketHandler : public basic::c2s_ProtocolHandler
{
public:
cPacketHandler() {}
virtual ~cPacketHandler() {}
virtual bool ReqLogin(basic::ReqLogin_Packet &packet)
{
cout << "ReqLogin " << endl;
return true;
}
virtual bool Work(basic::Work_Packet &packet)
{
if (g_print)
{
cout << "Work" << endl;
cout << "\tworkid = " << packet.workId << endl;
cout << "\tstatus = " << packet.status << endl;
cout << "\tstatusValue = " << packet.statusValue << endl;
cout << "\t";
for (auto v : packet.path)
cout << v << ",";
cout << endl;
cout << "\tname = " << packet.name << endl;
cout << packet.name << endl;
}
return true;
}
virtual bool AckWork(basic::AckWork_Packet &packet)
{
if (g_print)
cout << "ReqLoading " << packet.result << "\n";
return true;
}
virtual bool func5(basic::func5_Packet &packet)
{
if (g_print)
cout << "recv basic::func5_Packet - " << packet.str << endl;
return true;
}
virtual bool func6(basic::func6_Packet &packet)
{
if (g_print)
cout << "recv basic::func6_Packet - " << packet.value << endl;
return true;
}
};
BOOL CtrlHandler(DWORD fdwCtrlType)
{
g_isLoop = false;
return TRUE;
}
int main(const int argc, const char *argv[])
{
cout << "<bind port=\"10001\">" << endl << endl;
int port = 10001;
if (argc >= 2)
{
port = atoi(argv[2]);
}
if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE))
{
cout << "SetConsoleCtrlHandler failed, code : " << GetLastError() << endl;
return -1;
}
network2::cNetController netController;
network2::cUdpServer server;
cPacketHandler handler;
server.AddProtocolHandler(&handler);
if (!netController.StartUdpServer(&server, port, network2::DEFAULT_PACKETSIZE, 1024, 1))
{
cout << "Error Server Bind" << endl;
}
common::cTimer timer;
timer.Create();
int procPacketCnt = 0;
double oldT = timer.GetSeconds();
while (g_isLoop)
{
procPacketCnt += netController.Process(0.01f);
double curT = timer.GetSeconds();
if (curT - oldT > 1.f)
{
cout << "procPacketCnt = " << procPacketCnt << endl;
procPacketCnt = 0;
oldT = curT;
}
}
netController.Clear();
}
|
Python
|
UTF-8
| 2,638 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
"""Defines MotleyLogConfig to allow config changes should MotleyLogger conflict with other logging extensions."""
class MotleyLogConfig:
"""Configuration settings which can be changed to resolve potential conflicts with other logging extensions.
Used by the motleylog.motleylogger.MotleyLogger class when extending the python standard "logging" facility
to support a new "TRACE" level of messages. Generally these settings do not need to be changed. However, if
other extensions to "logging" also try to define a new "TRACE" level message there could be conflicts.
If this happens the "set" methods in this class should be used to change any conflicting settings. These
changes need to be made before any instances of MotleyLogger are instantiated, however.
"""
TRACE_LEVEL_NUM = 8 # The logging level for the new trace messages.
TRACE_LEVEL_NAME = "TRACE" # The name of the new trace level.
TRACE_METHOD_NAME = "trace" # The name of the logging method dynamically added to the instantiated logger.
@classmethod
def get_trace_level_num(cls):
"""Returns the trace extension logging level number.
Returns:
int : The trace extension logging level number.
"""
return cls.TRACE_LEVEL_NUM
@classmethod
def set_trace_level_num(cls,level_num):
"""Sets the trace extension logging level number.
Parameters:
level_num (int) : The trace extension logging level number.
"""
cls.TRACE_LEVEL_NUM = level_num
@classmethod
def get_trace_level_name(cls):
"""Returns the trace extension logging level name.
Returns:
str : The trace extension logging level name.
"""
return cls.TRACE_LEVEL_NAME
@classmethod
def set_trace_level_name(cls,level_name):
"""Sets the trace extension logging level name.
Parameters:
level_name (str) : The trace extension logging level name.
"""
cls.TRACE_LEVEL_NAME = level_name
@classmethod
def get_trace_method_name(cls):
"""Returns the trace extension dynamically added logger method name.
Returns:
str : The trace extension dynamically added logger method name.
"""
return cls.TRACE_METHOD_NAME
@classmethod
def set_trace_method_name(cls,method_name):
"""Sets the trace extension dynamically added logger method name.
Parameters:
method_name (str) : The trace extension dynamically added logger method name.
"""
cls.TRACE_METHOD_NAME = method_name
|
Java
|
GB18030
| 62,633 | 1.726563 | 2 |
[] |
no_license
|
package com.pvi.ap.reader.activity;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.httpclient.HttpException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.pvi.ap.reader.R;
import com.pvi.ap.reader.activity.pviappframe.PviActivity;
import com.pvi.ap.reader.activity.pviappframe.PviAlertDialog;
import com.pvi.ap.reader.activity.pviappframe.PviBottomBar;
import com.pvi.ap.reader.activity.pviappframe.PviDataList;
import com.pvi.ap.reader.activity.pviappframe.PviUiItem;
import com.pvi.ap.reader.activity.pviappframe.SelectSpinner;
import com.pvi.ap.reader.activity.pviappframe.PviUiItem.OnUiItemClickListener;
import com.pvi.ap.reader.data.common.Error;
import com.pvi.ap.reader.data.common.Logger;
import com.pvi.ap.reader.data.external.manager.CPManager;
import com.pvi.ap.reader.data.external.manager.CPManagerUtil;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
/**
* Ѽ¼ȯϢ鿴
*
* @author
* @author rd040 2010-11-17
*
*/
public class ExpenseProActivity extends PviActivity{
PviDataList listView; //viewʵ
ArrayList<PviUiItem[]> list; //бؼڲϢArrayListÿУÿʹһ鱣PviUiItem
PviBottomBar pbb; //ÿܵײ
private static final String TAG = "ExpenseProActivity";
private static int skinID = 1;//ƤID
private HashMap<String, String> ExpenseHistory = new HashMap<String, String>();
private HashMap<String, Object> userinfo = new HashMap<String, Object>();
private String ticketInfo = "";
private ExpenseListAdapter mExpenseListAdapter;
private ArrayList<HashMap<String, String>> expenseList = new ArrayList<HashMap<String, String>>();
private double totalFee; // ܶ
private double totalTicketFee; // ȯܶ
private TextView phonenum = null; // ʾֻŵUIؼ
private TextView totalexpense = null;
private Button myticket = null; // ҵȯť
private Button select = null; // ҵȯť
private TextView totalConsume = null;
private String selectType;
private int total = 0;
private int perpage = 6;
private int pages = 0;
private int curpage = 0;
private int start = 0;
private TextView mtvTotal; // ʾܼ¼
private String queryYear;
private String queryMonth;
//private TextView mtvQueryYear;
//private TextView mtvQueryMonth;
SelectSpinner yearSelect;
SelectSpinner monthSelect;
//private View mvLastMon;
//private View mvNextMon;
// Чѯꡢ
private ArrayList<String[]> validYearMon = new ArrayList<String[]>();
private int curYearMonIndex; // ǰѯ µ index
private int maxQueryMonthCount = 7; // ɲѯ7
private static final int GET_DATA = 101;
private static final int CLOSE_PD = 102;
public static final int SHOW_PD_LOADING = 103;
public static final int SET_UI_DATA = 104;
public static final int DO_DELETE_MESSAGE = 105;
public static final int SET_UI_DATA_PHONE = 106;
public static final int SET_UI_DATA_EXPLIST = 107;
public static final int SET_UI_DATA_TICKET = 108;
public static final int UPDATA_PAGER = 109;
public static final int ERR_CONNECT_EXP = 201;// 쳣
public static final int ERR_CONNECT_TIMEOUT = 202;// ӳʱ
public static final int ERR_RETCODE_NOT0 = 203; // ӿڷ0
public static final int ERR_CONNECT_FAILED = 204;// ʧ
public static final int ERR_CHECK_PHONENUM = 205;// ֻ
public static final int ERR_XML_PARSER = 206; // xml
private static final int GET_DATA_2 = 1012;
private static final int GET_DATA_3 = 1013;
private static final int SHOW_PD_NETOP = 301; //
private static final int SHOW_PD_NO_TICKET_INFO = 302; //ûдϢ
private static final int NOTE_INFO1 = 303;//ֻܲ7µѼ¼
private static final int NOTE_INFO2 = 304;//ֻܲ鵱ǰʱǰѼ¼
private static String description = null;
private static String type = null;
private static String date = null;
private static String price = null;
/**
* ҵȯб
* add by fly @ 2011-3-4
*/
private List<String> myticketList = null;
/**
* ҵȯб
* add by fly @ 2011-3-7
*/
private int totalCount = 0;
private PviAlertDialog pd;
private Handler mHandler = new H();
private boolean loading = false;//־ǰʱΪtrue
public void showMe(){
if("onResume".equals(selectType)){
Intent tmpIntent = new Intent(
MainpageActivity.SHOW_ME);
Bundle bundleToSend = new Bundle();
bundleToSend.putString("act", "com.pvi.ap.reader.activity.UserCenterActivity");
bundleToSend.putString("actTabName", "Ѽ¼");
bundleToSend.putString("sender", ExpenseProActivity.this.getClass().getName());
tmpIntent.putExtras(bundleToSend);
sendBroadcast(tmpIntent);
//mlvExpenseList.requestFocus();
tmpIntent = null;
bundleToSend = null;
selectType = "";
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mHandler.postAtFrontOfQueue(new Runnable() {
public void run() {
/*View view = (View)mlvExpenseList.getChildAt(0);
//System.out.println("===============1"+view.hasFocus());
if(view != null){
view.setFocusable(true);
}*/
select.requestFocus();
}
});
}
},1000);
}
hideTip();
}
private class H extends Handler {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
switch (msg.what) {
case GET_DATA:// ȡ Ѽ¼
new Thread() {
public void run() {
getExpense.run();
hideTip();
mHandler.post(enableButtons);
}
}.start();
break;
case 1099:
new Thread() {
public void run() {
getExpense.run();
// ȡЧIJѯꡢ
long times = CPManager.getServerTimeAsTimes();
for (int i = maxQueryMonthCount; i > 0; i--) {
//Calendar now = Calendar.getInstance();//ӦԷʱΪ
//Edit by fly
//ʱΪʱ
//2011-3-7
Calendar now = Calendar.getInstance();
now.setTimeInMillis(times);
now.add(Calendar.MONTH, 1 - i);
String tempStr[] = new String[2];
tempStr[0] = "" + now.get(Calendar.YEAR);
tempStr[1] = "" + (now.get(Calendar.MONTH) + 1);
validYearMon.add(tempStr);
}
// ѯһ
curYearMonIndex = maxQueryMonthCount - 1;
getQueryYearMon();
getUserInfo.run();
showMe();
}
}.start();
break;
case GET_DATA_2:// ȡȯϢ
new Thread() {
public void run() {
getHandsetUserTicketInfo.run();
}
}.start();
break;
case GET_DATA_3:// ȡ ûϢ
new Thread() {
public void run() {
// ȡЧIJѯꡢ
for (int i = maxQueryMonthCount; i > 0; i--) {
//Calendar now = Calendar.getInstance();//ӦԷʱΪ
//Edit by fly
//ʱΪʱ
//2011-3-7
long times = CPManager.getServerTimeAsTimes();
Calendar now = Calendar.getInstance();
now.setTimeInMillis(times);
now.add(Calendar.MONTH, 1 - i);
String tempStr[] = new String[2];
tempStr[0] = "" + now.get(Calendar.YEAR);
tempStr[1] = "" + (now.get(Calendar.MONTH) + 1);
validYearMon.add(tempStr);
}
// ѯһ
curYearMonIndex = maxQueryMonthCount - 1;
getQueryYearMon();
getUserInfo.run();
showMe();
}
}.start();
break;
case UPDATA_PAGER:// ·ҳ
updataPager();
break;
case CLOSE_PD:// رʾ
if (pd != null) {
pd.dismiss();
}
hideTip();
break;
case SHOW_PD_LOADING:// ʾϢ
if (pd != null) {
pd.dismiss();
}
//showAlert(getResources().getString(R.string.kyleHint05), false);
break;
case SET_UI_DATA:// ѻȡUI
break;
case SET_UI_DATA_TICKET://
if (pd != null) {
pd.dismiss();
}
pd = new PviAlertDialog(getParent());
pd.setTitle("ҵȯ");
pd.setMessage(ticketInfo);
pd.setCanClose(true);
pd.show();
break;
case SHOW_PD_NETOP://
if (pd != null) {
pd.dismiss();
}
showAlert("ڽ...", false);
break;
case SHOW_PD_NO_TICKET_INFO:// û
if (pd != null) {
pd.dismiss();
}
showAlert(Error.getErrorDescriptionForContent("result-code: 3226"));
break;
case ERR_CONNECT_EXP:// 쳣
if (pd != null) {
pd.dismiss();
}
// showAlert(getResources().getString(
// R.string.my_friend_connecterror), true);
showError();
break;
case ERR_CONNECT_TIMEOUT:// ӳʱ
if (pd != null) {
pd.dismiss();
}
//showAlert("ӳʱ", true);
showError();
break;
case ERR_RETCODE_NOT0:// ӿڷش
if (pd != null) {
pd.dismiss();
}
showAlert("ӿڷ״̬벻ȷ", true);
break;
case ERR_CONNECT_FAILED:// IOʧ
if (pd != null) {
pd.dismiss();
}
//showAlert(getResources().getString(
// R.string.my_friend_connectfailed), true);
showError();
break;
case ERR_CHECK_PHONENUM://
if (pd != null) {
pd.dismiss();
}
showAlert(getResources().getString(
R.string.my_friend_numchecking), true);
break;
case ERR_XML_PARSER:// XML
if (pd != null) {
pd.dismiss();
}
showAlert("XML", true);
break;
case SET_UI_DATA_PHONE:
/* if (userinfo.containsKey("Mobile")) {
phonenum.setText("ֻ룺 "
+ userinfo.get("Mobile").toString());
}*/
phonenum.setText("ֻ룺 "
+ UserInfoActivity.phoneNum);
break;
case SET_UI_DATA_EXPLIST:
setExpenseText();
list.clear();
if(expenseList!=null){
for(int i=0;i<expenseList.size();i++){
final PviUiItem[] items = new PviUiItem[]{
new PviUiItem("text1"+i, 0, 10, 10, 190, 50, "ֻ", false, true, null),
new PviUiItem("text2"+i, 0, 190, 10, 80, 50, "", false, true, null),
new PviUiItem("text3"+i, 0, 270, 10, 220, 50, "״̬", false, true, null),
new PviUiItem("text4"+i, 0, 495,10,65,50, null, false, true, null),
};
String description1=expenseList.get(i).get("contentName");
final String temp1 = expenseList.get(i).get("chargeMode");
String type1 = "";
if (temp1.equals("1")) {
type = "";
} else if (temp1.equals("2")) {
type = "";
} else if (temp1.equals("3")) {
type = "";
} else if (temp1.equals("4")) {
type = "";
} else if (temp1.equals("15")) {
type = "";
} else{
type = "";
}
String date1=expenseList.get(i).get("time");
String dateFormat1 = null;
try {
dateFormat1 = GlobalVar.TimeFormat("yyyy-MM-dd hh:mm:ss",date1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Double fee1 = Double.parseDouble(expenseList.get(i).get("fee"));
String price1=String.valueOf(fee1/100) + "Ԫ";
items[0].text = description1;
items[1].text = type1;
items[2].text = dateFormat1;
items[3].text = price1;
final int k = i;
OnClickListener l = new OnClickListener(){ //new һclick¼
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
description=expenseList.get(k).get("contentName");
final String temp1 = expenseList.get(k).get("chargeMode");
if (temp1.equals("1")) {
type = "";
} else if (temp1.equals("2")) {
type = "";
} else if (temp1.equals("3")) {
type = "";
} else if (temp1.equals("4")) {
type = "";
} else if (temp1.equals("15")) {
type = "";
} else{
type = "";
}
date=expenseList.get(k).get("time");
String dateFormat = null;
try {
dateFormat = GlobalVar.TimeFormat("yyyy-MM-dd hh:mm:ss",date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Double fee = Double.parseDouble(expenseList.get(k).get("fee"));
price=String.valueOf(fee/100) + "Ԫ";
mHandler.sendEmptyMessage(9999);
}
};
items[0].l = l;
items[1].l = l;
items[2].l = l;
items[3].l = l;
list.add(items);
}
}
if(listView!=null){
listView.setData(list);
}
break;
case NOTE_INFO1:
if (pd != null) {
pd.dismiss();
}
showAlert("ֻܲ鵱ǰʱǰ7µѼ¼", true);
break;
case NOTE_INFO2:
if (pd != null) {
pd.dismiss();
}
showAlert("ֻܲ鵱ǰʱǰ7µѼ¼", true);
break;
case 9999: //ʾϸϢ
if (pd != null) {
pd.dismiss();
}
PviAlertDialog showDialog = new PviAlertDialog(getParent());
showDialog.setTitle("Ϣ");
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.showexpenseproinfo,null);
TextView project = (TextView)layout.findViewById(R.id.expenseproject);
TextView expensetype = (TextView)layout.findViewById(R.id.expensetype);
TextView expensetime = (TextView)layout.findViewById(R.id.expensetime);
TextView expenseprice = (TextView)layout.findViewById(R.id.expenseprice);
/*
if(deviceType==1){
int typeOnClick = View.EINK_WAIT_MODE_NOWAIT | View.EINK_WAVEFORM_MODE_GC16 | View.EINK_UPDATE_MODE_FULL;
int typeFocus = View.EINK_WAIT_MODE_NOWAIT | View.EINK_WAVEFORM_MODE_DU | View.EINK_UPDATE_MODE_PARTIAL;
project.setUpdateMode(typeFocus);
expensetype.setUpdateMode(typeFocus);
expensetime.setUpdateMode(typeFocus);
expenseprice.setUpdateMode(typeFocus);
}*/
if(description!=null){
project.setText(description);
}
if(type!=null){
expensetype.setText(type);
}
if(date!=null){
String dataFormat = null;
try {
dataFormat = GlobalVar.TimeFormat("yyyy-MM-dd HH:mm:ss",date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
expensetime.setText(dataFormat);
}
if(price!=null){
expenseprice.setText(price);
}
showDialog.setView(layout);
showDialog.setCanClose(true);
//pd.setTimeout(4000);
showDialog.show();
break;
default:
;
}
}
}
public void showError(){
PviAlertDialog pd2 = new PviAlertDialog(getParent());
pd2.setTitle("ܰʾ");
pd2.setMessage("",Gravity.CENTER);
pd2.setCanClose(false);
pd2.setButton(DialogInterface.BUTTON_POSITIVE, "ȷ",
new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method
// stub
sendBroadcast(new Intent(MainpageActivity.BACK));
return;
}
});
pd2.show();
}
private class ExpenseListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<HashMap<String, String>> mList;
public ExpenseListAdapter(Context context,
ArrayList<HashMap<String, String>> list) {
mInflater = LayoutInflater.from(context);
mList = list;
}
public int getCount() {
return mList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.expenselistitem_ui1, null);
holder = new ViewHolder();
holder.tvExpName = (TextView) convertView
.findViewById(R.id.expname);
holder.tvExpType = (TextView) convertView
.findViewById(R.id.exptype);
holder.tvExpTime = (TextView) convertView
.findViewById(R.id.exptime);
holder.tvExpFee = (TextView) convertView
.findViewById(R.id.expfee);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
description=mList.get(position).get("contentName");
final String temp1 = mList.get(position).get("chargeMode");
if (temp1.equals("1")) {
type = "";
} else if (temp1.equals("2")) {
type = "";
} else if (temp1.equals("3")) {
type = "";
} else if (temp1.equals("4")) {
type = "";
} else if (temp1.equals("15")) {
type = "";
} else{
type = "";
}
date=mList.get(position).get("time");
Double fee = Double.parseDouble(mList.get(position).get("fee"));
price=String.valueOf(fee/100) + "Ԫ";
final int p = position;
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(p >= mList.size()){
return;
}
description=mList.get(p).get("contentName");
final String temp1 = mList.get(p).get("chargeMode");
if (temp1.equals("1")) {
type = "";
} else if (temp1.equals("2")) {
type = "";
} else if (temp1.equals("3")) {
type = "";
} else if (temp1.equals("4")) {
type = "";
} else if (temp1.equals("15")) {
type = "";
} else{
type = "";
}
date=mList.get(p).get("time");
Double fee = Double.parseDouble(mList.get(p).get("fee"));
price=String.valueOf(fee/100) + "Ԫ";
mHandler.sendEmptyMessage(9999);
/*
Intent tmpIntent = new Intent(MainpageActivity.START_ACTIVITY);
Bundle bundleToSend = new Bundle();
bundleToSend.putString("startType", "allwaysCreate");
bundleToSend.putString("actID", "ACT14310");
bundleToSend.putString("description",description);
bundleToSend.putString("type", type);
bundleToSend.putString("date", date);
bundleToSend.putString("price", price);
tmpIntent.putExtras(bundleToSend);
activity.sendBroadcast(tmpIntent);
tmpIntent = null;
bundleToSend = null;*/
}
});
try {
holder.tvExpName
.setText(description);
holder.tvExpType.setText(type);
String dataFormat = null;
try {
dataFormat = GlobalVar.TimeFormat("yyyy-MM-dd hh:mm:ss",date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
holder.tvExpTime.setText(dataFormat);
holder.tvExpFee.setText(price);
} catch (Exception e) {
}
if(deviceType==1){
// convertView.setUpdateMode(UPDATEMODE_5);
}
return convertView;
}
class ViewHolder {
TextView tvExpName;
TextView tvExpType;
TextView tvExpTime;
TextView tvExpFee;
}
}
@Override
public void initControls() {
super.initControls();
phonenum = (TextView) this.findViewById(R.id.phonenum);
totalexpense = (TextView) this.findViewById(R.id.totalexpense);
myticket = (Button) this.findViewById(R.id.myticket);
select = (Button) this.findViewById(R.id.select);
select.setFocusable(true);
select.setFocusableInTouchMode(true);
totalConsume = (TextView) this.findViewById(R.id.totalConsume);
// pager
mtvTotal = (TextView) findViewById(R.id.total);
//mvLastMon = findViewById(R.id.lastmon);
//mvNextMon = findViewById(R.id.nextmon);
//mtvQueryYear = (TextView) findViewById(R.id.queryYear);
//mtvQueryMonth = (TextView) findViewById(R.id.queryMonth);
yearSelect = (SelectSpinner) findViewById(R.id.yearselect);
monthSelect = (SelectSpinner) findViewById(R.id.monthselect);
long times = CPManager.getServerTimeAsTimes();
Calendar now = Calendar.getInstance();
now.setTimeInMillis(times);
LinkedHashMap yearMap = new LinkedHashMap();
yearMap.put(now.get(Calendar.YEAR)+"",now.get(Calendar.YEAR));
yearMap.put(now.get(Calendar.YEAR) -1 +"",now.get(Calendar.YEAR)-1);
//yearMap.put("2011",2011);
//yearMap.put("2010",2010);
yearSelect.setKey_value(yearMap);
yearSelect.setSelectKey(now.get(Calendar.YEAR)+"");
monthSelect.setSelectKey((now.get(Calendar.MONTH)+1)+"");
LinkedHashMap monthMap = new LinkedHashMap();
monthMap.put("1","1");
monthMap.put("2","2");
monthMap.put("3","3");
monthMap.put("4","4");
monthMap.put("5","5");
monthMap.put("6","6");
monthMap.put("7","7");
monthMap.put("8","8");
monthMap.put("9","9");
monthMap.put("10","10");
monthMap.put("11","11");
monthMap.put("12","12");
monthSelect.setKey_value(monthMap);
if(deviceType==1){
// findViewById(R.id.yearselect).invalidate(0, 0, 600,800,UPDATEMODE_4);
// phonenum.setUpdateMode(UPDATEMODE_5);
// totalexpense.setUpdateMode(UPDATEMODE_5);
// myticket.setUpdateMode(UPDATEMODE_5);
// select.setUpdateMode(UPDATEMODE_5);
// totalConsume.setUpdateMode(UPDATEMODE_5);
// yearSelect.setUpdateMode(UPDATEMODE_5);
// monthSelect.setUpdateMode(UPDATEMODE_5);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
perpage=6;
setContentView(R.layout.expenselist_ui1);
listView= (PviDataList)findViewById(R.id.list);
list = new ArrayList<PviUiItem[]>();
this.showPager = true;
pbb = ((GlobalVar)getApplication()).pbb;
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
selectType = "onResume";
showMessage("ڼ...");
// ʱȡûϢȡ¼¼
//mHandler.sendEmptyMessage(GET_DATA_3);
//mtvQueryYear.setText(queryYear);
//mtvQueryMonth.setText(queryMonth);
mHandler.sendEmptyMessage(1099);
}
private void getQueryYearMon() {
String tempStr[] = new String[2];
//tempStr = validYearMon.get(curYearMonIndex);
queryYear = yearSelect.getSelectValue();
queryMonth = monthSelect.getSelectValue();
//mtvQueryYear.setText(queryYear);
//mtvQueryMonth.setText(queryMonth);
}
private Runnable getExpense = new Runnable() {
@Override
public void run() {
//mHandler.sendEmptyMessage(SHOW_PD_LOADING);
loading = true;
Logger.i(TAG, "getExpense(String year=" + queryYear
+ ", String month=" + queryMonth + "):");
HashMap ahmHeaderMap = CPManagerUtil.getHeaderMap();
HashMap ahmNamePair = CPManagerUtil.getAhmNamePairMap();
//ahmNamePair.put("begintime", queryYear + queryMonth + "01");
Calendar tempCal = Calendar.getInstance();
queryYear = yearSelect.getSelectValue();
queryMonth = monthSelect.getSelectValue();
try{
tempCal.set(Integer.parseInt(queryYear), Integer
.parseInt(queryMonth) - 1, 1);
}catch (Exception e) {
// TODO: handle exception
//tempCal.set(Integer.parseInt(queryYear), Integer
// .parseInt(queryMonth) - 1, 1);
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
final String begintime = formatter.format(tempCal.getTime());
tempCal.add(Calendar.MONTH, 1);
tempCal.add(Calendar.DATE, -1);
final String endtime = formatter.format(tempCal.getTime());
//Logger.i(TAG,"begintime:"+begintime+", endtime:"+endtime);
ahmNamePair.put("begintime", begintime);
ahmNamePair.put("endtime", endtime);
if (start > 0) {
ahmNamePair.put("start", "" + start);
}
ahmNamePair.put("count", "" + perpage);
HashMap responseMap = null;
try {
// POSTʽ
responseMap = CPManager.getConsumeHistoryList(ahmHeaderMap,
ahmNamePair);
//mHandler.sendEmptyMessage(CLOSE_PD);
if(responseMap.get("result-code")!=null){
Logger.i(TAG,"result-code:"+responseMap.get("result-code").toString());
}
if (!responseMap.get("result-code").toString().contains(
"result-code: 0")) {
mHandler.sendEmptyMessage(ERR_RETCODE_NOT0);
Logger.i(TAG, responseMap.get("result-code").toString());
mHandler.post(enableButtons);
loading = false;
return;
}
} catch (HttpException e) {
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_CONNECT_EXP);
mHandler.post(enableButtons);
loading = false;
return;
} catch (SocketTimeoutException e) {
mHandler.sendEmptyMessage(ERR_CONNECT_TIMEOUT);
mHandler.post(enableButtons);
loading = false;
return;
} catch (IOException e) {
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_CONNECT_FAILED);
mHandler.post(enableButtons);
loading = false;
return;
}
byte[] responseBody = (byte[]) responseMap.get("ResponseBody");
// ݷֽ鹹DOM
Document dom = null;
try {
String xml = new String(responseBody);
xml = xml.replaceAll(">\\s+?<", "><");
dom = CPManagerUtil.getDocumentFrombyteArray(xml.getBytes());
} catch (ParserConfigurationException e) {
Logger.e(TAG, "ParserConfigurationException" + e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
} catch (SAXException e) {
Logger.e(TAG, "SAXException" + e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
} catch (IOException e) {
Logger.e(TAG, "IOException" + e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
}
try {
//б
mHandler.post(new Runnable(){
@Override
public void run() {
expenseList.clear();
}});
Element root = dom.getDocumentElement();
// ΪXMLĴ
NodeList nl1 = root.getChildNodes();
nl1 = nl1.item(0).getChildNodes();
int nl1Count = nl1.getLength();
for (int i = 0; i < nl1Count; i++) {
Element el1 = (Element) nl1.item(i);
if (el1.getNodeName().equals("totalRecordCount")) {
total = Integer.parseInt(el1.getFirstChild()
.getNodeValue());
pages = total / perpage;
if (total % perpage > 0) {
pages = pages + 1;
}
if (curpage == 0 && total > 0) {
curpage = 1;
}
mHandler.sendEmptyMessage(UPDATA_PAGER);
} else if (el1.getNodeName().equals("totalFee")) {
totalFee = Double.parseDouble(el1.getFirstChild()
.getNodeValue());
} else if (el1.getNodeName().equals("totalTicketFee")) {
totalTicketFee = Double.parseDouble(el1.getFirstChild()
.getNodeValue());
} else if (el1.getNodeName().equals("ConsumeRecordList")) {
NodeList nl2 = el1.getChildNodes();
int nl2Count = nl2.getLength();
for (int j = 0; j < nl2Count; j++) {
Element el2 = (Element) nl2.item(j);
if (el2.getNodeName().equals("ConsumeRecord")) {
final HashMap<String, String> tempHM = new HashMap<String, String>();
NodeList nl3 = el2.getChildNodes();
int nl3Count = nl3.getLength();
for (int k = 0; k < nl3Count; k++) {
Element el3 = (Element) nl3.item(k);
tempHM.put(el3.getNodeName(), el3
.getFirstChild().getNodeValue());
}
mHandler.post(new Runnable(){
@Override
public void run() {
expenseList.add(tempHM);
}});
}
}
}
}
mHandler.sendEmptyMessage(SET_UI_DATA_EXPLIST);
mHandler.post(enableButtons);
} catch (Exception e) {
Logger.e(TAG, "xml parser error:" + e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
}
loading = false;
}
};
private Runnable getUserInfo = new Runnable() {
@Override
public void run() {
loading = true;
/* Logger.i(TAG, "getUserInfo");
// Call ContentManager to getUserInfo then set to display
HashMap ahmHeaderMap = CPManagerUtil.getHeaderMap();
HashMap ahmNamePair = CPManagerUtil.getAhmNamePairMap();
HashMap responseMap = null;
try {
//mHandler.sendEmptyMessage(SHOW_PD_LOADING);
responseMap = CPManager.getUserInfo(ahmHeaderMap, ahmNamePair);
//mHandler.sendEmptyMessage(CLOSE_PD);
if (!responseMap.get("result-code").toString().contains(
"result-code: 0")) {
mHandler.sendEmptyMessage(ERR_RETCODE_NOT0);
Logger.i(TAG, responseMap.get("result-code").toString());
mHandler.post(enableButtons);
loading = false;
return;
}
} catch (HttpException e) {
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_CONNECT_EXP);
mHandler.post(enableButtons);
loading = false;
return;
} catch (SocketTimeoutException e) {
mHandler.sendEmptyMessage(ERR_CONNECT_TIMEOUT);
mHandler.post(enableButtons);
loading = false;
return;
} catch (IOException e) {
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_CONNECT_EXP);
mHandler.post(enableButtons);
loading = false;
return;
}
byte[] responseBody = (byte[]) responseMap.get("ResponseBody");
Document dom = null;
try {
dom = CPManagerUtil.getDocumentFrombyteArray(responseBody);
} catch (ParserConfigurationException e) {
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
} catch (SAXException e) {
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
} catch (IOException e) {
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
}
Element root = dom.getDocumentElement();
NodeList nl = root.getElementsByTagName("Parameter");
String name = "";
String value = "";
Element temp = null;
for (int i = 0; i < nl.getLength(); i++) {
temp = (Element) nl.item(i);
name = temp.getElementsByTagName("name").item(0)
.getFirstChild().getNodeValue();
try {
value = temp.getElementsByTagName("value").item(0)
.getFirstChild().getNodeValue();
} catch (Exception e) {
value = "";
}
userinfo.put(name, value);
}
*/
mHandler.sendEmptyMessage(SET_UI_DATA_PHONE);
mHandler.post(enableButtons);
loading = false;
}
};
protected int fetchFlag;
private Runnable getHandsetUserTicketInfo = new Runnable() {
@Override
public void run() {
loading = true;
ticketInfo = "";
fetchFlag = 0;
getMyticketList();
HashMap ahmHeaderMap = CPManagerUtil.getHeaderMap();
HashMap ahmNamePair = CPManagerUtil.getAhmNamePairMap();
HashMap responseMap = null;
try {
//mHandler.sendEmptyMessage(SHOW_PD_LOADING);
responseMap = CPManager.getHandsetUserTicketInfo(ahmHeaderMap,
ahmNamePair);
//mHandler.sendEmptyMessage(CLOSE_PD);
if (responseMap.get("result-code").toString().contains(
"result-code: 3226")) {
fetchFlag = -2;
mHandler.sendEmptyMessage(SHOW_PD_NO_TICKET_INFO);
mHandler.post(enableButtons);
loading = false;
return;
} else if (!responseMap.get("result-code").toString().contains(
"result-code: 0")) {
// ӿڷر״̬
fetchFlag = -1;
mHandler.sendEmptyMessage(ERR_RETCODE_NOT0);
mHandler.post(enableButtons);
loading = false;
return;
}
} catch (HttpException e) {
fetchFlag = -1;
// 쳣 ,һԭΪ URL
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_CONNECT_EXP);
mHandler.post(enableButtons);
loading = false;
return;
} catch (SocketTimeoutException e) {
fetchFlag = -1;
mHandler.sendEmptyMessage(ERR_CONNECT_TIMEOUT);
mHandler.post(enableButtons);
loading = false;
return;
} catch (IOException e) {
fetchFlag = -1;
// IO쳣 ,һԭΪ
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_CONNECT_FAILED);
mHandler.post(enableButtons);
loading = false;
return;
}
byte[] responseBody = (byte[]) responseMap.get("ResponseBody");
// ݷֽ鹹DOM
Document dom = null;
try {
dom = CPManagerUtil.getDocumentFrombyteArray(responseBody);
} catch (ParserConfigurationException e) {
fetchFlag = -1;
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
} catch (SAXException e) {
fetchFlag = -1;
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
} catch (IOException e) {
fetchFlag = -1;
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
}
Element root = dom.getDocumentElement();
// ΪXMLĴ
try {
NodeList nl = root.getElementsByTagName("ticketInfo");
if (nl.getLength() != 0) {
Element element = (Element) nl.item(0);
ticketInfo = element.getFirstChild().getNodeValue();
fetchFlag = 1;
//mHandler.sendEmptyMessage(SET_UI_DATA_TICKET);
//mHandler.post(enableButtons);
}
} catch (Exception e) {
fetchFlag = -1;
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
}
loading = false;
//תȯбҳ
Intent tmpIntent = new Intent(MainpageActivity.START_ACTIVITY);
Bundle bundleToSend = new Bundle();
bundleToSend.putString("startType", "allwaysCreate");
bundleToSend.putString("actID", "ACT14320");
bundleToSend.putInt("totalCount",totalCount);
bundleToSend.putString("ticketInfo",ticketInfo);
bundleToSend.putStringArrayList("ticketList", (ArrayList<String>)myticketList);
tmpIntent.putExtras(bundleToSend);
sendBroadcast(tmpIntent);
tmpIntent = null;
bundleToSend = null;
}
};
// ͳı
private void setExpenseText() {
Logger.i(TAG, "setExpenseText");
this.totalexpense.setText("ܼƣ " + totalFee / 100 + "Ԫ(ȯ"
+ totalTicketFee / 100 + "Ԫ)");
this.totalConsume.setText(totalFee / 100 + " Ԫ");
}
@Override
public void bindEvent() {
super.bindEvent();
//ҵȯ
this.myticket.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mHandler.post(disableButtons);
final Runnable showTip = new Runnable() {
@Override
public void run() {
final Intent tmpIntent = new Intent(
MainpageActivity.SHOW_TIP);
final Bundle sndBundle = new Bundle();
sndBundle.putString("pviapfStatusTip","ڽȯб...");
//sndBundle.putString("pviapfStatusTipTime",
// "2000");
tmpIntent.putExtras(sndBundle);
sendBroadcast(tmpIntent);
}
};
new Thread() {
public void run() {
mHandler.post(showTip);
}
}.start();
getTicketInfo();
}
});
this.select.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
if (isOutOfDate()) {
mHandler.sendEmptyMessage(NOTE_INFO2);
mHandler.post(enableButtons);
return;
}
// if(deviceType==1){
// getWindow().
// getDecorView()
// .getRootView()
// .setUpdateMode(View.EINK_WAIT_MODE_WAIT |
// View.EINK_WAVEFORM_MODE_GC16 |
// View.EINK_UPDATE_MODE_FULL);
// }
showMessage("ڼ...");
mHandler.post(disableButtons);
nextMon();
}
});
}
/*
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
return super.onKeyUp(keyCode, event);
}*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
//System.out.println(mlvExpenseList.hasFocus());
if(!listView.hasFocus()){
return false;
}
if(curpage > 1){
mHandler.post(disableButtons);
prevPage();
return true;
}else{
return true;
}
}
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
//System.out.println(mlvExpenseList.hasFocus());
if(!listView.hasFocus()){
return false;
}
if(curpage < pages){
mHandler.post(disableButtons);
nextPage();
return true;
}else{
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private OnUiItemClickListener menuclick = new OnUiItemClickListener(){
@Override
public void onUiItemClick(PviUiItem item) {
closePopmenu();
String vTag = item.id;
if (vTag.equals("myticket")) {
getTicketInfo();
} else if (vTag.equals("lastmon")) {//
prevMon();
} else if (vTag.equals("nextmon")) {//
nextMon();
}
}};
private void getTicketInfo() {
if(!loading){
mHandler.post(disableButtons);
mHandler.sendEmptyMessage(GET_DATA_2);
}
}
public OnUiItemClickListener getMenuclick() {
return this.menuclick;
}
/* private Runnable showTicket = new Runnable() {
@Override
public void run() {
}
};
private Thread showTicket = new Thread() {
@Override
public void run() {
try {
sleep(100);
} catch (InterruptedException e) {
;
}
int i = 0;
while (i < 50) {
if (fetchFlag != 0) {
if (fetchFlag == -2) {
ticketInfo = "ûȯϢ";
} else if (fetchFlag == -1) {
ticketInfo = "ԲʱδܻȯϢԺԡ";
}
pd = new PviAlertDialog(getParent());
pd.setTitle("ҵȯ");
pd.setMessage(ticketInfo);
pd.setCanClose(true);
pd.show();
return;
}
try {
sleep(100);
} catch (InterruptedException e) {
;
}
i++;
}
Logger.i(TAG, "showTicket timeout");
}
};*/
private void prevPage() {
if(!loading){
if(isOutOfDate()){
mHandler.sendEmptyMessage(NOTE_INFO2);
mHandler.post(enableButtons);
return;
}
if (total > 0 && curpage > 1) {
showMessage("ڼ...");
mHandler.post(disableButtons);
curpage = curpage - 1;
start = (curpage - 1) * perpage + 1;
mHandler.sendEmptyMessage(GET_DATA);
}
}
}
private void nextPage() {
if(!loading){
if(isOutOfDate()){
mHandler.sendEmptyMessage(NOTE_INFO2);
mHandler.post(enableButtons);
return;
}
if (total > 0 && curpage < pages) {
showMessage("ڼ...");
mHandler.post(disableButtons);
curpage = curpage + 1;
start = (curpage - 1) * perpage + 1;
mHandler.sendEmptyMessage(GET_DATA);
}
//mHandler.post(enableButtons);
}
}
private void prevMon() {
if(!loading){
mHandler.post(disableButtons);
Logger.i(TAG,"+prevMon");
// ҳʼ
start = 0;
curpage = 0;
// ꡢ¸
if (curYearMonIndex > 0) {
curYearMonIndex--;
getQueryYearMon();
// ݲѯ
mHandler.sendEmptyMessage(GET_DATA);
} else {
// ʾûֻܲô
mHandler.sendEmptyMessage(NOTE_INFO1);
mHandler.post(enableButtons);
return;
}
}else{
Logger.i(TAG,"-prevMon");
}
}
public boolean isOutOfDate(){
boolean isOutOfDate = true;
String year = yearSelect.getSelectValue();
String month = monthSelect.getSelectValue();
for(int i = 0;i<validYearMon.size();i++){
String[] str = validYearMon.get(i);
if(year.equals(str[0]) && month.equals(str[1])){
isOutOfDate = false;
return isOutOfDate;
}
}
return isOutOfDate;
}
private void nextMon() {
if(!loading){
mHandler.post(disableButtons);
Logger.i(TAG,"+nextMon");
// ҳʼ
if (!isOutOfDate()) {
start = 0;
curpage = 0;
curYearMonIndex++;
getQueryYearMon();
// ݲѯ
mHandler.sendEmptyMessage(GET_DATA);
} else {
// ʾûֻܲô
mHandler.sendEmptyMessage(NOTE_INFO2);
mHandler.post(enableButtons);
return;
}
// ꡢ¸
/*
if (curYearMonIndex < maxQueryMonthCount - 1) {
curYearMonIndex++;
getQueryYearMon();
// ݲѯ
mHandler.sendEmptyMessage(GET_DATA);
} else {
// ʾûֻܲô
mHandler.sendEmptyMessage(NOTE_INFO2);
mHandler.post(enableButtons);
return;
}*/
}else{
Logger.i(TAG,"-nextMon");
}
}
private void showAlert(String message, boolean canClose) {
pd = new PviAlertDialog(getParent());
pd.setTitle(getResources().getString(R.string.my_friend_hint));
pd.setMessage(message);
pd.setCanClose(canClose);
pd.setTimeout(4000);
pd.show();
}
public void showAlert(String message){
if(pd!=null && pd.isShowing()){
pd.dismiss();
}
pd = new PviAlertDialog(getParent());
pd.setTitle(getResources().getString(R.string.my_friend_hint));
//pd.setMessage(message);
TextView tv = new TextView(ExpenseProActivity.this);
tv.setText(message);
tv.setTextSize(21);
tv.setGravity(Gravity.CENTER);
tv.setTextColor(Color.BLACK);
pd.setView(tv);
pd.setCanClose(true);
pd.show();
}
private void updataPager() {
int a = curpage;
int b = (pages==0?1:pages);
if(a > b){
a = b;
}
updatePagerinfo(a+" / "+b);
}
private Runnable enableButtons = new Runnable(){
@Override
public void run() {
myticket.setClickable(true);
select.setClickable(true);
}
};
private Runnable disableButtons = new Runnable(){
@Override
public void run() {
myticket.setClickable(false);
select.setClickable(false);
}
};
//ȡҵȯбĵһҳ
public void getMyticketList(){
if(myticketList != null){
return;
}
myticketList = new ArrayList<String>();
HashMap ahmHeaderMap = CPManagerUtil.getHeaderMap();
HashMap ahmNamePair = CPManagerUtil.getAhmNamePairMap();
ahmNamePair.put("start", "0");
ahmNamePair.put("count", "7");
HashMap responseMap = null;
try {
//mHandler.sendEmptyMessage(SHOW_PD_LOADING);
responseMap = CPManager.getUserTicketList(ahmHeaderMap,
ahmNamePair);
//mHandler.sendEmptyMessage(CLOSE_PD);
if (responseMap.get("result-code").toString().contains(
"result-code: 3226")) {
fetchFlag = -2;
mHandler.sendEmptyMessage(SHOW_PD_NO_TICKET_INFO);
mHandler.post(enableButtons);
loading = false;
return;
} else if (!responseMap.get("result-code").toString().contains(
"result-code: 0")) {
// ӿڷر״̬
fetchFlag = -1;
mHandler.sendEmptyMessage(ERR_RETCODE_NOT0);
mHandler.post(enableButtons);
loading = false;
return;
}
} catch (HttpException e) {
fetchFlag = -1;
// 쳣 ,һԭΪ URL
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_CONNECT_EXP);
mHandler.post(enableButtons);
loading = false;
return;
} catch (SocketTimeoutException e) {
fetchFlag = -1;
mHandler.sendEmptyMessage(ERR_CONNECT_TIMEOUT);
mHandler.post(enableButtons);
loading = false;
return;
} catch (IOException e) {
fetchFlag = -1;
// IO쳣 ,һԭΪ
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_CONNECT_FAILED);
mHandler.post(enableButtons);
loading = false;
return;
}
byte[] responseBody = (byte[]) responseMap.get("ResponseBody");
try {
System.out.println(CPManagerUtil.getStringFrombyteArray(responseBody));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// ݷֽ鹹DOM
Document dom = null;
try {
dom = CPManagerUtil.getDocumentFrombyteArray(responseBody);
} catch (ParserConfigurationException e) {
fetchFlag = -1;
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
} catch (SAXException e) {
fetchFlag = -1;
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
} catch (IOException e) {
fetchFlag = -1;
Logger.e(TAG, e.getMessage());
mHandler.sendEmptyMessage(ERR_XML_PARSER);
mHandler.post(enableButtons);
loading = false;
return;
}
Element root = dom.getDocumentElement();
NodeList countList = root.getElementsByTagName("totalRecordCount");
totalCount = Integer.parseInt(countList.item(0).getFirstChild().getNodeValue());
System.out.println("=========totalCount========="+totalCount);
NodeList nl = root.getElementsByTagName("ticketInfo");
Element friendtemp = null;
NodeList friendinfotemp = null;
HashMap<String, Object> map = null;
if(nl!=null){
for (int i = 0; i < nl.getLength(); i++) {
//map = new HashMap<String, Object>();
//friendtemp = (Element) nl.item(i);
//friendinfotemp = friendtemp.getElementsByTagName("ticketInfo");
myticketList.add(nl.item(i).getFirstChild().getNodeValue());
}
}
System.out.println("====myticketList==="+myticketList);
loading = false;
}
@Override
public void OnNextpage() {
// TODO Auto-generated method stub
if(curpage < pages){
mHandler.post(disableButtons);
nextPage();
}
}
@Override
public void OnPrevpage() {
// TODO Auto-generated method stub
if(curpage > 1){
mHandler.post(disableButtons);
prevPage();
}
}
}
|
Java
|
UTF-8
| 766 | 2.15625 | 2 |
[] |
no_license
|
package ash.org;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class BaseClass {
public static WebDriver driver;
public static WebDriver getdriver() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\devap\\Documents\\Driver Jars\\chromedriver.exe ");
return driver = new ChromeDriver();
}
//url launch
public static void geturl(String url) {
driver.get(url);
}
//insert data
public static void insertdata(WebElement element, String text) {
element.sendKeys(text);
}
//click
public static void uclick(WebElement element) {
element.click();
}
//quit
public static void uquit() {
driver.quit();
}
}
|
Java
|
ISO-8859-1
| 8,030 | 2.9375 | 3 |
[] |
no_license
|
class EditorDeImagem {
public static ColorImage img;
private Color c;
private int r;
private int g;
private int b;
private final int MIN = 0;
private final int MAX = 255;
private double[][] sepiaValues = {{0.40,0.77,0.20},{0.35,0.69,0.17},{0.27,0.53,0.13}};
public static final int NOISE = 0;
public static final int CONTRAST = 1;
public static final int VIGNETTE = 2;
public static final int SEPIA = 3;
public static final int BLUR = 4;
public static final int FILM = 5;
private ColorImage[] history = new ColorImage[999];
private int iter = 0;
private boolean redo;
public EditorDeImagem(ColorImage img){
EditorDeImagem.img = img.copy();
history[iter] = img.copy();
iter = iter+1;
redo = false;
}
public ColorImage getImage(){
return img;
}
public void noise(int n){
redo = false;
for(int x=0; x<img.getWidth(); x++){
for(int y=0; y<img.getHeight(); y++){
int r1 = (int)(Math.random()*2);
if(r1==1){
int r2 = (int)(Math.random()*2);
c = img.getColor(x, y);
if(r2==0){
r = c.getR()+n;
g = c.getG()+n;
b = c.getB()+n;
if(r>MAX)
r = MAX;
if(r<MIN)
r = MIN;
if(g>MAX)
g = MAX;
if(g<MIN)
g = MIN;
if(b>MAX)
b = MAX;
if(b<MIN)
b = MIN;
c = new Color(r, g, b);
img.setColor(x, y, c);
}
else{
r = c.getR()-n;
g = c.getG()-n;
b = c.getB()-n;
if(r>MAX)
r = MAX;
if(r<MIN)
r = MIN;
if(g>MAX)
g = MAX;
if(g<MIN)
g = MIN;
if(b>MAX)
b = MAX;
if(b<MIN)
b = MIN;
c = new Color(r, g, b);
img.setColor(x, y, c);
}
}
}
}
history[iter] = img.copy();
iter = iter+1;
}
public void contrast(int n){
redo = false;
for(int x=0; x<img.getWidth(); x++){
for(int y=0; y<img.getHeight(); y++){
c = img.getColor(x,y);
r = c.getR();
g = c.getG();
b = c.getB();
if(c.getLuminance()>128){
r = r+n;
g = g+n;
b = b+n;
}
else{
r = r-n;
g = g-n;
b = b-n;
}
if(r>MAX){
r = MAX;
}
if(r<MIN){
r = MIN;
}
if(g>MAX){
g = MAX;
}
if(g<MIN){
g = MIN;
}
if(b>MAX){
b = MAX;
}
if(b<MIN){
b = MIN;
}
c = new Color(r,g,b);
img.setColor(x, y, c);
}
}
history[iter] = img.copy();
iter = iter+1;
}
public void vignette(int d){
redo = false;
if(d<0){
throw new IllegalArgumentException("Introduza um valor positivo");
}
int cx = img.getWidth()/2;
int cy = img.getHeight()/2;
for(int x=0; x<img.getWidth(); x++){
for(int y=0; y<img.getHeight(); y++){
int dc = (int)(Math.sqrt((x-cx)*(x-cx)+(y-cy)*(y-cy)));
if(dc>d){
c = img.getColor(x,y);
r = c.getR()-(d*dc)/100;
g = c.getG()-(d*dc)/100;
b = c.getB()-(d*dc)/100;
if(r>MAX){
r = MAX;
}
if(r<MIN){
r = MIN;
}
if(g>MAX){
g = MAX;
}
if(g<MIN){
g = MIN;
}
if(b>MAX){
b = MAX;
}
if(b<MIN){
b = MIN;
}
c = new Color(r, g, b);
img.setColor(x, y, c);
}
}
}
history[iter] = img.copy();
iter = iter+1;
}
public void sepia(){
redo = false;
for(int x=0; x<img.getWidth(); x++){
for(int y=0; y<img.getHeight(); y++){
c = img.getColor(x, y);
r = (int)(c.getR()*sepiaValues[0][0] + c.getG()*sepiaValues[0][1] + c.getB()*sepiaValues[0][2]);
g = (int)(c.getR()*sepiaValues[1][0] + c.getG()*sepiaValues[1][1] + c.getB()*sepiaValues[1][2]);
b = (int)(c.getR()*sepiaValues[2][0] + c.getG()*sepiaValues[2][1] + c.getB()*sepiaValues[2][2]);
if(r>MAX){
r = MAX;
}
if(r<MIN){
r = MIN;
}
if(g>MAX){
g = MAX;
}
if(g<MIN){
g = MIN;
}
if(b>MAX){
b = MAX;
}
if(b<MIN){
b = MIN;
}
c = new Color(r, g, b);
img.setColor(x, y, c);
}
}
history[iter] = img.copy();
iter = iter+1;
}
public void blur(int r){
redo = false;
if(r<0){
throw new IllegalArgumentException("Introduza um valor positivo");
}
int it = 0;
this.r = 0;
b = 0;
g = 0;
ColorImage newImg = new ColorImage(img.getWidth(), img.getHeight());
newImg = img.copy();
for(int x=0; x<img.getWidth(); x++){
for(int y=0; y<img.getHeight(); y++){
for(int i=x-r; i<x+r;i++){
for(int j=y-r; j<y+r; j++){
if(j>=0 && i>=0 && j<img.getHeight() && i<img.getWidth()){
c = newImg.getColor(i,j);
this.r = this.r+c.getR();
g = g+c.getG();
b = b+c.getB();
it = it+1;
}
}
}
this.r = this.r/it;
g = g/it;
b = b/it;
it = 0;
if(r>MAX){
r = MAX;
}
if(r<MIN){
r = MIN;
}
if(g>MAX){
g = MAX;
}
if(g<MIN){
g = MIN;
}
if(b>MAX){
b = MAX;
}
if(b<MIN){
b = MIN;
}
c = new Color(this.r, g, b);
this.r=0;
g=0;
b=0;
img.setColor(x, y, c);
}
}
history[iter] = img.copy();
iter = iter+1;
}
public void film(int l){
redo = false;
if(l<0){
throw new IllegalArgumentException("Introduza um valor positivo");
}
for(int x=0; x<l; x++){
for(int y=0; y<img.getHeight(); y++){
img.setColor(x,y,Color.BLACK);
if(x>l/4 && x<(3*l/4)){
img.setColor(x,y,Color.WHITE);
}
if(y<(img.getHeight()/10) || (y<img.getHeight()/3 && y>img.getHeight()/4) || (y<((2*img.getHeight()/4)+((img.getHeight()/3)-(img.getHeight()/4))) && y>2*img.getHeight()/4) || (y<((3*img.getHeight()/4)+((img.getHeight()/3)-(img.getHeight()/4))) && y>3*img.getHeight()/4) || (y<img.getHeight() && y>((img.getHeight())-((img.getHeight()/3)-(img.getHeight()/4)))+10)){
img.setColor(x,y,Color.BLACK);
}
}
}
for(int i=img.getWidth()-l-1; i<img.getWidth(); i++){
for(int j=0; j<img.getHeight(); j++) {
img.setColor(i,j,Color.BLACK);
if(i>img.getWidth()-(3*l/4) && i<img.getWidth()-l/4){
img.setColor(i,j,Color.WHITE);
}
if(j<(img.getHeight()/10) || (j<img.getHeight()/3 && j>img.getHeight()/4) || (j<((2*img.getHeight()/4)+((img.getHeight()/3)-(img.getHeight()/4))) && j>2*img.getHeight()/4) || (j<((3*img.getHeight()/4)+((img.getHeight()/3)-(img.getHeight()/4))) && j>3*img.getHeight()/4) || (j<img.getHeight() && j>((img.getHeight())-((img.getHeight()/3)-(img.getHeight()/4)))+10)){
img.setColor(i,j,Color.BLACK);
}
}
}
history[iter] = img.copy();
iter = iter+1;
}
public void applyCompositeEffect(EfeitoComposto c){
redo = false;
c.apply();
history[iter] = img.copy();
iter = iter+1;
//Aps ser criado um objeto do tipo EfeitoComposto necessrio utilizar
//o procedimento getImage para visualizar o efeito composto a ser aplicado
}
public void undo(){
redo = true;
if(iter<=1){
for(int z=0; z<history[0].getWidth(); z++){
for(int y=0; y<history[0].getHeight(); y++){
img.setColor(z,y,history[0].getColor(z,y));
}
}
}
else{
for(int z=0; z<history[iter-2].getWidth(); z++){
for(int y=0; y<history[iter-2].getHeight(); y++){
img.setColor(z,y,history[iter-2].getColor(z,y));
}
}
iter = iter-1;
}
}
public void redo(){
if(redo==true){
if(history[iter]==null || iter>=history.length){
for(int z=0; z<history[iter-1].getWidth(); z++){
for(int y=0; y<history[iter-1].getHeight(); y++){
img.setColor(z,y,history[iter-1].getColor(z,y));
}
}
}
else{
for(int z=0; z<history[iter].getWidth(); z++){
for(int y=0; y<history[iter].getHeight(); y++){
img.setColor(z,y,history[iter].getColor(z,y));
}
}
}
iter = iter+1;
}
}
}
|
SQL
|
UTF-8
| 20,506 | 3.625 | 4 |
[] |
no_license
|
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
DROP SCHEMA IF EXISTS `indiosis_main` ;
CREATE SCHEMA IF NOT EXISTS `indiosis_main` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `indiosis_main` ;
-- -----------------------------------------------------
-- Table `indiosis_main`.`Organization`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`Organization` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`Organization` (
`id` INT NOT NULL AUTO_INCREMENT ,
`acronym` VARCHAR(10) NULL ,
`name` VARCHAR(250) NOT NULL ,
`type` ENUM('association','company','ngo','consultant','recycler','clean-tech') NOT NULL DEFAULT 'company' ,
`description` TEXT NULL ,
`linkedin_id` INT NULL ,
`verified` TINYINT(1) NOT NULL DEFAULT 0 ,
`anonymous` TINYINT(1) NOT NULL DEFAULT 0 ,
`created_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`User`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`User` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`User` (
`id` INT NOT NULL AUTO_INCREMENT ,
`email` VARCHAR(45) NOT NULL ,
`password` CHAR(32) NOT NULL ,
`lastName` VARCHAR(45) NULL ,
`firstName` VARCHAR(45) NULL ,
`prefix` VARCHAR(20) NULL ,
`title` VARCHAR(250) NULL ,
`bio` TEXT NULL ,
`linkedin_id` VARCHAR(250) NULL ,
`oauth_token` VARCHAR(100) NULL ,
`oauth_secret` VARCHAR(100) NULL ,
`last_connected` TIMESTAMP NULL ,
`joined_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`verification_code` VARCHAR(100) NOT NULL DEFAULT 'verified' ,
`Organization_id` INT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_User_Organization_idx` (`Organization_id` ASC) ,
CONSTRAINT `fk_User_Organization`
FOREIGN KEY (`Organization_id` )
REFERENCES `indiosis_main`.`Organization` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`ClassificationSystem`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`ClassificationSystem` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`ClassificationSystem` (
`name` VARCHAR(20) NOT NULL ,
`fullName` VARCHAR(250) NULL ,
`revision` VARCHAR(50) NULL ,
PRIMARY KEY (`name`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`ClassCode`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`ClassCode` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`ClassCode` (
`number` VARCHAR(250) NOT NULL ,
`description` TEXT NOT NULL ,
`uom` VARCHAR(50) NULL ,
`ChildOf_number` VARCHAR(250) NULL ,
`ClassificationSystem_name` VARCHAR(20) NOT NULL ,
PRIMARY KEY (`number`) ,
INDEX `fk_ResourceCode_ClassificationSystem_idx` (`ClassificationSystem_name` ASC) ,
INDEX `fk_ResourceCode_ChildOf_idx` (`ChildOf_number` ASC) ,
CONSTRAINT `fk_ResourceCode_ClassificationSystem`
FOREIGN KEY (`ClassificationSystem_name` )
REFERENCES `indiosis_main`.`ClassificationSystem` (`name` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_ResourceCode_ChildOf`
FOREIGN KEY (`ChildOf_number` )
REFERENCES `indiosis_main`.`ClassCode` (`number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`CustomClass`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`CustomClass` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`CustomClass` (
`code` VARCHAR(255) NOT NULL ,
`name` TEXT NOT NULL ,
`description` TEXT NOT NULL ,
`MatchingCode_number` VARCHAR(250) NOT NULL ,
PRIMARY KEY (`code`) ,
INDEX `fk_CustomResource_ResourceCode1_idx` (`MatchingCode_number` ASC) ,
CONSTRAINT `fk_CustomResource_ResourceCode`
FOREIGN KEY (`MatchingCode_number` )
REFERENCES `indiosis_main`.`ClassCode` (`number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`ResourceFlow`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`ResourceFlow` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`ResourceFlow` (
`id` INT NOT NULL AUTO_INCREMENT ,
`label` VARCHAR(255) NULL ,
`qty` INT NULL ,
`qtyUom` VARCHAR(20) NULL ,
`frequency` VARCHAR(20) NULL ,
`reach` VARCHAR(250) NULL ,
`added_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`hideQty` TINYINT(1) NOT NULL DEFAULT 0 ,
`hideQtyUom` TINYINT(1) NOT NULL DEFAULT 0 ,
`hideLocation` TINYINT(1) NOT NULL DEFAULT 0 ,
`ClassCode_number` VARCHAR(250) NULL ,
`CustomClass_code` VARCHAR(255) NULL ,
`Provider_id` INT NULL ,
`Receiver_id` INT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_ResourceFlow_CustomClass_idx` (`CustomClass_code` ASC) ,
INDEX `fk_ResourceFlow_ClassCode_idx` (`ClassCode_number` ASC) ,
INDEX `fk_ResourceFlow_Provider_idx` (`Provider_id` ASC) ,
INDEX `fk_ResourceFlow_Receiver_idx` (`Receiver_id` ASC) ,
CONSTRAINT `fk_ResourceFlow_CustomClass`
FOREIGN KEY (`CustomClass_code` )
REFERENCES `indiosis_main`.`CustomClass` (`code` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_ResourceFlow_ClassCode`
FOREIGN KEY (`ClassCode_number` )
REFERENCES `indiosis_main`.`ClassCode` (`number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_ResourceFlow_Provider`
FOREIGN KEY (`Provider_id` )
REFERENCES `indiosis_main`.`Organization` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_ResourceFlow_Receiver`
FOREIGN KEY (`Receiver_id` )
REFERENCES `indiosis_main`.`Organization` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`Message`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`Message` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`Message` (
`id` INT NOT NULL AUTO_INCREMENT ,
`title` VARCHAR(250) NULL ,
`body` TEXT NULL ,
`sent_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`Sender_id` INT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_Message_Sender_idx` (`Sender_id` ASC) ,
CONSTRAINT `fk_Message_Sender`
FOREIGN KEY (`Sender_id` )
REFERENCES `indiosis_main`.`User` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`Symbiosis`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`Symbiosis` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`Symbiosis` (
`id` INT NOT NULL ,
`status` ENUM('REQ', 'ACPTED', 'REJ','ACTIVE','INACTIVE','FAILED') NOT NULL DEFAULT 'REQ' ,
`descrition` TEXT NULL ,
`created_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`expires_on` TIMESTAMP NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`ISBC`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`ISBC` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`ISBC` (
`id` INT NOT NULL AUTO_INCREMENT ,
`title` TEXT NOT NULL ,
`type` ENUM('wastex','ecopark','intra','local','regional','mutual') NOT NULL ,
`overview` TEXT NULL ,
`time_period` VARCHAR(45) NULL ,
`eco_drivers` TEXT NULL ,
`eco_barriers` TEXT NULL ,
`tech_drivers` TEXT NULL ,
`tech_barriers` TEXT NULL ,
`regul_drivers` VARCHAR(45) NULL ,
`regul_barriers` VARCHAR(45) NULL ,
`socioenv_benefits` VARCHAR(45) NULL ,
`contingencies` TEXT NULL ,
`source` TEXT NULL ,
`added_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`Location`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`Location` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`Location` (
`id` INT NOT NULL AUTO_INCREMENT ,
`label` VARCHAR(250) NOT NULL ,
`addressLine1` TEXT NULL ,
`addressLine2` TEXT NULL ,
`city` VARCHAR(250) NULL ,
`zip` VARCHAR(250) NULL ,
`state` VARCHAR(250) NULL ,
`country` VARCHAR(250) NOT NULL ,
`lat` VARCHAR(250) NULL ,
`lng` VARCHAR(250) NULL ,
`Organization_id` INT NULL ,
`ResourceFlow_id` INT NULL ,
`ISCase_id` INT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_Location_Organization_idx` (`Organization_id` ASC) ,
INDEX `fk_Location_ResourceFlow_idx` (`ResourceFlow_id` ASC) ,
INDEX `fk_Location_ISCase1_idx` (`ISCase_id` ASC) ,
CONSTRAINT `fk_Location_Organization`
FOREIGN KEY (`Organization_id` )
REFERENCES `indiosis_main`.`Organization` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Location_ResourceFlow`
FOREIGN KEY (`ResourceFlow_id` )
REFERENCES `indiosis_main`.`ResourceFlow` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Location_ISCase1`
FOREIGN KEY (`ISCase_id` )
REFERENCES `indiosis_main`.`ISBC` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`CommunicationMean`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`CommunicationMean` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`CommunicationMean` (
`id` INT NOT NULL AUTO_INCREMENT ,
`type` ENUM('email','phone','fax','skype','gtalk','msn','yahoo','website','twitter') NOT NULL ,
`value` VARCHAR(250) NOT NULL ,
`label` VARCHAR(250) NULL ,
`User_id` INT NULL ,
`Organization_id` INT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_CommunicationMean_User_idx` (`User_id` ASC) ,
INDEX `fk_CommunicationMean_Organization_idx` (`Organization_id` ASC) ,
CONSTRAINT `fk_CommunicationMean_User`
FOREIGN KEY (`User_id` )
REFERENCES `indiosis_main`.`User` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_CommunicationMean_Organization`
FOREIGN KEY (`Organization_id` )
REFERENCES `indiosis_main`.`Organization` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`Affiliation`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`Affiliation` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`Affiliation` (
`Parent_id` INT NOT NULL ,
`Child_id` INT NOT NULL ,
PRIMARY KEY (`Parent_id`, `Child_id`) ,
INDEX `fk_Affiliation_Child_idx` (`Child_id` ASC) ,
INDEX `fk_Affiliation_Parent_idx` (`Parent_id` ASC) ,
CONSTRAINT `fk_Affiliation_Parent`
FOREIGN KEY (`Parent_id` )
REFERENCES `indiosis_main`.`Organization` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Affiliation_Child`
FOREIGN KEY (`Child_id` )
REFERENCES `indiosis_main`.`Organization` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`CodeCorrelation`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`CodeCorrelation` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`CodeCorrelation` (
`ReferringCode_number` VARCHAR(250) NOT NULL ,
`CorrelatingCode_number` VARCHAR(250) NOT NULL ,
PRIMARY KEY (`ReferringCode_number`, `CorrelatingCode_number`) ,
INDEX `fk_CodeCorrelation_CorrelatingCode_idx` (`CorrelatingCode_number` ASC) ,
INDEX `fk_CodeCorrelation_ReferringCode_idx` (`ReferringCode_number` ASC) ,
CONSTRAINT `fk_CodeCorrelation_ReferringCode`
FOREIGN KEY (`ReferringCode_number` )
REFERENCES `indiosis_main`.`ClassCode` (`number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_CodeCorrelation_CorrelatingCode`
FOREIGN KEY (`CorrelatingCode_number` )
REFERENCES `indiosis_main`.`ClassCode` (`number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`Expertise`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`Expertise` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`Expertise` (
`ResourceCode_number` VARCHAR(250) NOT NULL ,
`Organization_id` INT NULL DEFAULT NULL ,
`User_id` INT NULL DEFAULT NULL ,
PRIMARY KEY (`ResourceCode_number`, `Organization_id`, `User_id`) ,
INDEX `fk_Expertise_ResourceCode_idx` (`ResourceCode_number` ASC) ,
INDEX `fk_Expertise_User_idx` (`User_id` ASC) ,
INDEX `fk_Expertise_Organization_idx` (`Organization_id` ASC) ,
CONSTRAINT `fk_Expertise_User`
FOREIGN KEY (`User_id` )
REFERENCES `indiosis_main`.`User` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Expertise_ResourceCode`
FOREIGN KEY (`ResourceCode_number` )
REFERENCES `indiosis_main`.`ClassCode` (`number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Expertise_Organization`
FOREIGN KEY (`Organization_id` )
REFERENCES `indiosis_main`.`Organization` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`SymbioticFlow`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`SymbioticFlow` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`SymbioticFlow` (
`Symbiosis_id` INT NOT NULL ,
`ResourceFlow_id` INT NOT NULL ,
PRIMARY KEY (`Symbiosis_id`, `ResourceFlow_id`) ,
INDEX `fk_SymbioticFlow_ResourceFlow_idx` (`ResourceFlow_id` ASC) ,
INDEX `fk_SymbioticFlow_Symbiosis_idx` (`Symbiosis_id` ASC) ,
CONSTRAINT `fk_SymbioticFlow_Symbiosis`
FOREIGN KEY (`Symbiosis_id` )
REFERENCES `indiosis_main`.`Symbiosis` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_SymbioticFlow_ResourceFlow`
FOREIGN KEY (`ResourceFlow_id` )
REFERENCES `indiosis_main`.`ResourceFlow` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`MessageRecipient`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`MessageRecipient` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`MessageRecipient` (
`Message_id` INT NOT NULL ,
`Recipient_id` INT NOT NULL ,
`read` TINYINT(1) NOT NULL DEFAULT 0 ,
PRIMARY KEY (`Message_id`, `Recipient_id`) ,
INDEX `fk_MessageRecipient_Recipient_idx` (`Recipient_id` ASC) ,
INDEX `fk_MessageRecipient_Message_idx` (`Message_id` ASC) ,
CONSTRAINT `fk_MessageRecipient_Message`
FOREIGN KEY (`Message_id` )
REFERENCES `indiosis_main`.`Message` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_MessageRecipient_Recipient`
FOREIGN KEY (`Recipient_id` )
REFERENCES `indiosis_main`.`User` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`Tag`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`Tag` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`Tag` (
`id` INT NOT NULL AUTO_INCREMENT ,
`label` ENUM('retain','expert','admin') NOT NULL ,
`User_id` INT NULL ,
`Organization_id` INT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_Tag_User1_idx` (`User_id` ASC) ,
INDEX `fk_Tag_Organization1_idx` (`Organization_id` ASC) ,
CONSTRAINT `fk_Tag_User1`
FOREIGN KEY (`User_id` )
REFERENCES `indiosis_main`.`User` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Tag_Organization1`
FOREIGN KEY (`Organization_id` )
REFERENCES `indiosis_main`.`Organization` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `indiosis_main`.`SymbioticLinkage`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `indiosis_main`.`SymbioticLinkage` ;
CREATE TABLE IF NOT EXISTS `indiosis_main`.`SymbioticLinkage` (
`ISCase_id` INT NOT NULL ,
`MaterialClass_number` VARCHAR(250) NULL ,
`CustomMaterial_code` VARCHAR(255) NULL ,
`SourceClass_number` VARCHAR(250) NOT NULL ,
`EndClass_number` VARCHAR(250) NOT NULL ,
`type` ENUM('reuse','sharing','joint') NULL ,
`qty` VARCHAR(250) NULL ,
`implementation` TEXT NULL ,
`benefit_source` TEXT NULL ,
`benefit_end` TEXT NULL ,
`remarks` TEXT NULL ,
PRIMARY KEY (`ISCase_id`, `MaterialClass_number`, `SourceClass_number`, `EndClass_number`, `CustomMaterial_code`) ,
INDEX `fk_ISCase_has_ClassCode_ClassCode1_idx` (`SourceClass_number` ASC) ,
INDEX `fk_ISCase_has_ClassCode_ISCase1_idx` (`ISCase_id` ASC) ,
INDEX `fk_ISCaseClass_ClassCode1_idx` (`MaterialClass_number` ASC) ,
INDEX `fk_SymbioticLink_ClassCode1_idx` (`EndClass_number` ASC) ,
INDEX `fk_SymbioticLinkage_CustomClass1_idx` (`CustomMaterial_code` ASC) ,
CONSTRAINT `fk_ISCase_has_ClassCode_ISCase1`
FOREIGN KEY (`ISCase_id` )
REFERENCES `indiosis_main`.`ISBC` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_ISCase_has_ClassCode_ClassCode1`
FOREIGN KEY (`SourceClass_number` )
REFERENCES `indiosis_main`.`ClassCode` (`number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_ISCaseClass_ClassCode1`
FOREIGN KEY (`MaterialClass_number` )
REFERENCES `indiosis_main`.`ClassCode` (`number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_SymbioticLink_ClassCode1`
FOREIGN KEY (`EndClass_number` )
REFERENCES `indiosis_main`.`ClassCode` (`number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_SymbioticLinkage_CustomClass1`
FOREIGN KEY (`CustomMaterial_code` )
REFERENCES `indiosis_main`.`CustomClass` (`code` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
-- -----------------------------------------------------
-- Data for table `indiosis_main`.`Organization`
-- -----------------------------------------------------
START TRANSACTION;
USE `indiosis_main`;
INSERT INTO `indiosis_main`.`Organization` (`id`, `acronym`, `name`, `type`, `description`, `linkedin_id`, `verified`, `anonymous`, `created_on`) VALUES (NULL, 'UNIL', 'University of Lausanne', 'consultant', 'Founded in 1537, the University of Lausanne is composed of seven faculties where approximately 12,400 students and 2,300 researchers work and study. Emphasis is placed on an interdisciplinary approach, with close cooperation between students, professors and teaching staff.', NULL, 1, 0, NULL);
COMMIT;
-- -----------------------------------------------------
-- Data for table `indiosis_main`.`User`
-- -----------------------------------------------------
START TRANSACTION;
USE `indiosis_main`;
INSERT INTO `indiosis_main`.`User` (`id`, `email`, `password`, `lastName`, `firstName`, `prefix`, `title`, `bio`, `linkedin_id`, `oauth_token`, `oauth_secret`, `last_connected`, `joined_on`, `verification_code`, `Organization_id`) VALUES (NULL, 'fred@roi-online.org', '2ed91c548d1e8fecb55650ea0a15d8e6', 'Andreae', 'Frédéric', 'Mr', 'Indiosis Administrator', 'Analyst at the UNIL.', NULL, NULL, NULL, NULL, NULL, 'verified', 1);
COMMIT;
-- -----------------------------------------------------
-- Data for table `indiosis_main`.`ClassificationSystem`
-- -----------------------------------------------------
START TRANSACTION;
USE `indiosis_main`;
INSERT INTO `indiosis_main`.`ClassificationSystem` (`name`, `fullName`, `revision`) VALUES ('HS', 'Harmonized System', '2005');
INSERT INTO `indiosis_main`.`ClassificationSystem` (`name`, `fullName`, `revision`) VALUES ('ISIC', 'International Standard Industrial Classification of All Economic Activities', '4');
COMMIT;
|
Java
|
UTF-8
| 596 | 1.921875 | 2 |
[] |
no_license
|
/**
* @Title IAccountBO.java
* @Package com.ibis.account.bo
* @Description
* @author miyb
* @date 2015-3-15 下午3:15:49
* @version V1.0
*/
package com.std.forum.bo;
public interface IAccountBO {
/**
* 用户间划账
* @param fromUserId
* @param toUserId
* @param direction
* @param amount
* @param fee
* @param remark
* @create: 2016年9月28日 下午8:10:25 xieyj
* @history:
*/
public void doTransferUsers(String fromUserId, String toUserId,
String direction, Long amount, Long fee, String remark);
}
|
Java
|
UTF-8
| 1,024 | 2.546875 | 3 |
[] |
no_license
|
package record.dao;
import static fw.JdbcTemplate.*;
import static fw.Query.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import record.dto.RecordDTO;
public class RecordDAOImpl implements RecordDAO{
@Override
public ArrayList<RecordDTO> eventList(String month, Connection con)
throws SQLException {
ArrayList<RecordDTO> list = new ArrayList<RecordDTO>();
RecordDTO dto = null;
PreparedStatement ptmt = con.prepareStatement(EVENT_LIST);
ptmt.setString(1, month);
ResultSet rs = ptmt.executeQuery();
while(rs.next()){
dto = new RecordDTO(rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getString(7),
rs.getString(8),
rs.getString(9),
rs.getString(10));
list.add(dto);
}
close(rs);
close(ptmt);
return list;
}
}
|
Markdown
|
UTF-8
| 569 | 3.984375 | 4 |
[] |
no_license
|
# Super Primes
A prime number is Super Prime if it is a sum of two primes. Find all the Super Primes upto N
**Example 1:**
```
Input:
N = 5
Output: 1
Explanation: 5 = 2 + 3, 5 is the
only super prime
```
**Example 2:**
```
Input:
N = 10
Output: 2
Explanation: 5 and 7 are super primes
```
**Your Task:**<br>
You don't need to read input or print anything. Your task is to complete the function **superPrimes()** which takes the N as input and returns the count of super primes.
**Expected Time Complexity:** O(Nlog(logN))<br>
**Expected Auxiliary Space:** O(N)
|
Java
|
UTF-8
| 517 | 1.882813 | 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 cleansweep;
import cleansweep.CleanSweep;
import cleansweep.CleanSweepImpl;
import utility.Coords;
/**
*
* @author MatthewSwan
*/
public class CleanSweepFactory {
public static CleanSweep createCleanSweep() {
CleanSweepImpl cleanSweep = new CleanSweepImpl();
return (CleanSweep) cleanSweep;
}
}
|
Python
|
UTF-8
| 2,638 | 3.375 | 3 |
[
"Unlicense"
] |
permissive
|
import math
import numpy as np
import matplotlib.pyplot as plt
# Constantes del problema
g = 9.81
m = 1.0
k = 18.0
h = 1.0
l = 2.0
pi = math.pi
# Resuelve la ecuación diferencial por el método de Euler
def euler_solve(A, omega, tMax, div):
# Tamaño del paso en el tiempo
deltaT = tMax / div
# Crea las listas donde se almacena la solución
t = np.linspace(0, tMax, div)
eventTime = tMax
theta1 = np.zeros_like(t)
theta2 = np.zeros_like(t)
# Condiciones iniciales
theta1[0] = 0.0
theta2[0] = 0.0
theta1Prime = 0.0
theta2Prime = 0.0
theta1BiPrime = 0.0
theta2BiPrime = 0.0
for i in range(1,div):
theta1BiPrime = -(k*theta1[i-1] + h*m*(2*A*math.pow(omega, 2.0)*math.cos(theta1[i-1])*math.sin(t[i-1]*omega) - 2*g*math.sin(theta1[i-1]) + h*math.sin(theta1[i-1] - theta2[i-1])*math.pow(theta2[i-1], 2.0) + h*math.cos(theta1[i-1] - theta2[i-1])*theta2BiPrime)) / (2*math.pow(h, 2.0)*m)
theta2BiPrime = (-k*theta2[i-1] + h*m*(-A*math.pow(omega, 2.0)*math.cos(theta2[i-1])*math.sin(t[i-1]*omega) + g*math.sin(theta2[i-1]) + h*math.sin(theta1[i-1] - theta2[i-1])*math.pow(theta1Prime, 2.0) - h*math.cos(theta1[i-1] - theta2[i-1])*theta1BiPrime)) / (math.pow(h, 2.0)*m)
theta1Prime += theta1BiPrime * deltaT
theta2Prime += theta2BiPrime * deltaT
theta1[i] = theta1[i-1] + theta1Prime * deltaT
theta2[i] = theta2[i-1] + theta2Prime * deltaT
if math.fabs(theta1[i]) > pi/2 or math.fabs(theta2[i]) > pi/2:
eventTime = t[i]
t = t[1:i]
theta1 = theta1[1:i]
theta2 = theta2[1:i]
break
return t, theta1, theta2, eventTime
# Aplica metodo numerico
(t, theta1, theta2, eventTime) = euler_solve(0.5, 1.0, 10.0, 500)
# Grafica theta1 vs t
plt.plot(t,theta1)
plt.xlabel('time')
plt.ylabel(r'$\theta_1(t)$')
plt.show()
# Grafica theta2 vs t
plt.plot(t,theta2)
plt.xlabel('time')
plt.ylabel(r'$\theta_2(t)$')
plt.show()
# Mapa de estabilidad
AMin = 0.1
AMax = 3.0
omegaMin = 0.1
omegaMax = 4.0
paramDelta = 0.1
horizontalRows = math.floor((AMax - AMin) / paramDelta);
verticalRows = math.floor((omegaMax - omegaMin) / paramDelta);
canvas = np.zeros([verticalRows+1, horizontalRows+1])
i = 0
for A in np.arange(AMin, AMax, paramDelta):
j = 0
for omega in np.arange(omegaMin, omegaMax, paramDelta):
(t, theta1, theta2, eventTime) = euler_solve(A, omega, 10.0, 1000)
canvas[verticalRows-j][i] = eventTime
j += 1
i += 1
plt.imshow(canvas)
plt.colorbar()
plt.xlabel('A')
plt.ylabel(r'$\omega$')
plt.show()
|
Java
|
UTF-8
| 2,107 | 2.90625 | 3 |
[] |
no_license
|
package com.walden.javadesignmode.mode.factorymode;
import android.util.Log;
import com.walden.javadesignmode.utils.S;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
/**
* Created by Administrator on 2017/6/20 0020.
*/
public class HeroFactory {
static ArrayList<Class> classList;
static HashMap<String, Hero> heroMap = new HashMap<>();
public static Hero createHero(Class c) {
Hero hero = null;
if (heroMap.containsValue(c.getSimpleName())) {
return heroMap.get(c.getName());
}
try {
hero = (Hero) Class.forName(c.getName()).newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
Log.d(S.TAG, "createHero: 类定义错误 ");
} catch (InstantiationException e) {
e.printStackTrace();
Log.d(S.TAG, "createHero: 实例化异常 ");
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.d(S.TAG, "createHero: 类找不到 ");
}
heroMap.put(hero.getClass().getSimpleName(), hero);
return hero;
}
public static Hero createHero() {
if (classList == null) {
classList = new ArrayList<>();
classList.add(HuoQiang.class);
classList.add(LaiEn.class);
classList.add(LanMao.class);
classList.add(WuYao.class);
}
Hero hero = null;
Random random = new Random();
int index = random.nextInt(classList.size());
try {
hero = (Hero) Class.forName(classList.get(index).getName()).newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
Log.d(S.TAG, "createHero: 类定义错误 ");
} catch (InstantiationException e) {
e.printStackTrace();
Log.d(S.TAG, "createHero: 实例化异常 ");
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.d(S.TAG, "createHero: 类找不到 ");
}
return hero;
}
}
|
Python
|
UTF-8
| 3,704 | 3.59375 | 4 |
[] |
no_license
|
"""
A solution to a ROSALIND bioinformatics problem.
Problem Title: Compute the Edit Distance Between Two Strings
Rosalind ID: BA5G
URL: http://rosalind.info/problems/ba5g/
"""
def alignRecontructionMoves(backtrack):
n = len(backtrack) - 1
m = len(backtrack[0]) - 1
moves = []
while n > 0 or m > 0:
moves.append(backtrack[n][m])
if backtrack[n][m] == "D":
n = n - 1
elif backtrack[n][m] == "R":
m = m - 1
else:
m = m - 1
n = n - 1
return moves[::-1]
def moves_to_strings_counter(first_word, second_word, moves):
pointer_w1 = 0
pointer_w2 = 0
w1 = []
w2 = []
counter=0
for move in moves:
if move == "D":
w1.append(first_word[pointer_w1])
pointer_w1 += 1
w2.append("-")
counter = counter + 1
if move == "R":
w1.append("-")
w2.append(second_word[pointer_w2])
pointer_w2 += 1
counter = counter + 1
if move == "Diag":
w1.append(first_word[pointer_w1])
pointer_w1 += 1
w2.append(second_word[pointer_w2])
pointer_w2 += 1
if move=="Mismatch":
counter=counter+1
w1.append(first_word[pointer_w1])
pointer_w1 += 1
w2.append(second_word[pointer_w2])
pointer_w2 += 1
return counter
def EditDistance(first, second):
s=[]
for i in range (len(first)+1):
s.append([])
s[0].append(0)
#first column
for i in range(1,len(first)+1):
s[i].append(s[i-1][0]-1)
#first row
for j in range(1,len(second)+1):
s[0].append(s[0][j-1]-1)
newFirst=""
newSecond=""
Backtrack=[]
for i in range (len(first)+1):
Backtrack.append([])
Backtrack[0].append('')
# first column
for i in range(1, len(first) + 1):
Backtrack[i].append("D")
# first row
for j in range(1, len(second) + 1):
Backtrack[0].append("R")
for i in range(1, len(first) + 1):
for j in range(1, len(second) + 1):
if first[i-1]==second[j-1]:
s[i].append(max(s[i - 1][j]-1, s[i][j - 1]-1, s[i - 1][j - 1] + 1))
else:
s[i].append(max(s[i - 1][j]-1, s[i][j - 1]-1, s[i - 1][j - 1]-1))
if s[i][j] == s[i - 1][j-1] +1:
Backtrack[i].append("Diag")
else:
if s[i][j]==s[i-1][j]-1:
Backtrack[i].append("D")
else:
if s[i][j]==s[i][j-1]-1:
Backtrack[i].append("R")
else:
Backtrack[i].append("Mismatch")
counter= moves_to_strings_counter(first,second,alignRecontructionMoves(Backtrack))
return counter
if __name__ == '__main__':
x = '''PLEASANTLY
MEANLY'''
inlines = x.split('\n')
first = inlines[0]
second = inlines[1]
res = EditDistance(first, second)
print(res)
x = '''GGACRNQMSEVNMWGCWWASVWVSWCEYIMPSGWRRMKDRHMWHWSVHQQSSPCAKSICFHETKNQWNQDACGPKVTQHECMRRRLVIAVKEEKSRETKMLDLRHRMSGRMNEHNVTLRKSPCVKRIMERTTYHRFMCLFEVVPAKRQAYNSCDTYTMMACVAFAFVNEADWWKCNCAFATVPYYFDDSCRMVCGARQCYRLWQWEVNTENYVSIEHAEENPFSKLKQQWCYIPMYANFAWSANHMFWAYIANELQLDWQHPNAHPIKWLQNFLMRPYHPNCGLQHKERITPLHKSFYGMFTQHHLFCKELDWRIMAHANRYYCIQHGWHTNNPMDPIDTRHCCMIQGIPKRDHHCAWSTCDVAPLQGNWMLMHHCHHWNRVESMIQNQHEVAAGIKYWRLNRNGKLPVHTADNYGVLFQRWWFLGWYNFMMWHYSLHFFAVNFYFPELNAGQMPRFQDDQNRDDVYDTCIWYFAWSNTEFMEVFGNMMMYSRPMTKMGFHGMMLPYIAINGLRSISHVNKGIGPISGENCNLSTGLHHYGQLRMVMCGYCTPYRTEVKNQREMISAVHCHQHIDWRWIWCSGHWFGSNKCDLRIEDLQNYEPAKNKSNWPYMKECRKTEPYQDNIETMFFHQHDLARDSGYIANGWHENCRQHQDFSNTFAGGHKGTPKGEHMRRSLYVWDTDCVEKCQWVPELFALCWWTPLPDGVPVMLGTYRQYMFGLVVLYWFEVKYSCHNSWDYYNFHEGTMKDSDPENWCFWGMQIIQFHDHGKPEFFQDPMKQIIKTECTAYNSFMMGHIGKTTIVYLVSYIGRLWMKSCCLTWPPYATAPIKWAEETLLDFGQGPHPKYACHFTHQNMIRLAKLPMYWLWKLMFHE
GMWGFVQVSTQSRFRHMWHWSVHQQSSECAKSICHHEWKNQWNQDACGPKVTQHECMANMPMHKCNNWFWRLVIAVKEEKVRETKMLDLIHRHWLVLNQGRMNEHNVTLRKSPCVKRIMHKWKSRTTFHRFMCLMASEVVPAKRGAQCWRQLGTYATYTVYTMMACVAFAFEYQQDNDNEADWWKCNCAFVPVYFDDSCRPVVGAFQCYRLGLPFGTGWNYAEENPFSKLKQQMHRKTMGECKNMMIWAYCANELQLPIKWGSMYHEHDFQLPPYHPNRFHKIRITILHKSFYGMFTQHHLFCKELDWRIMAWANRYYCIQHGWHTNNPDDPITRHKCMIQGGQNSRNADIRHMPVQCGNWGHAIGLEMPMPMHHCHHANRVESMIQTQHYWGPKLNRNADWWFLGWQNFEIFRMPILRWMGAYEWHYSLHFFAVNFYFPELNAGQMPRFQDDQNNNACYDVWAWSNTEFMEVNGIKKLRFGNMMMYSRPMTKMGFHGMMKSRSISHVNKGIGPISGENCSTGLHHYGQLTEVKNQREMISAVHCHQHIWCKCDLRIEPAKNKGYWPYQKEFCWRKQINSRKTEPYQVAPVINIETMFFDFWYIANGMHENCRRTGHKPNPDCVEKCQWVPELFALCWWRAMPDGVPVMLGTMFGLVVYWFEVKYSCHNSLYRRVTDYYNFHEGTMKDHEVPWNWDNEHCHDHGKAEFFFQMLKIPICDPMKAIIPSTEMVNTPWHPFSFMMGHDGKTTIVYSGSYIGRLWVPSRWKPYAPANWKMPIKWAEETLLMVPHPHFTHQQLWGTTLRLAKLPMYWLWKLMFHHLFGVK'''
inlines = x.split('\n')
first = inlines[0]
second = inlines[1]
res = EditDistance(first, second)
print(res)
x = '''PCYTKAGPVHSKRGAKILRPLLLTTNEIRMFFCDFEIEGADEIDEVEQHHAETFQGLTQSRSLHNCVHHVDMAADKTEHYKSLYDPAAFQWDRLLMTPAQDMNMATNAFAERWIKTMDCIHEHYGQHREGFWIKERNVSTTLNEEPRLCVIQVKQWLESQTISIKTPALVAPHDGVVNNLFKAQTKMLTCWLVKREDQTIWSMKQHHWNVTWQMWATSSPPTNMMIPRAKRECRFCSKMKWMWQAWSCDDWFTITRKCPVKVQRDQFMNNEWVYRWSISLRDRYCGRCARNCALQSMQDKPGPFALHCTICSWNFYNDGWQPIEANWGISHSGYACQKAPFILVGQNPTQLPKYHYPHYDRNVGLTWHCCDPADVARVYANSMCIVTKQAIAGSWWTDLGYHGRQLGEPGPLDFVTIWQTMPHILSQPQLYKKFFTMQVRCIGSHEVTHRDYIHPRFPNYDKSCHVNAGTWNLIVYSRDTNRNCCDAEWLMPEMHPVKATKHPPLIGDFSSEQSIGITNVAQIKNVQGLPHKKYDEKFWGQRPVLKVRRVIVFRHFACLIENEPPFVRSRKWNCYDKASSFLWHPCLGAILTSSMCWMILQKRWAPGHHTMEWIGFAVQPMILNFGEWHIESSVGQTKSHQLPAGSQCPHMENDNFHQIQLAVKMCHPSGGWHQGLLTETGPHHILECYECSSEYGEGCCEGPQNKANPRIISANFPKIVTGLSVSFLQKFMCKDSSQLVAILHRECLKHQVWIKQTFYMALKTNTKCNAPVMFNMAVHQFTMALNWGGLDARFSVCLRRQCPDVQATVCNRITCNYIVVWYVNHQPYADFCFIPTGIFHNHQHIYRTMPVENPNCGRDGCFGIYVWAFVPYQRQNNICFCLFACHVGHVFAEHTFWPGLMVHSTQQNIFDMKRKSIDNNLMFWYLILDTFLNTINKSWNEECPLQTNFSQQGTDRIAHKLLTLGIAMLGRFHHMRVAQRLRPTRMGTYGFHYSHQQDGYEVNDFEVRFSTPDIHTAWARLMRNKQSENFIDNATGCWKYLCHVSIQYHYSSNAHLFASSGYSAYARRRFLMDTYEQDHCPNVSETKPETLNPDSYHYRNSVQLKCQKDLLNKKVADSGTSKALNTQSFHIPAPYWGCRAWTAFIVSTLPHDIGECLEAFIFIDTCHPEQINNEPEGSCNTTSFLPNEKPMIEDCEIQSRCCNRRHPHDRECLFHFICVDMSLRSRIMWIRSDKNFIVLVSFHYGGCHWAFDVQMTPVWDQCYTVGGRGSDSNMDNLCFFMIAVDCTHNDTPYNNCCLFVCKMIVDNDTFLISPNMHCHYCGKYYYIRNIHPNHRSCKKVRCNHGEIARQCSRLMNMRFQFWMTFCPGMKQHSRWCYDWKFPAIDPCQCRGCQFQCHLGKHFPNAYYRYFSYKTIDRDHNYGRMWIKNKRQIASSQSGAWICGAYGWNTTQLISQCSYHKLLYFWSNRTVHKTRKVHELNVNGRNRIVNSFRVSDIMYNKKYIRQNQVAMNFRNIFLDYIIQFVMEWGDLGYPFMGTYVYFMMPRASDHTLKEVWHWCHGLICQVPQVDIMDAWFHFPTYPDEQWTNPAPAEWHSCMEEVGIASPKSVYGIDFANMPSSNKKEFRNFVTVVDHSWHLFWAFNLHSMGDGCYQLSQYFYKLQRNKNDRWTWDQFMSSHQQTPRRDQDELIYPCWPGFYAYEHENHDTVEKHVWVLDVCWHAGYKRFLSCRACGKTVAEYYCFWWFPGLAYDDVERYKNSMKYVIKFGHYPSSLESDPGTTGYHILRGGEVFFEKFLNLNECVHAKNLQWRMNQSSPCRPEWSCGWRNCEGGTVLQRRPVWKEIKQLTYVALLQLHMTYNMMFEARSIGAKGSYLRFFHFNPRPLCRWRMMAYHTTTTWMIAEFTQVYYCGNNRHPCEHVQKGHLKMYWNIHQVDSCAFCLQKLTHDMNWTGCKVYQRFQMILSLDFGCKGTGSQLEYWDHEYTQYCQNFWWIKPRDRDVPGNIKFYSCKWPEAENEQVQFGRNRLAMAEQELYITFYDIAGIKLQRQMPFCGNIPSMSLQNAWPQGTAVGWFAYCECQTPESWQVRSWTRYTGDTGCTIWAFETLMATWCCTQLYLHHYFLWEMHYQRLKSRWWLNAAKDVMKNQDFHKDHTALNYCAMYYYMFPQIGTYRRSQLGRYYHFYYTILWHLVFQKSVHFAAADIAQDVKSNCTGVWSPQDEHMSVIDLICSPLRWRFQDFAEAATCTMKGYLSEINYVMQGSRECIMDGRHSWVWSDNRRKYKTPQNTELAGSEIKSNWRDFYCSRIWQIKRKFWQREFMEGDYMWANDYCVKCYCQMEAMWMTCMGDKAHKNAPYQSHIFLWPKHGDCLVCPKELANSEMTREVWNCPKGWMVSCQICGHILDMMHKECYIRFMMQHAWTKQRGNNVVAWFPKYDTLNYNDWIAMHCPWLGLDVNGPVKRWEYGLQQDAGVIQLQPTAAMPYMHREMDNDSPVVNQMTGIIMCTVGHPLYISADANNTRLIHEKKAAFNAQVNNHLCAMRHIILWEYFQWDENLFAHCVFGRKCGNIRTKQPGLMDIMLMLASIYDWEYEPILQQPVVQVCFSGDTCSPFSAFRSCIQGMDASGWKDHQTVNWMFDTLFCRGMNNAMAHDCLEARQLKPKAVNPIPPDANTQHDVGNCHQHPQHMRWNLPHHCQKYEMESKKERVKAEYIWTICNDGTQVGTCRFCAQPYMIQVFAQTMCGIMMWMNYMKERTHRADIPIAFLFWGAVFEAPAYDMNTLIETVWSMWNKQQKAGVKVKRVWMCLFNQETHQSSGVKYHWQVYHLSYFHLGSYPGQNGDMRNDGWDFCLVAVHQEATQYWHIQKIKLCLRQMPDEWKPEKLTIRYYEPSHNAPIKATTMMRQSAIADMDVYHQTFHGDATYVRKNIHQDEYECGNNNKSNSLMTPKILCAREIHCTVTPWAANEEIPQHGNKCRAYDKYVVTFKNFIVFPPEQFGKVMRCVIRWGRNDCVYVHFYQSRHRCDPSSLPQVPLWMWGMCTSNSFESCDRNHASINVHWAYSVCIYITMPWYGQKLTLNTFNDPTPAFKMIYALVLRKPSAYRRWMSDDRWDGLQGSELTWHYAGEYLGLQMHHHDHKKPVQWHIYHKICLTGHEIAPKKNPCSKLWNCQNQDYTCFWTSWTRRSRLQMVQCCNFSLLGQIPEKREFSYAGNHQWWIMESRVPMVCWNPFLMDMARRCWHQTTDVLTHCESQTFHYIAVFHEHLLAQYNHHFEKMKQNYYHRHYTDPAWDWQMGLIGYGTQWDKYRYSQILQMSPACKTLPAPNHQTRNTFVMDEKMATAQPCMFSETQTVIFNSWPCITMVQNLAADQCTNWGEEVPCNEMFNLIWGLQHEIRLACQEQEEFAGVDMNTFTGDRSNQVVGENGSNWCACFAVAFTMILNKPPPCVVHDPCLPVGNKGPCMCGDYRCVPMQVQAIDINHIDSDQMLRPKFPVAHHTHHWRGKIGVVNAILRIKKQRVSIVAATHPHFTWEAWNIERMLAHQSRCVQANFEGSEMFEMTQVTHKTPPLFYEIEKPPTPGRCQCAQHIEFITSHIGIRSENNFWINWDPEVNRGSWRRPSENIFDSIDDCFWMPPCLNGRILKLMHLMNSEWVTWKNDGVETEAWGSIRCACIWLPMSKLFPGNTVRKLPSFSGHPFMTPPPTCVYQNFQCLAWHGLGSPAGQEEHKAYPAHSFRHQLYTPKNALVSGIKNTNPEQSLRIPLMLEVQFNTNAKYSLMTQFHKEMACRFMINGIPRWYVHSYGEEADQVNLYSCSLIWQQENMLIKRLTEDQCFCTITPHYLKNMIHINDLPLHGVVRMNMGVDWQFWCPQNAGSYTPQEFPFWNFTNQVLIRTADFMIKCTWVCVHILKMRTIGDEWYISSAMFGQDDNTSLCICTYHIPCLKGQWSYEERYHDSIFKADPRSFCWQMHCNSKMGCQKWACQPYYKPLSKAPWHSKINWWRIWKLWRARTMWISSVDKRELRDFWCSWAMCPVRRFQIQLDGKLWMDMCKEIQFQNTLWETEMPRYRKQDACVHDVKEQNNRFAWTIKTDSAFEDQRGQSFEADMGVNDWVCIGTPDRHHYWAKFMEWNEQETGSDCPEDYPKMMAFIIINGYQCKMCMSKPSWPQMPECIEIDYWRAGLNITYCYWLQIMHWNIDMRDGQENHRKGGGKHCHGRDHMLRNPIGSGAVGWPEKGNFKVLFVHDQDGITRVFHSNFCAEEKEVRQMQWMWCSFETGSNEMKFMGDFHDQYCPIMKLRAKWFWCMTTQLIEQYYDFMPNWLHSWLKCDLL
PCYGLHDVRGASEQSQTFTAEIRMFFCDFDIEGARGCERPTYMEIDEVEQHIATQSRSLHNSFESTSWDQHHVDMAWQEWDKWPDPTEHYIARVQDTESLYDYAAFQWIVIRLLMTPAQEYMATLRNYQIRDAFAERWFKTMDCIAEHYGQHNELFWIKERFVSTTLNEEPRLCVILESQTISIVHPHDLEDTKMLVCWGKYANEPWVKRESMKQHHWNVTWQMWAESSPPTNMMCNQKKPRAKRECRFCRKMKWMWQACSCDDWFTITRKMLDRDIPVRTPYPPMVLHYGWTQMRDQFMNNEWVYRSISLRDRYCGRCARNCALGRMQDKPGPFALHCTICSWHFYNICHEGEFQNQNIEIVAMAKADHSGYAEAPFILVGQNPTQKVHYYVFRNVGLTWHCCDGADIARVYNYKNSMMIVTKQATNVVGAGSHGAQLGEPGPLDFVTGCVNTMQEIWQIKSQPQLQKKVRIVFRDDYNDYYGYMFPTPIPRFPNYDKMCHVNIIYSRWGNRGRHCDAMEPVKATKHPPLYGWWSGCEHFSQCWRTCPKWEQLENNDIKNVQGLSDPIVHKKYIAVKHITEKRWSQPPVSTKHVYRIVFRHFAPIVHRVMNDVCSRKWNCSWDSSFLWHPCLDAILTSSMCWMILQMRQMLKPAPGHHAMEWMLSHVQRTWHFAVCPMEWHIESSVGQTKSYQLPAHMENDNRIQLAVKMCHPGGGWHQQLLTETGPHHILECYECSSEYGEGCCENNRIISANFPFLQKFMCKVEPDPQDNRECVHSGKHQVLAVLWKYCTIKQTFYTEALKTNTKCNAPLFNRMDKSHNNDMPVHQFTMALNWEGLDATFSFISIPNSVWCPDARRRDQSVQATVCNRITCNYIVVWYHQDLRCNDVRMLYADHIAWWAVCFINKAPTTGYRTMPVENPNCGRDGQVGRYIWNFVAYQQNNGCFCLFACHVVFAEHTFIPCLMVHSTQQNIKPLMFWYLILDTFLNTINNEEMPLQENFKSFDQLQQGTDRIAHKLLTLGIAMGRFHHMRVAIRLRYRKETAITRMGTTVDIWSGFKDHYSHQQKASNGVRFMKTCARALYMGNKQSYLCHVVWDQIQYHDCAQASSNAHDFRMCCTMVMDTYMWIDHCPNVSETKYHYRNSVTKRKQLKCVADSGTSKALGTQSFHIPRAWTLFIVSTLPHDIGECSEAFIFIDTCHPENIMTFHIPHTQKDVSFLPLEKPDWTIEDCRRHPHDRECLWLETQHFICCTTEIDMSLRSRIMWIRTDKNKQIVLVSRCYSMYQCHYEGDVWYNQRQDHPWDGQMTNLNGEVWFFGRGDSNFFMIAVDCTHNDTPYNKFDIVINDTFLEGKYYYIRNNHRSCKKVRCNHGFIARQCSRLMNMRFRMGMIFWMTFCPGMKQHSRWPIDKCQTRGKHFYNAYYRKQLRQHASSQSCAWICGAYGWNTTQLISQDWRRRSEMWHLSFWSNSTQHKLRKVHFIHLAVNGRNRIVNSFRVSDIMYNKKYIRQNQVVSYTNVTNMNFENIFLDYIIQFVMEKCQTKHTGSCDPHGIGLGYPFMATYVPLKEVHCVGLICQFPDIHPLIVWTMNYAHFPINIRRFECSYKQGCQISDEQWTNPAKFTPRPGAEWHSCMEEVGIAPALPKSMPSMNKKEFRNFVTVVVHSWHLFWAFHSRGDGCQYDLQDRNKNDCWTWCQFMSSCCPCSHQVTPRRDQDELIYPCFYAYEHYNHDTVEKHVEVLDVCWHAGYVRFCFWWFIGLAYDDVERYKNSGATQMEWVYVIKFGHSPSLESHKQQMPAMDHILSHGEVFFWKFLNLNECVHAKNLQWRMNQSSPCRPEWNCGCHKFASAMNCEGGTVLNVYRPVWKCIKQLTQNMMFEARSIRSKVNMHFNPRPLCRRVRMAAPSDYYHTTTTWMIAEFTQVYYCPNSRHPCEHLKMYWTMQKAWIHQSCVGLDQEDSEFCLCKLTLMLYRIDMNWTGCKQRFQMILSLRDGFKHCSAGYAYVGWGMYLHLEYWDHYQVAETQYCQNFWWEKRDVPGGIKFYSCENSERDENEQVQELFFCNRLAMLYMTFYDTAGKMQYGNIPSPSHWLLAGIQVTAVGWAAYHEDMYIAQTPESWQVRSSTRYTGDDGCTINAFETLMATWCCTDLNGMLYLHHVFLWVCLWRWWLNAHIRHNQQAPKDVMKNQDWHKIHGCALNYRAWNNYFGRYAFPTTHKCIGGRRYYHFYYTILWMLVSVAQNQATNWNAARIAQDVCGQIAKRNCTGVWSVQDEHMSVNVDLPCSPLRWRFQERAVDIWWAATCTMKGYLWEIRYVMQGHRECIMDGVWSDNRRVYKMPQNTECQQLAGSEIKSNERDNCDSMFRDYCCNGARIWQICRKFWQREIFLQWMEGYMWANDYNWKVHCDEACLFTWMTCMAPNSVHCFPKHGSCLVKELGMQECQWTSNSEPKGWMHFLCQHCHCCWRVTIQRFTGIQRPPDMQHAWTVAWFPKYDTLNYNDWDMMHCPWLGLDVNGPVKRWAGYIQLQPTAAMPYWHREMDNCNLQDQLPTGIIMCTSAYALFWRGHPYISADANNTRLIHEKTKAFHLCAMRHIILWEYLWTTRKVQWDENLFAHCVFGWKCANQCCRTKQPGLDGPHQDIAFYTQIDDPNTRAHWWPAHQYEPILQQPVVQVCQSGDCSPKYCCSPFSAFRSCIQGSWASGWKQHNTVNKMFDTKFIFPCYWFCRGMNNTMAHECLEARQHKPKAVNPWEPDADTQHDVGNCHQHHQHMRWMWLPHHCQKCEMESKKERVKAEYIQRMQGAFCTICNDGTQVGTCRFCAFAQTMCWMQAMKERTHRADIPTACLFWGAVFEARAYDGIRVYFNNNTLIETVWSMWNKQGKAGVKVKRVWMCLFNQETHQSSDPYFPKFQTPCEQLAKKWVVYHLSINFHLSSYPGQNGDMRNDGWDFKDSHMMIQVAVHQEATQYWHIQKIKLCLRQMPDEWKPEKLTIRYMQDEPSHNAPIRAQTMMRISAADMDVYEQTFHGDATYQDEWEQGNNKCVSLMTPRILCARVFPWLGEGHFWANEEKPQHGNKCRAYDKYVVTFKNFLVFQPEVFGKVMGMCITWCVRMFDCYQSYDRCDPSSLPQVTLWMWIDDHDAHVHWNYSVCIYIMPWYGQKLRLNHYYDPTPAFKMIYARVLRKPSAYMRSDDRWDGLQGSYLGLQMHHCTMDNWPNHHIYHKICLTGEVRIAPKKFYFHHRHCGGLCTSKLWNCQNQDYTQFNPWFTTEWTRRSRLQMVQCSNFSLLGCIPEKRENKYDGWPYHQWWTMESRVPMVCWNPFLMDMARRCFHLTTLVLTHCESQTFHYVFHEHFEKMKSNKACCEYHRMYTINKVNDEPAWLYFRYYVNGLPMSPACFTLGAPLHGLYWNPQTMDEMEKQIMTQGWKDREEWQPCMFSETQCITGDLRCVADMVANLAADQCTNWGEEQDPCNLWWGLHQIRLSCQEQEEFAGVDMQNDIGNHQEGENGSNWGACFAVAFTDILNKPPPCVVHDPRFYNYLGYCMCGDYRCVPFKIDKPQVQAIDINHIDSNQMLRPKFPVGKIGVVNAILRVAATHPHFDTAGLMKACTVEAEAWNFERMLAHQSRCVTEMFPLTNMTQVTHKTPPLFYEIEKPPTFIHYWYGPMTIGIASENNHWNWDPEVKFNRYSWRRPSEWSSIDDCFGMPPCLNGRAAPCLKMDPIAMQEVSNVETEAWPDIRTFPGNTVRKLPAFSGTNPPTCVLAWHGSGSAGQEEHKANPAHSETYKYRHQLYTPKNALVSGIKNTQPQQQGIWQSLYTLMTQQPVACHTEMACRFMIWGIEVTGRWYVHVNLYNCSLIWQQWTQQNTLIRFYQHLYLKEDQCFCTITFYTRHYIISDRKPVAKNMISNDMPLHGVKTIYHWMNMGVDWGIGWQWDEFPTWNFADWKINNQRLIRTADEMIMRTWYCTWVCVHILPVDNCFMRVIGMFGQDDNTFKGQWSYEERYHDSFFKADNMCNSKMGCQKYACPAVHTEEYYYKPLSKAPWHGKIMWWRIWKLVRARTMWISSVDKRDFVLDGKLWQQSRMCRKQDSCRNYHETYNNVTWGTAAQIWTIKTDSAFADQRGQSFFDRHMFADMGVEDWVCIGWSCLVPFCPDRHWYWANKMEWAPADICLSPGNPYCPELIALTYPKMMAFIIINGYQCKMCMSKPSPQMPECIEIHYPRAGLPITYCYWLQIMHWNIDMQYFVLLDGQENHRKGGGHGRDHMLRNCIASLIAVGWPEKGNFKVLFVHDQDAKSFHYEKQVRQMQYMWCSFETQRRNNHEMGDQPQMTHVQYCPIAKWFWCYHCTQLIEQYYARMTYTVLKCDLL'''
inlines = x.split('\n')
first = inlines[0]
second = inlines[1]
#res = EditDistance(first, second)
#print(res)
x = '''DFWEQMDDRMGIKWHGNDFPCPEAALSFKYLLDKVEQYASKNTVSRWMDAGVACLYWAPPEMSCRNCTDQMCQADIFPAQNLIARWDGLMSKMELWLIFGKCYDQHTMPHSRAICEGLRTEAIKIVMKSIAAWWSWYDINTSNPERKVWSSMSIFFKGIQIRSEWKCAQCGFWYLDCKVDRKYFMSCSLWTDQNWDNSQRRLCAQQGMMQKGFQKYFLTFMEVLWVSILKEYPGMWKNILPERTKWQRQMRPNEANRNMVSFKFRQEYAKLPIGFDDVLVNNWMECWPDVNDMRNVCVMKARMQWYVTGSHNTSGSTPKPHTSAWWDAIVLLQLSWWPFPPKWFAAYGRTKQYDVRTWSFPMKIVGRFRWFMMDDCYTVVTTEYFVTSDLSIFGGEKWWRAYKYGQGPDKEDVFSYHAWCHENSEWENCTLDQSAIVIYNYVENMEMCALSWQNKCWHSSWFRHVKLTRRQHEQWHPDIAHRNWCWDMFAFLHQTMYYYWTNQKSKSICPGDPGILAYFQEGLVWRTGLQNSIHFPVCAWRQEVAMEYACCLNGPYVVIFHKQNHECITKTDTFDSGKDKAGDCYTKAEKVEPWPDLHVWDYTDIGTICVKPVDKRAQQIQQGVGIDDNCSHMDCRCCKFDLYLLGNTIVWRPDTVQWTYFVPATMQDDAGVDANDHWENPYTMLIVKAWQLCCECQLEHNIFSPVATWRPLLPWPQNLTIPNEPRPVSELVFNVDRDYDVEDIIYYYWPFVGEWWDTIHDWANGHTHNHGNLTWHVHWDMGLNNCCAERYNYYWAYHMDFNMVQCQPKLLQGKLQSLRNSRYNHKLEYVWDAIGDAWRYTFILYHFCDRGHPMYFRRYSGYQLFKCHMWSNHTCGWLIESEDSEFNYNGYYNVIHMYSPSIKYNHHGSLHWPIEIMPKLYLAHIFLYYVRGEASFDTSCDCSDIQCGVVSNEDCDAAMDSDFGYWPLHEGQDQRIRAHVRHQAETIWWVNFDRNKEHPWDEYVWWMTWASFVMCWPSCWCNHNIDLTAFGPEKGFDCWPAFWTRNCYRPWCVNCVCQFWEISTYHEQHVTQDLSDNNSRTCSYWKQIHGMLSESDSFYIGPHREKIDDNAQVDMLQCKTVCKTFKNCFALWEKAQAPMWEEHGHYCTDCDLMTDIVTQYMCDCFGQDFSGAIGLARVKYLHVDGPNLACPQNFSVFVRLNWCVGLMWENQKDMCNNTEFTMCFSTPGQIKNHCITAPLRIKKAWMGGWCSPTSMDHWFWIQSTCAVIQGDQCVWAEWMTPTSSCHAQRWQTKQNCHVSVVYNNTAKEDESFGSHIKQSYRPDRRFWVISWPSCRVSWSDYWSYWGIGIPWAQCGTTDPIYFRFHKFIGEVQCQTMIRVCVTLVNLLRCVWQTFAPWWVWKNVNFLDIKWVNDWEKQWWDNDIRIHMEPQVTSFDTMVGKWAIYDVMYVEVFRTNLVKNHFVDMSEHMCTQFPSECHHSDFTDNVNFKLNPVSYHCWQKKPIDVSMIVCMFQLPFGAPIHYCYLTPEQNGFNSSPHDVYQHEPVTAAKKIGKADETWFRETPMTTMNCDPDRMLDTTKTGAFAEWWHHDITEDVYPHGFDTEYCYCFHVECFPYATMLPGDPLQDCMWDVEWPLLTRQERDERAHMKKNNQYNPHAPSCGWYPYRWNYACPVMRMYNVTTVACAYSCENIQDSRYGQAEGEKRTYFRKVGSGWQTNSLLGLEFWNGADPTTRDRMQNWQIGYIEKACTRPAVPDQKLTMLTIKGVTLMMLNYLDRQHTMTCKRALWQADTAGHPCFYPMPINVRHLRHEGGADCICSDYMQWLTVPAQHYGKIGLTTHDCSAGTLNFGYPNRYHQSGCGWARFDYFQIYDRMLKNLTFSWGNDCWMICKKFLWWHEASHTIMLDLLEKKGLDWQCICAHNSQDRTGACEKKYCPMCFYCTMLPPRVRDAYFWWSIDRQMKWKIINCAWEAGPHEWTHKAHVESRRYVTPMLCGEVFLDNTSKGQLEDHSEKEDYWLLVDGETIMGYGSIGAIVYWDSCWGQDIWCNAFHMDPGNIPVHRSGFYKSCDWIGGEGSCLKCTCIMAAGRPIQYSCFTGCHVQRQKCPHKARMWWQNYCNVMDHVKSKSEFTEFVRNYRMQDHMDSLNHYPHGRMFKIDDRPKNPGWGFNQWVFMFVRYQDRTKMHEHMVVFCHTYASIAHINSKYRYWHDYRFFMRRMCVYDVWTWTIQHQPHPVWYKTCVWDPEAIILTAKSMSCISMVVRAQEYPDYHPAPFWYLYRWTIHLRISCIYVHLIAEQFAMHSEQNNSHNIFNKCLESKDWKGHQNDAYAEVSELFIWNLNLAYQPIFQGWHFQVQTMDWFGATEQKMWNARIMWYKTDELTQRARHNGYYAWTRDKVVRDTMACEIILVYSLGEAHQWLKRGAAKCYAYHKISGYLQYPLHWPYPHWTKLDMGFQYWPECHCMVSGVQLDFGDPEGTGAKHNINYYALFRFQMKITDEGPGYPYMPFREGESMMRFECMSAKTLDNEEWRRKIIGRVPFNNVKKAMTQGADFYKLNVCCSQKITYDRCPMRYKGWTYHVWCQYDDRKDHRYHFIPSPHGQWCHSSITHISEIFHIWNPSAGSHHVWNEMYVKFKCCPKPEPNEDMGMVFVHNWKDMRANRTKWYKIPECSVFFLHHWSLQNEMCAPNVHWPMYNLVLSDLPMLYRGYANKPMQNGSDAYPEITMKRVDIMAQWQQGLMCWTGPPQVQSPDMYSFDIVYVYYWFKPHINLMAWMRIQLKAWVEKQQYGEEFCYSGIHMAWVNGGTTRPDCKATVLECTLLAGPCCDSCLMETVHRNEPWKMGKIMFNFGMCPCICIVALEWDQGHWGKCLPECMGNPHMAHCLGQQKIMYTGLDWYSNENWKTPNIFPETQWYYVHHFHGNEPLGPCESEQGMTMVESMQPCWRNFGCLNSYCQTMQIHVRTFQDQDFKNDFSKCEADYFSHWNMSCSYTGVRPTMWCEIPSYDMSQNSQTKMIMVWNNFVHTCIDHVWQKSGETSHHTNSVELGYMADYIVYQGAVRDAVHTKTPPCPCARYNIYPGECQWACALQGWHSADGWCEQWGNDTKYVHGEWQEEVGVCRELNGCDRSICYYKWKWWKCILHSEDIICMILCNHGNEYDQKQTQLHHICQIYCHWDYLAWEQVYTLKLCCKHIHDCWADEVWCVNNVLRVNKAWSCHRSLAHEQCDVWETVPDQTWNYRMDEATHERQAYHNNRGMIGWEFSRTSLVKSAWECMDAYCNARDPLSCEIAFWQMRNRPEIIHGLMPEPCRYNQMGHRVRNLKSWYNQIECDDGTLSQAYITVISKHIPLTTGAHVQRVKPRCRNVLLIVQSPQMPETNSRFAIHNMQRCEQDQGSWRTRCVSWYYGAPLEIELGGKYMSVITHTGCGCKGQTLQLEIIMDMVNARWGIYFYLIKDYWQSYITFRCMPPMMVYVISNRHEEYNCMAYMNPQLNNVERRHEIGYHGNPFGVNDIWICNLHEHIHNCQILRVGASAPVVCQVMIGNQQQKHVRVCTASTPLGLPCLRWMWQLTFPVMSVHIETYGCRQWHIVFTDPIAYNSMVMWRFDMTLHMTSYKLTCSWCIDPSLWYGWREPTTSPLHISCTKASGLSIWGMTMVIFSIWGGQSRWWYKKWIATMNRIIQTLESPAVPKSCDCMNWHLGCTKMGPHCYRCMLHLHSVIPSHSKIEFRAQFEDKARKCNPYEHYLGGEYVSHNKPHDIWDMGPHEGKDGASDYWQYFVKSQ
DFPMYSQNMEQMDDRMGIKWHGNDDPCPEIQPILEYLLDKVDQYNDMVSGIHHTTCADVSRWMDAGVASLYWEPPEMSCRNCTDQMCIADIFPAQHDQVLIPRWDHWSSPGTQAICLGLRTDWIKIFMKSIAHWWSWYDDTTMVMDQNKSNPERKEWSSMSEFFKGIQITSEWKCATKCGFWYLDCDRKYFNIKYVELWTAQNEDNSQRRLCAQQGDHQDHLTFMLRPNWMQVLWVSILWLEQMEYPGMWKNILNNWTHFRERTKWARNEANRAENMCVFLFRAQEGYAKLPIGFDDVLVNNWMECWPDVLEKCYLMRWKHKNSVCVMKARQTSGSTPKPNTSAWWDAVVLLQISWWPFPPKAFAAYGRTKQYDLVRAWPKAYLRNSFKICVNGRFDDCYTVGTTEYFVTSDLSIFGGIKFKCMKWWRAPKYGQGVDKEAPFSYHAWCHENSEWWNCTLDQSAVACVIFNYVLKWQSEAHCCALSWQNKCWRESSWFRHVKLTRRHHDQATVVLIAHRNCAHFCHDEQTMYYYWTNQKSPSICPGDPGDLASFQSCWPVQYIYRLVWYTGLQNSMDHLASGNPCLIWRQEVAMEYAGCSNGPYVVIFAKQNREQGYKNMWYMRTKTDLFDSGKDKAGDCYTKAEKQVDNEPIGSICVKPDNCSHMDQPFFTQRNMYLLGNTRVWRPDTVQWTYFVEKCAVAADDAFVDANDHWIVKAEQLCYGHESCNQLEHMIFSPVATWRPLLPWPQNLTIVDRDYDVEHIIYYTWPFVDWVENLTWHVHWDMGAPGGQYHMCFNMVQCQPKLLQGKLQSLRNSRYNHKLEYVWDAKGDAWRITFILYKNFCDRGHRALHQPAMVVLFKCRMGQQNCQSNHTCGWYYYCGESEIWCMCGKICYDSEFCAILYNGWPYSCTDAWYMVIHMYSPCIKYNHHGSLHFPIMIMPKLYLAHIFLYQDSLVRMNLQSLTGRSAPRENGSFDTSCLCSDISNEDHYAACDYSWLWFGYWPLFERIRAMRRHQAETIWWVNFDRNKVWWMTWASFVMWCNHNIDLGPEKGFDCWPACKTRNCYTPWCVNCVCQFWEISTYHCQHNPQDLSDNNSRTISYWKQIHAMLSESDIFYIGPHREKIDSNAQVKMLQCKTGCQTVCFALWEKAQAPMWETDCDDMTDIVTQYTSGAIGLADVSPWCRPKYSHLDGPNLICPQNCTVFCVGLMWENQMCNNTEFTKCSTAPYRIKKAWGTSSESEYGGWCGPTSMDMIHECQALWMRPGSSCHAQRPQTKQNCHVSVVYNNTAKEDDSGGKDICGSFGRQWQEIKQCIKNKTRPDRRFWPISGPSCKYPTYSSYWGIGIWAACGTTDPIMFHHNALNAFIGEVQCQRKYMIRVCVKCHAWFGLVNLLRCVWQTFAQWWVWKNVNFNDLVSPWDIKWVNDWEKIIRITMEWQVTSGKWAITDVMYVEVFRTNDAPLYPPWNHFVAMSEHMKGCTQMPKIHVSPPAQFTWNNNFKQNPVSYHCWQKKPIDVSMIVCMMFPAYTQVPFGAPIHYCYKQKITPEQNGFNSSPHDVYPKINQHEPVCAAKKIGFSETHRTGHKAGMTTMNCDPDRMLNTTWRHTGAFAEWWHHDITELVYPHGQDTEYCYCFHVECFPAATCLPGDMHCTCGMIRWDPEWPLLTRQERDERAHMKKNNQYLPHAPNYAWPVMRMYNVTTVACAYSCEEIQDDGIRYGQAEGNAYTYKRTYFRHIESWSWVGSGQTNSSLGLEKPWPCRWNGAIWPTTIDRPQNWQIGYDLVKIDQKLKFAWCPSLFMLTIKGVTLMYLDRADYNEKIGDTAGHPCNYPMPINVGHEGRICSKYYQWYTVPAQMTQISGKIGCSAGTMRKNFGYPNRYFPSGERYWQSGCGWADYFQIYNLTFSDGNDMICKKEAQTRRWWHEAIMLDLLEKKGLYTQCICAHYPHLDLNCCSQDSRTGAGESAQPWKYCPTSLPPRVRDAPEKWSIDRQMKWKIGPHTHAGIWQPYHVSFLPEGRMLMGVMVFYDASSKPTIWGAMDHSKDRETIAMGYGGSAIGAIVHEKSCWGQDIWCNAFWITYCRNDADPWNIWVHRSGFYKSCDPDVWVSKKCTCIMAAGRPIQYSCFTGCHVQRKCPHKARMWWQTHYVKHQKGCNVKSKSEGEYGQEDCFTEFVRNCWDSLNHYPHPPGHFHESGSQIPWGFNRWVFMFVRYQDRTEMHFCHTYIGYWHDYRFYLRRACVYDVWTQTIQHQPHPVWYTTCVWDPEAVAIKSMSDISMAYLLTVRAQQYPDIHPAHFWYLARWTIHFVIMFRISNIYVHLEQNSFHGTWIKRIFNKCLESVPHQNDAYNLNLDKSHRYQPIFQGWHFQVQKDWFGHRMINTEQKFFNFPREWNARDRTAEMIMWYKTDYALQIYLTQRARCRSSQYYAWTRDKVVAILRHMFDWLKRGAAKCYAYHKIQSCTGYLYPHWTKLDMGSQSWPECHCMVSGVQSDFGDWTEGNYYALFRFQMKITDEGPGYKYMAFFEGESMMRFEFMSAKLANEEWDRKIIGRVPFNNVRTTSKMEKACDFAHPRPEFVNPICVNCALNVCCSQKITYDRCPMRYKGWEYDDRKDHREETASHFISPHGQWCHSSITHISEIAPISNPSAGSHHVWNEMYVKFKCCPKPDGWSPCIIGPNGVTRMMHMVFYHFEMEKTHNWMHMWNNTTYRAYELPTKWYKIPECSVFFLHHWSLQVEHVEKNYCTRHCIPNVKEFTVECWPMYNLVLSDLPMLYRGYANNIDCCPMQNGSDAYPDITMIARHPAQQGPQVQYSIWDILQLLWDCYYWFSPHIFHLFAWMRIQLKAWVEKKRIYMKIWQYGEEFCYFQCQFIIHMAFVDGGTTSYIPEIGPICKATVLECLAVPVECDSECVHRNHPGIMVYICTPHLEHWGKCLPECGGSHPHMAHCLGQELMYTGLDWYTQFGYIFPFTQSYYVHHFHGPEPLGPNETRGIYMESEQQPCIKNFGCLNSYRQTMQIHVRTQDFKNDFIKCEADYFSHWDAMHESYTIAGRVWRPTMWCEIPSYSWPIFWYTKTWSQTRGIMVWNNFVTCPWMFLTWGIDHVWQKSVHACTQTFNETWQIYIVYQGAVHIKFLKTRGLPNPCARYSIYPGECQWNRACCLQGAITLHSARHPSDDGNDTKYVHIEWQEEVGVCREDICNCYVEDTGICYYKWKILHMILCNHGNEYDQKQWRLHHIGQIYCHLDYLAWEQVYTLLLCCKTIHDCWASAKYRDFSEVQCVNNVLRVYKAWCHRSLAAEQCHKWWVWETVPDQTWNYRMDEATHERQAYHNNRGGWEFSGTSLSMWECMDANARDPGDEKWSCEIPFWIDHGLMPEIWKLKSWYNQIECDDGTLSQAYITYISKHIWYLRALVQQGAHCNQRVKPRCRNGSPDTQVMYLLDVQSPQMPETNSRFAIHNMRQVHWLHNRTRLKKEIWIDGRYMSTKINQSTHTGCGTYQCHCPPEKGQPLQLEIIMDDQLMALTKDYWNSYITFREMPPMMVYVISNSCGRPMEEYNCPEIDNDLGFDYMLNACHPWHYVERCHEIGYHKNPFGVCDIWILRVFAGAGKSYADTHCGKPYIAVCQVMIGNQQQKHTKNGVKVHVWFSMGVCTASHHTYGGSMDNMICGNLRFMWQLTETYGFRQWMIVFECSNWIHNWRFKAMILLMTTCSWCIDPGSLNDPGWRKAVQPCPTVSPLHQPSCCKASGLSIWLMTMVIFSWYKKWIATMNRIIQTPESPAVPKSCDCMNWHLGHKEMLLTMIEKMGPHCYRCRLHLSPSHSKIEFRAQFEDKARKCNPFSNNKDEHYLGGEDDVKPHDIWDMGPREGKDGASDYWFYFVKSQ'''
inlines = x.split('\n')
first = inlines[0]
second = inlines[1]
#res = EditDistance(first, second)
#print(res)
|
JavaScript
|
UTF-8
| 4,981 | 2.703125 | 3 |
[] |
no_license
|
export function physics(p) {
// current acceleration is throttle (rTrigger) plus negative brake (lTrigger), then scaled down to be more intuitive
p.acceleration = p.input.rTrigger[0] + p.input.lTrigger[0] * -1;
// use acceleration as a multiplier for a limit in slow or fast speed for the current frame
let limit = (p.acceleration < 0) ? p.normalSpeed + (p.minSpeed - p.normalSpeed) * -p.acceleration : p.normalSpeed + (p.maxSpeed - p.normalSpeed) * p.acceleration;
// apply realistic scale to acceleration
p.acceleration *= 0.05;
// if accelerating or decelerating. apply acceleration up to calculated min/max speeds
if (p.acceleration > 0) {
// if above current limit, conform to limit by friction
if (p.speed > limit) {
p.speed = Math.max(p.speed - p.friction, limit);
}
// else accelerate up to limit
else {
// if going slower than normal speed, accel by friction as well
if (p.speed < p.normalSpeed) {
p.speed = Math.min(p.speed + p.acceleration + p.friction, limit);
}
else {
p.speed = Math.min(p.speed + p.acceleration, limit);
}
}
}
else if (p.acceleration < 0) {
// if below current limit, conform to limit by friction
if (p.speed < limit) {
p.speed = Math.min(p.speed + p.friction, limit);
}
// else decelerate down to limit
else {
// if going faster than normal speed, decel by friction as well
if (p.speed > p.normalSpeed) {
p.speed = Math.max(p.speed + p.acceleration - p.friction, limit);
}
else {
p.speed = Math.max(p.speed + p.acceleration, limit);
}
}
}
// else, check if above/below normalSpeed and move towards it according to friction
else {
if (p.speed > p.normalSpeed) {
p.speed -= p.friction;
if (p.speed < p.normalSpeed) {
p.speed = p.normalSpeed;
}
}
else {
p.speed += p.friction;
if (p.speed > p.normalSpeed) {
p.speed = p.normalSpeed;
}
}
}
// find distance between target angle and current angle
let angDiff = (p.input.angle[0] - p.angle);
// make sure distance uses shortest path (check going through -pi / pi breakpoint)
angDiff = Math.atan2(Math.sin(angDiff), Math.cos(angDiff));
// move current angle towards target according to distance with multipliers
// this method eases towards the angle, sharp start slow finish
//p.angle += angDiff * p.ease * p.input.magnitude[0];
// this method moves towards the angle at a constant rate, great for circles
p.angle += Math.sign(angDiff) * Math.min(Math.abs(angDiff), p.rotation) * p.input.magnitude[0];
p.vel.x = Math.cos(p.angle) * p.speed;
p.vel.y = Math.sin(p.angle) * p.speed;
/*if (p.bumperSpeed > 0) {
p.bumperSpeed -= p.bumperFriction;
if (p.bumperSpeed < 0) {
p.bumperSpeed = 0;
}
}
else {
p.bumperSpeed += p.bumperFriction;
if (p.bumperSpeed > 0) {
p.bumperSpeed = 0;
}
}*/
if (p.bumperTimer > 0) {
p.bumperTimer--;
if (p.bumperTimer <= 0) {
p.bumperSpeed = 0;
}
}
if (p.input.lBumper[0] && !p.input.lBumper[1]) {
p.bumperSpeed = Math.max(-p.maxBumperSpeed, p.bumperSpeed - p.setBumperSpeed);
p.bumperTimer = 5;
}
if (p.input.rBumper[0] && !p.input.rBumper[1]) {
p.bumperSpeed = Math.min(p.maxBumperSpeed, p.bumperSpeed + p.setBumperSpeed);
p.bumperTimer = 5;
}
for (let i=p.tailLength-1;i>0;i--) {
p.pos[i].x = p.pos[i-1].x;
p.pos[i].y = p.pos[i-1].y;
p.colours[i] = p.colours[i-1];
p.wrapped[i] = p.wrapped[i-1];
}
p.rotatedBumperSpeed.x = Math.cos(p.angle-Math.PI/2) * p.bumperSpeed;
p.rotatedBumperSpeed.y = Math.sin(p.angle-Math.PI/2) * p.bumperSpeed;
p.pos[0].x += p.vel.x + p.rotatedBumperSpeed.x;
p.pos[0].y += p.vel.y + p.rotatedBumperSpeed.y;
p.renderAngle = Math.atan2(p.vel.y + p.rotatedBumperSpeed.y, p.vel.x + p.rotatedBumperSpeed.x);
// blastzone wrapping
const w = document.body.clientWidth + 20;
const h = document.body.clientHeight + 20;
p.wrapped[0] = false;
if (p.pos[0].x > w/2) {
p.pos[0].x -= w;
p.wrapped[0] = true;
}
else if (p.pos[0].x < -w/2) {
p.pos[0].x += w;
p.wrapped[0] = true;
}
if (p.pos[0].y > h/2) {
p.pos[0].y -= h;
p.wrapped[0] = true;
}
else if (p.pos[0].y < -h/2) {
p.pos[0].y += h;
p.wrapped[0] = true;
}
// calculating colour between green and red for current frame according to speed
p.colours[0] = "rgb("+Math.round(Math.max(0, Math.min(255, ((p.maxSpeed-p.speed)/(p.maxSpeed - p.normalSpeed))*255)))+","+Math.round(Math.max(0, Math.min(255, ((p.speed-p.minSpeed)/(p.normalSpeed - p.minSpeed))*255)))+",0)";
p.collider.line.p1.x = p.pos[0].x;
p.collider.line.p1.y = p.pos[0].y;
if (p.wrapped[0]) {
p.collider.line.p2.x = p.pos[0].x;
p.collider.line.p2.y = p.pos[0].y;
}
else {
p.collider.line.p2.x = p.pos[1].x;
p.collider.line.p2.y = p.pos[1].y;
}
}
|
JavaScript
|
UTF-8
| 116 | 3.140625 | 3 |
[] |
no_license
|
var isPowerOfFour = function(num) {
if (num <= 0) return false;
return Math.log2(num)%2===0? true : false;
};
|
C++
|
UTF-8
| 317 | 2.734375 | 3 |
[] |
no_license
|
class Solution {
public:
int maxJump(vector<int>& stones)
{
int n = stones.size();
if (n==2)
return stones[1];
int ret = 0;
for (int i=0; i+2<n; i++)
ret = max(ret, stones[i+2]-stones[i]);
return ret;
}
};
|
Python
|
UTF-8
| 758 | 3.6875 | 4 |
[] |
no_license
|
str = 'cold'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
d={'name':'nari','phone':83744,'place':'tpt'}
enumerate=list(enumerate(d))
print(enumerate)
st="narendra" #1 reverse of string
print(st[::-1])
name='narendra' #2 reverse of string
reverse=reversed(name)
output=''.join(reverse)
print(output)
def reverse(s): #3 reverse of string
output=''
for i in range(len(s)-1,-1,-1):
output +=s[i]
return output
s=input('enter string')
output=reverse(s)
print(output)
def scrolling_text(text):
b = len(text)
c=[ text[i:]+text[:i] for i in range (b)]
d=[i.upper() for i in c]
print(d)
scrolling_text('codewars')
|
Markdown
|
UTF-8
| 822 | 3.34375 | 3 |
[] |
no_license
|
# lock-free stack
Задание №3: Необходимо реализовать lock-free стэк фиксированного размера (без приоритетов).
Реализовать программу, демонстрирующую корректность работы стэка.
Интерфейс должен быть следующим:
```cpp
template <class T>
class LockFreeStack {
public:
// конструктор стэка с заданной емкостью
LockFreeStack( int capacity );
// добавить элемент в стэк
void Push(T value);
// взять элемент из стэка
T Pop();
// проверяет, пустой ли стэк
bool IsEmpty();
// очищает стэк
void Clear();
}
```
|
C++
|
UTF-8
| 212 | 2.734375 | 3 |
[] |
no_license
|
# include <iostream>
class HashTable{
int key;
int value;
public:
HashTable():key(0), value(0){
}
HashTable(int k, int val):key(k), value(val){
}
int setValue(){
value++;
}
};
int main(){
}
|
Markdown
|
UTF-8
| 1,171 | 3.53125 | 4 |
[] |
no_license
|
**SplitwiseApp**
*Minimize Cash Flow Algorithm*
This project aims to ease several transactions into minimal transactions to make transactions more accessible and efficient. The underlying data structure used for the implementation of the project is heaps that can be visualized through a directed graph.

**Detailed Algorithm:**
*Do following for every person Pi where i is from 0 to n-1.*
1. Compute the net amount for every person. The net amount for person ‘i’ can be computed be subtracting sum of all debts from sum of all credits.
2. Find the two persons that are maximum creditor and maximum debtor. Let the maximum amount to be credited maximum creditor be maxCredit and maximum amount to be debited from maximum debtor be maxDebit. Let the maximum debtor be Pd and maximum creditor be Pc.
3. Find the minimum of maxDebit and maxCredit. Let minimum of two be x. Debit ‘x’ from Pd and credit this amount to Pc
4. If x is equal to maxCredit, then remove Pc from set of persons and recur for remaining (n-1) persons.
5. If x is equal to maxDebit, then remove Pd from set of persons and recur for remaining (n-1) persons.
|
Python
|
UTF-8
| 3,426 | 2.59375 | 3 |
[] |
no_license
|
import re
import requests
import json
import util
from distance import jarow
prefix_url = ""
suffix_url = ""
suffix_url1 = ""
def get(txt):
global prefix_url
global suffix_url
global suffix_url1
entity_type = " AND (entitytype:person)"
res = requests.get(prefix_url + txt.strip().lower() + suffix_url +suffix_url1)
return res.text
def get_merlinId(JSON):
pass
def get_title(JSON):
title = []
if JSON["returned"] > 0:
entities = JSON["entities"]
for entity in entities:
title.append(util.normalize(entity["title"][0]["default"]))
return title
else:
return None
def gen_index(lst):
index = {}
for item in lst:
words = util.normalize(item).split()
for i in range(len(words)):
if i == 0 and len(words) > 1:
try:
index[words[i]]["right"].append(words[i+1])
except:
index[words[i]] = {"left":[], "right":[words[i+1]]}
elif i == len(words)-1 and len(words) > 1:
try:
index[words[i]]["left"].append(words[i-1])
except:
index[words[i]] = {"right":[], "left":[words[i-1]]}
else:
if len(words) > 1:
try:
index[words[i]]["right"].append(words[i+1])
index[words[i]]["left"].append(words[i-1])
except:
index[words[i]] = {"left":[words[i-1]], "right":[words[i+1]]}
else:
pass
#print words
return index
def ngram(txt, n=2):
words = txt.split()
wlen = len(words)
ngrams = []
if wlen > n:
for i in range(wlen-n+1):
ngrams.append(" ".join(words[i:i+n]))
return ngrams
def gen_ngrams(lst):
ngrams = []
for item in lst:
ngrams += ngram(item)
return ngrams
def split_and_add(lst):
arr = []
rlst = [" and "]
for item in lst:
for r in rlst:
if item.find(r) > -1:
sp = item.split(r)
arr += sp
return arr
def find_similar(sent, lst):
dist = {}
lst = lst + split_and_add(lst)
for item in lst:
item = util.normalize(item)
sent = util.normalize(sent)
d = jarow(item, sent)
#print item , d
if d > 0.75:
dist[item] = d
#print dist
max_arr = util.get_max(dist)
return max_arr
def correct_left(rc, lc, index, rrc=None):
rc = util.normalize(rc)
dist = {}
try:
left_ctx = index[rc]["left"]
for item in left_ctx:
d = jarow(item, lc)
#print item , (d * 1.0)/len(item)
#print d
if d > 0.75:
dist[item] = d
max_arr = util.get_max(dist)
#print dist
return max_arr
except:
return None
def correct_right(lc, rc, index, llc=None):
lc = util.normalize(rc)
dist = {}
try:
right_ctx = index[rc]["right"]
for item in right_ctx:
d = jarow(item, rc)
#print item , (d * 1.0)/len(item)
if d > 0.75:
dist[item] = d
max_arr = util.get_max(dist)
#print dist
return max_arr
except:
return None
def long_substr(data):
substr = ''
if len(data) > 1 and len(data[0]) > 0:
for i in range(len(data[0])):
for j in range(len(data[0])-i+1):
if j > len(substr) and all(data[0][i:i+j] in x for x in data):
substr = data[0][i:i+j]
return substr
def auto_correct(sent):
#erica badu does not work , should check for it
#sent = "ericka badu"
txt = get(sent)
JSON = json.loads(txt)
res = get_title(JSON)
#print res
if not res == None:
"""
index = gen_index(res)
ans = correct_left("order", "lawn", index)
if ans == []:
print find_similar(sent, res)
"""
return find_similar(sent, res)
else:
return "-"
if __name__ == "__main__":
print auto_correct("erika badu")
|
TypeScript
|
UTF-8
| 283 | 2.65625 | 3 |
[] |
no_license
|
export interface ICsProcedure {
id?: number;
code?: string;
description?: string;
validityId?: number;
}
export class CsProcedure implements ICsProcedure {
constructor(public id?: number, public code?: string, public description?: string, public validityId?: number) {}
}
|
Markdown
|
UTF-8
| 1,119 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
---
title: Myztree
date: '2021-05-09T12:00:00.00Z'
description: 'Timed Rougelike Procedural Dungeon Crawler'
---
<iframe width="560" height="315"
src="https://www.youtube.com/embed/YvqnRPq5gks"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
## Timed Rougelike Procedural Dungeon Crawler
[Download Here.](https://mnchino.itch.io/myztree)
**Date**: Fall 2019 - Spring 2020<br>
**Engine**: Unreal 4 Engine<br>
**Type**: Game Dev Club Project.<br>
**Duration**: One Schoolyear
#### Description
This is a procedurally genearted dungeon crawler. The player traverses a programmatically created dungeon, collects items, wards off enemies, and advances to the next floor.
My work includes the research and development into the procedural AI programming, mapping generated floors to models in Unreal, and the player battle, progression, and overworld systems.
#### Developers
- **Desmond Oliver** (Project Lead, Musician, Programmer)
- **Anthony Ellis** (Lead Programmer, UI)
- **Lowen DiPaula** (Programmer)
- **Raychel Thress** (Artist)
- **Isaac Brown** (3D Modelling)
|
Python
|
UTF-8
| 170 | 2.9375 | 3 |
[] |
no_license
|
def dna_starts_with(in_seq, expected):
return in_seq[:(len(expected))] == expected
assert dna_starts_with('actggt', 'act')
assert not dna_starts_with('actggt', 'agt')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.