branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>yogge/themis-token<file_sep>/migrations/2_deploy_tokens.js const GETToken = artifacts.require(`./GETToken.sol`) module.exports = (deployer) => { const tokenName = "GETToken"; const tokenSymbol = "GET"; const decimalUints = 18; const icoStartTime = web3.eth.getBlock(web3.eth.blockNumber).timestamp; const icoLastingDate = 28; const icoTotalSupplyLimit = 1000000000 * 10 ** 18; const icoTokensPerEther = 10000; deployer.deploy(GETToken, tokenName, tokenSymbol, decimalUints, icoStartTime, icoLastingDate, icoTotalSupplyLimit, icoTokensPerEther) } <file_sep>/test/GETToken.js const GETToken = artifacts.require("GETToken"); const assertJump = require("zeppelin-solidity/test/helpers/assertJump.js"); const tokenName = "GETToken"; const tokenSymbol = "GET"; const decimalUints = 18; const icoStartTime = web3.eth.getBlock(web3.eth.blockNumber).timestamp; const icoLastingDate = 28; const icoTotalSupplyLimit = 1000000000 * 10 ** 18; const icoTokensPerEther = 10000; const timeController = (() => { const addSeconds = (seconds) => new Promise((resolve, reject) => web3.currentProvider.sendAsync({ jsonrpc: "2.0", method: "evm_increaseTime", params: [seconds], id: new Date().getTime() }, (error, result) => error ? reject(error) : resolve(result.result))); const addDays = (days) => addSeconds(days * 24 * 60 * 60); const currentTimestamp = () => web3.eth.getBlock(web3.eth.blockNumber).timestamp; return { addSeconds, addDays, currentTimestamp }; })(); async function advanceToBlock(number) { await timeController.addDays(number); } contract("GETToken ico", function(accounts) { beforeEach(async function () { this.GetTokenSale = await GETToken.new(tokenName, tokenSymbol, decimalUints, icoStartTime, icoLastingDate, icoTotalSupplyLimit, icoTokensPerEther); }); it("should right initialized", async function () { const actualTokenName = await this.GetTokenSale.name(); assert.equal(actualTokenName, tokenName, "wrong token name"); const actualSymbol = await this.GetTokenSale.symbol(); assert.equal(actualSymbol, tokenSymbol, "wrong symbol"); const actualDecinalUints = await this.GetTokenSale.decimals(); assert.equal(actualDecinalUints, decimalUints, "wrong decimals"); }); it("should allow to pause by owner", async function () { await this.GetTokenSale.pause(); const paused = await this.GetTokenSale.paused(); assert.equal(paused, true); }); it("should allow to unpause by owner", async function () { await this.GetTokenSale.pause(); await this.GetTokenSale.unpause(); const paused = await this.GetTokenSale.paused(); assert.equal(paused, false); }); it("should not allow to pause by not owner", async function() { try { await this.GetTokenSale.pause({from: accounts[1]}); } catch (error) { return assertJump(error); } assert.fail("should throw before"); }); it("should not allow to unpause by not owner", async function() { try { await this.GetTokenSale.unpause({from: accounts[1]}); } catch (error) { return assertJump(error); } assert.fail("should return before"); }); it("should send tokens to purchaser", async function() { const sendEther = 10; await this.GetTokenSale.sendTransaction({value: web3.toWei(sendEther, "ether"), from: accounts[1]}); const tokenBalance = await this.GetTokenSale.balanceOf(accounts[1]); const sellTokens = sendEther * icoTokensPerEther * 10 ** 18; assert.equal(tokenBalance.valueOf(), sellTokens); }); it("should allow to mint by owner(can mint)", async function() { const oriTokens = await this.GetTokenSale.balanceOf(accounts[1]).valueOf(); const success = await this.GetTokenSale.mint(accounts[1], 10 * 10 ** 18); assert(success, true, "mint tokens failed"); const nowTokens = await this.GetTokenSale.balanceOf(accounts[1]).valueOf(); assert(nowTokens - oriTokens, 10 * 10 ** 18, "wrong mint token amount"); }); it("should not allow to mint by not owner(can mint)", async function () { try { await this.GetTokenSale.mint(accounts[2], 10 * 10 ** 18, {from: accounts[1]}); } catch (error) { return assertJump(error); } assert.fail("should return before"); }); it("should not allow to mint by anyone(when finish mint)", async function () { const finishMint = await this.GetTokenSale.finishMinting(); assert(finishMint, true, "finish minting failed"); try { await this.GetTokenSale.mint(accounts[1], 10 * 10 ** 18); } catch (error) { return assertJump(error); } assert.fail("should return before"); }); it("should normal transfer tokens from account 0 to 1", async function () { const sendEther = 10; await this.GetTokenSale.sendTransaction({value: web3.toWei(sendEther, "ether"), from: accounts[0]}); await this.GetTokenSale.sendTransaction({value: web3.toWei(sendEther, "ether"), from: accounts[1]}); await this.GetTokenSale.transfer(accounts[1], sendEther * icoTokensPerEther * 10 ** 18, {from: accounts[0]}); const tokens = await this.GetTokenSale.balanceOf(accounts[1]).valueOf(); assert.equal(tokens, 20 * icoTokensPerEther * 10 ** 18, "transfer token wrong"); }); it("should allow to transfer from account 0 to 1(when approve)", async function() { const sendEther = 10; await this.GetTokenSale.sendTransaction({value: web3.toWei(sendEther, "ether"), from: accounts[0]}); const beforeTokens0 = await this.GetTokenSale.balanceOf(accounts[0]).valueOf(); const beforeTokens1 = await this.GetTokenSale.balanceOf(accounts[1]).valueOf(); await this.GetTokenSale.approve(accounts[1], sendEther * icoTokensPerEther * 10 ** 18, {from: accounts[0]}); const allowTokens = await this.GetTokenSale.allowance(accounts[0], accounts[1]); assert.equal(allowTokens, sendEther * icoTokensPerEther * 10 ** 18, "approve wrong"); await this.GetTokenSale.transferFrom(accounts[0], accounts[1], sendEther * icoTokensPerEther * 10 ** 18, {from: accounts[1]}); const afterTokens0 = await this.GetTokenSale.balanceOf(accounts[0]).valueOf(); const afterTokens1 = await this.GetTokenSale.balanceOf(accounts[1]).valueOf(); const transferTokens0 = beforeTokens0 - afterTokens0; const transferTokens1 = afterTokens1 - beforeTokens1; assert.equal(transferTokens0, sendEther * icoTokensPerEther * 10 ** 18, "account0: transfer from account 0 to 1 wrong"); assert.equal(transferTokens1, sendEther * icoTokensPerEther * 10 ** 18, "account1: transfer from account 0 to 1 wrong"); }); it("should not allow to transfer from account 0 to 1(when not approve)", async function () { const sendEther = 10; await this.GetTokenSale.sendTransaction({value: web3.toWei(sendEther, "ether"), from: accounts[0]}); try { await this.GetTokenSale.transferFrom(accounts[0], accounts[1], sendEther * 10 ** 18); } catch (error) { return assertJump(error); } assert.fail("should return before"); }) it("should not allow to purchase tokens when ico is over", async function () { const sendEther = 10; advanceToBlock(icoLastingDate+1); try { await this.GetTokenSale.sendTransaction({value: web3.toWei(sendEther, "ether"), from: accounts[1]}); } catch (error) { return assertJump(error); } assert.fail("should return before"); }); it("should allow to change ownership by owner", async function () { await this.GetTokenSale.transferOwnership(accounts[1]); await this.GetTokenSale.pause({from: accounts[1]}); const paused = await this.GetTokenSale.paused(); assert.equal(paused, true); }); });<file_sep>/README.md # themis-token-contract Themis Token Contract ## Local test 1.npm install 2.testrpc 3.truffle test
4e6bd0fa53f9ac39e87ae56c9b45f1536efa70cd
[ "JavaScript", "Markdown" ]
3
JavaScript
yogge/themis-token
b5d490a26e1ad8670d5f1c3768f8da5989a92713
876d35f0195db78b7ae535d7fa0ea7477661ab1e
refs/heads/master
<repo_name>dewabrata/ProjectX<file_sep>/app/src/main/java/com/projectx/main/modelservice/favourite/Favourite.java package com.projectx.main.modelservice.favourite; import com.projectx.main.Application.AppController; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.structure.BaseModel; @Table(database = AppController.class) public class Favourite extends BaseModel { public Favourite(String vendorId) { this.vendorId = vendorId; } public Favourite(){ } public String getVendorId() { return vendorId; } public void setVendorId(String vendorId) { this.vendorId = vendorId; } @Column @PrimaryKey private String vendorId; } <file_sep>/app/src/main/java/com/projectx/main/adapter/AdapterGridShopProductCard.java package com.projectx.main.adapter; import android.content.Context; import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.Paint; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.SetOptions; import com.projectx.main.R; import com.projectx.main.RestUtil.AppUtil; import com.projectx.main.activity.MainMenu; import com.projectx.main.activity.PhoneActivation; import com.projectx.main.modelservice.User.FirebaseFav; import com.projectx.main.modelservice.User.UserMobile; import com.projectx.main.modelservice.User.UserMobile_Table; import com.projectx.main.modelservice.favourite.Cart; import com.projectx.main.modelservice.favourite.Favourite; import com.projectx.main.modelservice.favourite.Favourite_Table; import com.projectx.main.modelservice.favourite.Star; import com.projectx.main.modelservice.favourite.Star_Table; import com.projectx.main.modelservice.vendor.Merchandise; import com.projectx.main.modelservice.vendor.Vendor; import com.projectx.main.utils.ImageUtil; import com.projectx.main.utils.Tools; import com.raizlabs.android.dbflow.sql.language.SQLite; import java.util.ArrayList; import java.util.List; public class AdapterGridShopProductCard extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<Merchandise> items = new ArrayList<>(); private Context ctx; private OnItemClickListener mOnItemClickListener; public void setOnItemClickListener(final OnItemClickListener mItemClickListener) { this.mOnItemClickListener = mItemClickListener; } public AdapterGridShopProductCard(Context context, List<Merchandise> items) { this.items = items; ctx = context; } public class OriginalViewHolder extends RecyclerView.ViewHolder { public ImageView image; public TextView title; public TextView price; public View lyt_parent; public ImageButton imgStar,imgShop; public OriginalViewHolder(View v) { super(v); image = (ImageView) v.findViewById(R.id.image); title = (TextView) v.findViewById(R.id.title); price = (TextView) v.findViewById(R.id.price); imgStar = (ImageButton) v.findViewById(R.id.imgStar); imgShop = (ImageButton) v.findViewById(R.id.imgShop); lyt_parent = (View) v.findViewById(R.id.lyt_parent); } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { RecyclerView.ViewHolder vh; View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_shop_product_card, parent, false); vh = new OriginalViewHolder(v); return vh; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { if (holder instanceof OriginalViewHolder) { final OriginalViewHolder view = (OriginalViewHolder) holder; final Merchandise p = items.get(position); view.title.setText(p.getName()); view.price.setText("Rp."+ AppUtil.formatCurrency(p.getPrice())); view.price.setPaintFlags(view.price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); // Tools.displayImageOriginal(ctx, view.image, p.image); ImageUtil.displayImage(view.image,p.getThumbnailUrl(),null); view.lyt_parent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(view, items.get(position), position); } } }); List<Star> lstFav = (ArrayList) SQLite.select().from(Star.class) .where(Star_Table.merchantId.eq(items.get(position).getId())) .queryList(); if (lstFav.size()>0){ view.imgStar.setImageResource(R.drawable.ic_star); view.imgStar.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(ctx, R.color.red_A100))); } view.imgShop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Cart cart = new Cart(items.get(position).getId()); cart.save(); } }); view.imgStar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View viewx) { if(view.imgStar.getImageTintList() == ColorStateList.valueOf(ContextCompat.getColor(ctx, R.color.red_A200))){ view.imgStar.setImageResource(R.drawable.ic_star_border); view.imgStar.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(ctx, R.color.red_A100))); Star star = new Star(items.get(position).getId()); star.delete(); }else{ view.imgStar.setImageResource(R.drawable.ic_star); view.imgStar.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(ctx, R.color.red_A200))); Star star = new Star(items.get(position).getId()); star.save(); } } }); } } @Override public int getItemCount() { return items.size(); } public interface OnItemClickListener { void onItemClick(View view, Merchandise obj, int pos); } public interface OnMoreButtonClickListener { void onItemClick(View view, Merchandise obj, MenuItem item); } }<file_sep>/app/src/main/java/com/projectx/main/modelservice/User/FirebaseFav.java package com.projectx.main.modelservice.User; public class FirebaseFav { private String category; private String id; private String parentVendor; private String type; private String vendor; public FirebaseFav(String category, String id, String parentVendor, String type, String vendor) { this.category = category; this.id = id; this.parentVendor = parentVendor; this.type = type; this.vendor = vendor; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getParentVendor() { return parentVendor; } public void setParentVendor(String parentVendor) { this.parentVendor = parentVendor; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor; } } <file_sep>/app/src/main/java/com/projectx/main/modelservice/vendor/Merchandise.java package com.projectx.main.modelservice.vendor; import java.io.Serializable; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.projectx.main.Application.AppController; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.structure.BaseModel; @Table(database = AppController.class) public class Merchandise extends BaseModel implements Serializable, Parcelable { @Column @SerializedName("startDate") @Expose private String startDate; @Column @SerializedName("categoryId") @Expose private String categoryId; @Column @SerializedName("imageUrl") @Expose private String imageUrl; @Column @SerializedName("promoPrice") @Expose private String promoPrice; @Column @SerializedName("price") @Expose private String price; @Column @SerializedName("endDate") @Expose private int endDate; @Column @SerializedName("active") @Expose private boolean active; @Column @SerializedName("itemId") @Expose private String itemId; @Column @SerializedName("name") @Expose private String name; @Column @SerializedName("thumbnailUrl") @Expose private String thumbnailUrl; @SerializedName("favourite") @Expose private int favourite; @Column @SerializedName("vendorId") @Expose private String vendorId; @Column @PrimaryKey @SerializedName("id") @Expose private String id; public final static Parcelable.Creator<Merchandise> CREATOR = new Creator<Merchandise>() { @SuppressWarnings({ "unchecked" }) public Merchandise createFromParcel(Parcel in) { return new Merchandise(in); } public Merchandise[] newArray(int size) { return (new Merchandise[size]); } } ; private final static long serialVersionUID = 2176815450935387092L; protected Merchandise(Parcel in) { this.startDate = ((String) in.readValue((String.class.getClassLoader()))); this.categoryId = ((String) in.readValue((String.class.getClassLoader()))); this.imageUrl = ((String) in.readValue((String.class.getClassLoader()))); this.promoPrice = ((String) in.readValue((String.class.getClassLoader()))); this.price = ((String) in.readValue((String.class.getClassLoader()))); this.endDate = ((int) in.readValue((int.class.getClassLoader()))); this.active = ((boolean) in.readValue((boolean.class.getClassLoader()))); this.itemId = ((String) in.readValue((String.class.getClassLoader()))); this.name = ((String) in.readValue((String.class.getClassLoader()))); this.thumbnailUrl = ((String) in.readValue((String.class.getClassLoader()))); this.favourite = ((int) in.readValue((int.class.getClassLoader()))); this.vendorId = ((String) in.readValue((String.class.getClassLoader()))); this.id = ((String) in.readValue((String.class.getClassLoader()))); } /** * No args constructor for use in serialization * */ public Merchandise() { } /** * * @param id * @param startDate * @param price * @param promoPrice * @param imageUrl * @param thumbnailUrl * @param name * @param categoryId * @param active * @param endDate * @param vendorId * @param itemId * @param favourite */ public Merchandise(String startDate, String categoryId, String imageUrl, String promoPrice, String price, int endDate, boolean active, String itemId, String name, String thumbnailUrl, int favourite, String vendorId, String id) { super(); this.startDate = startDate; this.categoryId = categoryId; this.imageUrl = imageUrl; this.promoPrice = promoPrice; this.price = price; this.endDate = endDate; this.active = active; this.itemId = itemId; this.name = name; this.thumbnailUrl = thumbnailUrl; this.favourite = favourite; this.vendorId = vendorId; this.id = id; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public Merchandise withStartDate(String startDate) { this.startDate = startDate; return this; } public String getCategoryId() { return categoryId; } public void setCategoryId(String categoryId) { this.categoryId = categoryId; } public Merchandise withCategoryId(String categoryId) { this.categoryId = categoryId; return this; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public Merchandise withImageUrl(String imageUrl) { this.imageUrl = imageUrl; return this; } public String getPromoPrice() { return promoPrice; } public void setPromoPrice(String promoPrice) { this.promoPrice = promoPrice; } public Merchandise withPromoPrice(String promoPrice) { this.promoPrice = promoPrice; return this; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Merchandise withPrice(String price) { this.price = price; return this; } public int getEndDate() { return endDate; } public void setEndDate(int endDate) { this.endDate = endDate; } public Merchandise withEndDate(int endDate) { this.endDate = endDate; return this; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public Merchandise withActive(boolean active) { this.active = active; return this; } public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public Merchandise withItemId(String itemId) { this.itemId = itemId; return this; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Merchandise withName(String name) { this.name = name; return this; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } public Merchandise withThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; return this; } public int getFavourite() { return favourite; } public void setFavourite(int favourite) { this.favourite = favourite; } public Merchandise withFavourite(int favourite) { this.favourite = favourite; return this; } public String getVendorId() { return vendorId; } public void setVendorId(String vendorId) { this.vendorId = vendorId; } public Merchandise withVendorId(String vendorId) { this.vendorId = vendorId; return this; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Merchandise withId(String id) { this.id = id; return this; } public void writeToParcel(Parcel dest, int flags) { dest.writeValue(startDate); dest.writeValue(categoryId); dest.writeValue(imageUrl); dest.writeValue(promoPrice); dest.writeValue(price); dest.writeValue(endDate); dest.writeValue(active); dest.writeValue(itemId); dest.writeValue(name); dest.writeValue(thumbnailUrl); dest.writeValue(favourite); dest.writeValue(vendorId); dest.writeValue(id); } public int describeContents() { return 0; } } <file_sep>/app/src/main/java/com/projectx/main/activity/VerificationHeader.java package com.projectx.main.activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.os.CountDownTimer; import android.support.annotation.NonNull; import android.support.design.widget.TextInputEditText; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseException; import com.google.firebase.FirebaseTooManyRequestsException; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.PhoneAuthCredential; import com.google.firebase.auth.PhoneAuthProvider; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.projectx.main.R; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; public class VerificationHeader extends AppCompatActivity { private TextView tv_coundown; private TextInputEditText txtInputPhone; private CountDownTimer countDownTimer; private String phone ; //firebase private FirebaseFirestore firestoreDB; private FirebaseUser firebaseUser; private static String uniqueIdentifier = null; private static final String UNIQUE_ID = "UNIQUE_ID"; private static final long ONE_HOUR_MILLI = 60*60*1000; private static final String TAG = "FirebasePhoneNumAuth"; private PhoneAuthProvider.OnVerificationStateChangedCallbacks callbacks; private FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_verification_header); initToolbar(); tv_coundown = (TextView) findViewById(R.id.tv_coundown); txtInputPhone = (TextInputEditText)findViewById(R.id.txtPhone); phone = getIntent().getStringExtra("phone"); if(phone!=null) { txtInputPhone.setText(phone); } firebaseAuth = FirebaseAuth.getInstance(); firestoreDB = FirebaseFirestore.getInstance(); createCallback(); getInstallationIdentifier(); getVerificationDataFromFirestoreAndVerify(null); verifyPhoneNumberInit(); countDownTimer(); ((AppCompatButton)findViewById(R.id.resend)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { resendVerificationCode("62"+txtInputPhone.getText().toString()); } }); } private void initToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(null); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private boolean validatePhoneNumber(String phoneNumber) { if (TextUtils.isEmpty(phoneNumber)) { txtInputPhone.setError("Invalid phone number."); return false; } return true; } private void verifyPhoneNumberInit() { if (!validatePhoneNumber(txtInputPhone.getText().toString())) { return; } verifyPhoneNumber("62"+txtInputPhone.getText().toString()); } private void verifyPhoneNumber(String phno){ PhoneAuthProvider.getInstance().verifyPhoneNumber(phno, 70, TimeUnit.SECONDS, this, callbacks); } private void countDownTimer() { countDownTimer = new CountDownTimer(1000 * 60 * 2, 1000) { @Override public void onTick(long l) { String text = String.format(Locale.getDefault(), "%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(l) % 60, TimeUnit.MILLISECONDS.toSeconds(l) % 60); tv_coundown.setText(text); } @Override public void onFinish() { tv_coundown.setText("00:00"); } }; countDownTimer.start(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } else { Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show(); } return super.onOptionsItemSelected(item); } private void createCallback() { callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { Log.d(TAG, "verification completed" + credential); signInWithPhoneAuthCredential(credential); } @Override public void onVerificationFailed(FirebaseException e) { Log.w(TAG, "verification failed", e); if (e instanceof FirebaseAuthInvalidCredentialsException) { // txtInputPhone.setError("Invalid phone number."); Toast.makeText(VerificationHeader.this, "Invalid phone number.", Toast.LENGTH_SHORT).show(); } else if (e instanceof FirebaseTooManyRequestsException) { Toast.makeText(VerificationHeader.this, "Trying too many timeS", Toast.LENGTH_SHORT).show(); } } @Override public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) { Log.d(TAG, "code sent " + verificationId); addVerificationDataToFirestore("62"+phone, verificationId); } }; } private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { firebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "code verified signIn successful"); firebaseUser = task.getResult().getUser(); // showSingInButtons(); } else { Log.w(TAG, "code verification failed", task.getException()); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // verifyCodeET.setError("Invalid code."); Toast.makeText(getApplicationContext(),"Invalid Code",Toast.LENGTH_LONG).show(); } } } }); } public synchronized String getInstallationIdentifier() { if (uniqueIdentifier == null) { SharedPreferences sharedPrefs = this.getSharedPreferences( UNIQUE_ID, Context.MODE_PRIVATE); uniqueIdentifier = sharedPrefs.getString(UNIQUE_ID, null); if (uniqueIdentifier == null) { uniqueIdentifier = UUID.randomUUID().toString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString(UNIQUE_ID, uniqueIdentifier); editor.commit(); } } return uniqueIdentifier; } private void getVerificationDataFromFirestoreAndVerify(final String code) { //initButtons(); firestoreDB.collection("phoneAuth").document(uniqueIdentifier) .get() .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot ds = task.getResult(); if(ds.exists()){ // disableSendCodeButton(ds.getLong("timestamp")); if(code != null){ // createCredentialSignIn(ds.getString("verificationId"), // code); }else{ verifyPhoneNumber(ds.getString("phone")); } }else{ // showSendCodeButton(); Log.d(TAG, "Code hasn't been sent yet"); } } else { Log.d(TAG, "Error getting document: ", task.getException()); } } }); } private void addVerificationDataToFirestore(String phone, String verificationId) { Map verifyMap = new HashMap(); verifyMap.put("phone", phone); // verifyMap.put("verificationId", verificationId); // verifyMap.put("timestamp",System.currentTimeMillis()); firestoreDB.collection("mobileUsers").document(uniqueIdentifier) .set(verifyMap) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "phone auth info added to db "); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding phone auth info", e); } }); } // [START resend_verification] public void resendVerificationCode(String phoneNumber) { PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback binding) callbacks); // resending // [END start_phone_auth] } // [END resend_verification] } <file_sep>/app/src/main/java/com/projectx/main/fragment/CategoryFragment.java package com.projectx.main.fragment; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.beloo.widget.chipslayoutmanager.SpacingItemDecoration; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QuerySnapshot; import com.projectx.main.Application.AppController; import com.projectx.main.R; import com.projectx.main.activity.MainMenu; import com.projectx.main.adapter.AdapterGridSingleLine; import com.projectx.main.modelservice.category.Category; import com.projectx.main.utils.Tools; import com.raizlabs.android.dbflow.config.FlowManager; import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper; import com.raizlabs.android.dbflow.structure.database.transaction.ProcessModelTransaction; import com.raizlabs.android.dbflow.structure.database.transaction.Transaction; import java.util.List; public class CategoryFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private static final String TAG ="Test" ; List<Category> lstCategory; FirebaseFirestore db; private RecyclerView recyclerView; private AdapterGridSingleLine mAdapter; private List<String> listImage; private View myFragment; public CategoryFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment CategoryFragment. */ // TODO: Rename and change types and number of parameters public static CategoryFragment newInstance(String param1, String param2) { CategoryFragment fragment = new CategoryFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment myFragment = inflater.inflate(R.layout.fragment_category, container, false); db = FirebaseFirestore.getInstance(); initComponent(); getDataList(); return myFragment; } @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onDetach() { super.onDetach(); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ private void getDataList(){ db.collection("category") .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { lstCategory = task.getResult().toObjects(Category.class); //set data and list adapter if (lstCategory.size()>0){ savedb(); } mAdapter = new AdapterGridSingleLine(getContext(), lstCategory); recyclerView.setAdapter(mAdapter); // on item list clicked mAdapter.setOnItemClickListener(new AdapterGridSingleLine.OnItemClickListener() { @Override public void onItemClick(View view, Integer obj, int position) { } }); } else { Log.d(TAG, "Error getting documents: ", task.getException()); } } }); } private void initComponent() { recyclerView = (RecyclerView) myFragment.findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2)); recyclerView.addItemDecoration(new SpacingItemDecoration(2, Tools.dpToPx(getContext(), 3))); recyclerView.setHasFixedSize(true); } public void savedb(){ FlowManager.getDatabase(AppController.class) .beginTransactionAsync(new ProcessModelTransaction.Builder<>( new ProcessModelTransaction.ProcessModel<Category>() { @Override public void processModel(Category orderItem, DatabaseWrapper wrapper) { orderItem.save(); } }).addAll(lstCategory).build()) // add elements (can also handle multiple) .error(new Transaction.Error() { @Override public void onError(Transaction transaction, Throwable error) { Toast.makeText(getActivity().getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show(); } }) .success(new Transaction.Success() { @Override public void onSuccess(Transaction transaction) { Toast.makeText(getActivity().getApplicationContext(),"Data Tersimpan",Toast.LENGTH_LONG).show(); } }).build().execute(); } } <file_sep>/app/src/main/java/com/projectx/main/activity/PhoneActivation.java package com.projectx.main.activity; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.firebase.ui.auth.AuthUI; import com.firebase.ui.auth.ErrorCodes; import com.firebase.ui.auth.IdpResponse; import com.firebase.ui.auth.ResultCodes; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.SetOptions; import com.projectx.main.modelservice.User.UserFirebase; import com.projectx.main.modelservice.User.UserMobile; import com.projectx.main.utils.Tools; import com.raizlabs.android.dbflow.sql.language.SQLite; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PhoneActivation extends AppCompatActivity { private static final int RC_SIGN_IN = 123; FirebaseFirestore db; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); db = FirebaseFirestore.getInstance(); FirebaseAuth auth = FirebaseAuth.getInstance(); if (auth.getCurrentUser() != null) { // already signed in updateStatus(true); } else { // not signed in startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setAvailableProviders( Arrays.asList( new AuthUI.IdpConfig.Builder(AuthUI.PHONE_VERIFICATION_PROVIDER).build() )) .build(), RC_SIGN_IN); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // RC_SIGN_IN is the request code you passed into startActivityForResult(...) when starting the sign in flow. if (requestCode == RC_SIGN_IN) { IdpResponse response = IdpResponse.fromResultIntent(data); // Successfully signed in if (resultCode == ResultCodes.OK) { insertDataUser(response); return; } else { // Sign in failed if (response == null) { // User pressed back button Log.e("Login","Login canceled by User"); return; } if (response.getErrorCode() == ErrorCodes.NO_NETWORK) { Log.e("Login","No Internet Connection"); return; } if (response.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) { Log.e("Login","Unknown Error"); return; } } Log.e("Login","Unknown sign in response"); } } UserFirebase user; @SuppressLint("RestrictedApi") public void insertDataUser(final IdpResponse response){ user = new UserFirebase(true,"", Tools.getDateNow(),"","",response.getPhoneNumber(),"","",true,"","android", response.getIdpSecret()); db.collection("mobileUsers") .document(response.getUser().getPhoneNumber()) .set(user, SetOptions.merge()) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { UserMobile user = new UserMobile(true,"", Tools.getDateNow(),"","",response.getPhoneNumber(),"","",true,"","android", response.getIdpSecret()); user.save(); updateStatus(true); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { }}); } public void updateStatus(boolean online){ String nophone = ""; List<UserMobile> lstUser = (ArrayList) SQLite.select().from(UserMobile.class) .queryList(); if (lstUser.size()>0){ nophone = lstUser.get(0).getId(); } DocumentReference updateStatus = db.collection("mobileUsers").document(nophone); updateStatus .update("online", online) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { startActivity(new Intent(PhoneActivation.this,MainMenu.class)); finish(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(),"Update status failed",Toast.LENGTH_SHORT).show(); startActivity(new Intent(PhoneActivation.this,MainMenu.class)); finish(); } }); } }<file_sep>/app/src/main/java/com/projectx/main/activity/ShoppingProductGrid.java package com.projectx.main.activity; import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.beloo.widget.chipslayoutmanager.SpacingItemDecoration; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.projectx.main.Application.AppController; import com.projectx.main.R; import com.projectx.main.RestUtil.APIClient; import com.projectx.main.RestUtil.APIInterfacesRest; import com.projectx.main.adapter.AdapterGridShopProductCard; import com.projectx.main.modelservice.User.UserMobile; import com.projectx.main.modelservice.category.Category; import com.projectx.main.modelservice.vendor.Merchandise; import com.projectx.main.modelservice.vendor.Merchandise_Table; import com.projectx.main.modelservice.vendor.Vendor; import com.projectx.main.utils.Tools; import com.raizlabs.android.dbflow.config.FlowManager; import com.raizlabs.android.dbflow.sql.language.SQLite; import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper; import com.raizlabs.android.dbflow.structure.database.transaction.ProcessModelTransaction; import com.raizlabs.android.dbflow.structure.database.transaction.Transaction; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ShoppingProductGrid extends AppCompatActivity { private View parent_view; private RecyclerView recyclerView; private AdapterGridShopProductCard mAdapter; List<Merchandise> items, listItems; Vendor dataVendor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shopping_product_grid); parent_view = findViewById(R.id.parent_view); // ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build(); // com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config); dataVendor = getIntent().getParcelableExtra("data"); if(dataVendor!=null) { getData(); } } private void initToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationIcon(R.drawable.ic_arrow_back); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Products"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Tools.setSystemBarColor(this, R.color.toolbarx); } private void initComponent() { recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new GridLayoutManager(this, 2)); recyclerView.addItemDecoration(new SpacingItemDecoration(2, Tools.dpToPx(this, 8))); recyclerView.setHasFixedSize(true); recyclerView.setNestedScrollingEnabled(false); listItems = (ArrayList) SQLite.select().from(Merchandise.class) .where(Merchandise_Table.vendorId.eq(dataVendor.getId())) .queryList(); //set data and list adapter mAdapter = new AdapterGridShopProductCard(this, listItems); recyclerView.setAdapter(mAdapter); // on item list clicked mAdapter.setOnItemClickListener(new AdapterGridShopProductCard.OnItemClickListener() { @Override public void onItemClick(View view, Merchandise obj, int position) { Snackbar.make(parent_view, "Item " + obj.getName() + " clicked", Snackbar.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_cart_setting, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } else { Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show(); } return super.onOptionsItemSelected(item); } APIInterfacesRest apiInterface; ProgressDialog progressDialog; private void getData(){ apiInterface = APIClient.getClient().create(APIInterfacesRest.class); if(progressDialog == null) { progressDialog = new ProgressDialog(ShoppingProductGrid.this); } progressDialog.setTitle("Loading"); progressDialog.show(); String child = "0"; if (dataVendor.isHasChild()){ child ="1"; }else{ child="0"; } String nophone = ""; List<UserMobile> lstUser = (ArrayList) SQLite.select().from(UserMobile.class) .queryList(); if (lstUser.size()>0){ nophone = lstUser.get(0).getId(); } Call<List<Merchandise>> merchantCall = apiInterface.getListMerchant1(dataVendor.getId(),dataVendor.getCategoryId(),child,Tools.getDateNow(),Tools.latitude,Tools.longitude,nophone); merchantCall.enqueue(new Callback<List<Merchandise>>() { @Override public void onResponse(Call<List<Merchandise>> call, Response<List<Merchandise>> response) { progressDialog.dismiss(); items = response.body(); if (items !=null) { savedb(); }else{ try { JSONObject jObjError = new JSONObject(response.errorBody().string()); Toast.makeText(ShoppingProductGrid.this, jObjError.getString("message"), Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(ShoppingProductGrid.this, e.getMessage(), Toast.LENGTH_LONG).show(); } } } @Override public void onFailure(Call<List<Merchandise>> call, Throwable t) { progressDialog.dismiss(); Toast.makeText(getApplicationContext(),"Maaf koneksi bermasalah",Toast.LENGTH_LONG).show(); call.cancel(); } }); } public void savedb(){ FlowManager.getDatabase(AppController.class) .beginTransactionAsync(new ProcessModelTransaction.Builder<>( new ProcessModelTransaction.ProcessModel<Merchandise>() { @Override public void processModel(Merchandise orderItem, DatabaseWrapper wrapper) { orderItem.save(); } }).addAll(items).build()) // add elements (can also handle multiple) .error(new Transaction.Error() { @Override public void onError(Transaction transaction, Throwable error) { Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show(); } }) .success(new Transaction.Success() { @Override public void onSuccess(Transaction transaction) { Toast.makeText(getApplicationContext(),"Data Tersimpan",Toast.LENGTH_LONG).show(); initToolbar(); initComponent(); } }).build().execute(); } } <file_sep>/app/src/main/java/com/projectx/main/activity/BottomSheetMap.java package com.projectx.main.activity; import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.projectx.main.R; import com.projectx.main.RestUtil.APIClient; import com.projectx.main.RestUtil.APIInterfacesRest; import com.projectx.main.modelservice.mapsvendor.MapsVendor; import com.projectx.main.modelservice.vendor.Merchandise; import com.projectx.main.modelservice.vendor.Vendor; import com.projectx.main.utils.Tools; import org.json.JSONObject; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class BottomSheetMap extends AppCompatActivity { private GoogleMap mMap; private BottomSheetBehavior bottomSheetBehavior; private Vendor dataVendor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bottom_sheet_map); dataVendor = getIntent().getParcelableExtra("data"); if (dataVendor !=null) { getData(); } Toast.makeText(this, "Swipe up bottom sheet", Toast.LENGTH_SHORT).show(); } APIInterfacesRest apiInterface; ProgressDialog progressDialog; List<MapsVendor> items; private void getData(){ apiInterface = APIClient.getClient().create(APIInterfacesRest.class); if(progressDialog == null) { progressDialog = new ProgressDialog(BottomSheetMap.this); } progressDialog.setTitle("Loading"); progressDialog.show(); String child = "0"; if (dataVendor.isHasChild()){ child ="1"; }else{ child="0"; } Call<List<MapsVendor>> merchantCall = apiInterface.getMapVendorLocation(dataVendor.getId(),dataVendor.getCategoryId(),child,dataVendor.getLat().toString(),dataVendor.getLon().toString()); merchantCall.enqueue(new Callback<List<MapsVendor>>() { @Override public void onResponse(Call<List<MapsVendor>> call, Response<List<MapsVendor>> response) { progressDialog.dismiss(); items = response.body(); if (items !=null) { initMapFragment(); initComponent(); }else{ try { JSONObject jObjError = new JSONObject(response.errorBody().string()); Toast.makeText(BottomSheetMap.this, jObjError.getString("message"), Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(BottomSheetMap.this, e.getMessage(), Toast.LENGTH_LONG).show(); } } } @Override public void onFailure(Call<List<MapsVendor>> call, Throwable t) { progressDialog.dismiss(); Toast.makeText(getApplicationContext(),"Maaf koneksi bermasalah",Toast.LENGTH_LONG).show(); call.cancel(); } }); } private void initComponent() { TextView txtAlamat = (TextView)findViewById(R.id.txtAlamat); txtAlamat.setText(dataVendor.getName()); // get the bottom sheet view LinearLayout llBottomSheet = (LinearLayout) findViewById(R.id.bottom_sheet); // init the bottom sheet behavior bottomSheetBehavior = BottomSheetBehavior.from(llBottomSheet); // change the state of the bottom sheet bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); // set callback for changes bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { } }); ((FloatingActionButton) findViewById(R.id.fab_directions)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); try { mMap.animateCamera(zoomingLocation()); } catch (Exception e) { } } }); } private void initMapFragment() { SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { mMap = Tools.configActivityMaps(googleMap); MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(dataVendor.getLat(),dataVendor.getLon())); mMap.addMarker(markerOptions); mMap.moveCamera(zoomingLocation()); mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); try { mMap.animateCamera(zoomingLocation()); } catch (Exception e) { } return true; } }); } }); } private CameraUpdate zoomingLocation() { return CameraUpdateFactory.newLatLngZoom(new LatLng(dataVendor.getLat(),dataVendor.getLon()), 13); } } <file_sep>/app/src/main/java/com/projectx/main/activity/VendorMenu.java package com.projectx.main.activity; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Toast; import com.balysv.materialripple.MaterialRippleLayout; import com.beloo.widget.chipslayoutmanager.SpacingItemDecoration; import com.github.florent37.rxgps.RxGps; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QuerySnapshot; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.projectx.main.Application.AppController; import com.projectx.main.R; import com.projectx.main.adapter.AdapterGridSingleLine; import com.projectx.main.adapter.AdapterGridSingleLineVendor; import com.projectx.main.modelservice.category.Category; import com.projectx.main.modelservice.vendor.Merchandise; import com.projectx.main.modelservice.vendor.Merchandise_Table; import com.projectx.main.modelservice.vendor.Vendor; import com.projectx.main.modelservice.vendor.Vendor_Table; import com.projectx.main.utils.ImageUtil; import com.projectx.main.utils.Tools; import com.raizlabs.android.dbflow.config.FlowManager; import com.raizlabs.android.dbflow.sql.language.SQLite; import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper; import com.raizlabs.android.dbflow.structure.database.transaction.ProcessModelTransaction; import com.raizlabs.android.dbflow.structure.database.transaction.Transaction; import java.util.ArrayList; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class VendorMenu extends AppCompatActivity { private static final String TAG ="Test" ; List<Vendor> lstCategory; FirebaseFirestore db; private View parent_view; private RecyclerView recyclerView; private AdapterGridSingleLineVendor mAdapter; private List<String> listImage; private Runnable runnable = null; private Handler handler = new Handler(); private Category dataCategory; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shopping_category_vendor); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build(); com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config); db = FirebaseFirestore.getInstance(); parent_view = findViewById(R.id.parent_view); dataCategory = getIntent().getParcelableExtra("data"); if (dataCategory !=null){ initToolbar(); initComponent(); getDataList(); }else{ } } private void getDataList(){ db.collection("vendors") .whereEqualTo("categoryId", dataCategory.getId()) .whereEqualTo("parentId","") .whereEqualTo("active",true) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { lstCategory = task.getResult().toObjects(Vendor.class); savedb(); } else { Log.d(TAG, "Error getting documents: ", task.getException()); } } }); } private void initToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationIcon(R.drawable.ic_arrow_back); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Categories"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Tools.setSystemBarColor(this, R.color.toolbarx); } private void initComponent() { recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new GridLayoutManager(this, 2)); recyclerView.addItemDecoration(new SpacingItemDecoration(2, Tools.dpToPx(getApplicationContext(), 3))); recyclerView.setHasFixedSize(true); } List<Vendor> listItems; public void savedb(){ FlowManager.getDatabase(AppController.class) .beginTransactionAsync(new ProcessModelTransaction.Builder<>( new ProcessModelTransaction.ProcessModel<Vendor>() { @Override public void processModel(Vendor orderItem, DatabaseWrapper wrapper) { orderItem.save(); } }).addAll(lstCategory).build()) // add elements (can also handle multiple) .error(new Transaction.Error() { @Override public void onError(Transaction transaction, Throwable error) { Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show(); } }) .success(new Transaction.Success() { @Override public void onSuccess(Transaction transaction) { Toast.makeText(getApplicationContext(),"Data Tersimpan",Toast.LENGTH_LONG).show(); //set data and list adapter listItems = (ArrayList) SQLite.select().from(Vendor.class) .where(Vendor_Table.categoryId.eq(dataCategory.getId())) .queryList(); mAdapter = new AdapterGridSingleLineVendor(VendorMenu.this, listItems); recyclerView.setAdapter(mAdapter); // on item list clicked mAdapter.setOnItemClickListener(new AdapterGridSingleLineVendor.OnItemClickListener() { @Override public void onItemClick(View view, Vendor obj, int position) { } }); } }).build().execute(); } } <file_sep>/app/src/main/java/com/projectx/main/modelservice/category/Category.java package com.projectx.main.modelservice.category; import android.os.Parcel; import android.os.Parcelable; import com.projectx.main.Application.AppController; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.structure.BaseModel; /** * Created by user on 3/11/2018. */ @Table(database = AppController.class) public class Category extends BaseModel implements Parcelable { @Column @PrimaryKey private String id; @Column private String imageUrl; @Column private String name; @Column private Boolean isActive; @Column private String thumbnailUrl; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean isActive() { return isActive; } public void setActive(Boolean isActive) { this.isActive = isActive; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.id); dest.writeString(this.imageUrl); dest.writeString(this.name); dest.writeByte((byte) (this.isActive ? 1 : 0)); dest.writeString(this.thumbnailUrl); } public Category() { } protected Category(Parcel in) { this.id = in.readString(); this.imageUrl = in.readString(); this.name = in.readString(); this.isActive =in.readByte() != 0; this.thumbnailUrl = in.readString(); } public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() { @Override public Category createFromParcel(Parcel source) { return new Category(source); } @Override public Category[] newArray(int size) { return new Category[size]; } }; }
12de8d5ccd56392c976034c99b8f9933aac8fee1
[ "Java" ]
11
Java
dewabrata/ProjectX
a12fc2449bae6dc62123586df4611eda417768c0
bffb4d0113d4ea900a1bb03ee5535dc6bf467f4c
refs/heads/master
<file_sep>package com.adjectivecolournoun.foobarreceiver.web; import com.adjectivecolournoun.foobarreceiver.domain.Thing; import com.adjectivecolournoun.foobarreceiver.repositories.ThingRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import static org.springframework.http.HttpStatus.NO_CONTENT; @RestController public class ReceivingController { private final ThingRepository repository; @Autowired public ReceivingController(ThingRepository repository) { this.repository = repository; } @RequestMapping("/receive") @ResponseStatus(NO_CONTENT) void receive(@RequestParam String thing) { repository.save(Thing.makeThing(thing)); } } <file_sep>package com.adjectivecolournoun.foobarreceiver.domain; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Thing { protected final Integer id; public Thing(Integer id) { this.id = id; } public static Thing makeThing(String thing) { if (thing.startsWith("foo")) { return Foo.makeFoo(thing); } else if (thing.startsWith("bar")) { return Bar.makeBar(thing); } else { throw new InvalidThingException(thing); } } protected static Matcher makeMatcher(String thing, String regex) { Matcher matcher = Pattern.compile(regex).matcher(thing); if (!matcher.matches()) { throw new InvalidThingException(thing); } return matcher; } } <file_sep>package com.adjectivecolournoun.foobarreceiver.domain; import java.util.Objects; import java.util.regex.Matcher; public class Foo extends Thing { private final String fooId; public Foo(Integer id, String fooId) { super(id); this.fooId = fooId; } static Thing makeFoo(String thing) { String regex = "foo:(\\d{4}):(\\p{XDigit}{4})"; Matcher matcher = makeMatcher(thing, regex); Integer thingId = Integer.valueOf(matcher.group(1)); String fooId = matcher.group(2); return new Foo(thingId, fooId); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Foo foo = (Foo) o; return Objects.equals(id, foo.id) && Objects.equals(fooId, foo.fooId); } @Override public int hashCode() { return Objects.hash(id, fooId); } @Override public String toString() { return "Foo{" + "id=" + id + ", fooId='" + fooId + '\'' + '}'; } } <file_sep># Thing service Create a service to receive Things over the network. Things come in two varieties: Foos and Bars. Both Foos and Bars will be posted to this service and should be stored for later retrieval. ## Thing formats All Things have an id. Different varieties of Thing have their own specific ids. ### Foo format foo:{id}:{fooid} id: 4 digits fooid: 4 hex digits ### Bar format bar:{id}:{barid}:{bazid} id: 4 digits barid: 3 hex digits bazid: 3 hex digits ## API The API will be HTTP based with the following endpoint: POST /receive?thing={foo | bar}<file_sep>package com.adjectivecolournoun.foobarreceiver.domain; import org.springframework.web.bind.annotation.ResponseStatus; import static org.springframework.http.HttpStatus.BAD_REQUEST; @ResponseStatus(BAD_REQUEST) public class InvalidThingException extends RuntimeException { public InvalidThingException(String thing) { super(thing); } }
f12145ae87cd42a4029e9ed7955e60592f77128e
[ "Markdown", "Java" ]
5
Java
andyjduncan/foobarreceiver
6af442a7fd908d7f2bdcb7d9d308fcfc6d3403b8
1f7176c1ad9807658f710f6732d7e96565b630c5
refs/heads/master
<repo_name>dylens/demoy<file_sep>/RD.md git init git remote add origin https://github.com/dylens/demoy.git git clone https://github.com/dylens/demoy.git git status #add into/remove from index git add/reset * git commit -m"" git log [--stat] git revert <commit> #discard changes in working directory git checkout -- RD.md git branch [develop] git checkout -b develop git branch -d develop git merge develop git pull origin master git push origin master<file_sep>/src/main/java/fory/powermock/MainClass.java package fory.powermock; public class MainClass { public int make(String name) { String content = StaticClass.get(name); return content.length(); } } <file_sep>/src/main/java/fory/powermock/StaticClass.java package fory.powermock; public class StaticClass { public static String get(String s) { return "hello " + s; } } <file_sep>/src/test/java/fory/powermock/MainClassTest.java package fory.powermock; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest(StaticClass.class) public class MainClassTest { public static final String DYE = "dye"; MainClass mainClass = new MainClass(); @Test public void testMake() throws Exception { PowerMock.mockStatic(StaticClass.class); PowerMock.expectPrivate(StaticClass.class, "get", DYE).andReturn("hello dye"); PowerMock.replayAll(); Assert.assertEquals(9, mainClass.make(DYE)); } }
557b3e2ad98f397dafe859fce1dd69082f779f62
[ "Markdown", "Java" ]
4
Markdown
dylens/demoy
b3c76bae5a99d5d397183c3a11a4496d7e0171a0
11f3c09144a6bd7ba1c099a3c999e253761bd53b
refs/heads/main
<repo_name>ElizaHrb18/Lab3-4<file_sep>/main.cpp #include <stdio.h> #include<iostream> #include<string.h> using namespace std; // definirea clasei de baza carte class carte { public: carte(char *nume) { strcpy(carte::nume, nume); }; void afiseaza_nume() { cout<<"\n Titlul cartii:"<<nume<<endl; }; private: char nume[40]; }; // definirea clasei derivate FisaLibrarie class FisaLibrarie: public carte { public: FisaLibrarie(char *nume, char *aut1, char *aut2, char *ed, int *np, double *p):carte(nume) { strcpy(FisaLibrarie ::autor1, aut1) ; strcpy(FisaLibrarie ::autor2, aut2) ; strcpy(FisaLibrarie ::editura, ed) ; FisaLibrarie ::nrpag=*np ; FisaLibrarie ::pret=*p ; }; void afiseaza_Libraria() { cout<<"\n Lista cartilor din librarie:"<<endl; cout<<"\n ===================================="<<endl; afiseaza_nume() ; cout <<"\n numele autorului: "<<autor1; cout <<"\n prenumele autorului: "<<autor2; cout <<"\n editura: "<<editura; cout <<"\n nr de pagini: "<<nrpag; cout <<"\n pretul cartii: "<<pret; cout<<"\n ===================================="<<endl; }; private: char autor1[40]; char autor2[40]; char editura[40]; int nrpag; double pret; }; int main() { FisaLibrarie fisa(); char wnume[40],wautor1[40],wautor2[40],weditura[40]; int wnrpag; double wpret; char r='d'; while(r=='d') { printf("\n denumirea cartii:"); gets(wnume); cout<<"\n numele autorului:"; cin>>wautor1; cout<<"\n prenumele autorului:"; cin>>wautor2; cout<<"\n editura:"; cin>>weditura; cout<<"\n nr. pagini:"; cin>>wnrpag; cout<<"\n pret:"; cin>>wpret; FisaLibrarie fisa(wnume,wautor1,wautor2,weditura,&wnrpag,&wpret); fisa.afiseaza_Libraria(); cout<<"\n continuati?(d/n):"; cin>>r; } }
f82bef44db2afe55c75721672fe21c985d2738e0
[ "C++" ]
1
C++
ElizaHrb18/Lab3-4
8a396a7a1486234863e352ced3e791c7a8aaee49
b47bafc21ccc7cbab7bb22954a535712dfc9595e
refs/heads/master
<repo_name>smithjph/Model-Selector<file_sep>/runSim.R require(caret) require(tidyverse) require(gridExtra) runSim <- function(dat, problem.type, target, error.metric){ # runs models and gives initial accuracy results # # args: dataset, type of problem (regression or classification), # target variable, error metric used to chose the best model # # returns: dataframe of algorithm type and error metrics # check for required packages list.of.packages <- c('caret','tidyverse','brnn','xgboost','neuralnet', 'leaps','rpart','fastAdaboost','deepboost','elasticnet', 'arm','plyr','mboost','randomGLM','RSNNS','e1071','naivebayes', 'LiblineaR','gridExtra') new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,'Package'])] if(length(new.packages)){ install.packages(new.packages) } # omit NAs and move the target variable to the first column dat %>% na.omit() %>% dplyr::select(target, everything()) -> dat # check target column type if(problem.type == 'regression' && class(dat[,1]) %in% c('factor', 'character', 'logical')){ print('Check the target column type', quote = F) stop() } if(problem.type == 'classification' && class(dat[,1]) != 'factor'){ print('Target column is not factor', quote = F) stop() } # create train and test sets set.seed(123) trainIndex <- createDataPartition(dat[[1]], p = 0.8, list = F, times = 1) train = dat[trainIndex,] test = dat[-trainIndex,] # set up training controls trainControl <- trainControl(method = 'cv', number = 10) # specify the models/algorithms for regression and classification if(problem.type == 'regression'){ model.methods = c('brnn','lm','leapBackward','leapForward','leapSeq', 'neuralnet','ridge','lasso','bayesglm','glmboost', 'rpart','randomGLM','xgbDART','xgbLinear','xgbTree', 'glm','mlp','mlpML','svmLinear2','knn') } if(problem.type == 'classification'){ model.methods = c('adaboost','deepboost','naive_bayes','svmLinearWeights2', 'bayesglm','xgbDART','xgbLinear','xgbTree','knn') } # initialize the out dataframe out = tibble(Algorithm = character(length(model.methods))) # create the formula form = reformulate(termlabels = names(train[,-1]), response = names(train[1])) # initialize iterator for the out dataframe x = 1 # initialize the model model = model.methods[1] # loop over the models for(model in model.methods){ # train model via caret mod.caret <- caret::train(form, data = train, method = model, trControl = trainControl, preProc = c('center', 'scale'), metric = error.metric) # fill in the algorithm and error metrics for each model out$Algorithm[x] = mod.caret$method if(problem.type == 'regression'){ out$RMSE[x] = mean(mod.caret$results$RMSE, na.rm = T) out$MAE[x] = mean(mod.caret$results$MAE, na.rm = T) out$r.squared[x] = mean(mod.caret$results$Rsquared, na.rm = T) } if(problem.type == 'classification'){ out$Accuracy[x] = mean(mod.caret$results$Accuracy, na.rm = T) } # increment x to move to the next row in our dataframe x = x + 1 } # create plots of error metrics i = 1 plotlist = list() for(i in 1:(ncol(out)-1)){ if(i == 1){ ylab = 'Algorithm' } else { ylab = '' } if(problem.type == 'regression'){ ggplot(out, aes(x = !!sym(names(out)[i+1]), y = reorder(!!sym(names(out)[1]), desc(!!sym(names(out)[i+1]))))) + geom_point() + ylab(ylab) + theme_bw() -> p } if(problem.type == 'classification'){ ggplot(out, aes(x = !!sym(names(out)[i+1]), y = reorder(!!sym(names(out)[1]), !!sym(names(out)[i+1])))) + geom_point() + ylab(ylab) + theme_bw() -> p } plotlist[[i]] = p } # combine plots into one p = grid.arrange(grobs = plotlist, nrow = 1) # print plots and return out dataframe print(p) return(out) } <file_sep>/README.md # Model-Selector Runs a number of different models and gives initial performance metrics to help with algorithm selection. Coded in R. <file_sep>/Model Selection.R setwd("~/Model Selection") source('runSim.R') data('mtcars') mtcars results = runSim(mtcars, 'regression', 'mpg', 'MAE') dat = mtcars problem.type = 'regression' target = 'mpg' data('iris') iris iris$flag = ifelse(iris$Species == 'versicolor', 1, 0) iris$flag = factor(iris$flag) results = runSim(iris, 'classification', 'flag', 'Accuracy') data('diamonds') diamonds results = runSim(diamonds, 'regression', 'carat', 'RMSE') dat = diamonds problem.type = 'regression' target = 'carat'
3434480f4af259de08130de7ba16cc404645ad92
[ "Markdown", "R" ]
3
R
smithjph/Model-Selector
0620b37418ccffc4ee460d67b9891b24ba356ab9
c8df2fa1134e622e40c8512f2f4307cfd818d128
refs/heads/master
<repo_name>yunjikim0603/knittingBetter<file_sep>/Project/src/comment/CommentDAO.java package comment; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; //import javax.naming.NamingException;//삭제 import javax.sql.DataSource; import board.BoardBean; public class CommentDAO { public Connection getConnection() throws Exception { Connection con = null; Context init = new InitialContext(); DataSource ds = (DataSource)init.lookup("java:comp/env/jdbc/MysqlDB"); con=ds.getConnection(); return con; } //content에 댓글 작성 public int insertComment(CommentBean cb) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; int comm_num = 0; try { con = getConnection(); //comm_num 최대값 구하기 String sql = "select max(comm_num) from comment"; pstmt = con.prepareStatement(sql); rs = pstmt.executeQuery(); if(rs.next()) { comm_num = rs.getInt("max(comm_num)") + 1; } //댓글 추가 sql = "insert into comment values (?,?,?,?,now())"; pstmt = con.prepareStatement(sql); pstmt.setInt(1, comm_num); pstmt.setInt(2, cb.getBoard_num());//board 번호 pstmt.setString(3, cb.getComm_id()); pstmt.setString(4, cb.getComm_content()); pstmt.executeUpdate(); //board DB에 댓글수 증가 sql = "update board set cmtCount = cmtCount + 1 where num = ?"; pstmt = con.prepareStatement(sql); pstmt.setInt(1, cb.getBoard_num()); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally { if(rs != null) try{rs.close();} catch (SQLException e) {} if(pstmt != null) try{pstmt.close();} catch (SQLException e) {} if(con != null) try{con.close();} catch (SQLException e) {} } //board 번호 전달 return cb.getBoard_num(); } //총 댓글 갯수 public int getCommentCount(int num) { int count = 0; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = getConnection(); String sql = "select count(*) from comment where board_num = ?"; pstmt = con.prepareStatement(sql); pstmt.setInt(1, num); //확인 rs = pstmt.executeQuery(); if(rs.next()) { count = rs.getInt("count(*)"); } } catch (Exception e) { e.printStackTrace(); } finally { if(rs != null) try{rs.close();} catch (SQLException e) {} if(pstmt != null) try{pstmt.close();} catch (SQLException e) {} if(con != null) try{con.close();} catch (SQLException e) {} } return count; } //board 번호로 댓글리스트 가져오기 public List getCommentList(int board_num, int startRow, int size) { List list = new ArrayList(); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = getConnection(); String sql = "select * from comment where board_num = ? order by comm_date desc limit ?,?"; pstmt = con.prepareStatement(sql); pstmt.setInt(1, board_num); pstmt.setInt(2, startRow-1); pstmt.setInt(3, size); rs = pstmt.executeQuery(); while(rs.next()) { CommentBean cb = new CommentBean(); cb.setComm_num(rs.getInt("comm_num")); cb.setBoard_num(rs.getInt("board_num")); cb.setComm_id(rs.getString("comm_id")); cb.setComm_content(rs.getString("comm_content")); cb.setComm_date(rs.getTimestamp("comm_date")); list.add(cb); } } catch (Exception e) { e.printStackTrace(); } finally { if(rs != null) try{rs.close();} catch (SQLException e) {} if(pstmt != null) try{pstmt.close();} catch (SQLException e) {} if(con != null) try{con.close();} catch (SQLException e) {} } return list; } //댓글 가져오기 public CommentBean getComment(int comm_num) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; CommentBean cb = null; try { con = getConnection(); String sql = "select * from comment where comm_num=?"; pstmt = con.prepareStatement(sql); pstmt.setInt(1, comm_num); rs = pstmt.executeQuery(); if(rs.next()) { cb = new CommentBean(); cb.setComm_num(rs.getInt("comm_num")); cb.setComm_content(rs.getString("comm_content")); } } catch (Exception e) { e.printStackTrace(); }finally { if(rs != null) try{rs.close();} catch (SQLException e) {} if(pstmt != null) try{pstmt.close();} catch (SQLException e) {} if(con != null) try{con.close();} catch (SQLException e) {} } return cb; } //댓글 수정 public void updateComment(CommentBean cb) { Connection con = null; PreparedStatement pstmt = null; try { con = getConnection(); String sql = "update comment set comm_content=? where comm_num=?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, cb.getComm_content()); pstmt.setInt(2, cb.getComm_num()); pstmt.executeUpdate(); }catch (Exception e) { e.printStackTrace(); }finally { if(pstmt != null) try{pstmt.close();} catch (SQLException e) {} if(con != null) try{con.close();} catch (SQLException e) {} } } //댓글 삭제 public int deleteComment(int comm_num, int board_num) { int count = 0; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = getConnection(); String sql = "delete from comment where comm_num=?"; pstmt = con.prepareStatement(sql); pstmt.setInt(1, comm_num); pstmt.executeUpdate(); //cmtCount 1 줄이기 sql = "update board set cmtCount = cmtCount - 1 where num=?"; pstmt = con.prepareStatement(sql); pstmt.setInt(1, board_num); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally { if(rs != null) try{rs.close();} catch (SQLException e) {} if(pstmt != null) try{pstmt.close();} catch (SQLException e) {} if(con != null) try{con.close();} catch (SQLException e) {} } return count; } } <file_sep>/Project/src/comment/CommentBean.java package comment; import java.sql.Timestamp; public class CommentBean { private int comm_num; private int board_num; private String comm_id; private String comm_content; private Timestamp comm_date; public int getComm_num() { return comm_num; } public void setComm_num(int comm_num) { this.comm_num = comm_num; } public int getBoard_num() { return board_num; } public void setBoard_num(int board_num) { this.board_num = board_num; } public String getComm_id() { return comm_id; } public void setComm_id(String comm_id) { this.comm_id = comm_id; } public String getComm_content() { return comm_content; } public void setComm_content(String comm_content) { this.comm_content = comm_content; } public Timestamp getComm_date() { return comm_date; } public void setComm_date(Timestamp comm_date) { this.comm_date = comm_date; } }
b5f35eb0eb352374d6870a013fe746ce03753485
[ "Java" ]
2
Java
yunjikim0603/knittingBetter
20b42e6c2937b9fba98bd01006560cdbf0b88647
3f21568835dc3f78397893910164555c34898d43
refs/heads/master
<file_sep>#!/usr/bin/env bash me=`basename "$0"` for file in *; do if [[ "$file" == "$me" ]]; then continue fi if [ -f "$file" ]; then ext="${file##*.}" name="${file%.*}" file -ib $file | sed 's/msvideo/avi/' | sed 's/matroska/mkv/' | grep -q $ext || echo $(file -i $file) fi done <file_sep># sh.check-file-extension
70194ef4049b4a0ddd54f4614cc536ddd58f1bdb
[ "Markdown", "Shell" ]
2
Shell
helgeelchenberg/sh.check-file-extension
462a6b6d1a9d681132a6d149e8d8333dc20a4ee9
ec13747b1f006ccda68b0d0435d4197e84f67909
refs/heads/master
<file_sep>// // Defines.h // FloorChat // // Created by chenguangjiang on 15/8/3. // Copyright (c) 2015年 Dengchenglin. All rights reserved. // #ifndef FloorChat_Defines_h #define FloorChat_Defines_h //同楼相关配置 //主域名 #define KBaseUrl @"http://192.168.3.11:8081/louyu"// //百度AppKey #define KBaiDuMapAppKey @"<KEY>" //环信AppKey #define KEaseMobAppKey @"yunluosoft#test"//@"yunluosoft#louyu"// //友盟统计 #define KUMTStatisticAppKey @"55e8347fe0f55a76bb0017ab" //友盟推送 #define KUMPushAppKey @"56d8233467e58eff29000792" #define DBLog(s, ...) NSLog(@"%s(%d): %@", __FUNCTION__, __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__]) #define KFLUrlKey @"<KEY>" #define IS_IPHONE4 ([[UIScreen mainScreen] bounds].size.height == 480) #define IS_IPHONE5 (([[UIScreen mainScreen] bounds].size.height-568)?NO:YES) #define kRGBColor(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a] #define kGYColor kRGBColor(64,146,174,1) #define kBackGroundColor kRGBColor(240,240,240,1) #define kGrayColor [UIColor colorWithPatternImage:[UIImage imageNamed:@"grayBack"]] #define kADWLocalizedString(s) NSLocalizedString(s, nil) #define kADWOriginObjectIsSubclassOfSpecifiedClass(originObject,specifiedClass) \ [[(NSObject *)originObject class] isSubclassOfClass:[specifiedClass class]] #define kADWImage(imageName) [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", \ [[NSBundle mainBundle] resourcePath], imageName]] //尺寸尺寸适配 #define ScreenHeight [[UIScreen mainScreen] bounds].size.height #define ScreenWidth [[UIScreen mainScreen] bounds].size.width #define autoX ScreenWidth/320 #define autoY (ScreenHeight>480 ? ScreenHeight/568 : 1.0) #define CGRectScaleMake(a, b, x, y) CGRectMake((a *autoX), (b * autoY), (x * autoX), (y * (autoY))) #define CGSizeScaleMake(a,b) CGSizeMake((a * autoX),(b * (autoY))) #define IS_iPhone6 (ScreenWidth == 375) ? YES : NO #define IS_iPhone6s (ScreenWidth == 414) ? YES : NO #define KeyboardHeight IS_iPhone6s #define autoFont ((ScreenWidth == 320) ? 1 : (autoX * 0.93)) #define CrudeFont @"Helvetica-Bold" #define kNavBarHeight 64 #define kTabBarHeight 49 #define kStartHeight 0 #define KTextViewHeight 200 *autoY //Cell高度 #define kTonglouCellHeight (90 *autoY) #define kMineCellHeight (44 *autoY) #define kMessageCellHeight (70 *autoFont) //颜色 #define kBoyColor kRGBColor(70 ,165,231,1) #define kGirlColor kRGBColor(250 ,62,66,1) #define kFCColor kRGBColor(138 ,92,59,1) #define kLineColor kRGBColor(235 ,235,235,1) //其他 //注册、找回密码获取验证码时间间隔 #define kTimerInterval 59 //系统消息 //未读评论数 #define kUnReadChatter @"100000" //新楼语提醒 #define kNewLouyuChatter @"100001" #endif
2461669119156f9fc39e736350ced69e0d907b8c
[ "C" ]
1
C
dengchenglin/LY
c99607615be6ecbe60cf74a6ecd1d26d18152400
246c273131dc5508e4fe1afedbc505445af9f58c
refs/heads/master
<repo_name>mdhamija94/W5D5<file_sep>/url_shortener/URLShortener/app/models/shortened_url.rb # == Schema Information # # Table name: shortened_urls # # id :bigint not null, primary key # long_url :string not null # short_url :string not null # user_id :integer not null # require 'securerandom' class ShortenedUrl < ApplicationRecord validates :short_url, presence: true, uniqueness: true validates :long_url, presence: true validates :user_id, presence: true belongs_to :submitter, primary_key: :id, foreign_key: :user_id, class_name: "User" has_many :visits, primary_key: :id, foreign_key: :url_id, class_name: 'Visit' has_many :visitors, through: :visits, source: :user def self.random_code gen = SecureRandom.urlsafe_base64 while ShortenedUrl.exists?(gen) gen = SecureRandom.urlsafe_base64 end gen end def self.url_factory(user, long_url) short = ShortenedUrl.new short.user_id, short.long_url = user.id, long_url short.short_url = ShortenedUrl.random_code short.save! end end <file_sep>/url_shortener/URLShortener/db/migrate/20190726232915_add_column_to_visits.rb class AddColumnToVisits < ActiveRecord::Migration[5.2] def change add_column :visits, :url_id, :integer, null: false end end
7dbac8c61a4b199cbd8234219f3a19cb58be1dce
[ "Ruby" ]
2
Ruby
mdhamija94/W5D5
43ec974f6f3180878db096c2ddd55e2f72ca5c6f
54578347458041504de9ad18d2290077fc3dbc1a
refs/heads/master
<repo_name>aadeliee22/Hubbard_NN<file_sep>/1_dmftsolver/QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/trng4_shared.dir/lcg64.cc.o" "CMakeFiles/trng4_shared.dir/lcg64_shift.cc.o" "CMakeFiles/trng4_shared.dir/minstd.cc.o" "CMakeFiles/trng4_shared.dir/mrg2.cc.o" "CMakeFiles/trng4_shared.dir/mrg3.cc.o" "CMakeFiles/trng4_shared.dir/mrg3s.cc.o" "CMakeFiles/trng4_shared.dir/mrg4.cc.o" "CMakeFiles/trng4_shared.dir/mrg5.cc.o" "CMakeFiles/trng4_shared.dir/mrg5s.cc.o" "CMakeFiles/trng4_shared.dir/mt19937.cc.o" "CMakeFiles/trng4_shared.dir/mt19937_64.cc.o" "CMakeFiles/trng4_shared.dir/yarn2.cc.o" "CMakeFiles/trng4_shared.dir/yarn3.cc.o" "CMakeFiles/trng4_shared.dir/yarn3s.cc.o" "CMakeFiles/trng4_shared.dir/yarn4.cc.o" "CMakeFiles/trng4_shared.dir/yarn5.cc.o" "CMakeFiles/trng4_shared.dir/yarn5s.cc.o" "libtrng4.pdb" "libtrng4.so" "libtrng4.so.22" "libtrng4.so.4.22" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/trng4_shared.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/QMC/trng4.build/Makefile # CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.18 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Disable VCS-based implicit rules. % : %,v # Disable VCS-based implicit rules. % : RCS/% # Disable VCS-based implicit rules. % : RCS/%,v # Disable VCS-based implicit rules. % : SCCS/s.% # Disable VCS-based implicit rules. % : s.% .SUFFIXES: .hpux_make_needs_suffix_list # Command-line flag to silence nested $(MAKE). $(VERBOSE)MAKESILENT = -s #Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/local/bin/cmake # The command to remove a file. RM = /usr/local/bin/cmake -E rm -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4 # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build #============================================================================= # Targets provided globally by CMake. # Special rule for the target install/strip install/strip: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/local/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip # Special rule for the target install/strip install/strip/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/local/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip/fast # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/local/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local # Special rule for the target install/local install/local/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/local/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." /usr/local/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target package_source package_source: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Run CPack packaging tool for source..." /usr/local/bin/cpack --config ./CPackSourceConfig.cmake /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/CPackSourceConfig.cmake .PHONY : package_source # Special rule for the target package_source package_source/fast: package_source .PHONY : package_source/fast # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/local/bin/cmake -P cmake_install.cmake .PHONY : install # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/local/bin/cmake -P cmake_install.cmake .PHONY : install/fast # Special rule for the target list_install_components list_install_components: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\"" .PHONY : list_install_components # Special rule for the target list_install_components list_install_components/fast: list_install_components .PHONY : list_install_components/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/local/bin/cmake --regenerate-during-build -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target package package: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Run CPack packaging tool..." /usr/local/bin/cpack --config ./CPackConfig.cmake .PHONY : package # Special rule for the target package package/fast: package .PHONY : package/fast # The main all target all: cmake_check_build_system $(CMAKE_COMMAND) -E cmake_progress_start /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/CMakeFiles /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build//CMakeFiles/progress.marks $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/CMakeFiles 0 .PHONY : all # The main clean target clean: $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named trng4_shared # Build rule for target. trng4_shared: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 trng4_shared .PHONY : trng4_shared # fast build rule for target. trng4_shared/fast: $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/build .PHONY : trng4_shared/fast #============================================================================= # Target rules for targets named trng4_static # Build rule for target. trng4_static: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 trng4_static .PHONY : trng4_static # fast build rule for target. trng4_static/fast: $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/build .PHONY : trng4_static/fast #============================================================================= # Target rules for targets named bernoulli_dist # Build rule for target. bernoulli_dist: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 bernoulli_dist .PHONY : bernoulli_dist # fast build rule for target. bernoulli_dist/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/bernoulli_dist.dir/build.make examples/CMakeFiles/bernoulli_dist.dir/build .PHONY : bernoulli_dist/fast #============================================================================= # Target rules for targets named discrete_dist # Build rule for target. discrete_dist: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 discrete_dist .PHONY : discrete_dist # fast build rule for target. discrete_dist/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/discrete_dist.dir/build.make examples/CMakeFiles/discrete_dist.dir/build .PHONY : discrete_dist/fast #============================================================================= # Target rules for targets named pi_block_openmp # Build rule for target. pi_block_openmp: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 pi_block_openmp .PHONY : pi_block_openmp # fast build rule for target. pi_block_openmp/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_openmp.dir/build.make examples/CMakeFiles/pi_block_openmp.dir/build .PHONY : pi_block_openmp/fast #============================================================================= # Target rules for targets named sample_output # Build rule for target. sample_output: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 sample_output .PHONY : sample_output # fast build rule for target. sample_output/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/sample_output.dir/build.make examples/CMakeFiles/sample_output.dir/build .PHONY : sample_output/fast #============================================================================= # Target rules for targets named Ising_model # Build rule for target. Ising_model: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 Ising_model .PHONY : Ising_model # fast build rule for target. Ising_model/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/Ising_model.dir/build.make examples/CMakeFiles/Ising_model.dir/build .PHONY : Ising_model/fast #============================================================================= # Target rules for targets named pi_block_tbb # Build rule for target. pi_block_tbb: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 pi_block_tbb .PHONY : pi_block_tbb # fast build rule for target. pi_block_tbb/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_tbb.dir/build.make examples/CMakeFiles/pi_block_tbb.dir/build .PHONY : pi_block_tbb/fast #============================================================================= # Target rules for targets named time # Build rule for target. time: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 time .PHONY : time # fast build rule for target. time/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/time.dir/build.make examples/CMakeFiles/time.dir/build .PHONY : time/fast #============================================================================= # Target rules for targets named cpp11 # Build rule for target. cpp11: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 cpp11 .PHONY : cpp11 # fast build rule for target. cpp11/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/cpp11.dir/build.make examples/CMakeFiles/cpp11.dir/build .PHONY : cpp11/fast #============================================================================= # Target rules for targets named hello_world # Build rule for target. hello_world: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 hello_world .PHONY : hello_world # fast build rule for target. hello_world/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/hello_world.dir/build.make examples/CMakeFiles/hello_world.dir/build .PHONY : hello_world/fast #============================================================================= # Target rules for targets named distributions # Build rule for target. distributions: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 distributions .PHONY : distributions # fast build rule for target. distributions/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/distributions.dir/build.make examples/CMakeFiles/distributions.dir/build .PHONY : distributions/fast #============================================================================= # Target rules for targets named pi # Build rule for target. pi: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 pi .PHONY : pi # fast build rule for target. pi/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi.dir/build.make examples/CMakeFiles/pi.dir/build .PHONY : pi/fast #============================================================================= # Target rules for targets named pi_block_mpi # Build rule for target. pi_block_mpi: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 pi_block_mpi .PHONY : pi_block_mpi # fast build rule for target. pi_block_mpi/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_mpi.dir/build.make examples/CMakeFiles/pi_block_mpi.dir/build .PHONY : pi_block_mpi/fast #============================================================================= # Target rules for targets named pi_leap_mpi # Build rule for target. pi_leap_mpi: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 pi_leap_mpi .PHONY : pi_leap_mpi # fast build rule for target. pi_leap_mpi/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_leap_mpi.dir/build.make examples/CMakeFiles/pi_leap_mpi.dir/build .PHONY : pi_leap_mpi/fast #============================================================================= # Target rules for targets named stl_container # Build rule for target. stl_container: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 stl_container .PHONY : stl_container # fast build rule for target. stl_container/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/stl_container.dir/build.make examples/CMakeFiles/stl_container.dir/build .PHONY : stl_container/fast #============================================================================= # Target rules for targets named correlated_normal_dist # Build rule for target. correlated_normal_dist: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 correlated_normal_dist .PHONY : correlated_normal_dist # fast build rule for target. correlated_normal_dist/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/correlated_normal_dist.dir/build.make examples/CMakeFiles/correlated_normal_dist.dir/build .PHONY : correlated_normal_dist/fast #============================================================================= # Target rules for targets named pi_leap_openmp # Build rule for target. pi_leap_openmp: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 pi_leap_openmp .PHONY : pi_leap_openmp # fast build rule for target. pi_leap_openmp/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_leap_openmp.dir/build.make examples/CMakeFiles/pi_leap_openmp.dir/build .PHONY : pi_leap_openmp/fast #============================================================================= # Target rules for targets named discrete_dist_c_style # Build rule for target. discrete_dist_c_style: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 discrete_dist_c_style .PHONY : discrete_dist_c_style # fast build rule for target. discrete_dist_c_style/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/discrete_dist_c_style.dir/build.make examples/CMakeFiles/discrete_dist_c_style.dir/build .PHONY : discrete_dist_c_style/fast #============================================================================= # Target rules for targets named plausibility_test # Build rule for target. plausibility_test: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 plausibility_test .PHONY : plausibility_test # fast build rule for target. plausibility_test/fast: $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/plausibility_test.dir/build.make examples/CMakeFiles/plausibility_test.dir/build .PHONY : plausibility_test/fast # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... edit_cache" @echo "... install" @echo "... install/local" @echo "... install/strip" @echo "... list_install_components" @echo "... package" @echo "... package_source" @echo "... rebuild_cache" @echo "... Ising_model" @echo "... bernoulli_dist" @echo "... correlated_normal_dist" @echo "... cpp11" @echo "... discrete_dist" @echo "... discrete_dist_c_style" @echo "... distributions" @echo "... hello_world" @echo "... pi" @echo "... pi_block_mpi" @echo "... pi_block_openmp" @echo "... pi_block_tbb" @echo "... pi_leap_mpi" @echo "... pi_leap_openmp" @echo "... plausibility_test" @echo "... sample_output" @echo "... stl_container" @echo "... time" @echo "... trng4_shared" @echo "... trng4_static" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>/1_dmftsolver/QMC/CMakeLists.txt # Copyright (c) 2020 <NAME> (<EMAIL>) CMAKE_MINIMUM_REQUIRED (VERSION 3.10 FATAL_ERROR) SET (LANGUAGES C CXX) PROJECT (INSTALL_LIBRARIES LANGUAGES ${LANGUAGES}) # add trng4 library INCLUDE (${CMAKE_CURRENT_SOURCE_DIR}/cmake/FindTRNG4.cmake) # add pybind11 library IF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/pybind11) SET (PYBIND11_GIT_REPOSITORY https://github.com/pybind/pybind11.git) MESSAGE (NOTICE " pybind11 library is cloned at the current source directory.") EXECUTE_PROCESS (COMMAND git clone ${PYBIND11_GIT_REPOSITORY} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) IF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/pybind11/CMakeLists.txt) MESSAGE (FATAL_ERROR " We can't find CMakeLists.txt! Please check a git repository again.") ENDIF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/pybind11/CMakeLists.txt) ENDIF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/pybind11) <file_sep>/1_dmftsolver/NRG/utility_cubic.py from triqs.utility import mpi import numpy as np from nrgljubljana_interface import Solver, SemiCircular import sys class BaseLatticeSolver: """ Here we assume that the Green's function of the quantum impurity model is under the paramagnetic phase (Spin up and down cases are identical.) """ def __init__(self): pass def load_data(self, imp_solver, filename): # Load previous data Delta_w = imp_solver.Delta_w['imp'].data.copy() if mpi.is_master_node(): try: Delta_w = self._load_hybridization_function(filename).reshape(Delta_w.shape) print ('READ THE PREVIOUS DATA:', filename) except IOError: print ('START WITH A DEFAULT SETTING') Delta_w = self._default_hybridization_function() Delta_w = mpi.bcast(Delta_w) self._set_hybridization_function(imp_solver, Delta_w) def _set_hybridization_function(self, imp_solver, data): # Matrix size of Green's functions in block 'bl' block_size = lambda bl : len(imp_solver.Delta_w[bl].indices[0]) for i, bl in enumerate(imp_solver.Delta_w.indices): assert(imp_solver.Delta_w[bl].data.shape == data.shape) for j, w in enumerate(imp_solver.Delta_w.mesh): for n in range(block_size(bl)): # only diagonal parts imp_solver.Delta_w[bl][w][n, n] = data[j, n, n] def _load_hybridization_function(self, filename): raise NotImplementedError def _default_hybridization_function(self): raise NotImplementedError class BetheLatticeSolver(BaseLatticeSolver): """ self-consistent equation: Delta_w = D^2/4*G_w, where Delta_w is a hybridization function and G_w full Green's function. """ def __init__(self, imp_solver, D): super(BetheLatticeSolver, self).__init__() # Initialize hybridization function (Bethe lattice) w, dosr, dosi = np.loadtxt('dos_cubic.dat', unpack = True, dtype = 'float64') Delta_w = imp_solver.Delta_w['imp'].data.copy() Delta_w = ((D/2)**2*(dosr+1j*dosi)).reshape(Delta_w.shape) self._set_hybridization_function(imp_solver, Delta_w) self._D = D self._default = imp_solver.Delta_w['imp'].data.copy() def update_hybridization_function(self, imp_solver, data): """ record a new hybridiazation function into 'imp_solver'. """ self._set_hybridization_function(imp_solver, data) def _load_hybridization_function(self, filename): """ return the hybridization function according to the self-consistent equation. """ w, _, _, _, Dr, Di, _,_,_,_,_,_ = np.loadtxt(filename, unpack = True, dtype = 'float64') return Dr+1j*Di def _default_hybridization_function(self): """ return the hybridization function of the non-interacting Green's function """ if mpi.is_master_node(): print ('INITIALIZE A HYBRIDIZATION FUNCTION WITH A CUBIC DOS.') return self._default <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/pi_block_tbb.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/pi_block_tbb.dir/pi_block_tbb.cc.o" "pi_block_tbb" "pi_block_tbb.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/pi_block_tbb.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/discrete_dist.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/discrete_dist.dir/discrete_dist.cc.o" "discrete_dist" "discrete_dist.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/discrete_dist.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/pi_leap_openmp.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/pi_leap_openmp.dir/pi_leap_openmp.cc.o" "pi_leap_openmp" "pi_leap_openmp.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/pi_leap_openmp.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/QMC/trng4.build/trng/CMakeFiles/trng4_static.dir/cmake_clean_target.cmake file(REMOVE_RECURSE "libtrng4.a" ) <file_sep>/1_dmftsolver/QMC/trng4.build/examples/Makefile # CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.18 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Disable VCS-based implicit rules. % : %,v # Disable VCS-based implicit rules. % : RCS/% # Disable VCS-based implicit rules. % : RCS/%,v # Disable VCS-based implicit rules. % : SCCS/s.% # Disable VCS-based implicit rules. % : s.% .SUFFIXES: .hpux_make_needs_suffix_list # Command-line flag to silence nested $(MAKE). $(VERBOSE)MAKESILENT = -s #Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/local/bin/cmake # The command to remove a file. RM = /usr/local/bin/cmake -E rm -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4 # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build #============================================================================= # Targets provided globally by CMake. # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/local/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local # Special rule for the target install/local install/local/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/local/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local/fast # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/local/bin/cmake -P cmake_install.cmake .PHONY : install # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/local/bin/cmake -P cmake_install.cmake .PHONY : install/fast # Special rule for the target list_install_components list_install_components: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\"" .PHONY : list_install_components # Special rule for the target list_install_components list_install_components/fast: list_install_components .PHONY : list_install_components/fast # Special rule for the target package_source package_source: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Run CPack packaging tool for source..." cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && /usr/local/bin/cpack --config ./CPackSourceConfig.cmake /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/CPackSourceConfig.cmake .PHONY : package_source # Special rule for the target package_source package_source/fast: package_source .PHONY : package_source/fast # Special rule for the target package package: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Run CPack packaging tool..." cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && /usr/local/bin/cpack --config ./CPackConfig.cmake .PHONY : package # Special rule for the target package package/fast: package .PHONY : package/fast # Special rule for the target install/strip install/strip: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/local/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip # Special rule for the target install/strip install/strip/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/local/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/local/bin/cmake --regenerate-during-build -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." /usr/local/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # The main all target all: cmake_check_build_system cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(CMAKE_COMMAND) -E cmake_progress_start /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/CMakeFiles /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/examples//CMakeFiles/progress.marks cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/all $(CMAKE_COMMAND) -E cmake_progress_start /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/CMakeFiles 0 .PHONY : all # The main clean target clean: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/preinstall .PHONY : preinstall/fast # clear depends depend: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend # Convenience name for target. examples/CMakeFiles/bernoulli_dist.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/bernoulli_dist.dir/rule .PHONY : examples/CMakeFiles/bernoulli_dist.dir/rule # Convenience name for target. bernoulli_dist: examples/CMakeFiles/bernoulli_dist.dir/rule .PHONY : bernoulli_dist # fast build rule for target. bernoulli_dist/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/bernoulli_dist.dir/build.make examples/CMakeFiles/bernoulli_dist.dir/build .PHONY : bernoulli_dist/fast # Convenience name for target. examples/CMakeFiles/discrete_dist.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/discrete_dist.dir/rule .PHONY : examples/CMakeFiles/discrete_dist.dir/rule # Convenience name for target. discrete_dist: examples/CMakeFiles/discrete_dist.dir/rule .PHONY : discrete_dist # fast build rule for target. discrete_dist/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/discrete_dist.dir/build.make examples/CMakeFiles/discrete_dist.dir/build .PHONY : discrete_dist/fast # Convenience name for target. examples/CMakeFiles/pi_block_openmp.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/pi_block_openmp.dir/rule .PHONY : examples/CMakeFiles/pi_block_openmp.dir/rule # Convenience name for target. pi_block_openmp: examples/CMakeFiles/pi_block_openmp.dir/rule .PHONY : pi_block_openmp # fast build rule for target. pi_block_openmp/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_openmp.dir/build.make examples/CMakeFiles/pi_block_openmp.dir/build .PHONY : pi_block_openmp/fast # Convenience name for target. examples/CMakeFiles/sample_output.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/sample_output.dir/rule .PHONY : examples/CMakeFiles/sample_output.dir/rule # Convenience name for target. sample_output: examples/CMakeFiles/sample_output.dir/rule .PHONY : sample_output # fast build rule for target. sample_output/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/sample_output.dir/build.make examples/CMakeFiles/sample_output.dir/build .PHONY : sample_output/fast # Convenience name for target. examples/CMakeFiles/Ising_model.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/Ising_model.dir/rule .PHONY : examples/CMakeFiles/Ising_model.dir/rule # Convenience name for target. Ising_model: examples/CMakeFiles/Ising_model.dir/rule .PHONY : Ising_model # fast build rule for target. Ising_model/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/Ising_model.dir/build.make examples/CMakeFiles/Ising_model.dir/build .PHONY : Ising_model/fast # Convenience name for target. examples/CMakeFiles/pi_block_tbb.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/pi_block_tbb.dir/rule .PHONY : examples/CMakeFiles/pi_block_tbb.dir/rule # Convenience name for target. pi_block_tbb: examples/CMakeFiles/pi_block_tbb.dir/rule .PHONY : pi_block_tbb # fast build rule for target. pi_block_tbb/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_tbb.dir/build.make examples/CMakeFiles/pi_block_tbb.dir/build .PHONY : pi_block_tbb/fast # Convenience name for target. examples/CMakeFiles/time.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/time.dir/rule .PHONY : examples/CMakeFiles/time.dir/rule # Convenience name for target. time: examples/CMakeFiles/time.dir/rule .PHONY : time # fast build rule for target. time/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/time.dir/build.make examples/CMakeFiles/time.dir/build .PHONY : time/fast # Convenience name for target. examples/CMakeFiles/cpp11.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/cpp11.dir/rule .PHONY : examples/CMakeFiles/cpp11.dir/rule # Convenience name for target. cpp11: examples/CMakeFiles/cpp11.dir/rule .PHONY : cpp11 # fast build rule for target. cpp11/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/cpp11.dir/build.make examples/CMakeFiles/cpp11.dir/build .PHONY : cpp11/fast # Convenience name for target. examples/CMakeFiles/hello_world.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/hello_world.dir/rule .PHONY : examples/CMakeFiles/hello_world.dir/rule # Convenience name for target. hello_world: examples/CMakeFiles/hello_world.dir/rule .PHONY : hello_world # fast build rule for target. hello_world/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/hello_world.dir/build.make examples/CMakeFiles/hello_world.dir/build .PHONY : hello_world/fast # Convenience name for target. examples/CMakeFiles/distributions.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/distributions.dir/rule .PHONY : examples/CMakeFiles/distributions.dir/rule # Convenience name for target. distributions: examples/CMakeFiles/distributions.dir/rule .PHONY : distributions # fast build rule for target. distributions/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/distributions.dir/build.make examples/CMakeFiles/distributions.dir/build .PHONY : distributions/fast # Convenience name for target. examples/CMakeFiles/pi.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/pi.dir/rule .PHONY : examples/CMakeFiles/pi.dir/rule # Convenience name for target. pi: examples/CMakeFiles/pi.dir/rule .PHONY : pi # fast build rule for target. pi/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi.dir/build.make examples/CMakeFiles/pi.dir/build .PHONY : pi/fast # Convenience name for target. examples/CMakeFiles/pi_block_mpi.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/pi_block_mpi.dir/rule .PHONY : examples/CMakeFiles/pi_block_mpi.dir/rule # Convenience name for target. pi_block_mpi: examples/CMakeFiles/pi_block_mpi.dir/rule .PHONY : pi_block_mpi # fast build rule for target. pi_block_mpi/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_mpi.dir/build.make examples/CMakeFiles/pi_block_mpi.dir/build .PHONY : pi_block_mpi/fast # Convenience name for target. examples/CMakeFiles/pi_leap_mpi.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/pi_leap_mpi.dir/rule .PHONY : examples/CMakeFiles/pi_leap_mpi.dir/rule # Convenience name for target. pi_leap_mpi: examples/CMakeFiles/pi_leap_mpi.dir/rule .PHONY : pi_leap_mpi # fast build rule for target. pi_leap_mpi/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_leap_mpi.dir/build.make examples/CMakeFiles/pi_leap_mpi.dir/build .PHONY : pi_leap_mpi/fast # Convenience name for target. examples/CMakeFiles/stl_container.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/stl_container.dir/rule .PHONY : examples/CMakeFiles/stl_container.dir/rule # Convenience name for target. stl_container: examples/CMakeFiles/stl_container.dir/rule .PHONY : stl_container # fast build rule for target. stl_container/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/stl_container.dir/build.make examples/CMakeFiles/stl_container.dir/build .PHONY : stl_container/fast # Convenience name for target. examples/CMakeFiles/correlated_normal_dist.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/correlated_normal_dist.dir/rule .PHONY : examples/CMakeFiles/correlated_normal_dist.dir/rule # Convenience name for target. correlated_normal_dist: examples/CMakeFiles/correlated_normal_dist.dir/rule .PHONY : correlated_normal_dist # fast build rule for target. correlated_normal_dist/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/correlated_normal_dist.dir/build.make examples/CMakeFiles/correlated_normal_dist.dir/build .PHONY : correlated_normal_dist/fast # Convenience name for target. examples/CMakeFiles/pi_leap_openmp.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/pi_leap_openmp.dir/rule .PHONY : examples/CMakeFiles/pi_leap_openmp.dir/rule # Convenience name for target. pi_leap_openmp: examples/CMakeFiles/pi_leap_openmp.dir/rule .PHONY : pi_leap_openmp # fast build rule for target. pi_leap_openmp/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_leap_openmp.dir/build.make examples/CMakeFiles/pi_leap_openmp.dir/build .PHONY : pi_leap_openmp/fast # Convenience name for target. examples/CMakeFiles/discrete_dist_c_style.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/discrete_dist_c_style.dir/rule .PHONY : examples/CMakeFiles/discrete_dist_c_style.dir/rule # Convenience name for target. discrete_dist_c_style: examples/CMakeFiles/discrete_dist_c_style.dir/rule .PHONY : discrete_dist_c_style # fast build rule for target. discrete_dist_c_style/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/discrete_dist_c_style.dir/build.make examples/CMakeFiles/discrete_dist_c_style.dir/build .PHONY : discrete_dist_c_style/fast # Convenience name for target. examples/CMakeFiles/plausibility_test.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 examples/CMakeFiles/plausibility_test.dir/rule .PHONY : examples/CMakeFiles/plausibility_test.dir/rule # Convenience name for target. plausibility_test: examples/CMakeFiles/plausibility_test.dir/rule .PHONY : plausibility_test # fast build rule for target. plausibility_test/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/plausibility_test.dir/build.make examples/CMakeFiles/plausibility_test.dir/build .PHONY : plausibility_test/fast Ising_model.o: Ising_model.cc.o .PHONY : Ising_model.o # target to build an object file Ising_model.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/Ising_model.dir/build.make examples/CMakeFiles/Ising_model.dir/Ising_model.cc.o .PHONY : Ising_model.cc.o Ising_model.i: Ising_model.cc.i .PHONY : Ising_model.i # target to preprocess a source file Ising_model.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/Ising_model.dir/build.make examples/CMakeFiles/Ising_model.dir/Ising_model.cc.i .PHONY : Ising_model.cc.i Ising_model.s: Ising_model.cc.s .PHONY : Ising_model.s # target to generate assembly for a file Ising_model.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/Ising_model.dir/build.make examples/CMakeFiles/Ising_model.dir/Ising_model.cc.s .PHONY : Ising_model.cc.s bernoulli_dist.o: bernoulli_dist.cc.o .PHONY : bernoulli_dist.o # target to build an object file bernoulli_dist.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/bernoulli_dist.dir/build.make examples/CMakeFiles/bernoulli_dist.dir/bernoulli_dist.cc.o .PHONY : bernoulli_dist.cc.o bernoulli_dist.i: bernoulli_dist.cc.i .PHONY : bernoulli_dist.i # target to preprocess a source file bernoulli_dist.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/bernoulli_dist.dir/build.make examples/CMakeFiles/bernoulli_dist.dir/bernoulli_dist.cc.i .PHONY : bernoulli_dist.cc.i bernoulli_dist.s: bernoulli_dist.cc.s .PHONY : bernoulli_dist.s # target to generate assembly for a file bernoulli_dist.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/bernoulli_dist.dir/build.make examples/CMakeFiles/bernoulli_dist.dir/bernoulli_dist.cc.s .PHONY : bernoulli_dist.cc.s correlated_normal_dist.o: correlated_normal_dist.cc.o .PHONY : correlated_normal_dist.o # target to build an object file correlated_normal_dist.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/correlated_normal_dist.dir/build.make examples/CMakeFiles/correlated_normal_dist.dir/correlated_normal_dist.cc.o .PHONY : correlated_normal_dist.cc.o correlated_normal_dist.i: correlated_normal_dist.cc.i .PHONY : correlated_normal_dist.i # target to preprocess a source file correlated_normal_dist.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/correlated_normal_dist.dir/build.make examples/CMakeFiles/correlated_normal_dist.dir/correlated_normal_dist.cc.i .PHONY : correlated_normal_dist.cc.i correlated_normal_dist.s: correlated_normal_dist.cc.s .PHONY : correlated_normal_dist.s # target to generate assembly for a file correlated_normal_dist.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/correlated_normal_dist.dir/build.make examples/CMakeFiles/correlated_normal_dist.dir/correlated_normal_dist.cc.s .PHONY : correlated_normal_dist.cc.s cpp11.o: cpp11.cc.o .PHONY : cpp11.o # target to build an object file cpp11.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/cpp11.dir/build.make examples/CMakeFiles/cpp11.dir/cpp11.cc.o .PHONY : cpp11.cc.o cpp11.i: cpp11.cc.i .PHONY : cpp11.i # target to preprocess a source file cpp11.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/cpp11.dir/build.make examples/CMakeFiles/cpp11.dir/cpp11.cc.i .PHONY : cpp11.cc.i cpp11.s: cpp11.cc.s .PHONY : cpp11.s # target to generate assembly for a file cpp11.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/cpp11.dir/build.make examples/CMakeFiles/cpp11.dir/cpp11.cc.s .PHONY : cpp11.cc.s discrete_dist.o: discrete_dist.cc.o .PHONY : discrete_dist.o # target to build an object file discrete_dist.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/discrete_dist.dir/build.make examples/CMakeFiles/discrete_dist.dir/discrete_dist.cc.o .PHONY : discrete_dist.cc.o discrete_dist.i: discrete_dist.cc.i .PHONY : discrete_dist.i # target to preprocess a source file discrete_dist.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/discrete_dist.dir/build.make examples/CMakeFiles/discrete_dist.dir/discrete_dist.cc.i .PHONY : discrete_dist.cc.i discrete_dist.s: discrete_dist.cc.s .PHONY : discrete_dist.s # target to generate assembly for a file discrete_dist.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/discrete_dist.dir/build.make examples/CMakeFiles/discrete_dist.dir/discrete_dist.cc.s .PHONY : discrete_dist.cc.s discrete_dist_c_style.o: discrete_dist_c_style.cc.o .PHONY : discrete_dist_c_style.o # target to build an object file discrete_dist_c_style.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/discrete_dist_c_style.dir/build.make examples/CMakeFiles/discrete_dist_c_style.dir/discrete_dist_c_style.cc.o .PHONY : discrete_dist_c_style.cc.o discrete_dist_c_style.i: discrete_dist_c_style.cc.i .PHONY : discrete_dist_c_style.i # target to preprocess a source file discrete_dist_c_style.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/discrete_dist_c_style.dir/build.make examples/CMakeFiles/discrete_dist_c_style.dir/discrete_dist_c_style.cc.i .PHONY : discrete_dist_c_style.cc.i discrete_dist_c_style.s: discrete_dist_c_style.cc.s .PHONY : discrete_dist_c_style.s # target to generate assembly for a file discrete_dist_c_style.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/discrete_dist_c_style.dir/build.make examples/CMakeFiles/discrete_dist_c_style.dir/discrete_dist_c_style.cc.s .PHONY : discrete_dist_c_style.cc.s distributions.o: distributions.cc.o .PHONY : distributions.o # target to build an object file distributions.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/distributions.dir/build.make examples/CMakeFiles/distributions.dir/distributions.cc.o .PHONY : distributions.cc.o distributions.i: distributions.cc.i .PHONY : distributions.i # target to preprocess a source file distributions.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/distributions.dir/build.make examples/CMakeFiles/distributions.dir/distributions.cc.i .PHONY : distributions.cc.i distributions.s: distributions.cc.s .PHONY : distributions.s # target to generate assembly for a file distributions.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/distributions.dir/build.make examples/CMakeFiles/distributions.dir/distributions.cc.s .PHONY : distributions.cc.s hello_world.o: hello_world.cc.o .PHONY : hello_world.o # target to build an object file hello_world.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/hello_world.dir/build.make examples/CMakeFiles/hello_world.dir/hello_world.cc.o .PHONY : hello_world.cc.o hello_world.i: hello_world.cc.i .PHONY : hello_world.i # target to preprocess a source file hello_world.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/hello_world.dir/build.make examples/CMakeFiles/hello_world.dir/hello_world.cc.i .PHONY : hello_world.cc.i hello_world.s: hello_world.cc.s .PHONY : hello_world.s # target to generate assembly for a file hello_world.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/hello_world.dir/build.make examples/CMakeFiles/hello_world.dir/hello_world.cc.s .PHONY : hello_world.cc.s pi.o: pi.cc.o .PHONY : pi.o # target to build an object file pi.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi.dir/build.make examples/CMakeFiles/pi.dir/pi.cc.o .PHONY : pi.cc.o pi.i: pi.cc.i .PHONY : pi.i # target to preprocess a source file pi.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi.dir/build.make examples/CMakeFiles/pi.dir/pi.cc.i .PHONY : pi.cc.i pi.s: pi.cc.s .PHONY : pi.s # target to generate assembly for a file pi.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi.dir/build.make examples/CMakeFiles/pi.dir/pi.cc.s .PHONY : pi.cc.s pi_block_mpi.o: pi_block_mpi.cc.o .PHONY : pi_block_mpi.o # target to build an object file pi_block_mpi.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_mpi.dir/build.make examples/CMakeFiles/pi_block_mpi.dir/pi_block_mpi.cc.o .PHONY : pi_block_mpi.cc.o pi_block_mpi.i: pi_block_mpi.cc.i .PHONY : pi_block_mpi.i # target to preprocess a source file pi_block_mpi.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_mpi.dir/build.make examples/CMakeFiles/pi_block_mpi.dir/pi_block_mpi.cc.i .PHONY : pi_block_mpi.cc.i pi_block_mpi.s: pi_block_mpi.cc.s .PHONY : pi_block_mpi.s # target to generate assembly for a file pi_block_mpi.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_mpi.dir/build.make examples/CMakeFiles/pi_block_mpi.dir/pi_block_mpi.cc.s .PHONY : pi_block_mpi.cc.s pi_block_openmp.o: pi_block_openmp.cc.o .PHONY : pi_block_openmp.o # target to build an object file pi_block_openmp.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_openmp.dir/build.make examples/CMakeFiles/pi_block_openmp.dir/pi_block_openmp.cc.o .PHONY : pi_block_openmp.cc.o pi_block_openmp.i: pi_block_openmp.cc.i .PHONY : pi_block_openmp.i # target to preprocess a source file pi_block_openmp.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_openmp.dir/build.make examples/CMakeFiles/pi_block_openmp.dir/pi_block_openmp.cc.i .PHONY : pi_block_openmp.cc.i pi_block_openmp.s: pi_block_openmp.cc.s .PHONY : pi_block_openmp.s # target to generate assembly for a file pi_block_openmp.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_openmp.dir/build.make examples/CMakeFiles/pi_block_openmp.dir/pi_block_openmp.cc.s .PHONY : pi_block_openmp.cc.s pi_block_tbb.o: pi_block_tbb.cc.o .PHONY : pi_block_tbb.o # target to build an object file pi_block_tbb.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_tbb.dir/build.make examples/CMakeFiles/pi_block_tbb.dir/pi_block_tbb.cc.o .PHONY : pi_block_tbb.cc.o pi_block_tbb.i: pi_block_tbb.cc.i .PHONY : pi_block_tbb.i # target to preprocess a source file pi_block_tbb.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_tbb.dir/build.make examples/CMakeFiles/pi_block_tbb.dir/pi_block_tbb.cc.i .PHONY : pi_block_tbb.cc.i pi_block_tbb.s: pi_block_tbb.cc.s .PHONY : pi_block_tbb.s # target to generate assembly for a file pi_block_tbb.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_block_tbb.dir/build.make examples/CMakeFiles/pi_block_tbb.dir/pi_block_tbb.cc.s .PHONY : pi_block_tbb.cc.s pi_leap_mpi.o: pi_leap_mpi.cc.o .PHONY : pi_leap_mpi.o # target to build an object file pi_leap_mpi.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_leap_mpi.dir/build.make examples/CMakeFiles/pi_leap_mpi.dir/pi_leap_mpi.cc.o .PHONY : pi_leap_mpi.cc.o pi_leap_mpi.i: pi_leap_mpi.cc.i .PHONY : pi_leap_mpi.i # target to preprocess a source file pi_leap_mpi.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_leap_mpi.dir/build.make examples/CMakeFiles/pi_leap_mpi.dir/pi_leap_mpi.cc.i .PHONY : pi_leap_mpi.cc.i pi_leap_mpi.s: pi_leap_mpi.cc.s .PHONY : pi_leap_mpi.s # target to generate assembly for a file pi_leap_mpi.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_leap_mpi.dir/build.make examples/CMakeFiles/pi_leap_mpi.dir/pi_leap_mpi.cc.s .PHONY : pi_leap_mpi.cc.s pi_leap_openmp.o: pi_leap_openmp.cc.o .PHONY : pi_leap_openmp.o # target to build an object file pi_leap_openmp.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_leap_openmp.dir/build.make examples/CMakeFiles/pi_leap_openmp.dir/pi_leap_openmp.cc.o .PHONY : pi_leap_openmp.cc.o pi_leap_openmp.i: pi_leap_openmp.cc.i .PHONY : pi_leap_openmp.i # target to preprocess a source file pi_leap_openmp.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_leap_openmp.dir/build.make examples/CMakeFiles/pi_leap_openmp.dir/pi_leap_openmp.cc.i .PHONY : pi_leap_openmp.cc.i pi_leap_openmp.s: pi_leap_openmp.cc.s .PHONY : pi_leap_openmp.s # target to generate assembly for a file pi_leap_openmp.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/pi_leap_openmp.dir/build.make examples/CMakeFiles/pi_leap_openmp.dir/pi_leap_openmp.cc.s .PHONY : pi_leap_openmp.cc.s plausibility_test.o: plausibility_test.cc.o .PHONY : plausibility_test.o # target to build an object file plausibility_test.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/plausibility_test.dir/build.make examples/CMakeFiles/plausibility_test.dir/plausibility_test.cc.o .PHONY : plausibility_test.cc.o plausibility_test.i: plausibility_test.cc.i .PHONY : plausibility_test.i # target to preprocess a source file plausibility_test.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/plausibility_test.dir/build.make examples/CMakeFiles/plausibility_test.dir/plausibility_test.cc.i .PHONY : plausibility_test.cc.i plausibility_test.s: plausibility_test.cc.s .PHONY : plausibility_test.s # target to generate assembly for a file plausibility_test.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/plausibility_test.dir/build.make examples/CMakeFiles/plausibility_test.dir/plausibility_test.cc.s .PHONY : plausibility_test.cc.s sample_output.o: sample_output.cc.o .PHONY : sample_output.o # target to build an object file sample_output.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/sample_output.dir/build.make examples/CMakeFiles/sample_output.dir/sample_output.cc.o .PHONY : sample_output.cc.o sample_output.i: sample_output.cc.i .PHONY : sample_output.i # target to preprocess a source file sample_output.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/sample_output.dir/build.make examples/CMakeFiles/sample_output.dir/sample_output.cc.i .PHONY : sample_output.cc.i sample_output.s: sample_output.cc.s .PHONY : sample_output.s # target to generate assembly for a file sample_output.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/sample_output.dir/build.make examples/CMakeFiles/sample_output.dir/sample_output.cc.s .PHONY : sample_output.cc.s stl_container.o: stl_container.cc.o .PHONY : stl_container.o # target to build an object file stl_container.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/stl_container.dir/build.make examples/CMakeFiles/stl_container.dir/stl_container.cc.o .PHONY : stl_container.cc.o stl_container.i: stl_container.cc.i .PHONY : stl_container.i # target to preprocess a source file stl_container.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/stl_container.dir/build.make examples/CMakeFiles/stl_container.dir/stl_container.cc.i .PHONY : stl_container.cc.i stl_container.s: stl_container.cc.s .PHONY : stl_container.s # target to generate assembly for a file stl_container.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/stl_container.dir/build.make examples/CMakeFiles/stl_container.dir/stl_container.cc.s .PHONY : stl_container.cc.s time.o: time.cc.o .PHONY : time.o # target to build an object file time.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/time.dir/build.make examples/CMakeFiles/time.dir/time.cc.o .PHONY : time.cc.o time.i: time.cc.i .PHONY : time.i # target to preprocess a source file time.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/time.dir/build.make examples/CMakeFiles/time.dir/time.cc.i .PHONY : time.cc.i time.s: time.cc.s .PHONY : time.s # target to generate assembly for a file time.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f examples/CMakeFiles/time.dir/build.make examples/CMakeFiles/time.dir/time.cc.s .PHONY : time.cc.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... edit_cache" @echo "... install" @echo "... install/local" @echo "... install/strip" @echo "... list_install_components" @echo "... package" @echo "... package_source" @echo "... rebuild_cache" @echo "... Ising_model" @echo "... bernoulli_dist" @echo "... correlated_normal_dist" @echo "... cpp11" @echo "... discrete_dist" @echo "... discrete_dist_c_style" @echo "... distributions" @echo "... hello_world" @echo "... pi" @echo "... pi_block_mpi" @echo "... pi_block_openmp" @echo "... pi_block_tbb" @echo "... pi_leap_mpi" @echo "... pi_leap_openmp" @echo "... plausibility_test" @echo "... sample_output" @echo "... stl_container" @echo "... time" @echo "... Ising_model.o" @echo "... Ising_model.i" @echo "... Ising_model.s" @echo "... bernoulli_dist.o" @echo "... bernoulli_dist.i" @echo "... bernoulli_dist.s" @echo "... correlated_normal_dist.o" @echo "... correlated_normal_dist.i" @echo "... correlated_normal_dist.s" @echo "... cpp11.o" @echo "... cpp11.i" @echo "... cpp11.s" @echo "... discrete_dist.o" @echo "... discrete_dist.i" @echo "... discrete_dist.s" @echo "... discrete_dist_c_style.o" @echo "... discrete_dist_c_style.i" @echo "... discrete_dist_c_style.s" @echo "... distributions.o" @echo "... distributions.i" @echo "... distributions.s" @echo "... hello_world.o" @echo "... hello_world.i" @echo "... hello_world.s" @echo "... pi.o" @echo "... pi.i" @echo "... pi.s" @echo "... pi_block_mpi.o" @echo "... pi_block_mpi.i" @echo "... pi_block_mpi.s" @echo "... pi_block_openmp.o" @echo "... pi_block_openmp.i" @echo "... pi_block_openmp.s" @echo "... pi_block_tbb.o" @echo "... pi_block_tbb.i" @echo "... pi_block_tbb.s" @echo "... pi_leap_mpi.o" @echo "... pi_leap_mpi.i" @echo "... pi_leap_mpi.s" @echo "... pi_leap_openmp.o" @echo "... pi_leap_openmp.i" @echo "... pi_leap_openmp.s" @echo "... plausibility_test.o" @echo "... plausibility_test.i" @echo "... plausibility_test.s" @echo "... sample_output.o" @echo "... sample_output.i" @echo "... sample_output.s" @echo "... stl_container.o" @echo "... stl_container.i" @echo "... stl_container.s" @echo "... time.o" @echo "... time.i" @echo "... time.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>/1_dmftsolver/QMC/practice.py import numpy as np from gfmod import * # nyquist frequency wn, Greal, Gimag = np.loadtxt('hello', unpack = True) giwn = Greal + Gimag*1j ntau = 10*len(wn) beta = 100 gtau = gftools.GreenInverseFourier(giwn, ntau, beta, (1, 0, 0)) giwn = gftools.GreenFourier(gtau, len(wn), beta) tau = np.linspace(0, beta, ntau) np.savetxt('hello-tau', np.array([tau, gtau]).T) ''' n = 0 for i in range (10000000): n += np.sin(i) print(n) ''' """ niwn = 60 ntau = 121 beta = 20 mu = 0 V = 1 D = 1 nmc = 3 nmeas = 100 Uarr = [1.0, 5.0] seed = 0 giwn = gftools.SemiCircularGreen(niwn, beta, mu, V, D) gtau = gftools.GreenInverseFourier(giwn, ntau, beta, (1, 0, 0)) import matplotlib.pyplot as plt tau = np.linspace(0, beta, len(gtau)) for i, U in enumerate(Uarr): solver = qmc.hfqmc(gtau, beta, U, seed) gtau_up, err_up, gtau_dw, err_dw = solver.meas(nmc, nmeas) plt.errorbar(tau, (gtau_up + gtau_dw)/2.0, (err_up + err_dw)/2, marker = 'o', markersize = 5, linewidth = 1, capsize = 5, label = r'$U=%.2f$'%U) plt.legend(loc = 'best', fontsize = 14, edgecolor = 'None', framealpha = 0.0) plt.tick_params(which = 'both', direction = 'in', labelsize = 14) plt.xlabel(r'$\tau$', fontsize = 14) plt.ylabel(r'$G(\tau)$', fontsize = 14) plt.show() """ <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/pi_block_mpi.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/pi_block_mpi.dir/pi_block_mpi.cc.o" "pi_block_mpi" "pi_block_mpi.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/pi_block_mpi.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/correlated_normal_dist.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/correlated_normal_dist.dir/correlated_normal_dist.cc.o" "correlated_normal_dist" "correlated_normal_dist.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/correlated_normal_dist.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/pi_leap_mpi.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/pi_leap_mpi.dir/pi_leap_mpi.cc.o" "pi_leap_mpi" "pi_leap_mpi.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/pi_leap_mpi.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/NRG/docc_14.py import subprocess as sub import argparse import numpy as np from scipy.integrate import simps parser = argparse.ArgumentParser() parser.add_argument("-U", help = "on-site interaction", type = float) parser.add_argument("-T", help = "temperature", type = float, default = 1e-4) parser.add_argument("-lamb", help = "lambda", type = float, default = 1.6) args = parser.parse_args() U = args.U T = args.T lamb = args.lamb filename = f'./B_14_{lamb:.1f}/Bethe-{U:.2f}.dat' w, Aw, Gwr, Gwi, Swr, Swi = np.loadtxt(filename, unpack = True, dtype = 'complex128') sub.run(['g++', 'docc_14.cpp', '-o', 'docc14', '-I/home/hyejin/fftw-3.3.9', '-L/opt/fftw/lib', '-lfftw3', '-std=gnu++11']) beta = 1.0/T N = 80000 omega = np.pi/beta * (2*np.arange(N+1)+1) # w_n def realtoimag(x): N = len(omega) return np.array([simps(x/(1j*omega[i]-w.real), w.real) for i in range (N)]) G_iw = np.zeros(len(omega), dtype = 'complex128') G_iw = realtoimag(Aw.real) np.savetxt(f'./Giw_{lamb:.1f}/Giw_1to4_{U:.2f}.dat', \ np.array([omega.real, G_iw.real, G_iw.imag]).T) np.savetxt(f'./num/{lamb:.1f}_{U:.2f}', np.array([f'{U:.2f}\n{lamb:.1f}']), fmt='%s') myint = open(f'./num/{lamb:.1f}_{U:.2f}') p = sub.Popen('./docc14', stdin=myint) p.wait() <file_sep>/1_dmftsolver/QMC/setup.py #!/usr/bin/env python3 import os import re import sys import sysconfig import platform import subprocess from setuptools import setup, Extension from setuptools.command.build_ext import build_ext # Refer to "https://www.benjack.io/2017/06/12/python-cpp-tests.html" # I changed minor parts of the code written in the above site. class CMakeExtension(Extension): def __init__(self, name, sourcedir=''): Extension.__init__(self, name, sources=[]) self.sourcedir = os.path.abspath(sourcedir) class CMakeBuild(build_ext): def run(self): try: out = subprocess.check_output(['cmake', '--version']) except OSError: raise RuntimeError( "CMake must be installed to build the following extensions: " + ", ".join(e.name for e in self.extensions)) for ext in self.extensions: self.build_extension(ext) def build_extension(self, ext): extdir = os.path.abspath( os.path.dirname(self.get_ext_fullpath(ext.name))) cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, '-DPYTHON_EXECUTABLE=' + sys.executable, '-Wno-dev'] build_args = ['--', '-j1'] env = os.environ.copy() if not os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env) subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_temp) # download trng4 and pybind11 libraries from github and install them at here module_name = 'install_libraries' setup ( name = module_name, version = '0.1', author = '<NAME>', author_email = '<EMAIL>', description = 'Python binding for libraries', long_description = '', platforms = ['linux'], # add extension module ext_modules = [CMakeExtension('cpp_extension')], # add custom build_ext command cmdclass = dict(build_ext=CMakeBuild), zip_safe = False ) # build main parts module_name = '_cpp_module' include_dirs = ['./pybind11/include', './trng4'] libraries = ['openblas', 'lapack', 'fftw3', 'trng4'] library_dirs = ['./trng4.build/trng'] define_macros = [('MAJOR_VERSION', '1'), ('MINOR_VERSION', '0'), ('NPY_NO_DEPRECATED_API', 'NPY_1_7_API_VERSION'), ('USE_TRNG4', None)] module = Extension(module_name, define_macros = define_macros, include_dirs = include_dirs, libraries = libraries, library_dirs = library_dirs, sources = ['./src/etc.cpp', './src/hirschfye_qmc.cpp', './src/green_tools.cpp', './src/pymodule_hfqmc.cpp'], language = 'c++', extra_compile_args = ['-std=c++11', '-O3']) setup (name = module_name, version = '1.0', description = '...', author = '<NAME>', author_email = '<EMAIL>', url = '...', long_description = "HF-QMC", platforms = ['linux'], ext_modules = [module]) print ('\n@Note! Type the following command to include a search path for dynamic linker: export LD_LIBRARY_PATH=$(pwd)/trng4.build/trng:$LD_LIBRARY_PATH') <file_sep>/1_dmftsolver/NRG/A_to_Giw/test_AtoG_Gtau/some.py import subprocess as sub U = 2.00 hey = f'{U:.2f}.txt' myint = open(f'{U:.2f}.txt') #myout = open('hey.txt') p = sub.Popen('./docc', stdin=myint)#, stdout=myout) p.wait() #myouy.flush() <file_sep>/1_dmftsolver/QMC/trng4.build/trng/cmake_install.cmake # Install script for directory: /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng # Set the install prefix if(NOT DEFINED CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX "/usr/local") endif() string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) if(BUILD_TYPE) string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") else() set(CMAKE_INSTALL_CONFIG_NAME "Release") endif() message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") endif() # Set the component getting installed. if(NOT CMAKE_INSTALL_COMPONENT) if(COMPONENT) message(STATUS "Install component: \"${COMPONENT}\"") set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") else() set(CMAKE_INSTALL_COMPONENT) endif() endif() # Install shared libraries without execute permission? if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) set(CMAKE_INSTALL_SO_NO_EXE "1") endif() # Is this installation the result of a crosscompile? if(NOT DEFINED CMAKE_CROSSCOMPILING) set(CMAKE_CROSSCOMPILING "FALSE") endif() # Set default install directory permissions. if(NOT DEFINED CMAKE_OBJDUMP) set(CMAKE_OBJDUMP "/usr/bin/objdump") endif() if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xUnspecifiedx" OR NOT CMAKE_INSTALL_COMPONENT) file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE STATIC_LIBRARY FILES "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/libtrng4.a") endif() if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xUnspecifiedx" OR NOT CMAKE_INSTALL_COMPONENT) foreach(file "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libtrng4.so.4.22" "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libtrng4.so.22" ) if(EXISTS "${file}" AND NOT IS_SYMLINK "${file}") file(RPATH_CHECK FILE "${file}" RPATH "") endif() endforeach() file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE SHARED_LIBRARY FILES "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/libtrng4.so.4.22" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/libtrng4.so.22" ) foreach(file "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libtrng4.so.4.22" "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libtrng4.so.22" ) if(EXISTS "${file}" AND NOT IS_SYMLINK "${file}") if(CMAKE_INSTALL_DO_STRIP) execute_process(COMMAND "/usr/bin/strip" "${file}") endif() endif() endforeach() endif() if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xUnspecifiedx" OR NOT CMAKE_INSTALL_COMPONENT) if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libtrng4.so" AND NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libtrng4.so") file(RPATH_CHECK FILE "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libtrng4.so" RPATH "") endif() file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE SHARED_LIBRARY FILES "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/libtrng4.so") if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libtrng4.so" AND NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libtrng4.so") if(CMAKE_INSTALL_DO_STRIP) execute_process(COMMAND "/usr/bin/strip" "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libtrng4.so") endif() endif() endif() if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xUnspecifiedx" OR NOT CMAKE_INSTALL_COMPONENT) file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/include/trng" TYPE FILE FILES "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/bernoulli_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/beta_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/binomial_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/cauchy_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/chi_square_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/constants.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/correlated_normal_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/cuda.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/discrete_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/exponential_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/extreme_value_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/fast_discrete_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/gamma_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/generate_canonical.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/geometric_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/hypergeometric_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/int_math.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/int_types.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/lagfib2plus.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/lagfib2xor.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/lagfib4plus.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/lagfib4xor.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/lcg64.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/lcg64_shift.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/limits.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/logistic_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/lognormal_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/math.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/maxwell_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/minstd.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg2.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg3.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg3s.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg4.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg5.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg5s.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mt19937_64.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mt19937.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/negative_binomial_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/normal_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/pareto_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/poisson_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/powerlaw_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/rayleigh_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/snedecor_f_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/special_functions.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/student_t_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/tent_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/truncated_normal_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/twosided_exponential_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/uniform01_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/uniform_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/uniform_int_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/uniformxx.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/utility.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/weibull_dist.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn2.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn3.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn3s.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn4.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn5.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn5s.hpp" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/zero_truncated_poisson_dist.hpp" ) endif() <file_sep>/1_dmftsolver/QMC/trng4.build/trng/Makefile # CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.18 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Disable VCS-based implicit rules. % : %,v # Disable VCS-based implicit rules. % : RCS/% # Disable VCS-based implicit rules. % : RCS/%,v # Disable VCS-based implicit rules. % : SCCS/s.% # Disable VCS-based implicit rules. % : s.% .SUFFIXES: .hpux_make_needs_suffix_list # Command-line flag to silence nested $(MAKE). $(VERBOSE)MAKESILENT = -s #Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/local/bin/cmake # The command to remove a file. RM = /usr/local/bin/cmake -E rm -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4 # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build #============================================================================= # Targets provided globally by CMake. # Special rule for the target install/strip install/strip: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/local/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip # Special rule for the target install/strip install/strip/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/local/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip/fast # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/local/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local # Special rule for the target install/local install/local/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/local/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." /usr/local/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target package_source package_source: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Run CPack packaging tool for source..." cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && /usr/local/bin/cpack --config ./CPackSourceConfig.cmake /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/CPackSourceConfig.cmake .PHONY : package_source # Special rule for the target package_source package_source/fast: package_source .PHONY : package_source/fast # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/local/bin/cmake -P cmake_install.cmake .PHONY : install # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/local/bin/cmake -P cmake_install.cmake .PHONY : install/fast # Special rule for the target list_install_components list_install_components: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\"" .PHONY : list_install_components # Special rule for the target list_install_components list_install_components/fast: list_install_components .PHONY : list_install_components/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/local/bin/cmake --regenerate-during-build -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target package package: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Run CPack packaging tool..." cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && /usr/local/bin/cpack --config ./CPackConfig.cmake .PHONY : package # Special rule for the target package package/fast: package .PHONY : package/fast # The main all target all: cmake_check_build_system cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(CMAKE_COMMAND) -E cmake_progress_start /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/CMakeFiles /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng//CMakeFiles/progress.marks cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 trng/all $(CMAKE_COMMAND) -E cmake_progress_start /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/CMakeFiles 0 .PHONY : all # The main clean target clean: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 trng/clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 trng/preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 trng/preinstall .PHONY : preinstall/fast # clear depends depend: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend # Convenience name for target. trng/CMakeFiles/trng4_shared.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 trng/CMakeFiles/trng4_shared.dir/rule .PHONY : trng/CMakeFiles/trng4_shared.dir/rule # Convenience name for target. trng4_shared: trng/CMakeFiles/trng4_shared.dir/rule .PHONY : trng4_shared # fast build rule for target. trng4_shared/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/build .PHONY : trng4_shared/fast # Convenience name for target. trng/CMakeFiles/trng4_static.dir/rule: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 trng/CMakeFiles/trng4_static.dir/rule .PHONY : trng/CMakeFiles/trng4_static.dir/rule # Convenience name for target. trng4_static: trng/CMakeFiles/trng4_static.dir/rule .PHONY : trng4_static # fast build rule for target. trng4_static/fast: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/build .PHONY : trng4_static/fast lcg64.o: lcg64.cc.o .PHONY : lcg64.o # target to build an object file lcg64.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/lcg64.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/lcg64.cc.o .PHONY : lcg64.cc.o lcg64.i: lcg64.cc.i .PHONY : lcg64.i # target to preprocess a source file lcg64.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/lcg64.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/lcg64.cc.i .PHONY : lcg64.cc.i lcg64.s: lcg64.cc.s .PHONY : lcg64.s # target to generate assembly for a file lcg64.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/lcg64.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/lcg64.cc.s .PHONY : lcg64.cc.s lcg64_shift.o: lcg64_shift.cc.o .PHONY : lcg64_shift.o # target to build an object file lcg64_shift.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/lcg64_shift.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/lcg64_shift.cc.o .PHONY : lcg64_shift.cc.o lcg64_shift.i: lcg64_shift.cc.i .PHONY : lcg64_shift.i # target to preprocess a source file lcg64_shift.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/lcg64_shift.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/lcg64_shift.cc.i .PHONY : lcg64_shift.cc.i lcg64_shift.s: lcg64_shift.cc.s .PHONY : lcg64_shift.s # target to generate assembly for a file lcg64_shift.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/lcg64_shift.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/lcg64_shift.cc.s .PHONY : lcg64_shift.cc.s minstd.o: minstd.cc.o .PHONY : minstd.o # target to build an object file minstd.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/minstd.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/minstd.cc.o .PHONY : minstd.cc.o minstd.i: minstd.cc.i .PHONY : minstd.i # target to preprocess a source file minstd.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/minstd.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/minstd.cc.i .PHONY : minstd.cc.i minstd.s: minstd.cc.s .PHONY : minstd.s # target to generate assembly for a file minstd.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/minstd.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/minstd.cc.s .PHONY : minstd.cc.s mrg2.o: mrg2.cc.o .PHONY : mrg2.o # target to build an object file mrg2.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg2.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg2.cc.o .PHONY : mrg2.cc.o mrg2.i: mrg2.cc.i .PHONY : mrg2.i # target to preprocess a source file mrg2.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg2.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg2.cc.i .PHONY : mrg2.cc.i mrg2.s: mrg2.cc.s .PHONY : mrg2.s # target to generate assembly for a file mrg2.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg2.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg2.cc.s .PHONY : mrg2.cc.s mrg3.o: mrg3.cc.o .PHONY : mrg3.o # target to build an object file mrg3.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg3.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg3.cc.o .PHONY : mrg3.cc.o mrg3.i: mrg3.cc.i .PHONY : mrg3.i # target to preprocess a source file mrg3.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg3.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg3.cc.i .PHONY : mrg3.cc.i mrg3.s: mrg3.cc.s .PHONY : mrg3.s # target to generate assembly for a file mrg3.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg3.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg3.cc.s .PHONY : mrg3.cc.s mrg3s.o: mrg3s.cc.o .PHONY : mrg3s.o # target to build an object file mrg3s.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg3s.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg3s.cc.o .PHONY : mrg3s.cc.o mrg3s.i: mrg3s.cc.i .PHONY : mrg3s.i # target to preprocess a source file mrg3s.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg3s.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg3s.cc.i .PHONY : mrg3s.cc.i mrg3s.s: mrg3s.cc.s .PHONY : mrg3s.s # target to generate assembly for a file mrg3s.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg3s.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg3s.cc.s .PHONY : mrg3s.cc.s mrg4.o: mrg4.cc.o .PHONY : mrg4.o # target to build an object file mrg4.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg4.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg4.cc.o .PHONY : mrg4.cc.o mrg4.i: mrg4.cc.i .PHONY : mrg4.i # target to preprocess a source file mrg4.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg4.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg4.cc.i .PHONY : mrg4.cc.i mrg4.s: mrg4.cc.s .PHONY : mrg4.s # target to generate assembly for a file mrg4.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg4.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg4.cc.s .PHONY : mrg4.cc.s mrg5.o: mrg5.cc.o .PHONY : mrg5.o # target to build an object file mrg5.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg5.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg5.cc.o .PHONY : mrg5.cc.o mrg5.i: mrg5.cc.i .PHONY : mrg5.i # target to preprocess a source file mrg5.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg5.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg5.cc.i .PHONY : mrg5.cc.i mrg5.s: mrg5.cc.s .PHONY : mrg5.s # target to generate assembly for a file mrg5.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg5.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg5.cc.s .PHONY : mrg5.cc.s mrg5s.o: mrg5s.cc.o .PHONY : mrg5s.o # target to build an object file mrg5s.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg5s.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg5s.cc.o .PHONY : mrg5s.cc.o mrg5s.i: mrg5s.cc.i .PHONY : mrg5s.i # target to preprocess a source file mrg5s.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg5s.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg5s.cc.i .PHONY : mrg5s.cc.i mrg5s.s: mrg5s.cc.s .PHONY : mrg5s.s # target to generate assembly for a file mrg5s.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mrg5s.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mrg5s.cc.s .PHONY : mrg5s.cc.s mt19937.o: mt19937.cc.o .PHONY : mt19937.o # target to build an object file mt19937.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mt19937.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mt19937.cc.o .PHONY : mt19937.cc.o mt19937.i: mt19937.cc.i .PHONY : mt19937.i # target to preprocess a source file mt19937.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mt19937.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mt19937.cc.i .PHONY : mt19937.cc.i mt19937.s: mt19937.cc.s .PHONY : mt19937.s # target to generate assembly for a file mt19937.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mt19937.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mt19937.cc.s .PHONY : mt19937.cc.s mt19937_64.o: mt19937_64.cc.o .PHONY : mt19937_64.o # target to build an object file mt19937_64.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mt19937_64.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mt19937_64.cc.o .PHONY : mt19937_64.cc.o mt19937_64.i: mt19937_64.cc.i .PHONY : mt19937_64.i # target to preprocess a source file mt19937_64.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mt19937_64.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mt19937_64.cc.i .PHONY : mt19937_64.cc.i mt19937_64.s: mt19937_64.cc.s .PHONY : mt19937_64.s # target to generate assembly for a file mt19937_64.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/mt19937_64.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/mt19937_64.cc.s .PHONY : mt19937_64.cc.s yarn2.o: yarn2.cc.o .PHONY : yarn2.o # target to build an object file yarn2.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn2.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn2.cc.o .PHONY : yarn2.cc.o yarn2.i: yarn2.cc.i .PHONY : yarn2.i # target to preprocess a source file yarn2.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn2.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn2.cc.i .PHONY : yarn2.cc.i yarn2.s: yarn2.cc.s .PHONY : yarn2.s # target to generate assembly for a file yarn2.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn2.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn2.cc.s .PHONY : yarn2.cc.s yarn3.o: yarn3.cc.o .PHONY : yarn3.o # target to build an object file yarn3.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn3.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn3.cc.o .PHONY : yarn3.cc.o yarn3.i: yarn3.cc.i .PHONY : yarn3.i # target to preprocess a source file yarn3.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn3.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn3.cc.i .PHONY : yarn3.cc.i yarn3.s: yarn3.cc.s .PHONY : yarn3.s # target to generate assembly for a file yarn3.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn3.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn3.cc.s .PHONY : yarn3.cc.s yarn3s.o: yarn3s.cc.o .PHONY : yarn3s.o # target to build an object file yarn3s.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn3s.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn3s.cc.o .PHONY : yarn3s.cc.o yarn3s.i: yarn3s.cc.i .PHONY : yarn3s.i # target to preprocess a source file yarn3s.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn3s.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn3s.cc.i .PHONY : yarn3s.cc.i yarn3s.s: yarn3s.cc.s .PHONY : yarn3s.s # target to generate assembly for a file yarn3s.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn3s.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn3s.cc.s .PHONY : yarn3s.cc.s yarn4.o: yarn4.cc.o .PHONY : yarn4.o # target to build an object file yarn4.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn4.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn4.cc.o .PHONY : yarn4.cc.o yarn4.i: yarn4.cc.i .PHONY : yarn4.i # target to preprocess a source file yarn4.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn4.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn4.cc.i .PHONY : yarn4.cc.i yarn4.s: yarn4.cc.s .PHONY : yarn4.s # target to generate assembly for a file yarn4.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn4.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn4.cc.s .PHONY : yarn4.cc.s yarn5.o: yarn5.cc.o .PHONY : yarn5.o # target to build an object file yarn5.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn5.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn5.cc.o .PHONY : yarn5.cc.o yarn5.i: yarn5.cc.i .PHONY : yarn5.i # target to preprocess a source file yarn5.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn5.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn5.cc.i .PHONY : yarn5.cc.i yarn5.s: yarn5.cc.s .PHONY : yarn5.s # target to generate assembly for a file yarn5.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn5.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn5.cc.s .PHONY : yarn5.cc.s yarn5s.o: yarn5s.cc.o .PHONY : yarn5s.o # target to build an object file yarn5s.cc.o: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn5s.cc.o cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn5s.cc.o .PHONY : yarn5s.cc.o yarn5s.i: yarn5s.cc.i .PHONY : yarn5s.i # target to preprocess a source file yarn5s.cc.i: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn5s.cc.i cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn5s.cc.i .PHONY : yarn5s.cc.i yarn5s.s: yarn5s.cc.s .PHONY : yarn5s.s # target to generate assembly for a file yarn5s.cc.s: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_shared.dir/build.make trng/CMakeFiles/trng4_shared.dir/yarn5s.cc.s cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(MAKE) $(MAKESILENT) -f trng/CMakeFiles/trng4_static.dir/build.make trng/CMakeFiles/trng4_static.dir/yarn5s.cc.s .PHONY : yarn5s.cc.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... edit_cache" @echo "... install" @echo "... install/local" @echo "... install/strip" @echo "... list_install_components" @echo "... package" @echo "... package_source" @echo "... rebuild_cache" @echo "... trng4_shared" @echo "... trng4_static" @echo "... lcg64.o" @echo "... lcg64.i" @echo "... lcg64.s" @echo "... lcg64_shift.o" @echo "... lcg64_shift.i" @echo "... lcg64_shift.s" @echo "... minstd.o" @echo "... minstd.i" @echo "... minstd.s" @echo "... mrg2.o" @echo "... mrg2.i" @echo "... mrg2.s" @echo "... mrg3.o" @echo "... mrg3.i" @echo "... mrg3.s" @echo "... mrg3s.o" @echo "... mrg3s.i" @echo "... mrg3s.s" @echo "... mrg4.o" @echo "... mrg4.i" @echo "... mrg4.s" @echo "... mrg5.o" @echo "... mrg5.i" @echo "... mrg5.s" @echo "... mrg5s.o" @echo "... mrg5s.i" @echo "... mrg5s.s" @echo "... mt19937.o" @echo "... mt19937.i" @echo "... mt19937.s" @echo "... mt19937_64.o" @echo "... mt19937_64.i" @echo "... mt19937_64.s" @echo "... yarn2.o" @echo "... yarn2.i" @echo "... yarn2.s" @echo "... yarn3.o" @echo "... yarn3.i" @echo "... yarn3.s" @echo "... yarn3s.o" @echo "... yarn3s.i" @echo "... yarn3s.s" @echo "... yarn4.o" @echo "... yarn4.i" @echo "... yarn4.s" @echo "... yarn5.o" @echo "... yarn5.i" @echo "... yarn5.s" @echo "... yarn5s.o" @echo "... yarn5s.i" @echo "... yarn5s.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: cd /home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>/0_toy_ising/isingspin.cpp #include <iostream> #include <fstream> #include <cmath> #include <random> #include <vector> #include <time.h> using namespace std; random_device rd; mt19937 gen(rd()); uniform_real_distribution<double> dis(0, 1); void initialize(vector<double>& v, int size) //initial -random- state { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if ((i + j) % 2 == 0) v[size * i + j] = 1; else v[size * i + j] = -1; } } /*for (int i = 0; i < size * size; i++) { v[i] = dis(gen) < 0.5 ? 1 : -1; }*/ } void neighbor(vector < vector <double> >& na, int size) { int sizes = size * size; for (int i = 0; i < size * size; i++) { na[i][0] = (i + size * (size - 1)) % sizes; na[i][1] = (i + size) % sizes; na[i][2] = (i - 1 + size) % size + (i / size) * size; na[i][3] = (i + 1) % size + (i / size) * size; } } double Magnet(vector<double>& v, int size) { double m = 0; for (vector<int>::size_type i = 0; i < v.size(); i++) { m = m + v.at(i); } m = abs(m) / (v.size()); //absolute value of average spin return m; } void Cluster_1step(vector<double>& v, int size, double padd, vector < vector <double> > na) { int i = size * size * dis(gen); double oldspin = v[i]; double newspin = -v[i]; vector<int> stack(size*size, 0); stack[0] = i; v[i] = newspin; int sp = 0, sh = 0; while (1) { if (v[na[i][0]] == oldspin && dis(gen) < padd) { sh++; stack.at(sh) = na[i][0]; v[na[i][0]] = newspin; } if (v[na[i][1]] == oldspin && dis(gen) < padd) { sh++; stack.at(sh) = na[i][1]; v[na[i][1]] = newspin; } if (v[na[i][2]] == oldspin && dis(gen) < padd) { sh++; stack.at(sh) = na[i][2]; v[na[i][2]] = newspin; } if (v[na[i][3]] == oldspin && dis(gen) < padd) { sh++; stack.at(sh) = na[i][3]; v[na[i][3]] = newspin; } sp++; if (sp > sh) break; i = stack.at(sp); } } void MC_1cycle(int size, double T, double& mag, vector < vector <double> > na, vector<double>& array) { int step1 = 2500, step2 = 5000; int scale=1; double Tstart = 2.3, clsizef = 2.86; double slope = (double(size)*size/clsizef)/(5-Tstart); if (T>Tstart) { scale = slope * (T - Tstart); if (scale == 0) scale = 1; } int trash_step = scale*(sqrt(size)); double padd = 1 - exp(-2 / T); for (int k = 0; k < step1; k++) { Cluster_1step(array, size, padd, na); } vector<double> magnet(step2, 0); for (int k = 0; k < step2; k++) { for (int h = 0; h < trash_step; h++) { Cluster_1step(array, size, padd, na); } magnet.at(k) = Magnet(array, size); } double Mag = 0; for (vector<int>::size_type i = 0; i < magnet.size(); i++) { Mag = Mag + magnet.at(i); } mag = Mag / step2; } int main() { int size = 32; double Mag = 0; vector < vector <double> > near(size * size, vector<double>(4, 0)); vector<double> array(size * size, 0); neighbor(near, size); initialize(array, size); clock_t start = clock(); ofstream File; File.open("isingspin_train32.txt"); cout << "File open" << endl; File << "temp m spin " << endl; for (int k = 150; k < 300; k++) { // 1.5 ~ 3.49, 150 for (int h = 0; h < 50; h++) { MC_1cycle(size, 0.01 * k, Mag, near, array); File << 0.01 * k << " " << Mag << " "; for (int i = 0; i < size*size; i++){ File << array.at(i) << " "; } File << endl; } cout << 0.01 * k << "end" << endl; } File.close(); cout << endl << "total time: " << (double(clock()) - double(start)) / CLOCKS_PER_SEC << " sec" << endl; return 0; } <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/stl_container.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/stl_container.dir/stl_container.cc.o" "stl_container" "stl_container.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/stl_container.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/cpp11.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/cpp11.dir/cpp11.cc.o" "cpp11" "cpp11.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/cpp11.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/IPT/DMFT_IPT_SOLVER/Makefile CC = g++ OPT = -std=c++14 LIBS = -lopenblas -llapack -lfftw3 -lgmpxx -lgmp -lboost_program_options TARGET = IPT all : $(TARGET) $(TARGET): main.o pade.o $(CC) -o $@ $^ $(LIBS) $(OPT) main.o : main.cpp $(CC) -c -o $@ $^ $(OPT) pade.o : pade.cpp $(CC) -c -o $@ $^ clean: rm -rf *.o $(TARGET) <file_sep>/1_dmftsolver/NRG/NRGdata_to_spectral_conversion.py import numpy as np import os.path as path D = 1 T = 1e-4 U = np.array([0.001*i for i in range(500, 5001)]) U14 = np.zeros(142, dtype = 'float64') U41 = np.zeros(129, dtype = 'float64') n = 0 for i, u in enumerate(U): if path.isfile(f'./B_14/Bethe-{u:.3f}.dat')==False: continue U14[n] = u n += 1 n = 0 for i, u in enumerate(U): if path.isfile(f'./B_41/Bethe-{u:.3f}.dat')==False: continue U41[n] = u n += 1 for i,u in enumerate(U14): w, A, _,_,_,_,_,_,_,_ = np.loadtxt(f'./B_14/Bethe-{u:.3f}.dat', unpack = True, dtype = 'float64') filename = f'./NRG_metal_insulator/Bethe-{u:.3f}.dat' np.savetxt(filename, np.array([w, A]).T, header = f"w A_w (D: {D}, T: {T}, U: {u:.3f}, half-filling)") for i,u in enumerate(U41): w, A, _,_,_,_,_,_,_,_ = np.loadtxt(f'./B_41/Bethe-{u:.3f}.dat', unpack = True, dtype = 'float64') filename = f'./NRG_insulator_metal/Bethe-{u:.3f}.dat' np.savetxt(filename, np.array([w, A]).T, header = f"w A_w (D: {D}, T: {T}, U: {u:.3f}, half-filling)") <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/Ising_model.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Ising_model.dir/Ising_model.cc.o" "Ising_model" "Ising_model.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Ising_model.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/NRG/dmft_nrg.py #!/usr/bin/python3 import argparse from triqs.utility import mpi import numpy as np from nrgljubljana_interface import Solver, SemiCircular import utility #================= Parameters ================= parser = argparse.ArgumentParser() parser.add_argument("-U", help = "on-site interaction", type = float) parser.add_argument("-T", help = "temperature", type = float, default = 2e-4) parser.add_argument("-D", help = "half bandwidth", type = float, default = 1) parser.add_argument("-niter", help = "# of iterations", type = int, default = 100) parser.add_argument("-keepE", help = "keep energy", type = float, default = 10.0) parser.add_argument("-tol", help = "tolerance of the convergence criterion", type = float, default = 1e-4) parser.add_argument("-load", help = "file name of previous data to restart a DMFT loop", type = str, default = None) args = parser.parse_args() D = args.D U = args.U T = args.T niter = args.niter keepE = args.keepE tol = args.tol filename = f'./4to1_3000/Bethe-{U:.2f}_solution.dat' #============================================== # particle-hole symmetric case mu = U/2 e_f = -U/2.0 # Set up the Impurity Solver imp_solver = Solver(model = "SIAM", symtype = "QS", mesh_max = 5.0, mesh_min = 1e-5, mesh_ratio = 1.01) # Solve Parameters sp = { "T": T, "Lambda": 2.0, "Nz": 4, "Tmin": 1e-6, "keep": 2000, "keepenergy": keepE, "bandrescale": 1.0 } # Model Parameters mp = { "U1": U, "eps1": e_f } sp["model_parameters"] = mp # Set up the Lattice Solver lattice_solver = utility.BetheLatticeSolver(imp_solver, D) # Load previous data lattice_solver.load_data(imp_solver, filename if args.load is None else args.load) # real frequency domain realFreq = np.array([w for w in imp_solver.Delta_w.mesh], dtype = 'complex128') G_old = np.zeros_like(realFreq) G_new = np.zeros_like(realFreq) # Start with a DMFT self-consistent loop for n in range(niter): if mpi.is_master_node(): print ('# OF ITERATIONS:', (n+1)) # Solve the impurity model imp_solver.solve(**sp) G_new = imp_solver.G_w['imp'].data.reshape([-1]) # Save results if mpi.is_master_node(): np.savetxt(filename, np.array([realFreq, \ imp_solver.A_w['imp'].data.reshape([-1]), \ imp_solver.G_w['imp'].data.reshape([-1]), \ imp_solver.Sigma_w['imp'].data.reshape([-1])]).T, \ header = f"w A_w G_w Sigma_w (D: {D}, T: {T}, U: {U}, half-filling)") diff = np.mean(np.abs(G_new-G_old)) if n > 0: if mpi.is_master_node(): print ("|G_NEW - G_OLD|: %.7f"%diff) if (diff < tol): if mpi.is_master_node(): print ("CONVERGE!") break else: if mpi.is_master_node(): print ('\n') else: if mpi.is_master_node(): print ('\n') G_old = G_new.copy() # Solve self-consistent equation lattice_solver.update_hybridization_function(imp_solver) <file_sep>/README.md # Introduction This page is for 'Machine learning prediction of metal-insulator transition in DMFT' 1. `0_toy_ising`: For toy problem of predicting order/disorder 2nd phase transition 2. `1_dmftsolver`: DMFT code & data 3. `2_nn`: Every important things are here. To see briefly, go to [`/2-nn/4_makefigure.ipynb`](https://github.com/aadeliee22/Hubbard_NN/blob/master/2_nn/4_makefigure.ipynb). <file_sep>/1_dmftsolver/ED/nb7/sc/get.sh #!/usr/bin/env bash #DIR='./i_to_m' if [ $# -eq 0 ]; then echo "ARG[1]: directory to load files" exit 1 fi DIR=$1 FILEs=($(find $DIR -type f -name 'result*')) function remove_prefix () { local PREFIX_=$(echo $1 | sed -e 's/\//\\\//g') RES=$(echo $2 | sed -e "s/$PREFIX_//g") } remove_prefix './' $DIR OFILE=result_${RES} if ! [ -e $OFILE ]; then touch $OFILE else rm $OFILE fi for FILE in ${FILEs[@]}; do CONT=($(cat $FILE)) remove_prefix $DIR/result_ $FILE U=$RES echo "$U ${CONT[4]}" >> $OFILE done sort -k1 -n $OFILE > $OFILE.dat rm $OFILE <file_sep>/1_dmftsolver/QMC/cmake/FindTRNG4.cmake # Copyright (c) 2020 <NAME> (<EMAIL>) IF (NOT TRNG4_FOUND) # Setting default paths IF (NOT TRNG4_INCLUDE_DIR) SET (TRNG4_INCLUDE_DIR /usr/local/include) ENDIF (NOT TRNG4_INCLUDE_DIR) MESSAGE (STATUS "TRNG4_INCLUDE_DIR (DEFAULT) : ${TRNG4_INCLUDE_DIR}") IF (NOT TRNG4_LIBRARY_DIR) SET (TRNG4_LIBRARY_DIR /usr/local/lib/) ENDIF (NOT TRNG4_LIBRARY_DIR) MESSAGE (STATUS "TRNG4_LIBRARY_DIR (DEFAULT) : ${TRNG4_LIBRARY_DIR}") # Check whether header files are in ${TRNG4_INCLUDE_DIR} or not. MESSAGE (STATUS "Checking for trng4 in the default path") SET (HEADER_FILES "yarn5.hpp;uniform01_dist.hpp;uniform_int_dist.hpp") FOREACH (HEADER_FILE ${HEADER_FILES}) MESSAGE (STATUS " Looking for ${HEADER_FILE}") FIND_PATH (HEADER_FILE_PATH NAMES ${HEADER_FILE} HINTS "${TRNG4_INCLUDE_DIR}/trng") IF (HEADER_FILE_PATH) MESSAGE (STATUS " Looking for ${HEADER_FILE} - found") ELSE () MESSAGE (NOTICE " ${HEADER_FILE} is not detected at the path: ${TRNG4_INCLUDE_DIR}") SET (TRNG4_FOUND FALSE) ENDIF (HEADER_FILE_PATH) ENDFOREACH () # suffix of the dynamic library IF (APPLE) SET (DYLIBSUFFIX dylib) ELSEIF (UNIX) SET (DYLIBSUFFIX so) ENDIF () # Check library FIND_LIBRARY (TRNG4_LIBRARY_DIR NAMES trng4 libtrng4 HINTS ${TRNG4_LIBRARY_DIR}) IF (EXISTS ${TRNG4_LIBRARY_DIR}/libtrng4.${DYLIBSUFFIX}) MESSAGE (STATUS "TRNG4 library - found") ELSE() MESSAGE (NOTICE " Library trng4 is not detected at the path: ${TRNG4_LIBRARY_DIR}") SET (TRNG4_FOUND FALSE) ENDIF (EXISTS ${TRNG4_LIBRARY_DIR}/libtrng4.${DYLIBSUFFIX}) IF (TRNG4_FOUND MATCHES FALSE) # repository stored in GitHub SET (TRNG4_GIT_REPOSITORY https://github.com/rabauke/trng4.git) # tag id of trng4 library compatible to cuda 10 SET (TRNG4_GIT_TAG_ID v4.22) IF (APPLE OR UNIX) # download trng4 source files from the external git repository IF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/trng4/CMakeLists.txt) EXECUTE_PROCESS (COMMAND git clone ${TRNG4_GIT_REPOSITORY} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) EXECUTE_PROCESS (COMMAND git checkout tags/${TRNG4_GIT_TAG_ID} -b temp WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/trng4) ENDIF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/trng4/CMakeLists.txt) # The library will be installed at "trng4.build". IF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/trng4.build) EXECUTE_PROCESS (COMMAND mkdir ${CMAKE_CURRENT_SOURCE_DIR}/trng4.build WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}) ENDIF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/trng4.build) IF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/trng4.build/trng/libtrng4.${DYLIBSUFFIX}) MESSAGE (NOTICE " trng4 library is being installed at the current source directory.") EXECUTE_PROCESS (COMMAND ${CMAKE_COMMAND} ${CMAKE_CURRENT_SOURCE_DIR}/trng4 WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/trng4.build) EXECUTE_PROCESS (COMMAND make WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/trng4.build) IF (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/trng4.build/trng/libtrng4.${DYLIBSUFFIX}) MESSAGE (NOTICE " Installation of trng4 library is now finished.") ELSE () MESSAGE (FATAL_ERROR " trng4 library is not installed yet.") ENDIF (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/trng4.build/trng/libtrng4.${DYLIBSUFFIX}) ELSE () MESSAGE (STATUS "TRNG4 library (${CMAKE_CURRENT_SOURCE_DIR}/trng4.build/trng/libtrng4.${DYLIBSUFFIX}) - found") ENDIF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/trng4.build/trng/libtrng4.${DYLIBSUFFIX}) SET (TRNG4_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/trng4/) SET (TRNG4_LIBRARY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/trng4.build/trng) ENDIF () ENDIF (TRNG4_FOUND MATCHES FALSE) # final SET (TRNG4_FOUND TRUE) INCLUDE_DIRECTORIES (SYSTEM ${TRNG4_INCLUDE_DIR}) LINK_DIRECTORIES(${TRNG4_LIBRARY_DIR}) SET (TRNG4_LIBRARIES trng4) ENDIF (NOT TRNG4_FOUND) <file_sep>/1_dmftsolver/QMC/trng4.build/trng/CMakeFiles/trng4_static.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/trng4_static.dir/lcg64.cc.o" "CMakeFiles/trng4_static.dir/lcg64_shift.cc.o" "CMakeFiles/trng4_static.dir/minstd.cc.o" "CMakeFiles/trng4_static.dir/mrg2.cc.o" "CMakeFiles/trng4_static.dir/mrg3.cc.o" "CMakeFiles/trng4_static.dir/mrg3s.cc.o" "CMakeFiles/trng4_static.dir/mrg4.cc.o" "CMakeFiles/trng4_static.dir/mrg5.cc.o" "CMakeFiles/trng4_static.dir/mrg5s.cc.o" "CMakeFiles/trng4_static.dir/mt19937.cc.o" "CMakeFiles/trng4_static.dir/mt19937_64.cc.o" "CMakeFiles/trng4_static.dir/yarn2.cc.o" "CMakeFiles/trng4_static.dir/yarn3.cc.o" "CMakeFiles/trng4_static.dir/yarn3s.cc.o" "CMakeFiles/trng4_static.dir/yarn4.cc.o" "CMakeFiles/trng4_static.dir/yarn5.cc.o" "CMakeFiles/trng4_static.dir/yarn5s.cc.o" "libtrng4.a" "libtrng4.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/trng4_static.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/ED/setup.py from distutils.core import setup, Extension module_name = '_ed_solver' include_dirs = ['./pybind11/include/'] libraries = ['stdc++', 'arpack', 'openblas', 'lapack'] module1 = Extension(module_name, define_macros = [('MAJOR_VERSION', '1'), ('MINOR_VERSION', '0'), ('NPY_NO_DEPRECATED_API', 'NPY_1_7_API_VERSION')], include_dirs = include_dirs, libraries = libraries, sources = ['./src/ed_solver.cpp'], language = 'c++', extra_compile_args = ['-std=c++11', '-O3']) setup (name = module_name, version = '1.0', description = '...', author = '<NAME>', author_email = '<EMAIL>', url = 'https://docs.python.org/extending/building', long_description = "dmft-ed solver", platforms = ['linux'], ext_modules = [module1]) <file_sep>/1_dmftsolver/QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/DependInfo.cmake # The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/lcg64.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/lcg64.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/lcg64_shift.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/lcg64_shift.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/minstd.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/minstd.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg2.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/mrg2.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg3.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/mrg3.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg3s.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/mrg3s.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg4.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/mrg4.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg5.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/mrg5.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mrg5s.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/mrg5s.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mt19937.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/mt19937.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/mt19937_64.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/mt19937_64.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn2.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/yarn2.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn3.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/yarn3.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn3s.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/yarn3s.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn4.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/yarn4.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn5.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/yarn5.cc.o" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/yarn5s.cc" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/CMakeFiles/trng4_shared.dir/yarn5s.cc.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. set(CMAKE_TARGET_DEFINITIONS_CXX "trng4_shared_EXPORTS" ) # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4/trng/.." ) # Pairs of files generated by the same build rule. set(CMAKE_MULTIPLE_OUTPUT_PAIRS "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/libtrng4.so" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/libtrng4.so.4.22" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/libtrng4.so.22" "/home/hyejin/Desktop/my_git/DMFT_VAE/1_QMC/Hirsch-Fye-QMC/trng4.build/trng/libtrng4.so.4.22" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep>/1_dmftsolver/NRG/dmft_nrg_dope_broyden.py #!/usr/bin/python3 import argparse from triqs.utility import mpi import numpy as np from nrgljubljana_interface import Solver, SemiCircular import utility from scipy import optimize, interpolate, integrate, special from scipy.integrate import simps, trapz from copy import deepcopy import sys import subprocess as sub import math, os, warnings #================= Parameters ================= parser = argparse.ArgumentParser() parser.add_argument("-U", help = "on-site interaction", type = float) parser.add_argument("-T", help = "temperature", type = float, default = 1e-4) parser.add_argument("-D", help = "half bandwidth", type = float, default = 1) parser.add_argument("-Occ", help = "Occupancy goal", type = float, default = 0.5) parser.add_argument("-alp", help = "alpha", type = float, default = 0.8) parser.add_argument("-lamb", help = "lambda", type = float, default = 2.4) parser.add_argument("-keepE", help = "keep energy", type = float, default = 12.0) parser.add_argument("-niter", help = "# of iterations", type = int, default = 100) parser.add_argument("-tol", help = "tolerance of the convergence criterion", type = float, default = 1e-3) parser.add_argument("-load", help = "file name of previous data to restart a DMFT loop", type = str, default = None) parser.add_argument("-way", help = "direction", type = int, default = None) args = parser.parse_args() D = args.D U = args.U T = args.T Occ = args.Occ alpha = args.alp keepE = args.keepE niter = args.niter tol = args.tol lamb = args.lamb way = args.way filename = f'./BD_{Occ:.2f}_{way:.0f}/Bethe-{U:.3f}.dat' #============================================== # particle-hole non-symmetric case mu = U * Occ B = 0.0 # Set up the Impurity Solver imp_solver = Solver(model = "SIAM", symtype = "QS", mesh_max = 5.0, mesh_min = 1e-5, mesh_ratio = 1.01) #imp_solver.set_verbosity(False) # Solve Parameters sp = { "T": T, "Lambda": lamb, "Nz": 4, "Tmin": 1e-6, \ "keep": 3000, "keepmin":1000, "keepenergy": keepE, "alpha": 0.4, "bandrescale": 1.0 } # Model Parameters mp = { "U1": U, "B1": B, "eps1": -mu } sp["model_parameters"] = mp ob = ["n_d"] # Set up the Lattice Solver lattice_solver = utility.BetheLatticeSolver(imp_solver, D) # Load previous data lattice_solver.load_data(imp_solver, filename if args.load is None else args.load) newG = lambda : imp_solver.G_w.copy() nr_blocks = lambda bgf : len([bl for bl in bgf.indices]) block_size = lambda bl : len(imp_solver.G_w[bl].indices[0]) identity = lambda bl : np.identity(block_size(bl)) index_range = lambda G : range(len(G.indices[0])) def fix_hyb_function(Delta, Delta_min): Delta_fixed = Delta.copy() for bl in Delta.indices: for w in Delta.mesh: for n in range(block_size(bl)): # only diagonal parts r = Delta[bl][w][n,n].real i = Delta[bl][w][n,n].imag Delta_fixed[bl][w][n,n] = r + 1j*(i if i<-Delta_min else -Delta_min) # Possible improvement: re-adjust the real part so that the Kramers-Kronig relation is maintained return Delta_fixed # Hilbert Transformation ht1 = lambda z: 2*(z-1j*np.sign(z.imag)*np.sqrt(1-z**2)) ht0 = lambda z: ht1(z/D) EPS = 1e-20 ht = lambda z: ht0(z.real+1j*(z.imag if z.imag>0.0 else EPS)) def calc_G(Sigma, mu): Gloc = newG() for bl in Gloc.indices: for w in Gloc.mesh: for i in range(block_size(bl)): for j in range(block_size(bl)): # assuming square matrix if i == j: Gloc[bl][w][i,i] = ht(w + mu - Sigma[bl][w][i,i]) # Hilbert-transform else: assert abs(Sigma[bl][w][i,j])<1e-10, "This implementation only supports diagonal self-energy" Gloc[bl][w][i,j] = 0.0 Glocinv = Gloc.inverse() Delta = newG() for bl in Delta.indices: for w in Delta.mesh: Delta[bl][w] = (w+mu)*identity(bl) - Sigma[bl][w] - Glocinv[bl][w] return Gloc, Delta # real frequency domain realFreq = np.array([w for w in imp_solver.Delta_w.mesh], dtype = 'complex128') A_w = np.zeros_like(realFreq) G_old = newG() G_new = newG() Delta_in = imp_solver.Delta_w.copy() Delta_min=1e-6 n = 0 class Converged(Exception): def __init__(self, message): self.message = message def dmft_step(Delta_in): global n, G_old, G_new if mpi.is_master_node(): print ('# OF ITERATIONS:', (n+1)) # Solve the impurity model Delta_fixed = fix_hyb_function(Delta_in, Delta_min) imp_solver.Delta_w << Delta_fixed imp_solver.solve(**sp) G_new, _ = calc_G(imp_solver.Sigma_w, mu) lattice_solver.update_hybridization_function(imp_solver, (D/2)**2 * G_new['imp'].data) # self-consistency Delta_out = imp_solver.Delta_w.copy() diff = np.mean(np.abs(G_new['imp'].data.reshape([-1])-G_old['imp'].data.reshape([-1]))) G_old = G_new.copy() nexpv = imp_solver.expv["n_d"] A_w = -1/np.pi*np.array(G_new['imp'].data.reshape([-1]).imag) n += 1 # Save results if mpi.is_master_node(): np.savetxt(filename, np.array([realFreq.real, \ A_w, \ G_new['imp'].data.reshape([-1]).real, \ G_new['imp'].data.reshape([-1]).imag, \ imp_solver.Sigma_w['imp'].data.reshape([-1]).real, \ imp_solver.Sigma_w['imp'].data.reshape([-1]).imag, \ imp_solver.chi_NN_w['imp'].data.reshape([-1]).real,\ imp_solver.chi_NN_w['imp'].data.reshape([-1]).imag,\ imp_solver.chi_SS_w['imp'].data.reshape([-1]).real,\ imp_solver.chi_SS_w['imp'].data.reshape([-1]).imag ]).T, \ header = f"w G_w Sigma_w chi_NN_w chi_SS_w (D: {D}, T: {T}, U: {U}, Occ: {Occ}, <n>: {nexpv:.7f})") if n > 0: if mpi.is_master_node(): print ("|G_NEW - G_OLD|: %.7f"%diff) print ("<n>: %.7f"%nexpv) if (diff < tol): if mpi.is_master_node(): print("Converge on G(w)") #raise Converged("Converge!!") else: if mpi.is_master_node(): print ('\n') else: if mpi.is_master_node(): print ('\n') return Delta_out nr_blocks = lambda bgf : len([bl for bl in bgf.indices]) def bgf_to_nparray(bgf): return np.hstack((bgf[bl].data.flatten() for bl in bgf.indices)) def nparray_to_gf(a, gf): b = a.reshape(gf.data.shape) gf.data[:,:,:] = b[:,:,:] def nparray_to_bgf(a): G = newG() split = np.split(a, nr_blocks(G)) # Here we assume all blocks are equally large for i, bl in enumerate(G.indices): nparray_to_gf(split[i], G[bl]) return G F = lambda D: dmft_step(D) - D npF = lambda x : bgf_to_nparray(F(nparray_to_bgf(x))) def solve_mix_B(Delta, alpha): xin = bgf_to_nparray(Delta) sol = optimize.broyden1(npF, xin, alpha=alpha, \ verbose=True, reduction_method="svd", max_rank = 8, f_tol = tol, maxiter = niter) # Start with a DMFT self-consistent loop solve_mix_B(imp_solver.Delta_w, alpha) #try: # solve_mix_B(imp_solver.Delta_w, alpha) #except Converged as c: # print(c.message) mpi.barrier() <file_sep>/1_dmftsolver/ED/nb7/bethe/m_to_i/read_data.sh #!/usr/bin/env bash UINIT=1.5 UFIN=4.0 dU=0.01 N=$(echo "($UFIN - $UINIT)/$dU" | bc) FILENAME='double_occ.out' decimal_cutting () { if [ ${1:2:4} == '00' ]; then CFLOAT=$(echo $1 | sed -e 's/.00/.0/g') elif [ ${1:3:4} == '0' ]; then CFLOAT=${1:0:3} else CFLOAT=$1 fi } touch $FILENAME echo "# U docc" >> $FILENAME for ((i=0; i<$(($N+1)); ++i)); do U=$(echo "$UINIT + $i*$dU" | bc -l) decimal_cutting $U if [ -e result_$CFLOAT ]; then INFO=($(cat result_$CFLOAT)) echo "$U ${INFO[3]}" >> $FILENAME fi done <file_sep>/1_dmftsolver/QMC/main.py #!/usr/bin/env python3 import numpy as np from gfmod import * import matplotlib.pyplot as plt import os #os.environ["OMP_NUM_THREADS"] = "2" # export OMP_NUM_THREADS=1 #os.environ["OPENBLAS_NUM_THREADS"] = "2" # export OPENBLAS_NUM_THREADS=1 #os.environ["NUMEXPR_NUM_THREADS"] = "2" # export NUMEXPR_NUM_THREADS=1 #os.environ["MKL_NUM_THREADS"] = "2" # export MKL_NUM_THREADS=1 #os.environ["VECLIB_MAXIMUM_THREADS"] = "2" # export VECLIB_MAXIMUM_THREADS=1 import sys import argparse parser = argparse.ArgumentParser() parser.add_argument("-U", help = "on-site interaction", type = float) parser.add_argument("-beta", help = "1/temperature", type = float, default = 50) parser.add_argument("-load", help = "previous data", type = str, default = None) parser.add_argument("-way", help = "direction", type = int) args = parser.parse_args() def main(): way = args.way beta = args.beta U = args.U niwn = 400 ntau = 1000 mu = 0 #muu = U/2.0 V = 1 D = 1 nmc = 3 nmeas = 4 seed = 0 numLoop = 50 delta_G = 5e-3 # imaginary time & Matsubara frequency giwn = gftools.SemiCircularGreen(niwn, beta, mu, V, D) gtau = gftools.GreenInverseFourier(giwn, ntau, beta, (1,0,0)) tau = np.linspace(0, beta, len(gtau)) omega = np.array([1j*(2*n+1.)*np.pi/beta for n in range(len(giwn))], dtype = 'complex128') # HF-QMC solver distance = lambda G1, G2: np.average(np.abs(G1-G2)) G_new = giwn.copy() if (args.load!=None): print ("---- LOAD DATA : ", args.load) w, Gr, Gi = np.loadtxt(args.load, unpack = True, dtype = 'float64') G_new = Gr + 1j*Gi print (f"---- START SELF-CONSISTENT LOOP: U = {U}.") for numiter in range(numLoop): G_old = G_new.copy() # Self-consistent equation G_bath = (iwn + mu - (D/2)^2*G)^-1 G_bath = 1.0/(omega + mu - (D/2.0)**2*G_old) gtau = gftools.GreenInverseFourier(G_bath, ntau, beta, (1,0,0)) # Solve solver = qmc.hfqmc(gtau, beta, U, seed) gtau_up, err_up, gtau_dw, err_dw = solver.meas(nmc, nmeas) gtau = (gtau_up + gtau_dw)/2.0 G_new = gftools.GreenFourier(gtau, niwn, beta) np.savetxt(f'./Bethe_{way:.0f}_beta{beta:.0f}/Gw-{U:.2f}.dat', np.array([omega.imag, G_new.real, G_new.imag]).T) np.savetxt(f'./Bethe_{way:.0f}_beta{beta:.0f}/Gt-{U:.2f}.dat', np.array([tau, gtau, (err_up + err_dw)/2]).T) if (numiter>0): dist = distance(G_new, G_old) print(" * |G_new-G_old| : ", dist) if (dist < delta_G): print(">>>> CONVERGE") break sys.stdout.flush() #fig, ax = plt.subplots(1,2, figsize=(11,4)) #ax[0].errorbar(tau, gtau, (err_up + err_dw)/2, marker = 'o',markersize = 3, linewidth = 1, capsize = 5) #ax[0].legend(loc = 'best', fontsize = 14, edgecolor = 'None', framealpha = 0.0) #ax[0].tick_params(which = 'both', direction = 'in', labelsize = 14) #ax[0].set_ylim(-0.55, 0.05) #ax[0].axhline(y=-0.5, linestyle='--', color='k', lw=1) #ax[0].set_xlabel(r'$\tau$', fontsize = 14) #ax[0].set_ylabel(r'$G(\tau)$', fontsize = 14) #ax[1].plot(omega.imag, G_new.imag, marker = '.', markersize = 5, linewidth=1) #ax[1].set_ylim(-1.5, 0.01) #plt.show() main() <file_sep>/1_dmftsolver/NRG/A_to_Giw/test_AtoG_Gtau/GiwtoGtau.cpp #include <stdio.h> #include <string> #include <vector> #include <iostream> #include <fstream> #include <cmath> #include <complex> #include <functional> #include <string> #include <cstring> #include <assert.h> #include <fftw3.h> /* --- How to use fftw3 library: -I/home/hyejin/fftw-3.3.9 -L/opt/fftw/lib -lfftw3 */ typedef std::vector<double> ImTimeGreen; typedef std::vector<std::complex<double> > ImFreqGreen; enum FOURIER_TRANSFORM { FORWARD = -1, BACKWARD = 1 }; void fft_1d_complex(const std::complex<double> * input, std::complex<double> * output, const int N, const FOURIER_TRANSFORM FFTW_DIRECTION) { fftw_complex * in = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex)*N)), * out = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex)*N)); fftw_plan p = fftw_plan_dft_1d(N, in, out, FFTW_DIRECTION, FFTW_ESTIMATE); for(int i=0; i<N; ++i) { in[i][0] = input[i].real(); in[i][1] = input[i].imag(); } fftw_execute(p); // repeat as needed for(int i=0; i<N; ++i) output[i] = std::complex<double>(out[i][0], out[i][1]); fftw_destroy_plan(p); fftw_free(in); fftw_free(out); } void GreenInverseFourier(const ImFreqGreen & giwn, const double beta, const std::vector<double> & M, ImTimeGreen & gtau) { // check whether mesh size satisfies the Nyquist theorem. assert(gtau.size()/2 >= giwn.size()); std::vector<std::complex<double> > iwn(giwn.size()); for (int n=0; n<giwn.size(); ++n) iwn[n] = std::complex<double>(0, (2*n+1)*M_PI/beta); std::vector<std::complex<double> > giwn_temp(gtau.size(), std::complex<double>(0, 0)), gtau_temp(gtau.size()); // giwn_temp[i] is 0.0 for i >= giwn.size(). for (int n=0; n<giwn.size(); ++n) giwn_temp[n] = giwn[n] - (M[0]/iwn[n] + M[1]/std::pow(iwn[n], 2) + M[2]/std::pow(iwn[n], 3)); fft_1d_complex(giwn_temp.data(), gtau_temp.data(), gtau.size()-1, FORWARD); for (int i=0; i<gtau.size()-1; ++i) { const double tau = beta*i/(gtau.size()-1.0); gtau[i] = 2.0/beta*(std::exp(std::complex<double>(0.0, -M_PI*tau/beta))*gtau_temp[i]).real() - 0.5*M[0] + (tau/2.0-beta/4.0)*M[1] + (tau*beta/4.0 - std::pow(tau, 2)/4.0)*M[2]; } std::complex<double> gedge(0, 0); // := G(beta) // giwn_temp[i] is 0.0 for i >= giwn.size(). for (int n=0; n<giwn.size(); ++n) gedge -= giwn_temp[n]; gedge *= 2.0/beta; gtau[gtau.size()-1] = gedge.real() - 0.5*M[0] + (beta/4.0)*M[1]; } int main() { int N = 5000; const double b = 100; int ntau = N*10; std::vector<double> w(N); std::vector<double> M(3); M[0] = 1.0, M[1] = 0.0, M[2] = 0.0; double G_real, G_imag; std::vector<std::complex<double> > G(N); std::vector<double> GT(ntau); std::string U; U = "3.50"; std::ifstream filein; filein.open("./Giw/Giw_1000_" + U + ".dat"); if (filein.is_open()){ std::cout << "Input file: U = " << U << std::endl; for (int i = 0; i < N; i++) { filein >> w[i] >> G_real >> G_imag; G[i].real(G_real); G[i].imag(G_imag); } GreenInverseFourier(G, b, M, GT); std::ofstream fileout; fileout.open("./Gtau/Gt_1000_" + U + ".dat"); for (int i = 0; i < ntau; i++){ fileout << GT[i] << std::endl; } fileout.close(); } else{ std::cout << "Error, no input file found" << std::endl; } filein.close(); return 0; } <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/distributions.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/distributions.dir/distributions.cc.o" "distributions" "distributions.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/distributions.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/NRG/dmft_nrg_cubic.py #!/usr/bin/python3 import argparse from triqs.utility import mpi import numpy as np from nrgljubljana_interface import Solver, SemiCircular import utility_cubic from scipy import optimize from copy import deepcopy import mpmath as mpm #================= Parameters ================= parser = argparse.ArgumentParser() parser.add_argument("-U", help = "on-site interaction", type = float) parser.add_argument("-T", help = "temperature", type = float, default = 1e-4) parser.add_argument("-D", help = "half bandwidth", type = float, default = 1) parser.add_argument("-alp", help = "alpha", type = float, default = 0.8) parser.add_argument("-lamb", help = "lambda", type = float, default = 2.4) parser.add_argument("-keepE", help = "keep energy", type = float, default = 12.0) parser.add_argument("-niter", help = "# of iterations", type = int, default = 100) parser.add_argument("-tol", help = "tolerance of the convergence criterion", type = float, default = 1e-4) parser.add_argument("-load", help = "file name of previous data to restart a DMFT loop", type = str, default = None) parser.add_argument("-way", help = "direction", type = int) args = parser.parse_args() D = args.D U = args.U T = args.T alpha = args.alp keepE = args.keepE niter = args.niter tol = args.tol lamb = args.lamb way = args.way filename = f'./C_{way:.0f}_beta10000/Cubic-{U:.3f}.dat' #============================================== # particle-hole symmetric case mu = U/2 e_f = -U/2.0 # Set up the Impurity Solver imp_solver = Solver(model = "SIAM", symtype = "QS", mesh_max = 5.0, mesh_min = 1e-5, mesh_ratio = 1.01) #imp_solver.set_verbosity(False) # Solve Parameters sp = { "T": T, "Lambda": lamb, "Nz": 4, "Tmin": 1e-6, \ "keep": 3000, "keepenergy": keepE, "alpha": 0.4, "bandrescale": 1.0 } # Model Parameters mp = { "U1": U, "eps1": e_f } sp["model_parameters"] = mp ob = ["n_d"] # Set up the Lattice Solver lattice_solver = utility_cubic.BetheLatticeSolver(imp_solver, D) # Load previous data lattice_solver.load_data(imp_solver, filename if args.load is None else args.load) n = 0 newG = lambda : imp_solver.G_w.copy() nr_blocks = lambda bgf : len([bl for bl in bgf.indices]) block_size = lambda bl : len(imp_solver.G_w[bl].indices[0]) identity = lambda bl : np.identity(block_size(bl)) def fix_hyb_function(Delta, Delta_min): Delta_fixed = Delta.copy() for bl in Delta.indices: for w in Delta.mesh: for n in range(block_size(bl)): # only diagonal parts r = Delta[bl][w][n,n].real i = Delta[bl][w][n,n].imag Delta_fixed[bl][w][n,n] = r + 1j*(i if i<-Delta_min else -Delta_min) # Possible improvement: re-adjust the real part so that the Kramers-Kronig relation is maintained return Delta_fixed # Hilbert Transformation def ht1(z): x1 = 1/2 + 1/2 * 3/(3*z)**2 - 1/2 * np.sqrt(1-9/(3*z)**2) * np.sqrt(1-1/(3*z)**2) x2 = x1/(x1-1) kp2 = 1/2 + 1/4 * x2 * np.sqrt(4-x2) - 1/4 * (2-x2) * np.sqrt(1-x2) km2 = kp2 - 1/2 * x2 * np.sqrt(4-x2) #kp2e = np.array([float(mp.ellipk(x).real)+1j*float(mp.ellipk(x).imag) for i,x in enumerate(kp2)]) #km2e = np.array([float(mp.ellipk(x).real)+1j*float(mp.ellipk(x).imag) for i,x in enumerate(km2)]) dos = 1/z * np.sqrt(1-3/4*x1) / (1-x1) * ((2/np.pi)*mpm.ellipk(complex(kp2))) * ((2/np.pi)*mpm.ellipk(complex(km2))) return dos ht0 = lambda z: ht1(z/D) EPS = 1e-20 ht = lambda z: ht0(z.real+1j*(z.imag if z.imag>0.0 else EPS)) def calc_G(Sigma, mu): Gloc = newG() for bl in Gloc.indices: for w in Gloc.mesh: for i in range(block_size(bl)): for j in range(block_size(bl)): # assuming square matrix if i == j: Gloc[bl][w][i,i] = ht(w + mu - Sigma[bl][w][i,i]) # Hilbert-transform else: assert abs(Sigma[bl][w][i,j])<1e-10, "This implementation only supports diagonal self-energy" Gloc[bl][w][i,j] = 0.0 Glocinv = Gloc.inverse() Delta = newG() for bl in Delta.indices: for w in Delta.mesh: Delta[bl][w] = (w+mu)*identity(bl) - Sigma[bl][w] - Glocinv[bl][w] return Gloc, Delta # real frequency domain realFreq = np.array([w for w in imp_solver.Delta_w.mesh], dtype = 'complex128') A_w = np.zeros_like(realFreq) G_old = newG() G_new = newG() Delta_in = imp_solver.Delta_w.copy() Delta_min=1e-6 class Converged(Exception): def __init__(self, message): self.message = message def dmft_step(Delta_in): global n, G_old, G_new if mpi.is_master_node(): print ('# OF ITERATIONS:', (n+1)) # Solve the impurity model Delta_fixed = fix_hyb_function(Delta_in, Delta_min) imp_solver.Delta_w << Delta_fixed imp_solver.solve(**sp) # Solve self-consistent equation G_new, Delta_out = calc_G(imp_solver.Sigma_w, mu) lattice_solver.update_hybridization_function(imp_solver, Delta_out['imp'].data) diff = np.mean(np.abs(G_new['imp'].data.reshape([-1])-G_old['imp'].data.reshape([-1]))) G_old = G_new.copy() nexpv = imp_solver.expv["n_d"] A_w = -1/np.pi*np.array(G_new['imp'].data.reshape([-1]).imag) n += 1 # Save results if mpi.is_master_node(): np.savetxt(filename, np.array([realFreq.real, \ A_w, \ G_new['imp'].data.reshape([-1]).real, \ G_new['imp'].data.reshape([-1]).imag, \ imp_solver.Delta_w['imp'].data.reshape([-1]).real, \ imp_solver.Delta_w['imp'].data.reshape([-1]).imag, \ imp_solver.Sigma_w['imp'].data.reshape([-1]).real, \ imp_solver.Sigma_w['imp'].data.reshape([-1]).imag, \ imp_solver.chi_NN_w['imp'].data.reshape([-1]).real,\ imp_solver.chi_NN_w['imp'].data.reshape([-1]).imag,\ imp_solver.chi_SS_w['imp'].data.reshape([-1]).real,\ imp_solver.chi_SS_w['imp'].data.reshape([-1]).imag ]).T, \ header = f"w G_w Sigma_w chi_NN_w chi_SS_w (D: {D}, T: {T}, U: {U}, half-filling)") if n > 0: if mpi.is_master_node(): print ("|G_new - G_old|: %.7f"%diff) print ("<n>: %.7f"%nexpv) if (diff < tol): if mpi.is_master_node(): raise Converged("Converge!!") else: if mpi.is_master_node(): print ('\n') else: if mpi.is_master_node(): print ('\n') return Delta_out def solve_mix_L(Delta, alpha): Delta_in = Delta.copy() while True: Delta_out = dmft_step(Delta_in) newDelta = alpha*Delta_out + (1-alpha)*Delta_in Delta_in << newDelta try: solve_mix_L(imp_solver.Delta_w, alpha) except Converged as c: print("END!") mpi.barrier() <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/discrete_dist_c_style.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/discrete_dist_c_style.dir/discrete_dist_c_style.cc.o" "discrete_dist_c_style" "discrete_dist_c_style.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/discrete_dist_c_style.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/NRG/dos_bethe.py from triqs.gf import * from triqs.operators import * from h5 import * from triqs.utility import mpi from nrgljubljana_interface import Solver, MeshReFreqPts, hilbert_transform_refreq import math, os, warnings import numpy as np from scipy import interpolate, integrate, special, optimize from collections import OrderedDict table = np.loadtxt('dos_bethe.dat') w, _ = np.loadtxt('dos_bethe.dat', unpack=True, dtype='float64') global dosA dosA = Gf(mesh=MeshReFreqPts(table[:,0]), target_shape=[]) for i, w in enumerate(dosA.mesh): dosA[w] = np.array([[ table[i,1] ]]) ht0 = lambda z: hilbert_transform_refreq(dosA, z) np.savetxt('dos_bethe_result', np.array([w, ht0(w)]).T) <file_sep>/1_dmftsolver/NRG/A_to_Giw/AtoG.py import numpy as np from scipy.integrate import simps, trapz from . import _cpp_module #import matplotlib.pyplot as plt D = 1. T = 0.01 beta = int(1./T) N = 1000 if T == 0.001: add_dir = '_0.001' U_c1, U_c2 = 2.2, 2.59 U = np.array([1.50, 2.00, 2.20, 2.40, 2.58, 2.59, 2.60, 2.80, 3.00, 3.50]) elif T == 0.01: add_dir = '' U_c1, U_c2 = 2.2, 2.37 U = np.array([1.50, 1.80, 2.00, 2.20, 2.36, 2.37, 2.40, 2.70, 3.00, 3.50]) directory = '' w_len = len(np.loadtxt(f'.{directory}/1to4{add_dir}/Bethe-{2.00:.2f}_solution.dat', \ unpack = True, dtype = 'complex128')[0]) x = np.zeros((len(U), w_len), dtype = 'float64') omega = np.pi/beta * (2*np.arange(N+1)+1) # w_n tau = np.linspace(0, beta, N*5) def G(x): N = len(omega) return np.array([simps(x/(1j*omega[i]-w.real), w.real) for i in range (N)]) G_omega = np.zeros((len(x), len(omega)), dtype = 'complex128') G_tau = np.zeros((len(x), len(tau)), dtype = 'complex128') for i, u in enumerate(U): w, A_w, G_w, S_w = np.loadtxt(f'.{directory}/1to4{add_dir}/Bethe-{u:.2f}_solution.dat', \ unpack = True, dtype = 'complex128') x[i] = A_w.real.copy() G_omega[i] = G(x[i]) G_tau[i] = GreenIF(G_omega, N*5, beta, (1,0,0)) np.savetxt(f'Gw.dat', np.concatenate([[omega.T], G_array]).T, header = f\"w G_w\") np.savetxt(f'Gt.dat', np.concatenate([[tau.T], G_tau]).T, header = f\"t G_t\") <file_sep>/COMPILE.sh #!/usr/bin/env bash INSTALL_PREFIX_TRIQS=`pwd`/triqs.build NCPU=20 #COMPILER_FLAGS="-DCMAKE_CXX_COMPILER=`which g++` -DCMAKE_C_COMPILER=`which gcc`" if ! [ -e triqs.src ]; then git clone https://github.com/TRIQS/triqs triqs.src fi if ! [ -e nrgljubljana_interface.src ]; then git clone https://github.com/TRIQS/nrgljubljana_interface nrgljubljana_interface.src fi mkdir -p triqs.build cd triqs.build eval "cmake ../triqs.src $COMPILER_FLAGS -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX_TRIQS" make -j $NCPU #make test make install cd ../ mkdir -p nrgljubljana_interface.build cd nrgljubljana_interface.build source $INSTALL_PREFIX_TRIQS/triqsvars.sh eval "cmake ../nrgljubljana_interface.src $COMPILER_FLAGS" make -j $NCPU make test make install <file_sep>/2_nn/drawfig.py import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib as mpl import numpy as np from matplotlib import rc import numpy as np import matplotlib.pyplot as plt import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import os.path as path import matplotlib.ticker as ticker from scipy.integrate import simps, trapz import matplotlib as mpl mpl.rcParams.update({ 'font.family' : 'STIXGeneral', 'mathtext.fontset' : 'stix', 'xtick.direction' : 'in' , 'xtick.labelsize' : 17.5 , 'xtick.top' : True , 'xtick.major.width' : 1.5, 'xtick.major.size' : 6, 'ytick.direction' : 'in' , 'ytick.labelsize' : 17.5 , 'ytick.right' : True , 'ytick.major.width' : 1.5, 'ytick.major.size' : 6, 'axes.labelsize' : 18, 'legend.frameon' : False, 'legend.fontsize' : 13, 'legend.handlelength' : 2, 'savefig.dpi' : 600, 'savefig.bbox' : 'tight', 'axes.linewidth' : 1.5, }) import matplotlib.ticker as ticker from mpl_toolkits.axes_grid1.inset_locator import inset_axes D = 1 out_node = 2 npoint = 2001 N = 10000 directory = '../1_dmftsolver/NRG' weq = np.linspace(-5, 5, npoint) w, A,Gr,Gi,_,_,_,_,_,_ = np.loadtxt(f'{directory}/Bethe_41_beta10000/Bethe-{2.25:.3f}.dat', \ unpack = True, dtype = 'complex128') #plt.plot(w.real, np.arange(len(w))) #plt.xlabel(r'real frequency $\omega$') #plt.ylabel('cumulant number') #plt.axhspan(1319-500, 1319+500, alpha=0.5, color='#ffee52') #plt.annotate(r'$\omega\simeq0$', xy=(0.4, 0.475), xycoords = 'axes fraction', fontsize=15, ha='center') #plt.show() number, bins, patches = plt.hist(w.real, bins=npoint) def G(x): return np.array([simps(x/(1j*omega[i]-w.real), w) for i in range (N)]) def Geq(x): return np.array([simps(x/(1j*omega[i]-weq), weq) for i in range (N)]) def Gmat(x): return -np.array([G(xx) for i, xx in enumerate(x)])/np.pi def Geqmat(x): return -np.array([Geq(xx) for i, xx in enumerate(x)])/np.pi omega = np.pi/10000 * (2*np.arange(N)+1) # w_n iwnumber = -Geq(number).imag/np.pi beta = 10000 U_c1_4, U_c2_4 = 2.25, 2.9 w_len = len(np.loadtxt(f'{directory}/Bethe_14_beta{beta:d}/Bethe-{2.000:.3f}.dat', \ unpack = True, dtype = 'complex128')[0]) up_num = 142 dn_num = 129 U = np.array([0.001*i for i in range(500, 5001)]) U1_4 = np.zeros(up_num, dtype = 'float64') U2_4 = np.zeros(dn_num, dtype = 'float64') n = 0 for i, u in enumerate(U): if path.isfile(f'{directory}/Bethe_14_beta{beta:d}/Bethe-{u:.3f}.dat')==False: continue U1_4[n] = u n += 1 n = 0 for i, u in enumerate(U): if path.isfile(f'{directory}/Bethe_41_beta{beta:d}/Bethe-{u:.3f}.dat')==False: continue U2_4[n] = u n += 1 x_test_iw_up = np.zeros((len(U1_4), 20000), dtype = 'float64') x_test_iw_dn = np.zeros((len(U2_4), 20000), dtype = 'float64') for i,u in enumerate(U1_4): iw, Giw_r, Giw_i = np.loadtxt(f'../1_dmftsolver/NRG/A_to_Giw/NRG/Bethe_14_beta{beta:d}/Bethe-Giw-{u:.3f}.dat',\ unpack = True, dtype = 'float64') x_test_iw_up[i, :10000], x_test_iw_up[i, 10000:] = (D/2)**2 * Giw_r, (D/2)**2 * Giw_i for i,u in enumerate(U2_4): iw, Giw_r, Giw_i = np.loadtxt(f'../1_dmftsolver/NRG/A_to_Giw/NRG/Bethe_41_beta{beta:d}/Bethe-Giw-{u:.3f}.dat',\ unpack = True, dtype = 'float64') x_test_iw_dn[i, :10000], x_test_iw_dn[i, 10000:] = (D/2)**2 * Giw_r, (D/2)**2 * Giw_i x_test_iw_up = torch.FloatTensor(-x_test_iw_up) x_test_iw_dn = torch.FloatTensor(-x_test_iw_dn) y_temp1 = np.array(U1_4 < U_c2_4) y_temp2 = np.array(U2_4 < U_c1_4) y_temp = np.concatenate([y_temp1, y_temp2]) y_test_4 = np.stack([y_temp, ~y_temp], axis = 1) y_test_4 = torch.FloatTensor(y_test_4) #UU_4 = np.concatenate((U1_4, U2_4)) def EDbath(e, V): return np.array([np.sum(V**2/(1j*omega[i]-e)) for i in range (N)]) beta = 100 directory1 = '../1_dmftsolver/ED' up_num = 211 dn_num = 211 U1_ed = np.zeros(up_num, dtype = 'float64') U2_ed = np.zeros(dn_num, dtype = 'float64') U_c1_ed, U_c2_ed = 2.4, 2.93 U = np.array([0.01*i for i in range(50, 501)]) n = 0 for i, u in enumerate(U): if path.isfile(f'{directory1}/ED_14_beta{beta:d}/checkpoint-{u:.2f}')==False: continue U1_ed[n] = u n += 1 n = 0 for i, u in enumerate(U): if path.isfile(f'{directory1}/ED_41_beta{beta:d}/checkpoint-{u:.2f}')==False: continue U2_ed[n] = u n += 1 x_test_ed_up = np.zeros((len(U1_ed), 20000), dtype = 'float64') x_test_ed_dn = np.zeros((len(U2_ed), 20000), dtype = 'float64') for i,u in enumerate(U1_ed): a = np.loadtxt(f'{directory1}/ED_14_beta{beta:d}/checkpoint-{u:.2f}', dtype = 'float64') e,V = a[:int(len(a)/2)], a[int(len(a)/2):] mid = EDbath(e,V) x_test_ed_up[i][:10000], x_test_ed_up[i][10000:] = mid.real, mid.imag for i,u in enumerate(U2_ed): a = np.loadtxt(f'{directory1}/ED_41_beta{beta:d}/checkpoint-{u:.2f}', dtype = 'float64') e,V = a[:int(len(a)/2)], a[int(len(a)/2):] mid = EDbath(e,V) x_test_ed_dn[i][:10000], x_test_ed_dn[i][10000:] = mid.real, mid.imag x_test_ed_up = torch.FloatTensor(-x_test_ed_up) x_test_ed_dn = torch.FloatTensor(-x_test_ed_dn) y_temp1 = np.array(U1_ed < U_c2_ed) y_temp2 = np.array(U2_ed < U_c1_ed) y_temp = np.concatenate([y_temp1, y_temp2]) y_test_ed = np.stack([y_temp, ~y_temp], axis = 1) y_test_ed = torch.FloatTensor(y_test_ed) UU_ed = np.concatenate((U1_ed, U2_ed)) class LRNet(nn.Module): def __init__(self, activate = None): super(LRNet, self).__init__() self.W1 = nn.Linear(20000, out_node)#, bias=False) self.b1 = nn.Linear(out_node, 1)#, bias=False) self.activate = activate() self.sig = nn.Sigmoid() def forward(self, x): x = self.W1(x)+self.b1.weight.data return self.sig(x) def accuracy(self, output, y): return np.average((output>=0.5)==y) class NN10Net(nn.Module): def __init__(self, activate = None): super(NN10Net, self).__init__() self.W1 = nn.Linear(20000, 10)#, bias=False) self.b1 = nn.Linear(10, 1, bias=False) self.W2 = nn.Linear(10, out_node)#, bias=False) self.b2 = nn.Linear(out_node, 1, bias=False) self.activate = activate() self.sig = nn.Sigmoid() def forward(self, x): x = self.activate(self.W1(x)+self.b1.weight.data) x = self.W2(x)+self.b2.weight.data return self.sig(x) def accuracy(self, output, y): return np.average((output>=0.5)==y) class NN100Net(nn.Module): def __init__(self, activate = None): super(NN100Net, self).__init__() self.W1 = nn.Linear(20000, 100)#, bias=False) self.b1 = nn.Linear(100, 1, bias=False) self.W2 = nn.Linear(100, out_node)#, bias=False) self.b2 = nn.Linear(out_node, 1, bias=False) self.activate = activate() self.sig = nn.Sigmoid() def forward(self, x): x = self.activate(self.W1(x)+self.b1.weight.data) x = self.W2(x)+self.b2.weight.data return self.sig(x) def accuracy(self, output, y): return np.average((output>=0.5)==y) func = nn.Sigmoid LRmodel = LRNet(activate = func) NN10model = NN10Net(activate = func) NN100model = NN100Net(activate = func) LRmodel.load_state_dict(torch.load('./frozen_mat/TLRmodel.pth')) NN10model.load_state_dict(torch.load('./frozen_mat/TNN10model.pth')) NN100model.load_state_dict(torch.load('./frozen_mat/TNN100model.pth')) xsize, ysize=1.2, 1.8 ax1 = plt.axes((0.1, 0, xsize, ysize), xticks = [], \ yticks = [], facecolor = 'None', frameon = False) plt.gcf().text(0.15,ysize-0.15, '(a)', fontsize = 25) inode_x, inode_y = 0.35, 0.8 hnode_x, hnode_y = 0.52, inode_y-0.12/2 onode_x, onode_y = 0.69, inode_y-0.12*2+0.12/2 # (a)-1 ###################################################################### r1 = mpatches.FancyBboxPatch((inode_x-0.04,inode_y-0.12*4-0.04), 0.08,0.56, \ boxstyle = mpatches.BoxStyle("Round", pad = 0.02, \ rounding_size = 0.07), \ alpha = 0.18, edgecolor = 'none', facecolor = 'r') ax1.add_patch(r1) # input layer for i in range(1): o = mpatches.Circle((inode_x, inode_y-0.12*i), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2, zorder = 2) ax1.add_patch(o) ax1.text(inode_x, inode_y-0.12*i, fr'$i_{i+1}$', fontsize = 18, \ ha='center', va='center', transform = ax1.transAxes) ax1.annotate('', xy=(inode_x-0.1, 0.8-0.12*i), xytext=(inode_x-0.05, inode_y-0.12*i), \ xycoords = 'axes fraction', ha='center', va='center', \ arrowprops={'arrowstyle':'<-', 'shrinkA':0, 'shrinkB':0,'lw':2,'mutation_scale':15}) for i in range(2): o = mpatches.Circle((inode_x, inode_y-0.08-0.03*i), \ radius = 0.004, facecolor = 'k', edgecolor = 'k', lw=2, zorder = 2) ax1.add_patch(o) o = mpatches.Circle((inode_x, inode_y-0.37-0.03*i), \ radius = 0.004, facecolor = 'k', edgecolor = 'k', lw=2, zorder = 2) ax1.add_patch(o) for i in range(2): o = mpatches.Circle((inode_x, inode_y-0.19-0.10*i), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2, zorder = 2) ax1.add_patch(o) ax1.annotate('', xy=(inode_x-0.1, inode_y-0.19-0.10*i), xytext=(inode_x-0.05, inode_y-0.19-0.10*i), \ xycoords = 'axes fraction', ha='center', va='center', \ arrowprops={'arrowstyle':'<-', 'shrinkA':0, 'shrinkB':0,'lw':2,'mutation_scale':15}) ax1.text(inode_x, inode_y-0.19-0.10*0, r'$i_n$', fontsize = 18, \ ha='center', va='center', transform = ax1.transAxes) ax1.text(inode_x, inode_y-0.19-0.10*1, r'$i_{n+1}$', fontsize = 18, \ ha='center', va='center', transform = ax1.transAxes) ax1.text(inode_x-0.31, inode_y, r'Re$\left[\Gamma(\omega_1+i\eta)\right]$', fontsize = 18, \ va='center', transform = ax1.transAxes) ax1.text(inode_x-0.31, inode_y-0.19, r'Re$\left[\Gamma(\omega_n+i\eta)\right]$', fontsize = 18, \ va='center', transform = ax1.transAxes) ax1.text(inode_x-0.31, inode_y-0.19-0.10*1, r'Im$\left[\Gamma(\omega_1+i\eta)\right]$', fontsize = 18, \ va='center', transform = ax1.transAxes) ax1.text(inode_x-0.31, inode_y-0.12*4, r'Im$\left[\Gamma(\omega_n+i\eta)\right]$', fontsize = 18, \ va='center', transform = ax1.transAxes) o = mpatches.Circle((inode_x, inode_y-0.12*4), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2, zorder = 2) ax1.add_patch(o) ax1.text(inode_x, inode_y-0.12*4, r'$i_{2n}$', fontsize = 18, \ ha='center', va='center', transform = ax1.transAxes) ax1.annotate('', xy=(inode_x-0.1, inode_y-0.12*4), xytext=(inode_x-0.05, inode_y-0.12*4), \ xycoords = 'axes fraction', ha='center', va='center', \ arrowprops={'arrowstyle':'<-', 'shrinkA':0, 'shrinkB':0,'lw':2,'mutation_scale':15}) # hidden layer for i in range(2): o = mpatches.Circle((hnode_x, hnode_y-0.12*i), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2, ls='--', zorder = 2) ax1.add_patch(o) ax1.text(hnode_x, hnode_y-0.12*i, fr'$h_{i+1}$', fontsize = 18, \ ha='center', va='center', transform = ax1.transAxes) for i in range(3): o = mpatches.Circle((hnode_x, hnode_y-0.12*2+0.04-0.04*i), \ radius = 0.004, facecolor = 'k', edgecolor = 'k', lw=2, zorder = 2) ax1.add_patch(o) o = mpatches.Circle((hnode_x, hnode_y-0.12*3), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2, ls='--', zorder = 2) ax1.add_patch(o) ax1.text(hnode_x, hnode_y-0.12*3, r'$h_{N_h}$', fontsize = 18, \ ha='center', va='center', transform = ax1.transAxes) # output layer for i in range(2): o = mpatches.Circle((onode_x, onode_y-0.12*i), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2, zorder = 2) ax1.add_patch(o) ax1.text(onode_x, onode_y-0.12*i, fr'$o_{i+1}$', fontsize = 18, \ ha='center', va='center', transform = ax1.transAxes) ax1.annotate('', xy=(onode_x+0.05, onode_y-0.12*i), xytext=(onode_x+0.1, onode_y-0.12*i), \ xycoords = 'axes fraction', ha='center', va='center', \ arrowprops={'arrowstyle':'<-', 'shrinkA':0, 'shrinkB':0,'lw':2,'mutation_scale':15}) ax1.text(onode_x+0.11, onode_y, r'$P_{\mathrm{metal}}$', fontsize = 18, \ va='center', transform = ax1.transAxes) ax1.text(onode_x+0.11, onode_y-0.12, r'$P_{\mathrm{insul}}$', fontsize = 18, \ va='center', transform = ax1.transAxes) # lines iy_coord = [inode_y] iy_coord.append(inode_y-0.19) iy_coord.append(inode_y-0.19-0.10*1) iy_coord.append(inode_y-0.12*4) hy_coord = [hnode_y-0.12*i for i in range(2)] hy_coord = [hnode_y-0.12*i for i in range(2)] hy_coord.append(hnode_y-0.12*3) # j = 0~2 oy_coord = [onode_y-0.12*i for i in range(2)] for i in range(4): for j in range(3): ax1.annotate('', \ xy = (inode_x, iy_coord[i]), \ xytext = (hnode_x, hy_coord[j]), \ xycoords='axes fraction', textcoords='axes fraction', \ arrowprops=dict(arrowstyle='-', color='black', \ shrinkA=0,shrinkB=0,lw=2), \ size = 'large', zorder = 1) for i in range(3): for j in range(2): ax1.annotate('', \ xy = (hnode_x, hy_coord[i]), \ xytext = (onode_x, oy_coord[j]), \ xycoords='axes fraction', textcoords='axes fraction', \ arrowprops=dict(arrowstyle='-', color='black', \ shrinkA=0,shrinkB=0,lw=2), \ size = 'large', zorder = 1) ax1.annotate('', xy=(inode_x, inode_y+0.126), xytext=(xsize-0.3, inode_y+0.126), xycoords='axes fraction',\ arrowprops=dict(arrowstyle='-', color='k', shrinkA=0, shrinkB=0,lw=2), zorder=0) ax1.annotate('', xy=(inode_x, inode_y+0.059), xytext=(inode_x, inode_y+0.126), xycoords='axes fraction',\ arrowprops=dict(arrowstyle='-', color='k', shrinkA=0, shrinkB=0,lw=2), zorder=0) ax1.annotate('initialize', xy=(inode_x, inode_y+0.126), xytext=(inode_x, inode_y+0.126), xycoords='axes fraction',\ arrowprops=dict(arrowstyle='-', color='k', shrinkA=0, shrinkB=0,lw=2), zorder=0) ax1.text(0.05, inode_y-0.12*4-0.15, 'Pre-training: Real frequency', fontsize = 22, \ va='center', transform = ax1.transAxes) ax1.annotate('', xy=(inode_x-0.207, inode_y-0.12*4-0.05), xytext=(inode_x-0.207, inode_y-0.12*4-0.12), fontsize=14, ha='center', va='top', xycoords='axes fraction', bbox=dict(boxstyle='round', fc='0.8'), arrowprops=dict(arrowstyle='-[, widthB=3.65, lengthB=.5',lw=2), transform = ax1.transAxes) ax1.text(inode_x+0.08, inode_y-0.12*4-0.02, r'$\mathrm{W}^{(1)}, \mathrm{b}^{(1)}$', fontsize = 18, \ va='center', transform = ax1.transAxes) ax1.text(hnode_x+0.085, hnode_y-0.12*3+0.02, r'$\mathrm{W}^{(2)}, \mathrm{b}^{(2)}$', fontsize = 18, \ va='center', transform = ax1.transAxes) ax1.text(inode_x-0.207, inode_y-0.19/2, r'$\cdots$', fontsize=40, rotation=90, \ va='center', ha='center', transform=ax1.transAxes) ax1.text(inode_x-0.207, inode_y-0.77/2, r'$\cdots$', fontsize=40, rotation=90, \ va='center', ha='center', transform=ax1.transAxes) #(a)-2 ########################################################### ax2 = plt.axes((xsize-0.15, 0, xsize, ysize), xticks = [], \ yticks = [], facecolor = 'None', frameon = False) inode_x, inode_y = 0.42, 0.8 hnode_x, hnode_y = 0.59, inode_y-0.12/2 onode_x, onode_y = 0.76, inode_y-0.12*2+0.12/2 r1 = mpatches.FancyBboxPatch((inode_x-0.04,inode_y-0.12*4-0.04), 0.08,0.56, \ boxstyle = mpatches.BoxStyle("Round", pad = 0.02, \ rounding_size = 0.07), \ alpha = 0.18, edgecolor = 'none', facecolor = 'b') ax2.add_patch(r1) # input layer for i in range(1): o = mpatches.Circle((inode_x, inode_y-0.12*i), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2, zorder = 2) ax2.add_patch(o) ax2.text(inode_x, inode_y-0.12*i, fr'$i^\prime_{i+1}$', fontsize = 18, \ ha='center', va='center', transform = ax2.transAxes) ax2.annotate('', xy=(inode_x-0.1, 0.8-0.12*i), xytext=(inode_x-0.05, inode_y-0.12*i), \ xycoords = 'axes fraction', ha='center', va='center', \ arrowprops={'arrowstyle':'<-', 'shrinkA':0, 'shrinkB':0,'lw':2,'mutation_scale':15}) for i in range(2): o = mpatches.Circle((inode_x, inode_y-0.08-0.03*i), \ radius = 0.004, facecolor = 'k', edgecolor = 'k', lw=2, zorder = 2) ax2.add_patch(o) o = mpatches.Circle((inode_x, inode_y-0.37-0.03*i), \ radius = 0.004, facecolor = 'k', edgecolor = 'k', lw=2, zorder = 2) ax2.add_patch(o) for i in range(2): o = mpatches.Circle((inode_x, inode_y-0.19-0.10*i), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2, zorder = 2) ax2.add_patch(o) ax2.annotate('', xy=(inode_x-0.1, inode_y-0.19-0.10*i), xytext=(inode_x-0.05, inode_y-0.19-0.10*i), \ xycoords = 'axes fraction', ha='center', va='center', \ arrowprops={'arrowstyle':'<-', 'shrinkA':0, 'shrinkB':0,'lw':2,'mutation_scale':15}) ax2.text(inode_x, inode_y-0.19-0.10*0, r'$i^\prime_m$', fontsize = 18, \ ha='center', va='center', transform = ax2.transAxes) ax2.text(inode_x, inode_y-0.19-0.10*1, r'$i^\prime_{m+1}$', fontsize = 17, \ ha='center', va='center', transform = ax2.transAxes) ax2.text(inode_x-0.265, inode_y, r'Re$\left[\Gamma(i\omega_1)\right]$', fontsize = 18, \ va='center', transform = ax2.transAxes) ax2.text(inode_x-0.265, inode_y-0.19, r'Re$\left[\Gamma(i\omega_m)\right]$', fontsize = 18, \ va='center', transform = ax2.transAxes) ax2.text(inode_x-0.265, inode_y-0.19-0.10*1, r'Im$\left[\Gamma(i\omega_1)\right]$', fontsize = 18, \ va='center', transform = ax2.transAxes) ax2.text(inode_x-0.265, inode_y-0.12*4, r'Im$\left[\Gamma(i\omega_m)\right]$', fontsize = 18, \ va='center', transform = ax2.transAxes) o = mpatches.Circle((inode_x, inode_y-0.12*4), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2, zorder = 2) ax2.add_patch(o) ax2.text(inode_x, inode_y-0.12*4, r'$i^\prime_{2m}$', fontsize = 18, \ ha='center', va='center', transform = ax2.transAxes) ax2.annotate('', xy=(inode_x-0.1, inode_y-0.12*4), xytext=(inode_x-0.05, inode_y-0.12*4), \ xycoords = 'axes fraction', ha='center', va='center', \ arrowprops={'arrowstyle':'<-', 'shrinkA':0, 'shrinkB':0,'lw':2,'mutation_scale':15}) for i in range(2): o = mpatches.Circle((hnode_x, hnode_y-0.12*i), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2,ls='--', zorder = 2) ax2.add_patch(o) ax2.text(hnode_x, hnode_y-0.12*i, fr'$h_{i+1}$', fontsize = 18, \ ha='center', va='center', transform = ax2.transAxes) for i in range(3): o = mpatches.Circle((hnode_x, hnode_y-0.12*2+0.04-0.04*i), \ radius = 0.004, facecolor = 'k', edgecolor = 'k', lw=2,zorder = 2) ax2.add_patch(o) o = mpatches.Circle((hnode_x, hnode_y-0.12*3), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2,ls='--', zorder = 2) ax2.add_patch(o) ax2.text(hnode_x, hnode_y-0.12*3, r'$h_{N_h}$', fontsize = 18, \ ha='center', va='center', transform = ax2.transAxes) for i in range(2): o = mpatches.Circle((onode_x, onode_y-0.12*i), \ radius = 0.036, facecolor = 'w', edgecolor = 'k', lw=2,zorder = 2) ax2.add_patch(o) ax2.text(onode_x, onode_y-0.12*i, fr'$o_{i+1}$', fontsize = 18, \ ha='center', va='center', transform = ax2.transAxes) ax2.annotate('', xy=(onode_x+0.05, onode_y-0.12*i), xytext=(onode_x+0.1, onode_y-0.12*i), \ xycoords = 'axes fraction', ha='center', va='center', \ arrowprops={'arrowstyle':'<-', 'shrinkA':0, 'shrinkB':0,'lw':2,'mutation_scale':15}) ax2.text(onode_x+0.11, onode_y, r'$P_{\mathrm{metal}}$', fontsize = 18, \ va='center', transform = ax2.transAxes) ax2.text(onode_x+0.11, onode_y-0.12, r'$P_{\mathrm{insul}}$', fontsize = 18, \ va='center', transform = ax2.transAxes) iy_coord = [inode_y] iy_coord.append(inode_y-0.19) iy_coord.append(inode_y-0.19-0.10*1) iy_coord.append(inode_y-0.12*4) hy_coord = [hnode_y-0.12*i for i in range(2)] hy_coord = [hnode_y-0.12*i for i in range(2)] hy_coord.append(hnode_y-0.12*3) # j = 0~2 oy_coord = [onode_y-0.12*i for i in range(2)] for i in range(4): for j in range(3): ax2.annotate('', \ xy = (inode_x, iy_coord[i]), \ xytext = (hnode_x, hy_coord[j]), \ xycoords='axes fraction', textcoords='axes fraction', \ arrowprops=dict(arrowstyle='-', color='black', \ shrinkA=0,shrinkB=0,lw=2), \ size = 'large', zorder = 1) for i in range(3): for j in range(2): ax2.annotate('', \ xy = (hnode_x, hy_coord[i]), \ xytext = (onode_x, oy_coord[j]), \ xycoords='axes fraction', textcoords='axes fraction', \ arrowprops=dict(arrowstyle='-', color='black', \ shrinkA=0,shrinkB=0,lw=2), \ size = 'large', zorder = 1) ax2.annotate('', xy=(inode_x, inode_y+0.057), xytext=(inode_x, inode_y+0.126), xycoords='axes fraction',\ arrowprops=dict(arrowstyle='->', color='k', shrinkA=0, shrinkB=0, lw=2,mutation_scale=20), zorder=0) ax2.annotate('', xy=(inode_x, inode_y+0.126), xytext=(0.1, inode_y+0.126), xycoords='axes fraction',\ arrowprops=dict(arrowstyle='-', color='k', shrinkA=0, shrinkB=0,lw=2,), zorder=0) ax2.text(inode_x-0.25, inode_y-0.12*4-0.15, 'Training: Matsubara frequency', fontsize = 22, \ va='center', transform = ax2.transAxes) ax2.annotate('', xy=(inode_x-0.184, inode_y-0.12*4-0.05), xytext=(inode_x-0.184, inode_y-0.12*4-0.12), fontsize=14, ha='center', va='top', xycoords='axes fraction', bbox=dict(boxstyle='round', fc='0.8'), arrowprops=dict(arrowstyle='-[, widthB=2.75, lengthB=.5', lw=2), transform = ax2.transAxes) ax2.text(inode_x+0.08, inode_y-0.12*4-0.02, r'$\mathrm{W}\prime^{(1)}, \mathrm{b}^{(1)}$', fontsize = 18, \ va='center', transform = ax2.transAxes) ax2.text(hnode_x+0.085, hnode_y-0.12*3+0.02, r'$\mathrm{W}^{(2)}, \mathrm{b}^{(2)}$', fontsize = 18, \ va='center', transform = ax2.transAxes) ax2.text(inode_x-0.185, inode_y-0.19/2, r'$\cdots$', fontsize=40, rotation=90, \ va='center', ha='center', transform=ax2.transAxes) ax2.text(inode_x-0.185, inode_y-0.77/2, r'$\cdots$', fontsize=40, rotation=90, \ va='center', ha='center', transform=ax2.transAxes) ax5 = plt.axes((0.7, 1.44, 0.12, 0.12), xticks = [], \ yticks = [], facecolor = 'None', frameon = True) ax6 = plt.axes((0.91, 1.22, 0.12, 0.12), xticks = [], \ yticks = [], facecolor = 'None', frameon = True) ax5.spines['top'].set_visible(False) ax6.spines['top'].set_visible(False) ax5.spines['right'].set_visible(False) ax6.spines['right'].set_visible(False) ax5.plot(np.linspace(-5,5,200),1/(1+np.exp(-np.linspace(-5,5,200)*2)), c='k', lw=2) ax5.set_xlabel(r'$y$', fontsize=15) ax5.xaxis.set_label_coords(0.95, -0.03) ax5.yaxis.set_label_coords(-0.15, 0.75) ax5.set_ylabel(r'$\sigma$', fontsize=15, rotation=0) ax5.set_ylim(-0.03,1.05) ax5.set_xlim(-5,5) ax6.plot(np.linspace(-5,5,200),1/(1+np.exp(-np.linspace(-5,5,200)*2)), c='k', lw=2) ax6.set_xlabel(r'$z$', fontsize=15) ax6.xaxis.set_label_coords(0.95, -0.03) ax6.yaxis.set_label_coords(-0.15, 0.75) ax6.set_ylabel(r'$\sigma$', fontsize=15, rotation=0) ax6.set_ylim(-0.03,1.05) ax6.set_xlim(-5,5) ax7 = plt.axes((1.74, 1.44, 0.12, 0.12), xticks = [], \ yticks = [], facecolor = 'None', frameon = True) ax8 = plt.axes((1.95, 1.22, 0.12, 0.12), xticks = [], \ yticks = [], facecolor = 'None', frameon = True) ax7.spines['top'].set_visible(False) ax8.spines['top'].set_visible(False) ax7.spines['right'].set_visible(False) ax8.spines['right'].set_visible(False) ax7.plot(np.linspace(-5,5,200),1/(1+np.exp(-np.linspace(-5,5,200)*2)), c='k', lw=2) ax7.set_xlabel(r'$y$', fontsize=15) ax7.xaxis.set_label_coords(0.95, -0.03) ax7.yaxis.set_label_coords(-0.15, 0.75) ax7.set_ylabel(r'$\sigma$', fontsize=15, rotation=0) ax7.set_ylim(-0.03,1.05) ax7.set_xlim(-5,5) ax8.plot(np.linspace(-5,5,200),1/(1+np.exp(-np.linspace(-5,5,200)*2)), c='k', lw=2) ax8.set_xlabel(r'$z$', fontsize=15) ax8.xaxis.set_label_coords(0.95, -0.03) ax8.yaxis.set_label_coords(-0.15, 0.75) ax8.set_ylabel(r'$\sigma$', fontsize=15, rotation=0) ax8.set_ylim(-0.03,1.05) ax8.set_xlim(-5,5) # (b) ################################################################# a, b = -0.2, 0 plt.gcf().text(0.15,-0.01, '(b)', fontsize = 25) plt.gcf().text(1.45,-0.01, '(c)', fontsize = 25) ax30 = plt.axes((0.5+a, -0.6, 0.5, 0.5), xticks = [], \ yticks = [], facecolor = 'None', frameon = True) ax31 = plt.axes((1.05+a, -0.6, 0.5, 0.5), xticks = [], \ yticks = [], facecolor = 'None', frameon = True) ax32 = plt.axes((1.6+b, -0.6, 0.5, 0.5), xticks = [], \ yticks = [], facecolor = 'None', frameon = True) ax40 = plt.axes((0.5+a, -1.3, 0.5, 0.5), xticks = [], \ yticks = [], facecolor = 'None', frameon = True) ax41 = plt.axes((1.05+a, -1.3, 0.5, 0.5), xticks = [], \ yticks = [], facecolor = 'None', frameon = True) ax42 = plt.axes((1.6+b, -1.3, 0.5, 0.5), xticks = [], \ yticks = [], facecolor = 'None', frameon = True) ax30.axvline(U_c1_4, c = '#99CC99', lw = '7'), ax30.axvline(U_c2_4, c = '#99CC99', lw = '7') ax30.plot(U2_4, NN100model.forward(x_test_iw_dn).data[:,0], 'ko--', ms=5, label = r'decreasing $U$') ax30.plot(U1_4, NN100model.forward(x_test_iw_up).data[:,0], 'bo--', ms=5, label = r'increasing $U$') ax30.annotate(r'$U_{c1}$', xy=(0.25, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax30.annotate(r'$U_{c2}$', xy=(0.78, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax30.plot(np.array([U_c1_4, U_c2_4]), np.zeros(2), 'r^', ms=25) ax30.set_ylim(0,1) ax30.set_xlim(1.6,3.5) ax31.axvline(U_c1_4, c = '#99CC99', lw = '7'), ax31.axvline(U_c2_4, c = '#99CC99', lw = '7') ax31.plot(U1_4, NN10model.forward(x_test_iw_up).data[:,0], 'bo--', ms=5, label = r'decreasing $U$') ax31.plot(U2_4, NN10model.forward(x_test_iw_dn).data[:,0], 'ko--', ms=5, label = r'increasing $U$') ax31.annotate(r'$U_{c1}$', xy=(0.25, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax31.annotate(r'$U_{c2}$', xy=(0.78, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax31.plot(np.array([U_c1_4, U_c2_4]), np.zeros(2), 'r^', ms=25) ax31.set_ylim(0,1) ax31.set_xlim(1.6,3.5) ax32.axvline(U_c1_4, c = '#99CC99', lw = '7'), ax32.axvline(U_c2_4, c = '#99CC99', lw = '7') ax32.plot(U2_4, LRmodel.forward(x_test_iw_dn).data[:,0], 'ko--', ms=5, label = r'decreasing $U$') ax32.plot(U1_4, LRmodel.forward(x_test_iw_up).data[:,0], 'bo--', ms=5, label = r'increasing $U$') ax32.annotate(r'$U_{c1}$', xy=(0.25, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax32.annotate(r'$U_{c2}$', xy=(0.78, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax32.plot(np.array([U_c1_4, U_c2_4]), np.zeros(2), 'r^', ms=25) ax32.set_ylim(0,1) ax32.set_xlim(1.6,3.5) ax40.axvline(U_c1_ed, c = '#99CC99', lw = '7'), ax40.axvline(U_c2_ed, c = '#99CC99', lw = '7') ax40.plot(U2_ed, NN100model.forward(x_test_ed_dn).data[:,0], 'ko--', ms=5, label = r'decreasing $U$') ax40.plot(U1_ed, NN100model.forward(x_test_ed_up).data[:,0], 'bo--', ms=5, label = r'increasing $U$') ax40.annotate(r'$U_{c1}$', xy=(0.32, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax40.annotate(r'$U_{c2}$', xy=(0.79, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax40.plot(np.array([U_c1_ed, U_c2_ed]), np.zeros(2), 'r^', ms=25) ax40.set_ylim(0,1) ax40.set_xlim(1.6,3.5) ax41.axvline(U_c1_ed, c = '#99CC99', lw = '7'), ax41.axvline(U_c2_ed, c = '#99CC99', lw = '7') ax41.plot(U2_ed, NN10model.forward(x_test_ed_dn).data[:,0], 'ko--', ms=5, label = r'decreasing $U$') ax41.plot(U1_ed, NN10model.forward(x_test_ed_up).data[:,0], 'bo--', ms=5, label = r'increasing $U$') ax41.annotate(r'$U_{c1}$', xy=(0.32, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax41.annotate(r'$U_{c2}$', xy=(0.79, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax41.plot(np.array([U_c1_ed, U_c2_ed]), np.zeros(2), 'r^', ms=25) ax41.set_ylim(0,1) ax41.set_xlim(1.6,3.5) ax42.axvline(U_c1_ed, c = '#99CC99', lw = '7'), ax42.axvline(U_c2_ed, c = '#99CC99', lw = '7') ax42.plot(U2_ed, LRmodel.forward(x_test_ed_dn).data[:,0], 'ko--', ms=5, label = r'decreasing $U$') ax42.plot(U1_ed, LRmodel.forward(x_test_ed_up).data[:,0], 'bo--', ms=5, label = r'increasing $U$') ax42.annotate(r'$U_{c1}$', xy=(0.32, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax42.annotate(r'$U_{c2}$', xy=(0.79, 0.1), xycoords = 'axes fraction', fontsize=16, ha='center') ax42.plot(np.array([U_c1_ed, U_c2_ed]), np.zeros(2), 'r^', ms=25) ax42.set_ylim(0,1) ax42.set_xlim(1.6,3.5) ax30.set_xticks([2.0, 2.5, 3.0, 3.5]) ax31.set_xticks([2.0, 2.5, 3.0, 3.5]) ax32.set_xticks([2.0, 2.5, 3.0, 3.5]) ax40.set_xticks([2.0, 2.5, 3.0, 3.5]) ax41.set_xticks([2.0, 2.5, 3.0, 3.5]) ax42.set_xticks([2.0, 2.5, 3.0, 3.5]) ax30.set_xticklabels([]) ax31.set_xticklabels([]) ax32.set_xticklabels([]) ax30.set_yticks([0.0, 0.5, 1.0]) ax31.set_yticks([0.0, 0.5, 1.0]) ax32.set_yticks([0.0, 0.5, 1.0]) ax40.set_yticks([0.0, 0.5, 1.0]) ax41.set_yticks([0.0, 0.5, 1.0]) ax42.set_yticks([0.0, 0.5, 1.0]) ax31.set_yticklabels([]) ax41.set_yticklabels([]) ax30.tick_params(labelsize=18) ax31.tick_params(labelsize=18) ax32.tick_params(labelsize=18) ax40.tick_params(labelsize=18) ax41.tick_params(labelsize=18) ax42.tick_params(labelsize=18) ax30.set_ylabel(r'$P_{\mathrm{metal}}$', fontsize=20) ax40.set_ylabel(r'$P_{\mathrm{metal}}$', fontsize=20) ax32.set_ylabel(r'$P_{\mathrm{metal}}$', fontsize=20) ax42.set_ylabel(r'$P_{\mathrm{metal}}$', fontsize=20) ax40.set_xlabel('U/D', fontsize=20) ax41.set_xlabel('U/D', fontsize=20) ax42.set_xlabel('U/D', fontsize=20) ax30.text(-0.45, 0.5, 'NRG', fontsize = 25, \ ha='center',va='center', transform = ax30.transAxes) ax40.text(-0.45, 0.5, 'ED', fontsize = 25, \ ha='center',va='center', transform = ax40.transAxes) ax30.text(0.5, 1.25, 'NN\n'+r'$N_h$=100', fontsize = 22, \ ha='center',va='center', transform = ax30.transAxes) ax31.text(0.5, 1.25, 'NN\n'+r'$N_h$=10', fontsize = 22, \ ha='center',va='center', transform = ax31.transAxes) ax32.text(0.5, 1.25, 'LR\n'+r'$N_h$=0', fontsize = 22, \ ha='center',va='center', transform = ax32.transAxes) handles,labels = ax30.get_legend_handles_labels() ax30.legend([handles[1], handles[0]], [labels[1], labels[0]],ncol=2, bbox_to_anchor=(0.8, -0.2), loc='center', fontsize=18) plt.savefig('fig2.pdf', bbox_inches='tight') <file_sep>/1_dmftsolver/ED/main.py #!/usr/bin/env python3 import sys import numpy as np import modules.ed_solver as ed import argparse parser = argparse.ArgumentParser() parser.add_argument("-U", help = "on-site interaction", type = float) parser.add_argument("-beta", help = "inverse temperature", type = float, default = 100) parser.add_argument("-load", help = "file name of previous data to restart a DMFT loop", type = str, default = None) args = parser.parse_args() def main(): # handling parameter beta = args.beta niwn = 5000 nbath = 5 # 2.3 ~ 2.9 phase coexistence region (metal & insulator) # U > 2.9 : insulator; U < 2.4 : metal U = args.U mu = U/2.0 D = 1.0 delta_G = 1e-4 numLoop = 100 prefix = './1to4_0.001/' # Matsubara frequency omega = np.array([1j*(2*n+1.)*np.pi/beta for n in range(niwn)], dtype = 'complex128') # ED solver solver = ed.solver(nbath = nbath, niwn = niwn, beta = beta) # distance measure between two Green's functions distance = lambda G1, G2 : np.sum(np.abs(G1 - G2)) G_new = np.zeros_like(omega) G_old = np.zeros_like(omega) if (args.load!=None): print ("load data from ", args.load) w, Gr, Gi = np.loadtxt(args.load, unpack = True, dtype = 'float64') G_new = Gr + 1j*Gi print ("--- START A SELF-CONSISTENT LOOP!") for numIter in range(numLoop): print ("ITERATION: ", numIter+1) G_old = G_new.copy() # self-consistent equation (Bethe lattice): BathGreen = (iwn + mu - (D/2)^2*G)^-1 BathGreen = 1.0/(omega + mu -(D/2.0)**2*G_old) G_new, density, double_occ = solver.solve({'U' : U, 'mu' : mu}, BathGreen) print (" - <N>: ", density) print (" - <N_up*N_dw>: ", double_occ) # save current states np.savetxt(prefix + f'checkpoint-{U:.2f}', solver.get_pvec().reshape([1, -1])) np.savetxt(prefix + f'Giw-{U:.2f}.dat', np.array([omega.imag, G_new.real, G_new.imag]).T) with open(prefix + f'result-{U:.2f}', 'w') as f: f.write('DENSITY: %f\n'%density) f.write('DOUBLE-OCC: %f\n'%double_occ) f.write('SUM-RULE: %f\n'%np.sum(solver.get_pvec()[nbath:]**2)) f.flush() if (numIter > 0): dist = distance(G_new, G_old) print (" * |G_NEW - G_OLD| : ", dist) if (dist < delta_G): print (">>> CONVERGE!") break print ("\n") sys.stdout.flush() if __name__ == "__main__": main() <file_sep>/1_dmftsolver/NRG/A_to_Giw/test_AtoG_Gtau/docc.cpp #include <stdio.h> #include <string> #include <vector> #include <iostream> #include <fstream> #include <cmath> #include <complex> #include <functional> #include <string> #include <cstring> #include <assert.h> #include <fftw3.h> /* --- How to use fftw3 library: -I/home/hyejin/fftw-3.3.9 -L/opt/fftw/lib -lfftw3 */ typedef std::vector<double> ImTimeGreen; typedef std::vector<std::complex<double> > ImFreqGreen; enum FOURIER_TRANSFORM { FORWARD = -1, BACKWARD = 1 }; void fft_1d_complex(const std::complex<double> * input, std::complex<double> * output, const int N, const FOURIER_TRANSFORM FFTW_DIRECTION) { fftw_complex * in = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex)*N)), * out = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex)*N)); fftw_plan p = fftw_plan_dft_1d(N, in, out, FFTW_DIRECTION, FFTW_ESTIMATE); for(int i=0; i<N; ++i) { in[i][0] = input[i].real(); in[i][1] = input[i].imag(); } fftw_execute(p); // repeat as needed for(int i=0; i<N; ++i) output[i] = std::complex<double>(out[i][0], out[i][1]); fftw_destroy_plan(p); fftw_free(in); fftw_free(out); } void GreenInverseFourier(const ImFreqGreen & giwn, const double beta, const std::vector<double> & M, ImTimeGreen & gtau) { // check whether mesh size satisfies the Nyquist theorem. assert(gtau.size()/2 >= giwn.size()); std::vector<std::complex<double> > iwn(giwn.size()); for (int n=0; n<giwn.size(); ++n) iwn[n] = std::complex<double>(0, (2*n+1)*M_PI/beta); std::vector<std::complex<double> > giwn_temp(gtau.size(), std::complex<double>(0, 0)), gtau_temp(gtau.size()); // giwn_temp[i] is 0.0 for i >= giwn.size(). for (int n=0; n<giwn.size(); ++n){ giwn_temp[n] = giwn[n] - (M[0]/iwn[n] + M[1]/std::pow(iwn[n], 2) + M[2]/std::pow(iwn[n], 3)); } fft_1d_complex(giwn_temp.data(), gtau_temp.data(), gtau.size()-1, FORWARD); for (int i=0; i<gtau.size()-1; ++i){ gtau_temp[i] += giwn_temp[gtau.size()-1]; } for (int i=0; i<gtau.size()-1; ++i) { double tau = beta*i/(gtau.size()-1.0); gtau[i] = 2.0/beta*(std::exp(std::complex<double>(0.0, -M_PI*tau/beta))*gtau_temp[i]).real() - 0.5*M[0] + (tau/2.0-beta/4.0)*M[1] + (tau*beta/4.0 - std::pow(tau, 2)/4.0)*M[2]; } std::complex<double> gedge(0, 0); // := G(beta) // giwn_temp[i] is 0.0 for i >= giwn.size(). for (int n=0; n<giwn.size(); ++n) gedge -= giwn_temp[n]; gedge *= 2.0/beta; gtau[gtau.size()-1] = gedge.real() - 0.5*M[0] + (beta/4.0)*M[1]; } int main() { int N = 5000; const double beta = 50; int ntau = N*10; std::vector<double> w(N); std::vector<double> M(3); double G_real, G_imag, S_real, S_imag, I_real, I_imag; std::vector<std::complex<double> > G(N); std::vector<std::complex<double> > S(N); std::vector<std::complex<double> > I(N); std::vector<double> GT(ntau); //std::string UU[] = {"1.50", "1.80", "2.00", "2.20", "2.25", "2.30", "2.40", "2.50","2.55", "2.60", "2.80", "3.00", "3.20", "3.50"}; std::string UU[] = {"1.50", "2.00", "2.10", "2.20", "2.30", "2.40", "2.50","2.60", "2.70", "2.80", "3.00", "3.50"}; for (int j = 0; j < 12; j++){ double U = std::atof(UU[j].c_str()); double mu = U/2.0; M[0] = -0.5*U, M[1] = 0.0, M[2] = 0.0; //std::ifstream filein1; filein1.open("./Giw/Giw_1to4_1000_" + UU[j] + ".dat"); //std::ifstream filein2; filein2.open("./Giw/Giw_4to1_1000_" + UU[j] + ".dat"); std::ifstream filein1; filein1.open("../../1_dmftsolver/IPT/DMFT_IPT_SOLVER/1to4_0.02/Giw-" + UU[j] + ".dat"); std::ifstream filein2; filein2.open("../../1_dmftsolver/IPT/DMFT_IPT_SOLVER/4to1_0.02/Giw-" + UU[j] + ".dat"); if (filein1.is_open()){ std::cout << std::fixed; std::cout.precision(6); std::cout << U << " "; for (int i = 0; i < N; i++) { filein1 >> w[i] >> G_real >> G_imag; S_real = mu-G_real*(0.25+1/(G_real*G_real+G_imag*G_imag)); S_imag = w[i]-G_imag*(0.25-1/(G_real*G_real+G_imag*G_imag)); I_real = G_real*S_real - G_imag*S_imag; I_imag = G_real*S_imag + G_imag*S_real; G[i].real(G_real); G[i].imag(G_imag); S[i].real(S_real); S[i].imag(S_imag); I[i].real(I_real); I[i].imag(-I_imag); } GreenInverseFourier(I, beta, M, GT); std::cout << GT[0]/U << " "; for (int i = 0; i < N; i++) { filein2 >> w[i] >> G_real >> G_imag; S_real = mu-G_real*(0.25+1/(G_real*G_real+G_imag*G_imag)); S_imag = w[i]-G_imag*(0.25-1/(G_real*G_real+G_imag*G_imag)); I_real = G_real*S_real - G_imag*S_imag; I_imag = G_real*S_imag + G_imag*S_real; G[i].real(G_real); G[i].imag(G_imag); S[i].real(S_real); S[i].imag(S_imag); I[i].real(I_real); I[i].imag(-I_imag); } GreenInverseFourier(I, beta, M, GT); std::cout << GT[0]/U << std::endl; //std::ofstream fileout; //fileout.open("./Gtau/Gt_1000_" + U + ".dat"); //for (int i = 0; i < ntau; i++){ // fileout << GT[i] << std::endl; //} //fileout.close(); } else{ std::cout << "Error, no input file found" << std::endl; } filein1.close(); filein2.close(); } return 0; } <file_sep>/1_dmftsolver/QMC/trng4.build/examples/CMakeFiles/pi_block_openmp.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/pi_block_openmp.dir/pi_block_openmp.cc.o" "pi_block_openmp" "pi_block_openmp.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/pi_block_openmp.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/1_dmftsolver/NRG/Linear_14_beta1000/read.py import sys import numpy as np w, A_w, G_w, S_w = np.loadtxt(sys.argv[1], unpack = True, dtype = 'complex128') np.savetxt('./result/A_w-'+sys.argv[1], np.array([w.real, A_w.real]).T) np.savetxt('./result/G_w_real-'+sys.argv[1], np.array([w.real, G_w.real]).T) np.savetxt('./result/G_w_imag-'+sys.argv[1], np.array([w.real, G_w.imag]).T) np.savetxt('./result/S_w_real-'+sys.argv[1], np.array([w.real, S_w.real]).T) np.savetxt('./result/S_w_imag-'+sys.argv[1], np.array([w.real, S_w.imag]).T)
2148a784cbb01befca8253d62597118c7c98436d
[ "CMake", "Markdown", "Makefile", "Python", "C++", "Shell" ]
46
CMake
aadeliee22/Hubbard_NN
9b498b672cf44e71c2750644456abfa27e893c1d
ecbc177fcb6480980364af4c375bde486c704c45
refs/heads/master
<file_sep>#Fish Stocking Map ##Project URL http://s3.amazonaws.com/vt-stock-exchange/index ##Overview This project takes fish stocking data published by the Vermont [Department of Fish and Wildlife](http://vtfishandwildlife.com) to create an interactive map to navigate the data. The published data on stocking includes: - Number of fish - Species - Town - Average size - Body of water - Age of fish - Date stocked ##\#CodeForBTV This project was a part of the first [\#CodeForBTV](http://codeforbtv.org/) event. \#CodeForBTV took place on June 1-2, 2013 as a part of the [National Day of Civic Hacking](http://hackforchange.org/). ##Future Plans ###Fish Stocking Map - The map could be further improved by a date filter that allows users to see when the fish were stocked. - A map layer including VT surface waters would be interesting. - Automate data upload. - Add scale back to map ###Plug and Chug VT Map This project could be used as a template to create interactive maps of the state of Vermont organized by town. A better base map would be helpful, possibly using older census data. ##Source - Data: [VT Fish and Wildlife](http://www.anr.state.vt.us/fwd/stockingschedule.aspx) - Choropleth: [Vermont Public Radio](http://www.vpr.net) ##Technology Used - [D3](http://d3js.org) - [Leaflet](http://leafletjs.com) - [Chosen](http://harvesthq.github.io/chosen/) - [Bootstrap](http://twitter.github.io/bootstrap/) ##Authors - [<NAME>](http://www.github.com/joeydi) - [<NAME>](http://www.github.com/mattparrilla) <file_sep>var Fish = Fish || {}; Fish.csv_file = './fish.csv'; Fish.json_file = './vt.json'; Fish.cloudmade_api_key = '8ee2a50541944fb9bcedded5165f09d9'; Fish.data_field = 'total'; Fish.default_center = [44, -72.4]; Fish.default_zoom = 8; Fish.default_color = '#ccc'; Fish.ranges = { 'Orange Red': ['#fee8c8', '#fdd49e', '#fdbb84', '#fc8d59', '#ef6548', '#d7301f', '#b30000', '#7f0000'], 'Blue Green': ['#CCECE6', '#99D8C9', '#66C2A4', '#2CA25F', '#006D2C', '#238B45', '#006D2C', '#00441B'], 'Blue Purple': ['#BFD3E6', '#9EBCDA', '#8C96C6', '#8856A7', '#810F7C', '#88419D', '#810F7C', '#4D004B'], 'Green Blue': ['#CCEBC5', '#A8DDB5', '#7BCCC4', '#43A2CA', '#0868AC', '#2B8CBE', '#0868AC', '#084081'], 'Purple Blue': ['#D0D1E6', '#A6BDDB', '#74A9CF', '#2B8CBE', '#045A8D', '#0570B0', '#045A8D', '#023858'] }; Fish.range = 'Orange Red'; Fish.basemaps = { 'Cloudmade: Fine Line': new L.TileLayer.CloudMade({key: Fish.cloudmade_api_key, styleId: 1}), 'Cloudmade: Fresh': new L.TileLayer.CloudMade({key: Fish.cloudmade_api_key, styleId: 997}), 'Cloudmade: Red Alert': new L.TileLayer.CloudMade({key: Fish.cloudmade_api_key, styleId: 8}), 'Cloudmade: Midnight': new L.TileLayer.CloudMade({key: Fish.cloudmade_api_key, styleId: 999}), 'OpenStreetMap': new L.TileLayer.OpenStreetMap(), 'OpenCycleMap': new L.TileLayer.OpenCycleMap(), 'Mapquest OSM': new L.TileLayer.MapQuestOpen.OSM(), 'Mapquest Aerial': new L.TileLayer.MapQuestOpen.Aerial(), 'Mapbox: World Bright': new L.TileLayer.MapBox({user: 'mapbox', map: 'world-bright'}), 'Mapbox: Map Vyofok3q': new L.TileLayer.MapBox({user: 'examples', map: 'map-vyofok3q'}), 'Mapbox: Iceland': new L.TileLayer.MapBox({user: 'kkaefer', map: 'iceland'}), 'Mapbox: Natural Earth': new L.TileLayer.MapBox({user: 'mapbox', map: 'natural-earth-2'}) }; Fish.basemap_layer = 'OpenCycleMap'; Fish.species_acronym_map = { bkt: 'Brook Trout', lat: 'Lake Trout', rbt: 'Rainbow Trout', stt: 'Steelhead Trout', bnt: 'Brown Trout', las: 'Landlocked Salmon' }; Fish.fill_algorithm = function(d) { var val = d.properties[Fish.data_field]; if (val) { return Fish.color(val); } else { // return Fish.default_color; return null; } }; Fish.get_feature_bounds = function(feature) { var coordinates = feature.geometry.coordinates[0], bounds; for (var i = 0; i < coordinates.length; i++) { var latlng = coordinates[i], latlng = new L.LatLng(latlng[1], latlng[0]); if (i === 0) { bounds = new L.LatLngBounds(latlng); } if (latlng.lat > 0) { bounds.extend(latlng); } } return bounds; } // Initialize leaflet map Fish.map = new L.Map('map', { center: Fish.default_center, zoom: Fish.default_zoom, zoomControl: false }); Fish.map.addLayer(Fish.basemaps[Fish.basemap_layer]); var svg = d3.select(Fish.map.getPanes().overlayPane).append("svg"), g = svg.append("g").attr("class", "leaflet-zoom-hide"); Fish.draw_features = function() { var topology = Fish.topology; for (var i = 0; i < Fish.data.length; i++) { var zip = "0" + Fish.data[i].parent; for (var j = 0; j < topology.objects.vermont.geometries.length; j++) { var jsonZip = topology.objects.vermont.geometries[j].properties.zipcode; if (zip == jsonZip) { topology.objects.vermont.geometries[j].properties = Fish.data[i]; break; } } } var collection = topojson.feature(topology, topology.objects.vermont); Fish.collection = collection; var bounds = d3.geo.bounds(collection), path = d3.geo.path().projection(project); Fish.features = g.selectAll("path") .data(collection.features) .enter().append('path') .attr('d', path) .style('fill', Fish.fill_algorithm); Fish.features.on('mouseover', function(d) { var xPosition = d3.mouse(this)[0]; var yPosition = d3.mouse(this)[1] - 10; g.append('text') .attr('id', 'tooltip') .attr('x', function() { if (xPosition < 400) { return xPosition + 40; } else if (xPosition < 420) { return xPosition + 20; } else if (xPosition > 650) { return xPosition - 20; } else { return xPosition }}) .attr('y', function() { if (yPosition < 210) { return yPosition + 30 } else { return yPosition -10 }}) .attr('text-anchor', 'middle') .text(d.properties.town); d3.select(this).style('fill', "#509e2f"); }); Fish.features.on('mouseout', function(d) { d3.select("#tooltip").remove(); if (d3.select(this).attr('class') !== 'active') { d3.select(this).transition().duration(250).style({'fill': Fish.fill_algorithm, opacity: 0.75}); } }); Fish.features.on('click', Fish.select_feature); Fish.map.on('viewreset', reset); reset(); // Reposition the SVG to cover the features. function reset() { var bottomLeft = project(bounds[0]), topRight = project(bounds[1]); svg.attr("width", topRight[0] - bottomLeft[0]) .attr("height", bottomLeft[1] - topRight[1]) .style("margin-left", bottomLeft[0] + "px") .style("margin-top", topRight[1] + "px"); g.attr("transform", "translate(" + -bottomLeft[0] + "," + -topRight[1] + ")"); Fish.features.attr("d", path); } // Use Leaflet to implement a D3 geographic projection. function project(x) { var point = Fish.map.latLngToLayerPoint(new L.LatLng(x[1], x[0])); return [point.x, point.y]; } } Fish.select_feature = function(feature) { var bounds = Fish.get_feature_bounds(feature), town = feature.properties.town table_rows = []; // Get associated rows from csv var town_data = Fish.data.filter(function(row) { return row.parent == town; }); for (var i = 0; i < town_data.length; i++) { var csv_row = town_data[i]; $.each(Fish.species_acronym_map, function(k, species) { var count = parseInt(csv_row[k]), length = parseFloat(csv_row[k + '-length']), table_row = { 'town': csv_row.town, 'waterway': csv_row.water, 'species': species, 'length': length, 'count': count }; if (count) { table_rows.push(table_row); } }); } // Sort the table rows by town then waterway table_rows = table_rows.sort(function(a, b) { return a.waterway > b.waterway; }); table_rows = table_rows.sort(function(a, b) { return a.town > b.town; }); $('#infobox h3, #infobox p').hide(); $('#infobox table').show(); $('#infobox tbody tr').remove(); var towns = []; for (var i = 0; i < table_rows.length; i++) { var row = table_rows[i], tr = $('<tr />'); tr.append($('<td />', {html: row.town})); tr.append($('<td />', {html: row.waterway})); tr.append($('<td />', {html: row.species})); tr.append($('<td />', {html: row.length.toFixed(1) + '&rdquo;'})); tr.append($('<td />', {html: add_commas(row.count)})); $('#infobox tbody').append(tr); towns.push(row.town); } if (!table_rows.length) { var tr = $('<tr />'); tr.append($('<td />', { colspan: 5, html: '<strong>No fish stocked in this town :(</strong>' })); $('#infobox tbody').append(tr); } // Hide town column if only one town_data towns = uniquify_array(towns); if (towns.length == 1) { $('#infobox td:first-child, #infobox th:first-child').hide(); } else { $('#infobox td:first-child, #infobox th:first-child').show(); } $('#infobox h2').text(town); Fish.map.fitBounds(bounds.pad(0.25)); if (d3.select('#map .active')) { d3.select('#map .active').attr('class', '').style('fill', Fish.fill_algorithm); } d3.select(this).attr('class', 'active'); } Fish.redraw_features = function() { Fish.features.transition().duration(500).style('fill', Fish.fill_algorithm); } Fish.load_json = function() { d3.json(Fish.json_file, function(error, topology) { // Store the topology Fish.topology = topology; Fish.draw_features(); Fish.update_zoom_control(Fish.collection.features); }); } Fish.load_csv = function() { d3.csv(Fish.csv_file, function(data) { // Store the data Fish.data = data; Fish.build_quantiles(); Fish.load_json(); }); } Fish.build_quantiles = function() { // Grab the values to quantile Fish.domain = Fish.data.map(function(row) { return parseInt(row[Fish.data_field]); }); Fish.domain = Fish.domain.filter(function(val) { return val; }); // Define scale to sort data values into color buckets Fish.color = d3.scale.quantile() .domain(Fish.domain) .range(Fish.ranges[Fish.range]); } Fish.init_species_menu = function() { var species = $('#species li'); species.click(function() { $(this).parent().find('.active').removeClass('active'); $(this).addClass('active'); Fish.data_field = $(this).data('field'); Fish.build_quantiles(); Fish.redraw_features(); }); }; Fish.init_controls = function() { var buttons = $('#zoom button'); buttons.click(function() { var zoom = $(this).data('zoom'); switch(zoom) { case 'state': Fish.map.setView(Fish.default_center, Fish.default_zoom); case 'zoom-in': Fish.map.zoomIn(); case 'zoom-out': Fish.map.zoomOut(); } }); var zcta = $('#zcta'); zcta.chosen(); zcta.change(function() { var town = $(this).val(), features = Fish.collection.features, bounds; for (var i = 0; i < features.length; i++) { var feature = features[i]; if (feature.properties.town == town) { Fish.select_feature(feature); break; } } }); var color = $('#color'); color.change(function() { var color = $(this).val(); Fish.range = color; // Define scale to sort data values into color buckets Fish.color = d3.scale.quantile() .domain(Fish.domain) .range(Fish.ranges[Fish.range]); Fish.redraw_features(); }); $.each(Fish.ranges, function(k, range) { option = $('<option/>', { value: k, text: k }); if (k == Fish.range) { option.attr('selected', 'selected'); } color.append(option); }); color.chosen(); var basemap = $('#basemap'); basemap.change(function() { Fish.map.removeLayer(Fish.basemaps[Fish.basemap_layer]); Fish.basemap_layer = $(this).val(); Fish.map.addLayer(Fish.basemaps[Fish.basemap_layer]); }); $.each(Fish.basemaps, function(k, v) { option = $('<option/>', { value: k, text: k, }); if (k == Fish.basemap_layer) { option.attr('selected', 'selected'); } basemap.append(option); }); basemap.chosen(); }; Fish.update_zoom_control = function(features) { var select = $('#zcta'); select.find('option').remove(); features = features.filter(function(feature) { return 'MASTER' == feature.properties.water; }); for (var i = 0; i < features.length; i++) { var feature = features[i]; var option = $('<option/>', { value: feature.properties.town, text: feature.properties.town }); select.append(option); } select.trigger('liszt:updated'); } function add_commas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } function uniquify_array(arr) { var i, len=arr.length, out=[], obj={}; for (i=0;i<len;i++) { obj[arr[i]]=0; } for (i in obj) { out.push(i); } return out; } $(document).ready(function() { Fish.load_csv(); Fish.init_species_menu(); Fish.init_controls(); });
c280f32c51f343969e9bbc947ab92147ee028956
[ "Markdown", "JavaScript" ]
2
Markdown
codeforbtv/fish-stocking-schedule
3734dc4eb4c4645ff3ec0f0e376003bc6c31fbb4
cf6b00ad53ad83ae1aa8a1c512c37376eb04e8a8
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Fri May 13 08:12:29 2016 @author: Arshad """ import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib.mlab import bivariate_normal import numpy as np from mpl_toolkits.mplot3d import Axes3D def kalman_prediction_2d (iteration, mu_prev, sigma_prev, ut, zt) : ''' Implementasi di bagian ini. ''' #Prediction At = np.matrix(((1,0,1,0),(0,1,0,1),(0,0,1,0),(0,0,0,1))) Bt = np.matrix(((0.5,0),(0,0.5),(1,0),(0,1))) Ct = np.matrix(((1,0,0,0),(0,1,0,0))) Ex = np.matrix(((0.25,0,0.5,0),(0,0.25,0,0.5),(0.5,0,1,0),(0,0.5,0,1))) Ez = np.matrix(((0.25,0),(0,0.25))) I = np.matrix(((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1))) mu_bar = At * mu_prev + Bt * ut sigma_bar = At * sigma_prev * At.transpose() + Ex #Correction\ Kt = sigma_bar * Ct.transpose() * 1/(Ct*sigma_bar*Ct.transpose() +Ez) mu_t = mu_bar + Kt * (zt - Ct * mu_bar) sigma_t = (I-Kt*Ct)*sigma_bar zt_plot = np.array([[zt[0,0]],[zt[1,0]],[0],[0]]) plot_update(iteration, mu_prev, sigma_prev, zt_plot, Ex, mu_t, sigma_t) return [mu_t,sigma_t] def plot_update(i, mu_prev, sigma_prev, zt, sigma_zt, mu_t, sigma_t): X = np.linspace(-2.5, 2.5, 60) Y = np.linspace(-2.5, 2.5, 60) X, Y = np.meshgrid(X, Y) mu_prev_plot = np.array([[mu_prev[0,0]],[mu_prev[1,0]]]) sigma_prev_plot = np.array([[sigma_prev[0,0],0],[0,sigma_prev[1,1]]]) zt_plot = np.array([zt[0,0],zt[1,0]]) sigma_zt = np.array([[sigma_zt[0,0],0],[0,sigma_zt[1,1]]]) mu_t_plot = np.array([mu_t[0,0],mu_t[1,0]]) sigma_t_plot = np.array([[sigma_t[0,0],0],[0,sigma_t[1,1]]]) Z_prev = pdf_2dgauss(X,Y,mu_prev_plot,sigma_prev_plot) Z_zt = pdf_2dgauss(X,Y,zt_plot,sigma_zt) Z_t = pdf_2dgauss(X,Y,mu_t_plot,sigma_t_plot) fig = plt.figure('iteration' + `i`) ax = fig.gca(projection='3d') #surf_zt = ax.plot_surface(X, Y, Z_zt, rstride=1, cstride=1, cmap=cm.terrain, linewidth=0, antialiased=False) surf_prev = ax.plot_surface(X, Y, Z_prev, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) surf_t = ax.plot_surface(X, Y, Z_t, rstride=1, cstride=1, cmap=cm.PiYG, linewidth=0, antialiased=False) ax.set_zlim(0, 0.5) ax.zaxis.set_major_locator(LinearLocator(5)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) fig.colorbar(surf_prev, shrink=0.5, aspect=5) #fig.colorbar(surf_zt, shrink=0.5, aspect=5) fig.colorbar(surf_t, shrink=0.5, aspect=5) plt.title('State Estimation') plt.show() def pdf_2dgauss (X, Y, mu, sigma): return bivariate_normal(X, Y, np.sqrt(sigma[ 0 ][ 0 ]), np.sqrt(sigma[ 1 ][ 1 ]), mu[0], mu[1], sigma[ 0 ][ 1 ]) #print(Rt) <file_sep># -*- coding: utf-8 -*- """ Created on Thu Apr 30 01:11:23 2015 @author: anwar.maxsum """ #simExtRemoteApiStart(19999) import vrep import numpy as np import matplotlib import sys import kalman2d print 'Python program : V-Rep' vrep.simxFinish(-1) clientID=vrep.simxStart('127.0.0.1',19999,True,True,5000,5) if clientID!=-1: print 'Coonect to remote API Server' else: print 'Connection not successful' sys.exit('Could not connect') i = 0 offSetX = 0 offsetY = 0 initX = 0.5 initY = -2.0 ''' _____ ____ |_ _|__ | _ \ ___ | |/ _ \ _____| | | |/ _ \ | | (_) |_____| |_| | (_) | |_|\___/ |____/ \___/ Konstruksi matriks-matriks yang dibutuhkan agar dapat dijalankan pada algoritma kalman filter 2D berdasarkan informasi dibawah ini (Menggunakan fungsi matrix pada numpy). Lakukan juga pengkonstruksian matriks yang dibutuhkan pada class kalman2d.py. Sampling rate (t) = 1.0 Velocity = 0.05 Posisi awal robot = (0.5,-2.0) Variance X = 1.0 Variance Y = 1.0 Implemetasikan algoritma Kalman Filter 2D pada class kalman2d.kalman_prediction_2d ''' #Get motor handle errorCode,left_motor=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_leftMotor',vrep.simx_opmode_oneshot_wait) errorCode,right_motor=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_rightMotor',vrep.simx_opmode_oneshot_wait) # Get ultrasound sensors handle errorCode,usensor1=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor8',vrep.simx_opmode_oneshot_wait) # Get camera sensors handle errorCode,cam_handle=vrep.simxGetObjectHandle(clientID,'Camera',vrep.simx_opmode_oneshot_wait) errorCode,resolution,image=vrep.simxGetVisionSensorImage(clientID,cam_handle,0,vrep.simx_opmode_oneshot_wait) pX = pY = 0.0 for i in range (1,30) : errorCode,gpsX=vrep.simxGetFloatSignal(clientID,'gpsX',vrep.simx_opmode_oneshot_wait); errorCode,gpsY=vrep.simxGetFloatSignal(clientID,'gpsY',vrep.simx_opmode_oneshot_wait); pX += gpsX pY += gpsY offSetX = (pX/30) - initX offSetY = (pY/30) - initY for i in range(1,11): #while True : print 'Iteration : ', i # Get ultrasound sensors handle #errorCode,usensor1=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor8',vrep.simx_opmode_oneshot_wait) # Read ultrasound sensor #errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector=vrep.simxReadProximitySensor(clientID,usensor1,vrep.simx_opmode_buffer) #errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector=vrep.simxReadProximitySensor(clientID,usensor1,vrep.simx_opmode_oneshot_wait) #print errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector #Set motor vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) # Read ultrasound sensor errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector=vrep.simxReadProximitySensor(clientID,usensor1,vrep.simx_opmode_oneshot_wait) #errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector=vrep.simxReadProximitySensor(clientID,usensor1,vrep.simx_opmode_oneshot_wait) # print errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector #Read GPS Sensor errorCode,gpsX=vrep.simxGetFloatSignal(clientID,'gpsX',vrep.simx_opmode_oneshot_wait); errorCode,gpsY=vrep.simxGetFloatSignal(clientID,'gpsY',vrep.simx_opmode_oneshot_wait); gpsX = gpsX - offSetX gpsY = gpsY - offSetY mu_prev = np.matrix(((0.5),(-2),(0.05),(0.05))) sigma_prev = np.matrix(((0.25,0,0.5,0),(0,0.25,0,0.5),(0.5,0,1,0),(0,0.5,0,1))) zt = np.matrix(((gpsX),(gpsY))) [mu_temp, sigma_temp]=kalman2d.kalman_prediction_2d(i, mu_prev, sigma_prev, 0, zt) mu_t = mu_temp sigma_t = sigma_temp print 'iteration : ', i, 'mu = ', mu_t, 'sigma = ', sigma_t, '\n' i=i+1 vrep.simxSetJointTargetVelocity(clientID,left_motor,0,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,0,vrep.simx_opmode_oneshot_wait) print 'Done....' <file_sep>import vrep import sys import time print 'Python program : V-Rep' vrep.simxFinish(-1) clientID=vrep.simxStart('127.0.0.1',19999,True,True,5000,5) if clientID!=1: print 'Connect to remote API Server' else: print 'Connection not successful' sys.exit('Could not connect') #Get motor handle errorCode,left_motor=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_leftMotor',vrep.simx_opmode_oneshot_wait) errorCode,right_motor=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_rightMotor',vrep.simx_opmode_oneshot_wait) #get fire handle errorCode,left_motor=vrep.simxGetObjectHandle(clientID,'fire#1',vrep.simx_opmode_oneshot_wait) #Get sensor handle errorCode,usensor1=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor1',vrep.simx_opmode_oneshot_wait) errorCode,usensor2=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor2',vrep.simx_opmode_oneshot_wait) errorCode,usensor3=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor3',vrep.simx_opmode_oneshot_wait) errorCode,usensor4=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor4',vrep.simx_opmode_oneshot_wait) errorCode,usensor5=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor5',vrep.simx_opmode_oneshot_wait) errorCode,usensor6=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor6',vrep.simx_opmode_oneshot_wait) errorCode,usensor7=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor7',vrep.simx_opmode_oneshot_wait) errorCode,usensor8=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor8',vrep.simx_opmode_oneshot_wait) errorCode,usensor9=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor9',vrep.simx_opmode_oneshot_wait) errorCode,usensor10=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor10',vrep.simx_opmode_oneshot_wait) errorCode,usensor11=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor11',vrep.simx_opmode_oneshot_wait) errorCode,usensor12=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor12',vrep.simx_opmode_oneshot_wait) errorCode,usensor13=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor13',vrep.simx_opmode_oneshot_wait) errorCode,usensor14=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor14',vrep.simx_opmode_oneshot_wait) errorCode,usensor15=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor15',vrep.simx_opmode_oneshot_wait) errorCode,usensor16=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor16',vrep.simx_opmode_oneshot_wait) errorCode,usensorV=vrep.simxGetObjectHandle(clientID,'Vision_sensor',vrep.simx_opmode_oneshot_wait) errorCode,usensorV1=vrep.simxGetObjectHandle(clientID,'Vision_sensor1',vrep.simx_opmode_oneshot_wait) errorCode,usensorV2=vrep.simxGetObjectHandle(clientID,'Vision_sensor2',vrep.simx_opmode_oneshot_wait) #for i in range(1,100): # # vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) # vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) lroute = True for i in range(1,10000): vrep.simxSetJointTargetVelocity(clientID,left_motor,0,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,0,vrep.simx_opmode_oneshot_wait) #sensor api error_code, det_state, aux = vrep.simxReadVisionSensor(clientID, usensorV,vrep.simx_opmode_oneshot_wait) print 'Sensor : vision det state: ', det_state if det_state == True: print 'fire detected' else: error_code, det_state, aux = vrep.simxReadVisionSensor(clientID, usensorV1,vrep.simx_opmode_oneshot_wait) print det_state, aux[1][1] if aux[1][1] > 0.3: lroute = not (lroute) print lroute if(lroute): print 'left following' error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor4,vrep.simx_opmode_oneshot_wait) print 'Sensor : 4 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: #Sensor8 #Sensor4 true error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor8,vrep.simx_opmode_oneshot_wait) print 'Sensor : 8 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: vrep.simxSetJointTargetVelocity(clientID,left_motor,-2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,-2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,-1,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: #Sensor8 error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor8,vrep.simx_opmode_oneshot_wait) print 'Sensor : 8 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: #Sensor7 error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor7,vrep.simx_opmode_oneshot_wait) print 'Sensor : 7 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: vrep.simxSetJointTargetVelocity(clientID,left_motor,-2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,4,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,4,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,4,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,4,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,1,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,1,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); #Sensor4 false else: #Sensor8 error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor8,vrep.simx_opmode_oneshot_wait) print 'Sensor : 8 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: #Sensor7 error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor7,vrep.simx_opmode_oneshot_wait) print 'Sensor : 7 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: vrep.simxSetJointTargetVelocity(clientID,left_motor,-2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,4,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,4,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,4,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,4,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,1,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,-2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: #to do right following print 'right following'<file_sep># RobotikUTS Folder uts robotik + ngoding python + ngoding fire + graph trajctory + graph speed -data eksperimen <file_sep>import vrep import sys print 'Python program : V-Rep' vrep.simxFinish(-1) clientID=vrep.simxStart('127.0.0.1',19999,True,True,5000,5) if clientID!=1: print 'Connect to remote API Server' else: print 'Connection not successful' sys.exit('Could not connect') #Get motor handle errorCode,left_motor=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_leftMotor',vrep.simx_opmode_oneshot_wait) errorCode,right_motor=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_rightMotor',vrep.simx_opmode_oneshot_wait) #Get sensor handle errorCode,usensor16=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor16',vrep.simx_opmode_oneshot_wait) errorCode,usensor4=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor4',vrep.simx_opmode_oneshot_wait) errorCode,usensor3=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor3',vrep.simx_opmode_oneshot_wait) #for i in range(1,100): # # vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) # vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) for i in range(1,10000): vrep.simxSetJointTargetVelocity(clientID,left_motor,0,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,0,vrep.simx_opmode_oneshot_wait) #if det_state == True: # if det_point[2]<0.3: # vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) # vrep.simxSetJointTargetVelocity(clientID,right_motor,1,vrep.simx_opmode_oneshot_wait) error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor4,vrep.simx_opmode_oneshot_wait) print 'Iteration : 4 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: vrep.simxSetJointTargetVelocity(clientID,left_motor,3,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,0,vrep.simx_opmode_oneshot_wait) else: error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor16,vrep.simx_opmode_oneshot_wait) print 'Iteration : 16 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,1,vrep.simx_opmode_oneshot_wait) else: vrep.simxSetJointTargetVelocity(clientID,left_motor,0,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,1,vrep.simx_opmode_oneshot_wait) else: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,1,vrep.simx_opmode_oneshot_wait) else: error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor16,vrep.simx_opmode_oneshot_wait) print 'Iteration : 16 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: if det_point[2]<0.1: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,0,vrep.simx_opmode_oneshot_wait) else: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,1,vrep.simx_opmode_oneshot_wait) else: vrep.simxSetJointTargetVelocity(clientID,left_motor,-1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,1,vrep.simx_opmode_oneshot_wait) else: vrep.simxSetJointTargetVelocity(clientID,left_motor,0,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,1,vrep.simx_opmode_oneshot_wait) <file_sep>import vrep import sys import time print 'Python program : V-Rep' vrep.simxFinish(-1) clientID=vrep.simxStart('127.0.0.1',19999,True,True,5000,5) if clientID!=1: print 'Connect to remote API Server' else: print 'Connection not successful' sys.exit('Could not connect') #Get motor handle errorCode,left_motor=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_leftMotor',vrep.simx_opmode_oneshot_wait) errorCode,right_motor=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_rightMotor',vrep.simx_opmode_oneshot_wait) #Get sensor handle errorCode,usensor1=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor1',vrep.simx_opmode_oneshot_wait) errorCode,usensor2=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor2',vrep.simx_opmode_oneshot_wait) errorCode,usensor3=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor3',vrep.simx_opmode_oneshot_wait) errorCode,usensor4=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor4',vrep.simx_opmode_oneshot_wait) errorCode,usensor5=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor5',vrep.simx_opmode_oneshot_wait) errorCode,usensor6=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor6',vrep.simx_opmode_oneshot_wait) errorCode,usensor7=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor7',vrep.simx_opmode_oneshot_wait) errorCode,usensor8=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor8',vrep.simx_opmode_oneshot_wait) errorCode,usensor9=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor9',vrep.simx_opmode_oneshot_wait) errorCode,usensor10=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor10',vrep.simx_opmode_oneshot_wait) errorCode,usensor11=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor11',vrep.simx_opmode_oneshot_wait) errorCode,usensor12=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor12',vrep.simx_opmode_oneshot_wait) errorCode,usensor13=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor13',vrep.simx_opmode_oneshot_wait) errorCode,usensor14=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor14',vrep.simx_opmode_oneshot_wait) errorCode,usensor15=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor15',vrep.simx_opmode_oneshot_wait) errorCode,usensor16=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor16',vrep.simx_opmode_oneshot_wait) errorCode,usensorV=vrep.simxGetObjectHandle(clientID,'Vision_sensor',vrep.simx_opmode_oneshot_wait) errorCode,usensorV1=vrep.simxGetObjectHandle(clientID,'Vision_sensor1',vrep.simx_opmode_oneshot_wait) errorCode,usensorV2=vrep.simxGetObjectHandle(clientID,'Vision_sensor2',vrep.simx_opmode_oneshot_wait) #for i in range(1,100): # # vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) # vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) for i in range(1,10000): vrep.simxSetJointTargetVelocity(clientID,left_motor,0,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,0,vrep.simx_opmode_oneshot_wait) #Sensor4 true error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor4,vrep.simx_opmode_oneshot_wait) print 'Sensor : 4 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: #Sensor1 #Sensor4 true error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor1,vrep.simx_opmode_oneshot_wait) print 'Sensor : 1 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,-1,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,-1,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,-1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: #Sensor1 error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor1,vrep.simx_opmode_oneshot_wait) print 'Sensor : 1 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: #Sensor2 error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor2,vrep.simx_opmode_oneshot_wait) print 'Sensor : 2 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.2: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,-2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,-1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); #Sensor4 false else: #Sensor1 error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor1,vrep.simx_opmode_oneshot_wait) print 'Sensor : 1 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: #Sensor2 error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor2,vrep.simx_opmode_oneshot_wait) print 'Sensor : 2 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.2: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,-1,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: #Sensor2 error_code, det_state, det_point, det_handle, det_vec = vrep.simxReadProximitySensor(clientID, usensor2,vrep.simx_opmode_oneshot_wait) print 'Sensor : 2 det state: ', det_state,' det point : ', det_point[2] if det_state == True: if det_point[2]<0.3: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,-1,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,-1,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); else: vrep.simxSetJointTargetVelocity(clientID,left_motor,1,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) time.sleep(0.5); <file_sep># -*- coding: utf-8 -*- """ Created on Thu Apr 30 04:58:34 2015 @author: anwar.maxsum """ # Pemodelan Kalman Filter # Robot bergerak dengan kecepatan konstan # X(t) = 1*X(t-1) + 0.05V + epsilon # Z(t) = gps (Xt) + delta # C = 1 # delta = N (0, 0.01) # epsilon = N (0,005) import matplotlib.pyplot as mp import numpy as np # from scitools.std import * def kalman_prediction (iteration, mu_prev, sigma_prev, ut, gpsY) : #inplementasikan kalman filter berdasarkan model #Prediction mu_bar = 1 * mu_prev + 0.05 * ut sigma_bar = 1 * sigma_prev * 1 + delta #Correction\ Kt = sigma_t * 1 * 1/(1*sigma_t*1+0.01) mu_t = mu_bar + Kt * (gpsY - 1 * mu_bar) sigma_t = (1-Kt*1)*sigma_bar # plot x(t-1), z, dan x(t) figureName = 'iteration' + `iteration` mp.figure(figureName) #for mu, sig in [(mu_prev, sigma_prev), (gpsY, 0.001), (mu_t, sigma_t)]: for mu, sig in [(mu_bar, sigma_bar), (gpsY, 0.001), (mu_t, sigma_t)]: #for mu, sig in [(mu_prev, sigma_prev),(gpsY, 0.001)]: mp.plot(gaussian(np.linspace(-100.0, 100.0, 400), mu, sig)) mp.show() return [mu_t,sigma_t] def gaussian(x, mu, sig): return np.exp(-np.power(x - mu, 2.) / 2 * np.power(sig, 2.)) def plot(x, title): fig = mp.figure() ax = fig.add_subplot(111) ax.set_xlabel('robot position') ax.set_ylabel('bel(x)') fig.suptitle(title) <file_sep># -*- coding: utf-8 -*- """ Created on Thu Apr 30 01:11:23 2015 @author: anwar.maxsum """ #simExtRemoteApiStart(19999) import vrep import numpy import matplotlib import sys import kalman print 'Python program : V-Rep' vrep.simxFinish(-1) clientID=vrep.simxStart('127.0.0.1',19999,True,True,5000,5) if clientID!=-1: print 'Coonect to remote API Server' else: print 'Connection not successful' sys.exit('Could not connect') i = 0 v = 0.05 offSetX = 0 offsetY = 0 initX = 0.5 initY = -2.0 mu_t = 2.0 sigma_t = 0.01 #Get motor handle errorCode,left_motor=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_leftMotor',vrep.simx_opmode_oneshot_wait) errorCode,right_motor=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_rightMotor',vrep.simx_opmode_oneshot_wait) # Get ultrasound sensors handle errorCode,usensor1=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor8',vrep.simx_opmode_oneshot_wait) # Get camera sensors handle errorCode,cam_handle=vrep.simxGetObjectHandle(clientID,'Camera',vrep.simx_opmode_oneshot_wait) errorCode,resolution,image=vrep.simxGetVisionSensorImage(clientID,cam_handle,0,vrep.simx_opmode_oneshot_wait) pX = pY = 0.0 for i in range (1,30) : errorCode,gpsX=vrep.simxGetFloatSignal(clientID,'gpsX',vrep.simx_opmode_oneshot_wait); errorCode,gpsY=vrep.simxGetFloatSignal(clientID,'gpsY',vrep.simx_opmode_oneshot_wait); pX += gpsX pY += gpsY offSetX = (pX/30) - initX offSetY = (pY/30) - initY for i in range(1,11): #while True : print 'Iteration : ', i # Get ultrasound sensors handle #errorCode,usensor1=vrep.simxGetObjectHandle(clientID,'Pioneer_p3dx_ultrasonicSensor8',vrep.simx_opmode_oneshot_wait) # Read ultrasound sensor #errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector=vrep.simxReadProximitySensor(clientID,usensor1,vrep.simx_opmode_buffer) #errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector=vrep.simxReadProximitySensor(clientID,usensor1,vrep.simx_opmode_oneshot_wait) #print errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector #Set motor vrep.simxSetJointTargetVelocity(clientID,left_motor,2,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,2,vrep.simx_opmode_oneshot_wait) # Read ultrasound sensor errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector=vrep.simxReadProximitySensor(clientID,usensor1,vrep.simx_opmode_oneshot_wait) #errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector=vrep.simxReadProximitySensor(clientID,usensor1,vrep.simx_opmode_oneshot_wait) # print errorCode,detectionState,detectedPoint,detectedObjectHandle,detectedSurfaceNormalVector #Read GPS Sensor errorCode,gpsX=vrep.simxGetFloatSignal(clientID,'gpsX',vrep.simx_opmode_oneshot_wait); errorCode,gpsY=vrep.simxGetFloatSignal(clientID,'gpsY',vrep.simx_opmode_oneshot_wait); gpsX = gpsX - offSetX gpsY = gpsY - offSetY [mu_temp, sigma_temp]=kalman.kalman_prediction(i, mu_t, sigma_t, 2, gpsY) mu_t = mu_temp sigma_t = sigma_temp print 'iteration : ', i, 'mu = ', mu_t, 'sigma = ', sigma_t, '\n' i=i+1 vrep.simxSetJointTargetVelocity(clientID,left_motor,0,vrep.simx_opmode_oneshot_wait) vrep.simxSetJointTargetVelocity(clientID,right_motor,0,vrep.simx_opmode_oneshot_wait) print 'Done....'
62c1c73dfb112cf375acf1224b2e2d40472191fe
[ "Markdown", "Python" ]
8
Python
tricerafi/RobotikUTS
a5ae0433f11cbc88af20e515131edee2528e97fa
d4f53beb5cc3ea3ec1d33c20f923979ee001db59
refs/heads/master
<file_sep>#!/bin/bash echo "The following files are in this directory:" for file in $(ls) do mv $file ${file:9} done
ed0a3db37dc9607365cb683511c928b05676538b
[ "Shell" ]
1
Shell
spyjetfayed/HtDP
ef0e7fb74a2973d8f17e47d4d56d3099e8b0be32
f3aa18236c1297c0af1bf77be649ba2e8d7bce50
refs/heads/master
<repo_name>dhofland/CS108---HW4-Sudoku-and-Databases<file_sep>/Android DB project/DB project/app/src/main/java/edu/stanford/cs108/cityinformation/MainActivity.java package edu.stanford.cs108.cityinformation; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { DBSingleton dbSingleton = DBSingleton.getInstance(); SQLiteDatabase db = dbSingleton.getDb(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); db = openOrCreateDatabase("CitiesDB", MODE_PRIVATE, null); // // to clear // String reset = "DROP TABLE IF EXISTS CitiesDB;"; // db.execSQL(reset); Cursor tablesCursor = db.rawQuery( "SELECT * FROM sqlite_master WHERE type='table' AND name='CitiesDB';", null); if (tablesCursor.getCount() == 0) { setUpDB(); } dbSingleton.setDb(db); // SQLiteDatabase db2 = dbSingleton.getDb(); // // Cursor tablesCursor2 = db.rawQuery( // "SELECT * FROM sqlite_master WHERE type='table' AND name='CitiesDB';", // null); // // if (tablesCursor2.getCount() == 0) { // setUpDB(); // } } private void setUpDB() { String setUpString = "Create table CitiesDB (name TEXT, continent TEXT, population INTEGER, _id INTEGER PRIMARY KEY AUTOINCREMENT);"; db.execSQL(setUpString); String populate = "insert into CitiesDB values " + "(\"Cairo\",\"Africa\",15200000, NULL),\n" + "(\"Lagos\",\"Africa\",21000000, NULL),\n" + "(\"Kyoto\",\"Asia\",1474570, NULL),\n" + "(\"Mumbai\",\"Asia\",20400000, NULL),\n" + "(\"Shanghai\",\"Asia\",24152700, NULL),\n" + "(\"Melbourne\",\"Australia\",3900000, NULL),\n" + "(\"London\",\"Europe\",8580000, NULL),\n" + "(\"Rome\",\"Europe\",2715000, NULL),\n" + "(\"Rostov-on-Don\",\"Europe\",1052000, NULL),\n" + "(\"San Francisco\",\"North America\",5780000, NULL),\n" + "(\"San Jose\",\"North America\",7354555, NULL),\n" + "(\"New York\",\"North America\",21295000, NULL),\n" + "(\"Rio de Janeiro\",\"South America\",12280702, NULL),\n" + "(\"Santiago\",\"South America\",5507282, NULL);"; db.execSQL(populate); } public void resetDB(View view) { String reset = "DROP TABLE IF EXISTS CitiesDB;"; // dbSingleton.executeString(reset); db.execSQL(reset); setUpDB(); Toast resetToast = Toast.makeText( getApplicationContext(), "Database Reset", Toast.LENGTH_SHORT); resetToast.show(); } public void onSearch(View view) { Intent intent = new Intent(this,lookUpActivity.class); startActivity(intent); } public void onAdd(View view) { Intent intent = new Intent(this,addCity.class); startActivity(intent); } } <file_sep>/Android DB project/DB project/app/src/main/java/edu/stanford/cs108/cityinformation/addCity.java package edu.stanford.cs108.cityinformation; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class addCity extends AppCompatActivity { String cityName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_city); Button updateButton = (Button) findViewById(R.id.add_button); final DBSingleton dbSingleton = DBSingleton.getInstance(); updateButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { String resultString = createString(); dbSingleton.executeString(resultString); addToast(); finish(); } } ); } private void addToast() { Toast toast = Toast.makeText( addCity.this, cityName + " Added", Toast.LENGTH_SHORT); toast.show(); } private String createString() { TextView inputCity = (TextView) findViewById(R.id.input_city); TextView inputContinent = (TextView) findViewById(R.id.input_continent); TextView inputPopulation = (TextView) findViewById(R.id.input_population); cityName = inputCity.getText().toString(); String continent = inputContinent.getText().toString(); String populationString = inputPopulation.getText().toString(); Integer population = Integer.parseInt(populationString); String result = "insert into CitiesDB values (\"" + cityName + "\", \"" + continent + "\", " + population + ", NULL);"; return result; } } <file_sep>/hw4SudokuDB/src/assign4/Sudoku.java package assign4; import java.util.*; /* * Encapsulates a Sudoku grid to be solved. * CS108 Stanford. */ public class Sudoku { // Provided -- the deliverable main(). // You can edit to do easier cases, but turn in // solving hardGrid. public static void main(String[] args) { Sudoku sudoku; // return with hardGrid sudoku = new Sudoku(hardGrid); System.out.println(sudoku); // print the raw problem int count = sudoku.solve(); System.out.println("solutions:" + count); System.out.println("elapsed:" + sudoku.getElapsed() + "ms"); System.out.println(sudoku.getSolutionText()); } protected class Spot { private int row; private int column; private int val; private int originalPossibleSize; private ArrayList<Integer> possible = new ArrayList<Integer>(); private ArrayList<Integer> forbidden = new ArrayList<Integer>(); private ArrayList<Integer> allOptions = new ArrayList<Integer>(); private Spot(int i, int j, int val) { row = i; // row 0-8, topleft is (0,0) column = j; // column 0-8 this.val = val; findOptions(); checkPossible(); originalPossibleSize = possible.size(); } public void findOptions() { possible.clear(); forbidden.clear(); for (int k = 1; k <= input.length; k ++) { possible.add(k); } findForbidden(); computePossible(); } public ArrayList<Integer> possibleList() { return possible; } public int possibleSize() { return originalPossibleSize; } private void checkPossible() { if (possible.size() == 1) { val = possible.get(0); solution[row][column] = val; } } private void findForbidden() { checkRow(row); checkColumn(column); checkBlock(row, column); } private void checkRow(int row) { for (int i = 0; i < input.length; i ++) { int otherVal = solution[row][i]; if (otherVal != 0) { if (!forbidden.contains(otherVal)) { forbidden.add(otherVal); } } } } private void checkColumn(int column) { for (int i = 0; i < input.length; i ++) { int otherVal = solution[i][column]; if (otherVal != 0) { if (!forbidden.contains(otherVal)) { forbidden.add(otherVal); } } } } private void checkBlock(int row, int column) { int top = row - row%3; int left = column - column%3; for (int i = top; i < top + 3; i ++) { for (int j = left; j < left + 3; j ++) { int otherVal = solution[i][j]; if (otherVal != 0) { if (!forbidden.contains(otherVal)) { forbidden.add(otherVal); } } } } } private void computePossible() { possible.removeAll(forbidden); } public void set(int val) { this.val = val; } public int getVal() { return val; } } /** * Sets up based on the given ints. */ public Sudoku(int[][] ints) { // YOUR CODE HEREinput input = new int[ints.length][ints[0].length]; solution = new int[ints.length][ints[0].length]; firstSolution = new int[ints.length][ints[0].length]; copyGrid(ints, input); copyGrid(ints, solution); configureSpots(); } private void copyGrid(int[][] input, int[][] dest) { for (int i = 0; i < input.length; i ++) { System.arraycopy(input[i], 0, dest[i], 0, input[0].length); } } /** * Sets up based on the given string. */ public Sudoku(String text) { int[][] ints = stringsToGrid(text); input = new int[ints.length][ints[0].length]; solution = new int[ints.length][ints[0].length]; firstSolution = new int[ints.length][ints[0].length]; copyGrid(ints, input); copyGrid(ints, solution); configureSpots(); } private void configureSpots() { for (int i = 0; i < input.length; i ++) { for (int j = 0; j < input[i].length; j ++) { // only makes spots for zero-elements if (input[i][j] == 0) { Spot currentSpot = new Spot(i, j, input[i][j]); int rank = currentSpot.possibleSize(); if (rank >= 2) { if (orderMap.containsKey(rank)) { orderMap.get(rank).add(currentSpot); } else { ArrayList<Spot> order = new ArrayList<Spot>(); order.add(currentSpot); orderMap.put(rank, order); } } } } } } // instance variables private int[][] input; private int[][] firstSolution; private int[][] solution; private HashMap<Integer, ArrayList<Spot>> orderMap = new HashMap<Integer, ArrayList<Spot>>(); private long startTime; private int solutionsCount = 0; @Override public String toString() { return printGrid(input); } private String printGrid(int[][] grid) { String result = ""; StringBuilder str = new StringBuilder(); for (int i = 0; i < grid.length; i ++) { for (int j = 0; j < grid[0].length; j ++) { String current = Integer.toString(grid[i][j]); current += " "; str.append(current); } str.append('\n'); } result = str.toString(); result = result.substring(0, 170); return result; } /** * Solves the puzzle, invoking the underlying recursive search. */ public int solve() { startTime = System.currentTimeMillis(); spotHelper(orderMap); return solutionsCount; } private void spotHelper(HashMap<Integer, ArrayList<Spot>> map) { /** update hashmap, if arraylist is empty, don't * replace and check if this is a solution. if so, break */ if (!(solutionsCount == 100)) { if (map.isEmpty()) { solutionsCount ++; if (solutionsCount == 1) { copyGrid(solution, firstSolution); } } else { // find the next spot to be filled Spot nextSpot = nextSpot(map); int originalSize = nextSpot.possibleSize(); // Update hashmap. If hashmap is now empty, increment counter. ArrayList<Spot> list = map.remove(originalSize); list.remove(nextSpot); if (!list.isEmpty()) { map.put(originalSize, list); } // try different values and recurse int val; nextSpot.findOptions(); ArrayList<Integer> possible = nextSpot.possibleList(); // find next spot-value Iterator<Integer> it = possible.iterator(); while (it.hasNext()) { int next = it.next(); val = next; // update solutions solution[nextSpot.row][nextSpot.column] = val; // System.out.println("\n" + printGrid(solution)); // recurse spotHelper(map); // remove from solution solution[nextSpot.row][nextSpot.column] = 0; } list.add(0, nextSpot); map.put(originalSize, list); } } } private Spot nextSpot(HashMap<Integer, ArrayList<Spot>> map) { Spot result = null;; Set<Integer> keys = map.keySet(); for(int i = 1; i <= 9; i ++) { if (keys.contains(i)) { ArrayList<Spot> list = map.get(i); result = list.get(0); break; } } return result; } public String getSolutionText() { return printGrid(firstSolution); } public long getElapsed() { // YOUR CODE HERE long result = System.currentTimeMillis() - startTime; return result; } // TESTCASE!! WEGHALEN!! public static final int[][] zeroGrid = Sudoku.stringsToGrid( "0 0 0 0 0 0 0 0 0", "0 0 0 0 0 0 0 0 0", "0 0 0 0 0 0 0 0 0", "0 0 0 0 0 0 0 0 0", "0 0 0 0 0 0 0 0 0", "0 0 0 0 0 0 0 0 0", "0 0 0 0 0 0 0 0 0", "0 0 0 0 0 0 0 0 0", "0 0 0 0 0 0 0 0 0"); // Provided grid data for main/testing // The instance variable strategy is up to you. // Provided easy 1 6 grid // (can paste this text into the GUI too) public static final int[][] easyGrid = Sudoku.stringsToGrid( "1 6 4 0 0 0 0 0 2", "2 0 0 4 0 3 9 1 0", "0 0 5 0 8 0 4 0 7", "0 9 0 0 0 6 5 0 0", "5 0 0 1 0 2 0 0 8", "0 0 8 9 0 0 0 3 0", "8 0 9 0 4 0 2 0 0", "0 7 3 5 0 9 0 0 1", "4 0 0 0 0 0 6 7 9"); // Provided medium 5 3 grid public static final int[][] mediumGrid = Sudoku.stringsToGrid( "530070000", "600195000", "098000060", "800060003", "400803001", "700020006", "060000280", "000419005", "000080079"); // Provided hard 3 7 grid // 1 solution this way, 6 solutions if the 7 is changed to 0 public static final int[][] hardGrid = Sudoku.stringsToGrid( "3 7 0 0 0 0 0 8 0", "0 0 1 0 9 3 0 0 0", "0 4 0 7 8 0 0 0 3", "0 9 3 8 0 0 0 1 2", "0 0 0 0 4 0 0 0 0", "5 2 0 0 0 6 7 9 0", "6 0 0 0 2 1 0 4 0", "0 0 0 5 3 0 9 0 0", "0 3 0 0 0 0 0 5 1"); public static final int SIZE = 9; // size of the whole 9x9 puzzle public static final int PART = 3; // size of each 3x3 part public static final int MAX_SOLUTIONS = 100; // Provided various static utility methods to // convert data formats to int[][] grid. /** * Returns a 2-d grid parsed from strings, one string per row. * The "..." is a Java 5 feature that essentially * makes "rows" a String[] array. * (provided utility) * @param rows array of row strings * @return grid */ public static int[][] stringsToGrid(String... rows) { int[][] result = new int[rows.length][]; for (int row = 0; row<rows.length; row++) { result[row] = stringToInts(rows[row]); } return result; } /** * Given a single string containing 81 numbers, returns a 9x9 grid. * Skips all the non-numbers in the text. * (provided utility) * @param text string of 81 numbers * @return grid */ public static int[][] textToGrid(String text) { int[] nums = stringToInts(text); if (nums.length != SIZE*SIZE) { throw new RuntimeException("Needed 81 numbers, but got:" + nums.length); } int[][] result = new int[SIZE][SIZE]; int count = 0; for (int row = 0; row<SIZE; row++) { for (int col=0; col<SIZE; col++) { result[row][col] = nums[count]; count++; } } return result; } /** * Given a string containing digits, like "1 23 4", * returns an int[] of those digits {1 2 3 4}. * (provided utility) * @param string string containing ints * @return array of ints */ public static int[] stringToInts(String string) { int[] a = new int[string.length()]; int found = 0; for (int i=0; i<string.length(); i++) { if (Character.isDigit(string.charAt(i))) { a[found] = Integer.parseInt(string.substring(i, i+1)); found++; } } int[] result = new int[found]; System.arraycopy(a, 0, result, 0, found); return result; } }
a00eb52b856f7ee2cdd686cde7fe61ccda6c7a3f
[ "Java" ]
3
Java
dhofland/CS108---HW4-Sudoku-and-Databases
b5c9365d32b2befd1ec5d93fc2478a5957e85b63
6d1c5d7d6a10d79629aebb85c932e079c3f18a8d
refs/heads/master
<file_sep># Simple Image API ## Description > This is a simple Image API that can get 30 images with user searching keywords from different API. #### The API used in this project: - [Pixabay](https://pixabay.com/) - [Unsplash](https://unsplash.com/) #### The dependencies/libraries/vs code add-on used in this project: - [Express](https://expressjs.com/) - [Node-Fetch](https://www.npmjs.com/package/node-fetch) - [bcrypt](https://www.npmjs.com/package/bcrypt) : Using its algorithm to create encrypted key for the users' password - [jsonwebtoken(JWT)](https://www.npmjs.com/package/jsonwebtoken) : Generating session id/valid token according to ther users' action - [REST Client](https://marketplace.visualstudio.com/items?itemName=humao.rest-client) ## Quick Start ``` bash # Install dependencies npm install # Serve on localhost:3000 npm start # Then, follow the step of request.rest ``` <file_sep>const express = require('express'); const fetch = require('node-fetch'); const bcrypt = require('bcrypt') const jwt = require('jsonwebtoken'); const app = express(); const port = process.env.PORT || 3000; //the server started at port 3000 app.listen(port, () => { console.log(`Starting server at ${port}`); }); app.use(express.static('public')); app.use(express.json({ limit: '1mb' })); const users_list = [] //Routes app.get('/users', (req, res) => { //for debugging test: check the user account and encrypted account res.json(users_list) }) app.post('/users/reg', async (req, res) => { //register part: let user create account try { const hashedPassword = await bcrypt.hash(req.body.password, 10) const user = { name: req.body.name, password: <PASSWORD>Password } users_list.push(user) //console.log(user) res.send("Account Created \n" + JSON.stringify(user)) } catch { res.status(500).send() } }) app.post('/users/login', async (req, res) => { const user = users_list.find(user => user.name === req.body.name) if (user == null) { return res.status(400).send('Cannot find user') //If the user account no found or not created will be return status 400 } try { if (await bcrypt.compare(req.body.password, user.password)) { // If the user login properly, an only valid for 60s token will be send to users //console.log(new Date()); //console.log("1 - " + JSON.stringify(user)) //console.log("2 - " + JSON.stringify(users_list)) //console.log("User login - "); jwt.sign(user, 'secretkey', { expiresIn: '60s' }, (err, token) => { console.log("token - " + token) res.json({ token //return token and show on the body }); }); //res.send('Success') } else { res.send('Login failed') } } catch { res.status(500).send() } }) function verifyToken(req, res, next) { // Verify the token make sure the user are logged in and got valid token // By Bearer token const bearerHeader = req.headers['authorization']; if (typeof bearerHeader !== undefined) { const bearer = bearerHeader.split(' '); const bearerToken = bearer[1]; req.token = bearerToken; next(); } else { res.sendStatus(403); // if cant pass the verification then return 403 } } app.post('/q=:q', verifyToken, async (request, response) => { jwt.verify(request.token, 'secretkey', async (err, authData) => { if (err) { response.sendStatus(403) } else { var IMGData = [{ //initializing the data format first image_ID: "", thumbnails: "", preview: "", title: "", source: "", tags: [] }] const search_item = request.params.q //console.log(search_item) const API_KEY_Pixabay = '16881123-3276b8db86ea7c7b2ae8a572c'; const url_Pixabay = `https://pixabay.com/api/?key=${API_KEY_Pixabay}&q=${search_item}&image_type=photo&pretty=true` //const url_Pixabay = `https://api.npoint.io/722bdd3fa708cd040a63` const Pixabay_response = await fetch(url_Pixabay).catch((error) => { console.error('Error: ', error); }); const Pixabay_imgdata = await Pixabay_response.json() var arrayLength = Pixabay_imgdata.hits.length; var i = 0; // As the data returned by the API is different, so i use 2 loops to handle them and merge them together later on for (i = 0; i < arrayLength; i++) { var tags = Pixabay_imgdata.hits[i].tags.split(', ') //console.log(tags.length) IMGData[i] = { image_ID: Pixabay_imgdata.hits[i].id, thumbnails: Pixabay_imgdata.hits[i].largeImageURL, preview: Pixabay_imgdata.hits[i].previewURL, title: Pixabay_imgdata.hits[i].webformatURL, source: 'Pixabay', tags: tags } } const API_KEY_unsplash = '<KEY>'; const url_unsplash = `https://api.unsplash.com/search/photos?page=1&query=${search_item}&client_id=${API_KEY_unsplash}` //const url_unsplash = `https://api.npoint.io/2dc1897782c515dc1cc1`; // I copied the api response to another API provider to prevent exceeding the API call limit const unsplash_response = await fetch(url_unsplash).catch((error) => { console.error('Error: ', error); }); const unsplash_imgdata = await unsplash_response.json() var arrayLength = i + unsplash_imgdata.results.length; for (i; i < arrayLength; i++) { var secArrLength = unsplash_imgdata.results.length; for (let j = 0; j < secArrLength; j++) { var tagArrLength = unsplash_imgdata.results[j].tags.length; var tagsArr = []; for (let k = 0; k < tagArrLength; k++) { tagsArr[k] = unsplash_imgdata.results[j].tags[k].title IMGData[i] = { image_ID: unsplash_imgdata.results[j].id, thumbnails: unsplash_imgdata.results[j].urls.thumb, preview: unsplash_imgdata.results[j].urls.regular, title: unsplash_imgdata.results[j].urls.raw, source: 'Unsplash', tags: tagsArr } } } } //console.log(IMGData.length) if (IMGData = null) { response.send("Please try later") } else { response.send(IMGData) //return a json object array of image data to the user } } }); });
12bfe19c254ace9b0849890622d9c96ef29ff1f3
[ "Markdown", "JavaScript" ]
2
Markdown
Carlchk/Simple-Image-API
fd337908913dbf2a8cbde67cac441169c6ba0d99
7328b1ac166312a586181fd730cde7155eca0e59
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace csharp_tr_function_1 { class Program { public static void Main(string[] args) { //calling function basic basic(); //waiting line Console.ReadLine(); } //function basic will be created here //this is called function definition public static void basic() { //collecting the input string input = Console.ReadLine(); //showing the output Console.WriteLine("output is - " + input); } } }
ed1ef34c81f8fc6b036db47ac49ccb0aa42c7d65
[ "C#" ]
1
C#
Jay-study-nildana/csharp_tr_function_1
afed1ac9e935d95d270033abcf00806fa8f713b1
4e892d8108bbfdbcedbfee0e49895ca6c17446ff
refs/heads/master
<file_sep>package com.sunasterisk.loltournaments.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseAdapter import com.sunasterisk.loltournaments.base.BaseViewHolder import com.sunasterisk.loltournaments.base.SetDataAdapter import com.sunasterisk.loltournaments.data.model.remote.Tournament import com.sunasterisk.loltournaments.databinding.ItemTournamentBinding class TournamentAdapter( private val onItemClick: (Tournament) -> Unit ) : BaseAdapter<Tournament, TournamentAdapter.ViewHolder>(Tournament.diffUtil), SetDataAdapter<Tournament> { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_tournament, parent, false ), onItemClick ) class ViewHolder( private val binding: ItemTournamentBinding, onItemClick: (Tournament) -> Unit ) : BaseViewHolder<Tournament>(binding, onItemClick) { override fun onBind(item: Tournament) { super.onBind(item) binding.tournament = item } } } <file_sep>package com.sunasterisk.loltournaments.ui.tournament import androidx.navigation.fragment.findNavController import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.data.model.remote.Team import com.sunasterisk.loltournaments.databinding.FragmentTournamentTeamsBinding import com.sunasterisk.loltournaments.ui.adapter.TeamAdapter import com.sunasterisk.loltournaments.ui.teams.TeamsFragmentDirections import org.koin.androidx.viewmodel.ext.android.sharedViewModel class TournamentTeamsFragment : BaseFragment<FragmentTournamentTeamsBinding>() { override val layoutResource get() = R.layout.fragment_tournament_teams override val viewModel by sharedViewModel<TournamentDetailsViewModel>() override fun initViews() { } override fun initData() { val teamAdapter = TeamAdapter(this::onTeamClick) binding.apply { lifecycleOwner = viewLifecycleOwner tournamentViewModel = viewModel recyclerViewTeam.adapter = teamAdapter } } override fun initActions() { } private fun onTeamClick(team: Team) { findNavController().navigate( TournamentDetailsFragmentDirections.actionTournamentDetailsFragmentToTeamDetailsFragment(team) ) } } <file_sep>package com.sunasterisk.loltournaments.ui.more import android.app.Dialog import android.content.Intent import androidx.navigation.fragment.findNavController import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.base.BaseViewModel import com.sunasterisk.loltournaments.databinding.FragmentMoreBinding class MoreFragment : BaseFragment<FragmentMoreBinding>() { override val layoutResource get() = R.layout.fragment_more override val viewModel: BaseViewModel? get() = null override fun initViews() { } override fun initData() { } override fun initActions() { binding.apply { cardAboutApp.setOnClickListener { openAboutAppDialog() } cardShare.setOnClickListener { shareApp() } } } private fun openAboutAppDialog() { activity?.let { Dialog(it).apply { setContentView(R.layout.fragment_about_app) show() } } } private fun shareApp() { val intent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_TEXT, getString(R.string.link_app)) } startActivity(intent) } } <file_sep>package com.sunasterisk.loltournaments.ui.player import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.databinding.FragmentPlayerDetailsBinding import org.koin.androidx.viewmodel.ext.android.viewModel class PlayerDetailsFragment : BaseFragment<FragmentPlayerDetailsBinding>() { override val layoutResource get() = R.layout.fragment_player_details override val viewModel by viewModel<PlayerDetailsViewModel>() override fun initViews() { } override fun initData() { binding.apply { lifecycleOwner = viewLifecycleOwner playerViewModel = viewModel } val arg: PlayerDetailsFragmentArgs by navArgs() viewModel.setPlayer(arg.player) } override fun initActions() { binding.imagePlayerBack.setOnClickListener { findNavController().popBackStack() } } } <file_sep>package com.sunasterisk.loltournaments.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseAdapter import com.sunasterisk.loltournaments.base.BaseViewHolder import com.sunasterisk.loltournaments.data.model.remote.Team import com.sunasterisk.loltournaments.databinding.ItemTeamBinding class TeamAdapter( private val onItemClick: (Team) -> Unit ) : BaseAdapter<Team, TeamAdapter.ViewHolder>(Team.diffUtil) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_team, parent, false ), onItemClick ) class ViewHolder( private val binding: ItemTeamBinding, onItemClick: (Team) -> Unit ) : BaseViewHolder<Team>(binding, onItemClick) { override fun onBind(item: Team) { super.onBind(item) binding.team = item } } } <file_sep>package com.sunasterisk.loltournaments.data.model.remote import android.os.Parcelable import androidx.recyclerview.widget.DiffUtil import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import kotlinx.android.parcel.RawValue @Parcelize data class Serie( @SerializedName("begin_at") val beginAt: String, @SerializedName("end_at") val endAt: String, val id: Int, @SerializedName("league_id") val leagueId: Int, val league: League, @SerializedName("full_name") val name: String, val season: String, val slug: String, val tier: String, val tournaments: List<Tournament>, @SerializedName("winner_id") val winnerId: Int, val year: Int ) : Parcelable { var background: Int? = null companion object { val diffUtil = object : DiffUtil.ItemCallback<Serie>() { override fun areItemsTheSame(oldItem: Serie, newItem: Serie): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Serie, newItem: Serie): Boolean { return oldItem == newItem } } } } <file_sep>package com.sunasterisk.loltournaments.data.model.remote import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class League( val id: Int, val name: String, val series: List<Serie>, @SerializedName("image_url") val imageUrl: String ): Parcelable <file_sep>package com.sunasterisk.loltournaments.ui.home import androidx.navigation.fragment.findNavController import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.data.model.remote.Serie import com.sunasterisk.loltournaments.databinding.FragmentSerieCompletedBinding import com.sunasterisk.loltournaments.ui.adapter.SerieAdapter import org.koin.androidx.viewmodel.ext.android.sharedViewModel class SerieCompletedFragment : BaseFragment<FragmentSerieCompletedBinding>() { override val layoutResource get() = R.layout.fragment_serie_completed override val viewModel by sharedViewModel<HomeViewModel>() override fun initViews() {} override fun initData() { val serieAdapter = SerieAdapter(this::onSerieClick) binding?.apply { lifecycleOwner = viewLifecycleOwner serieViewModel = viewModel recyclerSeriesCompleted.adapter = serieAdapter } } override fun initActions() {} private fun onSerieClick(serie: Serie) { findNavController().navigate( HomeFragmentDirections.actionHomeFragmentToSerieDetailsFragment(serie) ) } } <file_sep>package com.sunasterisk.loltournaments.ui.teams import android.widget.SearchView import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.data.model.remote.Team import com.sunasterisk.loltournaments.databinding.FragmentTeamsBinding import com.sunasterisk.loltournaments.ui.adapter.TeamAdapter import com.sunasterisk.loltournaments.ultils.PaginationScrollListener import com.sunasterisk.loltournaments.ultils.hideKeyboard import kotlinx.android.synthetic.main.fragment_teams.* import org.koin.androidx.viewmodel.ext.android.viewModel @Suppress("DEPRECATION") class TeamsFragment : BaseFragment<FragmentTeamsBinding>() { override val layoutResource get() = R.layout.fragment_teams override val viewModel by viewModel<TeamsViewModel>() override fun initViews() { } override fun initData() { val teamAdapter = TeamAdapter(this::onTeamClick) binding.apply { lifecycleOwner = viewLifecycleOwner teamsViewModel = viewModel recyclerViewTeams.adapter = teamAdapter } if (viewModel.isSearchMode.value == false) viewModel.setSearchMode(false) } override fun initActions() { initSearchListener() initRecyclerViewListener() } private fun initSearchListener() { binding.let { searchViewTeams.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { context?.let { context -> view?.hideKeyboard(context) } query?.let { viewModel.apply { setTeamAcronym(it) setSearchMode(true) } } return true } override fun onQueryTextChange(newText: String?): Boolean { if (newText.isNullOrBlank()) { viewModel.setSearchMode(false) } return true } }) } } private fun initRecyclerViewListener() { binding.recyclerViewTeams.setOnScrollListener(object : PaginationScrollListener(recyclerViewTeams.layoutManager as LinearLayoutManager) { override fun onScrollLastItem() { viewModel.increaseCurrentPage() } override fun isScrolling(): Boolean { return viewModel.isLastPage.value == true } }) } private fun onTeamClick(team: Team) { findNavController().navigate( TeamsFragmentDirections.actionTeamsFragmentToTeamDetailsFragment(team) ) } } <file_sep>package com.sunasterisk.loltournaments.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseAdapter import com.sunasterisk.loltournaments.base.BaseViewHolder import com.sunasterisk.loltournaments.data.model.remote.Player import com.sunasterisk.loltournaments.databinding.ItemPlayerBinding class PlayerAdapter( private val onItemClick: (Player) -> Unit ) : BaseAdapter<Player, PlayerAdapter.ViewHolder>(Player.diffUtil) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_player, parent, false ), onItemClick ) class ViewHolder( private val binding: ItemPlayerBinding, onItemClick: (Player) -> Unit ) : BaseViewHolder<Player>(binding, onItemClick) { override fun onBind(item: Player) { super.onBind(item) binding.imagePlayerRole.apply { item.role?.let { when (it) { ROLE_TOP -> setImageResource(R.drawable.ic_role_top) ROLE_JUN -> setImageResource(R.drawable.ic_role_jun) ROLE_MID -> setImageResource(R.drawable.ic_role_mid) ROLE_ADC -> setImageResource(R.drawable.ic_role_adc) ROLE_SUP -> setImageResource(R.drawable.ic_role_sup) else -> null } } } binding.player = item } } companion object { const val ROLE_TOP = "top" const val ROLE_JUN = "jun" const val ROLE_MID = "mid" const val ROLE_ADC = "adc" const val ROLE_SUP = "sup" } } <file_sep>package com.sunasterisk.loltournaments.ui.tournament import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.databinding.FragmentTournamentDetailsBinding import com.sunasterisk.loltournaments.ui.adapter.ViewPagerAdapter import kotlinx.android.synthetic.main.fragment_tournament_details.* import org.koin.androidx.viewmodel.ext.android.sharedViewModel class TournamentDetailsFragment : BaseFragment<FragmentTournamentDetailsBinding>() { override val layoutResource get() = R.layout.fragment_tournament_details override val viewModel by sharedViewModel<TournamentDetailsViewModel>() private val tournamentTeamsFragment = TournamentTeamsFragment() private val tournamentMatchesFragment = TournamentMatchesFragment() override fun initViews() { initTabLayoutWithViewPager() } override fun initData() { binding.apply { lifecycleOwner = viewLifecycleOwner tournamentViewModel = viewModel } val arg: TournamentDetailsFragmentArgs by navArgs() viewModel.getData(arg.tournament) } override fun initActions() { binding.imageTournamentBack.setOnClickListener { findNavController().popBackStack() } } private fun initTabLayoutWithViewPager() { val homeViewPagerAdapter = ViewPagerAdapter(childFragmentManager) homeViewPagerAdapter.addFragment( tournamentTeamsFragment, getString(R.string.title_teams) ) homeViewPagerAdapter.addFragment( tournamentMatchesFragment, getString(R.string.title_matches) ) pagerTournamentInfo.adapter = homeViewPagerAdapter tabTournamentInfo.setupWithViewPager(pagerTournamentInfo) } } <file_sep>package com.sunasterisk.loltournaments.data.model.remote import android.os.Parcelable import androidx.recyclerview.widget.DiffUtil import com.google.gson.annotations.SerializedName import com.sunasterisk.loltournaments.data.model.local.PlayerLocal import kotlinx.android.parcel.Parcelize @Parcelize data class Player( @SerializedName("current_team") val currentTeam: Team?, val id: Int, val birthday: String?, @SerializedName("first_name") val firstName: String?, @SerializedName("last_name") val lastName: String?, @SerializedName("image_url") val imageUrl: String?, val name: String, val hometown: String?, val nationality: String?, val role: String?, val slug: String ) : Parcelable { var teamId = currentTeam?.id val fullName: String get() = "$firstName $lastName" fun toLocalPlayer() = PlayerLocal( teamId ?: TEAM_NULL, id, birthday, firstName, lastName, imageUrl, name, hometown, nationality, role, slug ) companion object { const val TEAM_NULL = 0 val diffUtil = object : DiffUtil.ItemCallback<Player>() { override fun areItemsTheSame(oldItem: Player, newItem: Player) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Player, newItem: Player) = oldItem == newItem } } } <file_sep>package com.sunasterisk.loltournaments.base import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import kotlinx.coroutines.CoroutineExceptionHandler abstract class BaseViewModel : ViewModel() { protected val _error = MutableLiveData<String>() val error get() = _error protected val _isLoading = MutableLiveData<Boolean>() val isLoading get() = _isLoading val exceptionHandler = CoroutineExceptionHandler { _, throwable -> _error.postValue(throwable.message) _isLoading.postValue(false) } } <file_sep>package com.sunasterisk.loltournaments.data.source import com.sunasterisk.loltournaments.data.model.local.PlayerLocal import com.sunasterisk.loltournaments.data.model.local.TeamLocal import com.sunasterisk.loltournaments.data.model.remote.* interface LolDataSource { interface Local { suspend fun insertTeam(teamLocal: TeamLocal): Long suspend fun getAllTeams(): List<TeamLocal>? suspend fun getTeamById(teamId: Int): List<TeamLocal>? suspend fun deleteTeam(teamLocal: TeamLocal): Int suspend fun insertPlayer(playerLocal: PlayerLocal): Long suspend fun getPlayerByTeamId(teamId: Int): List<PlayerLocal>? suspend fun deletePlayer(playerLocal: PlayerLocal): Int } interface Remote { suspend fun getLeagues(leagueIds: String, sortValue: String): List<League> suspend fun getSeries(time: String, leagueId: Int) : List<Serie> suspend fun getTournamentById(tournamentId: Int): List<Tournament> suspend fun getMatchByTournamentId(matchId: Int): List<Match> suspend fun getTeamById(teamId: Int): List<Team> suspend fun getTeams(page: Int) : List<Team> suspend fun getTeamByAcronym(teamAcronym: String, page: Int): List<Team> suspend fun getTeamByName(teamName: String, page: Int): List<Team> } } <file_sep>package com.sunasterisk.loltournaments.ultils import android.widget.TextView import androidx.databinding.BindingAdapter import java.text.SimpleDateFormat @BindingAdapter("android:textDate", "android:withHour", requireAll = false) fun TextView.setTextDate(textDate: String?, withHour: Boolean) { textDate?.let { var patternFormat = PATTERN_DATE var patternParse = PATTERN_DATE_REVERSE var dateString = it.split(DELIMITER_T).first() if (withHour) { patternFormat = PATTERN_DATE_WITH_HOUR patternParse = PATTERN_DATE_FULL dateString = it.split(DELIMITER_T).let { dateSplit -> "${dateSplit.first()} ${dateSplit.last().split(DELIMITER_Z).first()}" } } val simpleDateFormat = SimpleDateFormat(patternFormat) val date = SimpleDateFormat(patternParse).parse(dateString) this.text = simpleDateFormat.format(date) } } const val PATTERN_DATE_REVERSE = "yyyy-MM-dd" const val PATTERN_DATE_FULL = "yyyy-MM-dd HH:mm:ss" const val PATTERN_DATE = "dd-MM-yyyy" const val PATTERN_DATE_WITH_HOUR = "HH:mm dd-MM-yyyy" const val DELIMITER_T = "T" const val DELIMITER_Z = "Z" <file_sep>package com.sunasterisk.loltournaments.data.repository import com.sunasterisk.loltournaments.data.model.local.PlayerLocal import com.sunasterisk.loltournaments.data.model.local.TeamLocal import com.sunasterisk.loltournaments.data.model.remote.Serie import com.sunasterisk.loltournaments.data.model.remote.Team import com.sunasterisk.loltournaments.data.source.LolDataSource class LolRepositoryImp( private val remote: LolDataSource.Remote, private val local: LolDataSource.Local ) : LolRepository { override suspend fun insertLocalTeam(teamLocal: TeamLocal) = local.insertTeam(teamLocal) override suspend fun getAllLocalTeams() = local.getAllTeams() override suspend fun getLocalTeamById(teamId: Int) = local.getTeamById(teamId) override suspend fun deleteLocalTeam(teamLocal: TeamLocal) = local.deleteTeam(teamLocal) override suspend fun insertLocalPlayer(playerLocal: PlayerLocal) = local.insertPlayer(playerLocal) override suspend fun getPlayerByTeamId(teamId: Int) = local.getPlayerByTeamId(teamId) override suspend fun deleteLocalPlayer(playerLocal: PlayerLocal) = local.deletePlayer(playerLocal) override suspend fun getLeagues(leagueIds: String, sortValue: String) = remote.getLeagues(leagueIds, sortValue) override suspend fun getSeries(time: String, leagueId: Int): List<Serie> = remote.getSeries(time, leagueId) override suspend fun getTournamentById(tournamentId: Int) = remote.getTournamentById(tournamentId) override suspend fun getMatchByTournamentId(matchId: Int) = remote.getMatchByTournamentId(matchId) override suspend fun getTeamById(teamId: Int) = remote.getTeamById(teamId) override suspend fun getTeams(page: Int) = remote.getTeams(page) override suspend fun getTeamByAcronym(teamAcronym: String, page: Int) = remote.getTeamByAcronym(teamAcronym, page) override suspend fun getTeamByName(teamName: String, page: Int) = remote.getTeamByName(teamName, page) } <file_sep>package com.sunasterisk.loltournaments.data.model.remote import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class Opponent( val opponent: Team, val type: String ): Parcelable <file_sep>package com.sunasterisk.loltournaments.data.source.local import com.sunasterisk.loltournaments.data.model.local.PlayerLocal import com.sunasterisk.loltournaments.data.model.local.TeamLocal import com.sunasterisk.loltournaments.data.source.LolDataSource import com.sunasterisk.loltournaments.data.source.local.dao.PlayerDao import com.sunasterisk.loltournaments.data.source.local.dao.TeamDao class LolLocalDataSource( private val playerDao: PlayerDao, private val teamDao: TeamDao) : LolDataSource.Local { override suspend fun insertTeam(teamLocal: TeamLocal) = teamDao.insertTeam(teamLocal) override suspend fun getAllTeams() = teamDao.getAllTeams() override suspend fun getTeamById(teamId: Int) = teamDao.getTeamById(teamId) override suspend fun deleteTeam(teamLocal: TeamLocal) = teamDao.deleteTeam(teamLocal) override suspend fun insertPlayer(playerLocal: PlayerLocal) = playerDao.insertPlayer(playerLocal) override suspend fun getPlayerByTeamId(teamId: Int) = playerDao.getPlayerByTeamId(teamId) override suspend fun deletePlayer(playerLocal: PlayerLocal) = playerDao.deletePlayer(playerLocal) } <file_sep>package com.sunasterisk.loltournaments.ui.tournament import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.sunasterisk.loltournaments.base.BaseViewModel import com.sunasterisk.loltournaments.data.model.remote.Match import com.sunasterisk.loltournaments.data.model.remote.Team import com.sunasterisk.loltournaments.data.model.remote.Tournament import com.sunasterisk.loltournaments.data.repository.LolRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class TournamentDetailsViewModel(private val lolRepository: LolRepository) : BaseViewModel() { private val _tournament = MutableLiveData<Tournament>() val tournament: LiveData<Tournament> get() = _tournament private val _matches = MutableLiveData<List<Match>>() val matches: LiveData<List<Match>> get() = _matches private val _winner = MutableLiveData<Team>() val winner get() = _winner fun getData(tournament: Tournament) { getTournaments(tournament.id) tournament.winnerId?.let { getTeam(it) } getMatches(tournament.id) } private fun getTournaments(tournamentId: Int) { _isLoading.postValue(true) viewModelScope.launch(Dispatchers.IO + exceptionHandler) { _tournament.postValue(lolRepository.getTournamentById(tournamentId).first()) _isLoading.postValue(false) } } private fun getMatches(tournamentId: Int) { viewModelScope.launch(Dispatchers.IO + exceptionHandler) { _matches.postValue(lolRepository.getMatchByTournamentId(tournamentId)) } } private fun getTeam(teamId: Int) { viewModelScope.launch(Dispatchers.IO + exceptionHandler) { _winner.postValue(lolRepository.getTeamById(teamId).first()) } } } <file_sep>package com.sunasterisk.loltournaments.ui.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.databinding.DataBindingUtil import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.data.model.remote.League import com.sunasterisk.loltournaments.databinding.ItemLeagueBinding class LeagueAdapter(context: Context) : ArrayAdapter<League>(context, 0) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { return initView(position, convertView, parent) } override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { return initView(position, convertView, parent) } private fun initView(position: Int, convertView: View?, parent: ViewGroup): View { val binding = DataBindingUtil.inflate<ItemLeagueBinding>( LayoutInflater.from(parent.context), R.layout.item_league, parent, false ) binding.league = getItem(position) return binding.root } fun setData(leagues: List<League>) { clear() addAll(leagues) notifyDataSetChanged() } } <file_sep># Lol-Tournaments NamNH - Dealine 29/06 <file_sep>package com.sunasterisk.loltournaments.data.model.remote import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class MatchResult( val score: Int, @SerializedName("team_id") val teamId: Int ): Parcelable <file_sep>package com.sunasterisk.loltournaments.data.model.local import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.sunasterisk.loltournaments.data.model.remote.Team @Entity(tableName = "teams") data class TeamLocal( @PrimaryKey @ColumnInfo(name = "teamId") val id: Int, @ColumnInfo(name = "acronym") val acronym: String?, @ColumnInfo(name = "imageUrl") val imageUrl: String, @ColumnInfo(name = "location") val location: String?, @ColumnInfo(name = "name") val name: String, val slug: String ) { fun toRemoteTeam() = Team(acronym, id, imageUrl, location, name, slug) } <file_sep>include ':app' rootProject.name = "LoL Tournaments" <file_sep>package com.sunasterisk.loltournaments.ultils import android.widget.ImageView import androidx.databinding.BindingAdapter import com.bumptech.glide.Glide import com.sunasterisk.loltournaments.R @BindingAdapter("loadImageUrl", "placeholder", "circleCrop", requireAll = false) fun ImageView.loadImage(url: String?, placeholder: Int?, circleCrop: Boolean) { url?.let { if (placeholder != null) { if (circleCrop) { Glide.with(this).load(it).placeholder(placeholder).circleCrop().into(this) } else { Glide.with(this).load(it).placeholder(placeholder).into(this) } } else { Glide.with(this).load(it).placeholder(R.drawable.ic_placeholder).into(this) } } } <file_sep>package com.sunasterisk.loltournaments.base import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import java.lang.IllegalStateException abstract class BaseFragment<T : ViewDataBinding> : Fragment() { protected abstract val layoutResource: Int abstract val viewModel: BaseViewModel? private var _binding: T? = null protected val binding: T get() = _binding!! ?: throw IllegalStateException(ERROR_VIEW_DATA_BINDING) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = DataBindingUtil.inflate<T>(inflater, layoutResource, container, false) .apply { _binding = this } .root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initViews() initData() initActions() } protected abstract fun initViews() protected abstract fun initData() protected abstract fun initActions() companion object { const val ERROR_VIEW_DATA_BINDING = "ViewDataBinding is null." } } <file_sep>package com.sunasterisk.loltournaments.di import com.sunasterisk.loltournaments.data.source.remote.API_KEY import com.sunasterisk.loltournaments.data.source.remote.ApiService import com.sunasterisk.loltournaments.data.source.remote.BASE_URL import com.sunasterisk.loltournaments.data.source.remote.TOKEN import okhttp3.Interceptor import okhttp3.OkHttpClient import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory val networkModule = module { single { initHttpClient() } single { initRetrofit(get()) } single { createApiService(get()) } } fun initHttpClient(): OkHttpClient { val interceptor = Interceptor { chain -> val original = chain.request() val request = original.newBuilder().url( original.url.newBuilder() .addQueryParameter( TOKEN, API_KEY ) .build() ).build() chain.proceed(request) } return OkHttpClient.Builder().addInterceptor(interceptor).build() } fun initRetrofit(client: OkHttpClient): Retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() fun createApiService(retrofit: Retrofit): ApiService? = retrofit.create(ApiService::class.java) <file_sep>package com.sunasterisk.loltournaments.ui.main import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.navigation.Navigation import androidx.navigation.ui.setupWithNavController import com.sunasterisk.loltournaments.R import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private val navController by lazy { Navigation.findNavController(this, R.id.fragmentHost) } private val menuList = listOf( R.id.homeFragment, R.id.teamsFragment, R.id.favoriteFragment, R.id.moreFragment ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) bottomNav.setupWithNavController(navController) } private fun openExitDialog() { AlertDialog.Builder(this).apply { setMessage(MESSAGE_EXIT) setPositiveButton(OPTION_YES) { _, _ -> finish() } setNegativeButton(OPTION_NO, null) show() } } override fun onBackPressed() { if (navController.currentDestination?.id in menuList) { openExitDialog() } else { super.onBackPressed() } } companion object { const val MESSAGE_EXIT = "Do you want exit app?" const val OPTION_YES = "YES" const val OPTION_NO = "NO" fun getIntent(context: Context) = Intent(context, MainActivity::class.java) } } <file_sep>package com.sunasterisk.loltournaments.ui.tournament import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.data.model.remote.Match import com.sunasterisk.loltournaments.databinding.FragmentTournamentMatchesBinding import com.sunasterisk.loltournaments.ui.adapter.MatchAdapter import org.koin.androidx.viewmodel.ext.android.sharedViewModel class TournamentMatchesFragment : BaseFragment<FragmentTournamentMatchesBinding>() { override val layoutResource get() = R.layout.fragment_tournament_matches override val viewModel by sharedViewModel<TournamentDetailsViewModel>() override fun initViews() { } override fun initData() { val matchAdapter = MatchAdapter(this::onMatchClick) binding.apply { lifecycleOwner = viewLifecycleOwner tournamentViewModel = viewModel recyclerViewMatch.adapter = matchAdapter } } override fun initActions() { } private fun onMatchClick(match: Match) { } } <file_sep>package com.sunasterisk.loltournaments import android.app.Application import com.sunasterisk.loltournaments.di.databaseModule import com.sunasterisk.loltournaments.di.networkModule import com.sunasterisk.loltournaments.di.sourceModule import com.sunasterisk.loltournaments.di.viewModelModule import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin class LolApplication: Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@LolApplication) modules(listOf(networkModule, databaseModule, sourceModule, viewModelModule)) } } } <file_sep>package com.sunasterisk.loltournaments.ultils import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.RecyclerView import com.sunasterisk.loltournaments.base.SetDataAdapter @BindingAdapter("android:data") fun <T> RecyclerView.setData(data: List<T>?) { (adapter as SetDataAdapter<T>).setData(data) } <file_sep>package com.sunasterisk.loltournaments.ultils import java.lang.StringBuilder fun<T> List<T>.toListString(): String { val builder = StringBuilder() for (item in this) { builder.append(item.toString()) builder.append(COMMA) } return builder.toString() } const val COMMA = "," <file_sep>package com.sunasterisk.loltournaments.ui.player import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.sunasterisk.loltournaments.base.BaseViewModel import com.sunasterisk.loltournaments.data.model.remote.Player class PlayerDetailsViewModel : BaseViewModel() { private val _player = MutableLiveData<Player>() val player: LiveData<Player> = _player fun setPlayer(player: Player) { _player.value = player } } <file_sep>package com.sunasterisk.loltournaments.data.repository import com.sunasterisk.loltournaments.data.model.local.PlayerLocal import com.sunasterisk.loltournaments.data.model.local.TeamLocal import com.sunasterisk.loltournaments.data.model.remote.* interface LolRepository { suspend fun insertLocalTeam(teamLocal: TeamLocal): Long suspend fun getAllLocalTeams(): List<TeamLocal>? suspend fun getLocalTeamById(teamId: Int): List<TeamLocal>? suspend fun deleteLocalTeam(teamLocal: TeamLocal): Int suspend fun insertLocalPlayer(playerLocal: PlayerLocal): Long suspend fun getPlayerByTeamId(teamId: Int): List<PlayerLocal>? suspend fun deleteLocalPlayer(playerLocal: PlayerLocal): Int suspend fun getLeagues(leagueIds: String, sortValue: String) : List<League> suspend fun getSeries(time: String, leagueId: Int) : List<Serie> suspend fun getTournamentById(tournamentId: Int): List<Tournament> suspend fun getMatchByTournamentId( matchId: Int): List<Match> suspend fun getTeamById(teamId: Int): List<Team> suspend fun getTeams(page: Int) : List<Team> suspend fun getTeamByAcronym(teamAcronym: String, page: Int): List<Team> suspend fun getTeamByName(teamName: String, page: Int): List<Team> } <file_sep>package com.sunasterisk.loltournaments.ui.teams import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.viewModelScope import com.sunasterisk.loltournaments.base.BaseViewModel import com.sunasterisk.loltournaments.data.model.remote.Team import com.sunasterisk.loltournaments.data.repository.LolRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class TeamsViewModel(private val lolRepository: LolRepository) : BaseViewModel() { private val currentPage = MutableLiveData<Int>() private val teamAcronym = MutableLiveData<String>() private val _isSearchMode = MutableLiveData(false) val isSearchMode: LiveData<Boolean> get() = _isSearchMode private val _isLastPage = MutableLiveData(false) val isLastPage: LiveData<Boolean> = _isLastPage private val _teams = MutableLiveData<List<Team>>() val teams: LiveData<List<Team>> = Transformations.switchMap(currentPage) { if (isSearchMode.value == true) { teamAcronym.value?.let { acronym -> getTeamByAcronym(acronym, it) } } else { getTeams(it) } _teams } private fun getTeams(page: Int) { _isLoading.value = true viewModelScope.launch(Dispatchers.IO + exceptionHandler) { val currentTeams = mutableListOf<Team>() val teamsLoaded = lolRepository.getTeams(page) if (currentPage.value != FIRST_PAGE) { teams.value?.let { currentTeams.addAll(it) } } if (!teamsLoaded.isNullOrEmpty()) { currentTeams.addAll(teamsLoaded) _teams.postValue(currentTeams) } else { _isLastPage.postValue(true) } _isLoading.postValue(false) } } private fun getTeamByAcronym(teamAcronym: String, page: Int) { _isLoading.value = true viewModelScope.launch(Dispatchers.IO + exceptionHandler) { val currentTeams = mutableListOf<Team>() val teamsLoaded = lolRepository.getTeamByAcronym(teamAcronym, page) if (currentPage.value != FIRST_PAGE) { teams.value?.let { currentTeams.addAll(it) } } currentTeams.addAll(teamsLoaded) _teams.postValue(currentTeams) if (teamsLoaded.isNullOrEmpty()) { if (currentPage.value == FIRST_PAGE) getTeamByName(teamAcronym, page) _isLastPage.postValue(true) } _isLoading.postValue(false) } } private fun getTeamByName(teamName: String, page: Int) { _isLoading.postValue(true) viewModelScope.launch(Dispatchers.IO + exceptionHandler) { val currentTeams = mutableListOf<Team>() val teamsLoaded = lolRepository.getTeamByName(teamName, page) if (currentPage.value != FIRST_PAGE) { teams.value?.let { currentTeams.addAll(it) } } currentTeams.addAll(teamsLoaded) _teams.postValue(currentTeams) if (teamsLoaded.isNullOrEmpty()) _isLastPage.postValue(true) _isLoading.postValue(false) } } fun setSearchMode(isSearchMode: Boolean) { this._isSearchMode.value = isSearchMode currentPage.value = FIRST_PAGE _isLastPage.value = false _isLoading.value = true } fun increaseCurrentPage() { currentPage.value = currentPage.value?.plus(1) } fun setTeamAcronym(teamAcronym: String) { this.teamAcronym.value = teamAcronym } companion object { const val FIRST_PAGE = 1 } } <file_sep>package com.sunasterisk.loltournaments.di import com.sunasterisk.loltournaments.data.repository.LolRepository import com.sunasterisk.loltournaments.data.repository.LolRepositoryImp import com.sunasterisk.loltournaments.data.source.LolDataSource import com.sunasterisk.loltournaments.data.source.local.LolLocalDataSource import com.sunasterisk.loltournaments.data.source.remote.LolRemoteDataSource import org.koin.dsl.module val sourceModule = module { single<LolRepository> { LolRepositoryImp(get(), get()) } single<LolDataSource.Local> { LolLocalDataSource(get(), get()) } single<LolDataSource.Remote> { LolRemoteDataSource(get()) } } <file_sep>package com.sunasterisk.loltournaments.ui.spash import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.sunasterisk.loltournaments.ui.main.MainActivity class SplashScreen : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) startActivity(MainActivity.getIntent(this)) finish() } } <file_sep>package com.sunasterisk.loltournaments.data.source.local.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import com.sunasterisk.loltournaments.data.model.local.PlayerLocal @Dao interface PlayerDao { @Insert fun insertPlayer(playerLocal: PlayerLocal): Long @Query("SELECT * FROM players WHERE teamId = :teamId") fun getPlayerByTeamId(teamId: Int) : List<PlayerLocal>? @Delete fun deletePlayer(playerLocal: PlayerLocal): Int } <file_sep>package com.sunasterisk.loltournaments.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseAdapter import com.sunasterisk.loltournaments.base.BaseViewHolder import com.sunasterisk.loltournaments.data.model.remote.Serie import com.sunasterisk.loltournaments.databinding.ItemSerieBinding class SerieAdapter( private val onItemClick: (Serie) -> Unit ) : BaseAdapter<Serie, SerieAdapter.ViewHolder>(Serie.diffUtil) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_serie, parent, false ), onItemClick ) class ViewHolder( private val binding: ItemSerieBinding, onItemClick: (Serie) -> Unit ) : BaseViewHolder<Serie>(binding, onItemClick) { override fun onBind(item: Serie) { super.onBind(item) item.background = when (adapterPosition % BACKGROUND_COUNT) { POSITION_0 -> R.drawable.serie_background_1 POSITION_1 -> R.drawable.serie_background_2 POSITION_2 -> R.drawable.serie_background_3 POSITION_3 -> R.drawable.serie_background_4 POSITION_4 -> R.drawable.serie_background_5 POSITION_5 -> R.drawable.serie_background_6 POSITION_6 -> R.drawable.serie_background_7 POSITION_7 -> R.drawable.serie_background_8 POSITION_8 -> R.drawable.serie_background_9 POSITION_9 -> R.drawable.serie_background_10 else -> R.drawable.serie_background_1 } item.background?.let { binding.imageSerie.setImageResource(it) } binding.serie = item } } companion object { const val POSITION_0 = 0 const val POSITION_1 = 1 const val POSITION_2 = 2 const val POSITION_3 = 3 const val POSITION_4 = 4 const val POSITION_5 = 5 const val POSITION_6 = 6 const val POSITION_7 = 7 const val POSITION_8 = 8 const val POSITION_9 = 9 const val BACKGROUND_COUNT = 10 } } <file_sep>package com.sunasterisk.loltournaments.data.model.remote import android.os.Parcelable import androidx.recyclerview.widget.DiffUtil import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Match( val id: Int, val name: String, @SerializedName("scheduled_at") val scheduledAt: String, @SerializedName("number_of_games") val numberOfGames: Int, val opponents: List<Opponent>, @SerializedName("league_id") val leagueId: Int, val league: League, @SerializedName("serie_id") val serieId: Int, val serie: Serie, @SerializedName("tournament_id") val tournamentId: Int, val tournament: Tournament, val winner: Team, val results: List<MatchResult>, val slug: String ) : Parcelable { val titleName: String get() { if (name.matches(Regex(REGEX_MATCH))) { val nameSplit = name.split(COLON) return nameSplit.first() + COLON } return MATCH } val typeMatch: String get() = BO + numberOfGames fun getFirstTeam() = opponents.first().opponent fun getSecondTeam() = opponents.last().opponent fun getScore(): String { val scoreFirstTeam = results.first().score val scoreSecondTeam = results.last().score if (scoreFirstTeam == ZERO && scoreSecondTeam == ZERO) { return VS } return "$scoreFirstTeam$DASH$scoreSecondTeam" } companion object { const val DASH = "-" const val COLON = ":" const val MATCH = "Match:" const val VS = "VS" const val BO = "BO" const val REGEX_MATCH = ".*: .*" const val ZERO = 0 val diffUtil = object : DiffUtil.ItemCallback<Match>() { override fun areItemsTheSame(oldItem: Match, newItem: Match) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Match, newItem: Match) = oldItem == newItem } } } <file_sep>package com.sunasterisk.loltournaments.data.source.local.database import androidx.room.Database import androidx.room.RoomDatabase import com.sunasterisk.loltournaments.data.model.local.PlayerLocal import com.sunasterisk.loltournaments.data.model.local.TeamLocal import com.sunasterisk.loltournaments.data.source.local.dao.PlayerDao import com.sunasterisk.loltournaments.data.source.local.dao.TeamDao @Database( entities = [TeamLocal::class, PlayerLocal::class], version = LolDatabase.VERSION, exportSchema = false ) abstract class LolDatabase : RoomDatabase() { abstract fun playerDao(): PlayerDao abstract fun teamDao(): TeamDao companion object { const val DATABASE_NAME = "lol.db" const val VERSION = 1 } } <file_sep>package com.sunasterisk.loltournaments.data.model.remote import android.os.Parcelable import androidx.recyclerview.widget.DiffUtil import com.google.gson.annotations.SerializedName import com.sunasterisk.loltournaments.data.model.local.TeamLocal import kotlinx.android.parcel.Parcelize @Parcelize data class Team( val acronym: String?, val id: Int, @SerializedName("image_url") val imageUrl: String, val location: String?, val name: String, var players: List<Player>, val slug: String ) : Parcelable { constructor( acronym: String?, id: Int, imageUrl: String, location: String?, name: String, slug: String ) : this(acronym, id, imageUrl, location, name, listOf(), slug) fun setPlayersId() { players.map { player -> player.teamId = id player } } fun toLocalTeam() = TeamLocal(id, acronym, imageUrl, location, name, slug) companion object { val diffUtil = object : DiffUtil.ItemCallback<Team>() { override fun areItemsTheSame(oldItem: Team, newItem: Team) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Team, newItem: Team) = oldItem == newItem } } } <file_sep>package com.sunasterisk.loltournaments.data.source.remote import com.sunasterisk.loltournaments.data.model.remote.* import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface ApiService { @GET(PATH_LEAGUE) suspend fun getLeagues( @Query(QUERY_FILTER_ID) leagueIds: String, @Query(QUERY_SORT) sortValue: String ): List<League> @GET("$PATH_SERIE/{$PATH_TIME}") suspend fun getSeries( @Path(PATH_TIME) time: String, @Query(QUERY_FILTER_LEAGUE_ID) leagueId: Int ): List<Serie> @GET(PATH_TOURNAMENT) suspend fun getTournamentById( @Query(QUERY_FILTER_ID) tournamentId: Int ): List<Tournament> @GET(PATH_MATCH) suspend fun getMatchByTournamentId( @Query(QUERY_FILTER_TOURNAMENT_ID) matchId: Int, @Query(QUERY_SEARCH_PER_PAGE) perPage: Int = PER_PAGE_100 ): List<Match> @GET(PATH_TEAM) suspend fun getTeamById( @Query(QUERY_FILTER_ID) teamId: Int ): List<Team> @GET(PATH_TEAM) suspend fun getTeams( @Query(QUERY_SEARCH_PAGE) page: Int ): List<Team> @GET(PATH_TEAM) suspend fun getTeamByAcronym( @Query(QUERY_SEARCH_TEAM_ACRONYM) teamAcronym: String, @Query(QUERY_SEARCH_PAGE) page: Int ): List<Team> @GET(PATH_TEAM) suspend fun getTeamByName( @Query(QUERY_SEARCH_TEAM_NAME) teamName: String, @Query(QUERY_SEARCH_PAGE) page: Int ): List<Team> } <file_sep>package com.sunasterisk.loltournaments.data.source.remote import com.sunasterisk.loltournaments.data.source.LolDataSource class LolRemoteDataSource( private val apiService: ApiService ) : LolDataSource.Remote { override suspend fun getLeagues(leagueIds: String, sortValue: String) = apiService.getLeagues(leagueIds, sortValue) override suspend fun getSeries(time: String, leagueId: Int) = apiService.getSeries(time, leagueId) override suspend fun getTournamentById(tournamentId: Int) = apiService.getTournamentById(tournamentId) override suspend fun getMatchByTournamentId(matchId: Int) = apiService.getMatchByTournamentId(matchId) override suspend fun getTeamById(teamId: Int) = apiService.getTeamById(teamId) override suspend fun getTeams(page: Int) = apiService.getTeams(page) override suspend fun getTeamByAcronym(teamAcronym: String, page: Int) = apiService.getTeamByAcronym(teamAcronym, page) override suspend fun getTeamByName(teamName: String, page: Int) = apiService.getTeamByName(teamName, page) } <file_sep>package com.sunasterisk.loltournaments.ui.team import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.sunasterisk.loltournaments.base.BaseViewModel import com.sunasterisk.loltournaments.data.model.remote.Team import com.sunasterisk.loltournaments.data.repository.LolRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class TeamDetailsViewModel(private val lolRepository: LolRepository) : BaseViewModel() { private val _team = MutableLiveData<Team>() val team: LiveData<Team> get() = _team private var _isFavorite = MutableLiveData<Boolean>() val isFavorite: LiveData<Boolean> get() = _isFavorite fun getTeam(team: Team) { if (team.players.isNullOrEmpty()) { viewModelScope.launch(Dispatchers.IO + exceptionHandler) { val team = lolRepository.getTeamById(team.id).first().apply { setPlayersId() } _team.postValue(team) } } else { team.setPlayersId() _team.value = team } getFavorite(team.id) } private fun getFavorite(teamId: Int) { viewModelScope.launch(Dispatchers.IO + exceptionHandler) { val team = lolRepository.getLocalTeamById(teamId) _isFavorite.postValue(!team.isNullOrEmpty()) } } fun setFavorite() { viewModelScope.launch(Dispatchers.IO + exceptionHandler) { team.value?.let { if (isFavorite.value == false) { lolRepository.insertLocalTeam(it.toLocalTeam()) for (player in it.players) { lolRepository.insertLocalPlayer(player.toLocalPlayer()) } } else { lolRepository.deleteLocalTeam(it.toLocalTeam()) for (player in it.players) { lolRepository.deleteLocalPlayer(player.toLocalPlayer()) } } getFavorite(it.id) } } } } <file_sep>package com.sunasterisk.loltournaments.ui.home import android.view.View import android.widget.AdapterView import androidx.lifecycle.Observer import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.data.source.remote.* import com.sunasterisk.loltournaments.databinding.FragmentHomeBinding import com.sunasterisk.loltournaments.ui.adapter.LeagueAdapter import com.sunasterisk.loltournaments.ui.adapter.ViewPagerAdapter import kotlinx.android.synthetic.main.fragment_home.* import org.koin.androidx.viewmodel.ext.android.sharedViewModel class HomeFragment : BaseFragment<FragmentHomeBinding>() { override val layoutResource get() = R.layout.fragment_home override val viewModel by sharedViewModel<HomeViewModel>() private val fragmentSerieCompleted = SerieCompletedFragment() private val fragmentSerieRunning = SerieRunningFragment() private val fragmentSerieUpcoming = SerieUpcomingFragment() private val leagueAdapter by lazy { context?.let { LeagueAdapter(it) } } private val leagueIds = listOf( LCK_LEAGUE_ID, LPL_LEAGUE_ID, WORLD_LEAGUE_ID, MSI_LEAGUE_ID, VCS_LEAGUE_ID, LEC_LEAGUE_ID, LCS_LEAGUE_ID ) override fun initViews() { initSpinnerLeague() initTabLayoutWithViewPager() } override fun initData() { binding.apply { lifecycleOwner = viewLifecycleOwner homeViewModel = viewModel } viewModel.getLeagues(leagueIds, QUERY_VALUE_ID) } override fun initActions() { binding.spinnerLeague.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long ) { viewModel.setCurrentLeagueId(leagueIds[position]) } } viewModel.leagues.observe(viewLifecycleOwner, Observer { if (spinnerLeague.count != it.size) leagueAdapter?.setData(it) }) } private fun initTabLayoutWithViewPager() { val homeViewPagerAdapter = ViewPagerAdapter(childFragmentManager) homeViewPagerAdapter.addFragment(fragmentSerieCompleted, getString(R.string.title_completed)) homeViewPagerAdapter.addFragment(fragmentSerieRunning, getString(R.string.title_running)) homeViewPagerAdapter.addFragment(fragmentSerieUpcoming, getString(R.string.title_upcoming)) pagerSeries.adapter = homeViewPagerAdapter tabSeries.setupWithViewPager(pagerSeries) } private fun initSpinnerLeague() { binding.spinnerLeague.adapter = leagueAdapter } } <file_sep>package com.sunasterisk.loltournaments.data.source.local.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import com.sunasterisk.loltournaments.data.model.local.TeamLocal @Dao interface TeamDao { @Insert fun insertTeam(teamLocal: TeamLocal): Long @Query("SELECT * FROM teams") fun getAllTeams(): List<TeamLocal>? @Query("SELECT * FROM teams WHERE teamId = :teamId") fun getTeamById(teamId: Int): List<TeamLocal>? @Delete fun deleteTeam(teamLocal: TeamLocal): Int } <file_sep>package com.sunasterisk.loltournaments.ui.serie import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.data.model.remote.Tournament import com.sunasterisk.loltournaments.databinding.FragmentSerieDetailsBinding import com.sunasterisk.loltournaments.ui.adapter.TournamentAdapter import kotlinx.android.synthetic.main.fragment_serie_details.* import org.koin.androidx.viewmodel.ext.android.viewModel class SerieDetailsFragment : BaseFragment<FragmentSerieDetailsBinding>() { override val layoutResource get() = R.layout.fragment_serie_details override val viewModel by viewModel<SerieDetailsViewModel>() override fun initViews() { } override fun initData() { val tournamentAdapter = TournamentAdapter(this::onTournamentClick) binding.apply { lifecycleOwner = viewLifecycleOwner serieViewModel = viewModel } val arg: SerieDetailsFragmentArgs by navArgs() viewModel.setSerie(arg.serie) arg.serie.background?.let { serie -> imageSerieBackground.setImageResource(serie) } recyclerViewTournament.adapter = tournamentAdapter } override fun initActions() { binding.let { imageSerieBack.setOnClickListener { onBackClick() } } } private fun onTournamentClick(tournament: Tournament) { findNavController().navigate( SerieDetailsFragmentDirections.actionSerieDetailsFragmentToTournamentDetailsFragment( tournament ) ) } private fun onBackClick() { findNavController().popBackStack() } } <file_sep>package com.sunasterisk.loltournaments.di import com.sunasterisk.loltournaments.ui.favorite.FavoriteViewModel import com.sunasterisk.loltournaments.ui.home.HomeViewModel import com.sunasterisk.loltournaments.ui.player.PlayerDetailsViewModel import com.sunasterisk.loltournaments.ui.serie.SerieDetailsViewModel import com.sunasterisk.loltournaments.ui.team.TeamDetailsViewModel import com.sunasterisk.loltournaments.ui.teams.TeamsViewModel import com.sunasterisk.loltournaments.ui.tournament.TournamentDetailsViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val viewModelModule = module { viewModel { HomeViewModel(get()) } viewModel { SerieDetailsViewModel(get()) } viewModel { TournamentDetailsViewModel(get()) } viewModel { TeamsViewModel(get()) } viewModel { TeamDetailsViewModel(get()) } viewModel { FavoriteViewModel(get()) } viewModel { PlayerDetailsViewModel() } } <file_sep>package com.sunasterisk.loltournaments.ui.team import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.data.model.remote.Player import com.sunasterisk.loltournaments.databinding.FragmentTeamDetailsBinding import com.sunasterisk.loltournaments.ui.adapter.PlayerAdapter import org.koin.androidx.viewmodel.ext.android.viewModel class TeamDetailsFragment : BaseFragment<FragmentTeamDetailsBinding>() { override val layoutResource = R.layout.fragment_team_details override val viewModel by viewModel<TeamDetailsViewModel>() override fun initViews() { } override fun initData() { val playerAdapter = PlayerAdapter(this::onPlayerClick) binding.apply { lifecycleOwner = viewLifecycleOwner teamViewModel = viewModel recyclerViewTeam.adapter = playerAdapter } val arg: TeamDetailsFragmentArgs by navArgs() viewModel.getTeam(arg.team) } override fun initActions() { binding.imageTeamBack.setOnClickListener { findNavController().popBackStack() } } private fun onPlayerClick(player: Player) { findNavController().navigate( TeamDetailsFragmentDirections.actionTeamDetailsFragmentToPlayerDetailsFragment(player) ) } } <file_sep>package com.sunasterisk.loltournaments.ui.favorite import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.sunasterisk.loltournaments.base.BaseViewModel import com.sunasterisk.loltournaments.data.model.remote.Player import com.sunasterisk.loltournaments.data.model.remote.Team import com.sunasterisk.loltournaments.data.repository.LolRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class FavoriteViewModel( private val lolRepository: LolRepository ) : BaseViewModel() { private val _teams = MutableLiveData<List<Team>>() val teams: LiveData<List<Team>> = _teams fun getFavoriteTeams() { _isLoading.value = true viewModelScope.launch(Dispatchers.IO + exceptionHandler) { val teams = lolRepository.getAllLocalTeams()?.map { val team = it.toRemoteTeam() getPlayerByTeamId(it.id)?.let { players -> team.players = players } team } teams?.let { _teams.postValue(it) } _isLoading.postValue(false) } } private suspend fun getPlayerByTeamId(teamId: Int): List<Player>? { val players = lolRepository.getPlayerByTeamId(teamId) return players?.map { it.toRemotePlayer() } } } <file_sep>package com.sunasterisk.loltournaments.data.model.remote import android.os.Parcelable import androidx.recyclerview.widget.DiffUtil import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import kotlinx.android.parcel.RawValue @Parcelize data class Tournament( @SerializedName("begin_at") val beginAt: String, @SerializedName("end_at") val endAt: String, val id: Int, @SerializedName("league_id") val leagueId: Int, val league: League, val matches: List<Match>, val name: String, @SerializedName("prizepool") val prizePool: String, @SerializedName("serie_id") val serieId: Int, val serie: Serie, val slug: String, val teams: List<Team>, @SerializedName("winner_id") val winnerId: Int, ) : Parcelable { companion object { val diffUtil = object : DiffUtil.ItemCallback<Tournament>() { override fun areItemsTheSame(oldItem: Tournament, newItem: Tournament): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Tournament, newItem: Tournament): Boolean { return oldItem == newItem } } } } <file_sep>package com.sunasterisk.loltournaments.data.model.local import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.sunasterisk.loltournaments.data.model.remote.Player @Entity(tableName = "players") data class PlayerLocal( @ColumnInfo(name = "teamId") val teamId: Int, @PrimaryKey @ColumnInfo(name = "playerId") val id: Int, val birthday: String?, @ColumnInfo(name = "firstName") val firstName: String?, @ColumnInfo(name = "lastName") val lastName: String?, @ColumnInfo(name = "imageUrl") val imageUrl: String?, @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "hometown") val hometown: String?, @ColumnInfo(name = "nationality") val nationality: String?, @ColumnInfo(name = "role") val role: String?, @ColumnInfo(name = "slug") val slug: String ) { fun toRemotePlayer() = Player( null, id, birthday, firstName, lastName, imageUrl, name, hometown, nationality, role, slug ) } <file_sep>package com.sunasterisk.loltournaments.base interface SetDataAdapter<T> { fun setData(data: List<T>?) } <file_sep>package com.sunasterisk.loltournaments.ui.serie import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.sunasterisk.loltournaments.base.BaseViewModel import com.sunasterisk.loltournaments.data.model.remote.Serie import com.sunasterisk.loltournaments.data.model.remote.Team import com.sunasterisk.loltournaments.data.repository.LolRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class SerieDetailsViewModel(private val lolRepository: LolRepository) : BaseViewModel() { private val _serie = MutableLiveData<Serie>() val serie: LiveData<Serie> get() = _serie private val _winner = MutableLiveData<Team>() val winner get() = _winner fun setSerie(serie: Serie) { getTeam(serie.winnerId) _serie.value = serie } private fun getTeam(teamId: Int) { viewModelScope.launch(Dispatchers.IO + exceptionHandler) { _winner.postValue(lolRepository.getTeamById(teamId).first()) } } } <file_sep>package com.sunasterisk.loltournaments.ultils import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager import androidx.core.view.isVisible import androidx.databinding.BindingAdapter fun View.hideKeyboard(context: Context) { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(this.windowToken, 0) } @BindingAdapter("isVisible") fun View.setVisible(isVisible: Boolean) { this.visibility = if (isVisible) View.VISIBLE else View.GONE } <file_sep>package com.sunasterisk.loltournaments.ui.favorite import androidx.navigation.fragment.findNavController import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseFragment import com.sunasterisk.loltournaments.data.model.remote.Team import com.sunasterisk.loltournaments.databinding.FragmentFavoriteBinding import com.sunasterisk.loltournaments.ui.adapter.TeamAdapter import org.koin.androidx.viewmodel.ext.android.viewModel class FavoriteFragment : BaseFragment<FragmentFavoriteBinding>() { override val layoutResource get() = R.layout.fragment_favorite override val viewModel by viewModel<FavoriteViewModel>() override fun initViews() { } override fun initData() { val teamAdapter = TeamAdapter(this::onTeamClick) binding.apply { lifecycleOwner = viewLifecycleOwner favoriteViewModel = viewModel recyclerViewFavorite.adapter = teamAdapter } viewModel.getFavoriteTeams() } override fun initActions() { } private fun onTeamClick(team: Team) { findNavController().navigate( FavoriteFragmentDirections.actionFavoriteFragmentToTeamDetailsFragment(team) ) } } <file_sep>package com.sunasterisk.loltournaments.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.viewModelScope import com.sunasterisk.loltournaments.base.BaseViewModel import com.sunasterisk.loltournaments.data.model.remote.League import com.sunasterisk.loltournaments.data.model.remote.Serie import com.sunasterisk.loltournaments.data.repository.LolRepository import com.sunasterisk.loltournaments.data.source.remote.PATH_COMPLETED import com.sunasterisk.loltournaments.data.source.remote.PATH_RUNNING import com.sunasterisk.loltournaments.data.source.remote.PATH_UPCOMING import com.sunasterisk.loltournaments.ultils.toListString import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class HomeViewModel(private val lolRepository: LolRepository) : BaseViewModel() { private val _leagues = MutableLiveData<List<League>>() val leagues: LiveData<List<League>> get() = _leagues private val _leagueId = MutableLiveData<Int>() private val leagueId: LiveData<Int> get() = _leagueId private val _serieCompleted = MutableLiveData<List<Serie>>() val serieCompleted: LiveData<List<Serie>> get() = Transformations.switchMap(leagueId) { getSerie(_serieCompleted, it, PATH_COMPLETED) _serieCompleted } private val _serieRunning = MutableLiveData<List<Serie>>() val serieRunning: LiveData<List<Serie>> get() = Transformations.switchMap(leagueId) { getSerie(_serieRunning, it, PATH_RUNNING) _serieRunning } private val _serieUpcoming = MutableLiveData<List<Serie>>() val serieUpcoming: LiveData<List<Serie>> get() = Transformations.switchMap(leagueId) { getSerie(_serieUpcoming, it, PATH_UPCOMING) _serieUpcoming } fun getLeagues(leagueIds: List<Int>, sortValue: String) { _isLoading.postValue(true) viewModelScope.launch(Dispatchers.IO + exceptionHandler) { val leagues = lolRepository.getLeagues(leagueIds.toListString(), sortValue) _leagues.postValue(leagues) _isLoading.postValue(false) } } fun setCurrentLeagueId(leagueId: Int) { _leagueId.value = leagueId } private fun getSerie(serie: MutableLiveData<List<Serie>>, leagueId: Int, pathTime: String) { viewModelScope.launch(Dispatchers.IO + exceptionHandler) { serie.postValue(lolRepository.getSeries(pathTime, leagueId)) } } } <file_sep>package com.sunasterisk.loltournaments.di import android.content.Context import androidx.room.Room import com.sunasterisk.loltournaments.data.source.local.database.LolDatabase import org.koin.android.ext.koin.androidContext import org.koin.dsl.module val databaseModule = module { single { initDatabase(androidContext()) } single { get<LolDatabase>().playerDao() } single { get<LolDatabase>().teamDao() } } fun initDatabase(context: Context) = Room.databaseBuilder( context, LolDatabase::class.java, LolDatabase.DATABASE_NAME ).build() <file_sep>package com.sunasterisk.loltournaments.data.source.remote const val BASE_URL = "https://api.pandascore.co/lol/" const val TOKEN = "token" const val API_KEY = "key" const val PATH_LEAGUE = "leagues" const val PATH_SERIE = "series" const val PATH_TOURNAMENT = "tournaments" const val PATH_COMPLETED = "past" const val PATH_RUNNING = "running" const val PATH_UPCOMING = "upcoming" const val PATH_MATCH = "matches" const val PATH_TEAM = "teams" const val PATH_TIME = "time" const val QUERY_FILTER_ID = "filter[id]" const val QUERY_FILTER_LEAGUE_ID = "filter[league_id]" const val QUERY_FILTER_TOURNAMENT_ID = "filter[tournament_id]" const val QUERY_SEARCH_TEAM_ACRONYM = "search[acronym]" const val QUERY_SEARCH_TEAM_NAME = "search[name]" const val QUERY_SEARCH_PAGE = "page" const val QUERY_SEARCH_PER_PAGE = "per_page" const val PER_PAGE_100 = 100 const val QUERY_SORT = "sort" const val QUERY_VALUE_ID = "id" const val WORLD_LEAGUE_ID = 297 const val MSI_LEAGUE_ID = 300 const val VCS_LEAGUE_ID = 4141 const val LCK_LEAGUE_ID = 293 const val LPL_LEAGUE_ID = 294 const val LEC_LEAGUE_ID = 4197 const val LCS_LEAGUE_ID = 4198 <file_sep>package com.sunasterisk.loltournaments.ultils import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView abstract class PaginationScrollListener( private val linearLayoutManager: LinearLayoutManager ) : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val totalItem = linearLayoutManager.itemCount val visibleItemCount = linearLayoutManager.childCount val firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition() if (isScrolling()) return if (firstVisibleItemPosition + visibleItemCount >= totalItem) onScrollLastItem() } abstract fun onScrollLastItem() abstract fun isScrolling(): Boolean } <file_sep>package com.sunasterisk.loltournaments.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.sunasterisk.loltournaments.R import com.sunasterisk.loltournaments.base.BaseAdapter import com.sunasterisk.loltournaments.base.BaseViewHolder import com.sunasterisk.loltournaments.data.model.remote.Match import com.sunasterisk.loltournaments.databinding.ItemMatchBinding class MatchAdapter( private val onItemClick: (Match) -> Unit ) : BaseAdapter<Match, MatchAdapter.ViewHolder>(Match.diffUtil) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_match, parent, false ), onItemClick ) class ViewHolder( private val binding: ItemMatchBinding, onItemClick: (Match) -> Unit ) : BaseViewHolder<Match>(binding, onItemClick) { override fun onBind(item: Match) { super.onBind(item) binding.match = item } } }
43ce22b542debdc5756d8d7585a67d10b1d5336a
[ "Markdown", "Kotlin", "Gradle" ]
62
Kotlin
awesome-academy/Lol-Tournaments
6a7e184f2985a8ab14b36ef6d590d6b973a4cb1d
ebf4342971c0c1352b23e293fe0921c22f2eee73
refs/heads/master
<file_sep>export WORKON_HOME=$HOME/.venvs source /usr/local/bin/virtualenvwrapper.sh # bash completion [ -f /usr/local/etc/bash_completion ] && . /usr/local/etc/bash_completion # PS1 original #export PS1='\h:\W \u\$ ' # PS1 customized export PS1='\[\e[31m\]\u\[\e[m\] \w \[\e[34m\]$(vcprompt)\[\e[m\]\[\e[32m\]\\$\[\e[m\] ' export CLICOLOR=1 export PATH="$PATH" export BROWSER=open alias vim="nvim" alias vi="nvim" alias nvi="nvim" # added by Anaconda3 4.4.0 installer export PATH="$PATH:/anaconda/bin" test -e "${HOME}/.iterm2_shell_integration.bash" && source "${HOME}/.iterm2_shell_integration.bash" export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
96877863bac00423d51f93fbfa7e7559730d9fa0
[ "Shell" ]
1
Shell
seonghyeonkimm/config
bc4a61eb6a17a7a287cd728adc66c99e3b0df1c6
651274651fdc6333e33ef283f0d1704b913356c9
refs/heads/master
<repo_name>chenkang084/kitoon-bg<file_sep>/models/db.js var settings = require('../settings'), Db = require('mongodb').Db, Connection = require('mongodb').Connection, Server = require('mongodb').Server; var con = new Db(settings.db, new Server(settings.host, settings.port), { safe: true }); module.exports = con; con.open(function(err,db){ db.collection('users',function(err,collection){ collection.insert({ name:'jack2', age:10 },{ safe:true },function(){ }) }) db.collection('users',function(err,collection){ let rs = collection.findOne({name:'jack'},function(err,rs){ console.log(rs); console.log(10); }) }) }); // con.close(); <file_sep>/routes/modules.js let routers = function routers(app) { //allow custom header and CORS app.all('*', function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); if (req.method == 'OPTIONS') { res.send(200); /让options请求快速返回/ } else { next(); } }); app.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); app.get('/getData', function(req, res, next) { res.send({ title: 'Express' }); }); app.post('/api/v1/auth/login', function(req, res, next) { res.send({ "message": "Logged in" }); }); app.get('/api/v1/users/me', function(req, res, next) { res.send({"username":"admin","email":"<EMAIL>","role":"admin","groups":[],"type":0,"status":true,"firstname":"","lastname":"","notificationenabled":false}); }); } module.exports = routers;
35f16095f92472433ceb71715aefcf4def55a9fd
[ "JavaScript" ]
2
JavaScript
chenkang084/kitoon-bg
2d51cabce4968ce1479e283599ecca53568a6425
11e3eaf00bf8ac8e4d22f0d22cae39c561d1754c
refs/heads/master
<repo_name>dashiwa/garbage_2<file_sep>/ens/ens.features.field_instance.inc <?php /** * @file * ens.features.field_instance.inc */ /** * Implements hook_field_default_field_instances(). */ function ens_field_default_field_instances() { $field_instances = array(); // Exported field_instance: 'commerce_product-product-commerce_price' $field_instances['commerce_product-product-commerce_price'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => '', 'display' => array( 'default' => array( 'label' => 'hidden', 'module' => 'commerce_price', 'settings' => array( 'calculation' => 'calculated_sell_price', ), 'type' => 'commerce_price_formatted_amount', 'weight' => 0, ), 'full' => array( 'label' => 'hidden', 'module' => 'commerce_price', 'settings' => array( 'calculation' => 'calculated_sell_price', ), 'type' => 'commerce_price_formatted_amount', 'weight' => 0, ), 'node_teaser' => array( 'label' => 'hidden', 'module' => 'commerce_price', 'settings' => array( 'calculation' => 'calculated_sell_price', ), 'type' => 'commerce_price_formatted_amount', 'weight' => 0, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'commerce_price', 'label' => 'Price', 'required' => TRUE, 'settings' => array( 'user_register_form' => FALSE, ), 'widget' => array( 'module' => 'commerce_price', 'settings' => array( 'currency_code' => 'default', ), 'type' => 'commerce_price_full', 'weight' => 2, ), ); // Exported field_instance: 'commerce_product-product-field_actname' $field_instances['commerce_product-product-field_actname'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Акция', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 16, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_actname', 'label' => 'ACTNAME', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 60, ), 'type' => 'text_textfield', 'weight' => 19, ), ); // Exported field_instance: 'commerce_product-product-field_actprc' $field_instances['commerce_product-product-field_actprc'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => '% Скидки', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 4, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_actprc', 'label' => 'ACTPRC', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 32, ), 'type' => 'text_textfield', 'weight' => 7, ), ); // Exported field_instance: 'commerce_product-product-field_article' $field_instances['commerce_product-product-field_article'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Артикул', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 1, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_article', 'label' => 'Article', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 32, ), 'type' => 'text_textfield', 'weight' => 4, ), ); // Exported field_instance: 'commerce_product-product-field_brand' $field_instances['commerce_product-product-field_brand'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'торг. марка', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'taxonomy', 'settings' => array(), 'type' => 'taxonomy_term_reference_link', 'weight' => 8, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_brand', 'label' => 'BRAND', 'required' => 0, 'settings' => array( 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 0, 'module' => 'taxonomy', 'settings' => array( 'autocomplete_path' => 'taxonomy/autocomplete', 'size' => 60, ), 'type' => 'taxonomy_autocomplete', 'weight' => 11, ), ); // Exported field_instance: 'commerce_product-product-field_category_product' $field_instances['commerce_product-product-field_category_product'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Категория товара', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'taxonomy', 'settings' => array(), 'type' => 'taxonomy_term_reference_link', 'weight' => 17, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_category_product', 'label' => 'Category product', 'required' => 0, 'settings' => array( 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 0, 'module' => 'taxonomy', 'settings' => array( 'autocomplete_path' => 'taxonomy/autocomplete', 'size' => 60, ), 'type' => 'taxonomy_autocomplete', 'weight' => 20, ), ); // Exported field_instance: 'commerce_product-product-field_discnt' $field_instances['commerce_product-product-field_discnt'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Скидка', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 7, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_discnt', 'label' => 'DISCNT', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 32, ), 'type' => 'text_textfield', 'weight' => 10, ), ); // Exported field_instance: 'commerce_product-product-field_image_product' $field_instances['commerce_product-product-field_image_product'] = array( 'bundle' => 'product', 'deleted' => 0, 'description' => '', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'image', 'settings' => array( 'image_link' => '', 'image_style' => '', ), 'type' => 'image', 'weight' => 18, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_image_product', 'label' => 'Image product', 'required' => 0, 'settings' => array( 'alt_field' => 1, 'default_image' => 0, 'file_directory' => 'product', 'file_extensions' => 'png gif jpg jpeg', 'max_filesize' => '', 'max_resolution' => '', 'min_resolution' => '', 'title_field' => 1, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'image', 'settings' => array( 'preview_image_style' => 'thumbnail', 'progress_indicator' => 'throbber', ), 'type' => 'image_image', 'weight' => 21, ), ); // Exported field_instance: 'commerce_product-product-field_ls' $field_instances['commerce_product-product-field_ls'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'мин. партия', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'number', 'settings' => array( 'decimal_separator' => '.', 'prefix_suffix' => TRUE, 'scale' => 0, 'thousand_separator' => ' ', ), 'type' => 'number_integer', 'weight' => 6, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_ls', 'label' => 'LS', 'required' => 0, 'settings' => array( 'max' => '', 'min' => '', 'prefix' => '', 'suffix' => '', 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 0, 'module' => 'number', 'settings' => array(), 'type' => 'number', 'weight' => 9, ), ); // Exported field_instance: 'commerce_product-product-field_matname' $field_instances['commerce_product-product-field_matname'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Материал', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'taxonomy', 'settings' => array(), 'type' => 'taxonomy_term_reference_link', 'weight' => 9, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_matname', 'label' => 'MATNAME', 'required' => 0, 'settings' => array( 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 0, 'module' => 'taxonomy', 'settings' => array( 'autocomplete_path' => 'taxonomy/autocomplete', 'size' => 60, ), 'type' => 'taxonomy_autocomplete', 'weight' => 12, ), ); // Exported field_instance: 'commerce_product-product-field_pmopt' $field_instances['commerce_product-product-field_pmopt'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => '', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 19, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_pmopt', 'label' => 'PMOPT', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 32, ), 'type' => 'text_textfield', 'weight' => 6, ), ); // Exported field_instance: 'commerce_product-product-field_pqty' $field_instances['commerce_product-product-field_pqty'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'кол-во в упак', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'number', 'settings' => array( 'decimal_separator' => '.', 'prefix_suffix' => TRUE, 'scale' => 0, 'thousand_separator' => ' ', ), 'type' => 'number_integer', 'weight' => 5, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_pqty', 'label' => 'PQTY', 'required' => 0, 'settings' => array( 'max' => '', 'min' => '', 'prefix' => '', 'suffix' => '', 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 0, 'module' => 'number', 'settings' => array(), 'type' => 'number', 'weight' => 8, ), ); // Exported field_instance: 'commerce_product-product-field_rub1' $field_instances['commerce_product-product-field_rub1'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Код рубр.1 1-й уровень вложения (пример: TCODE="009" TNAME="Новогодний ассортимент" )', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 10, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_rub1', 'label' => 'RUB1', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 32, ), 'type' => 'text_textfield', 'weight' => 13, ), ); // Exported field_instance: 'commerce_product-product-field_rub2' $field_instances['commerce_product-product-field_rub2'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Код рубр.2 2-й уровень вложения (пример: PCODE="036 " PNAME="Мягкая игрушка новогодняя" )', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 11, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_rub2', 'label' => 'RUB2', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 32, ), 'type' => 'text_textfield', 'weight' => 14, ), ); // Exported field_instance: 'commerce_product-product-field_rub3' $field_instances['commerce_product-product-field_rub3'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Код рубр.3 3-й уровень вложения (пример: PARTNO="0175 " PARTNAME="Мягкая игрушка")', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 12, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_rub3', 'label' => 'RUB3', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 60, ), 'type' => 'text_textfield', 'weight' => 15, ), ); // Exported field_instance: 'commerce_product-product-field_rub4' $field_instances['commerce_product-product-field_rub4'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Код рубр.4 4-й уровень вложения (пример: CODE="0175 " NAME="Мягкие игрушки (новогодние)")', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 13, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_rub4', 'label' => 'RUB4', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 32, ), 'type' => 'text_textfield', 'weight' => 16, ), ); // Exported field_instance: 'commerce_product-product-field_um' $field_instances['commerce_product-product-field_um'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'В наличие (шт)', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'number', 'settings' => array( 'decimal_separator' => '.', 'prefix_suffix' => TRUE, 'scale' => 0, 'thousand_separator' => ' ', ), 'type' => 'number_integer', 'weight' => 2, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_um', 'label' => 'UM', 'required' => 0, 'settings' => array( 'max' => '', 'min' => '', 'prefix' => '', 'suffix' => '', 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 0, 'module' => 'number', 'settings' => array(), 'type' => 'number', 'weight' => 5, ), ); // Exported field_instance: 'commerce_product-product-field_vol' $field_instances['commerce_product-product-field_vol'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Объем упаковки (м3)(.1250)', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 15, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_vol', 'label' => 'VOL', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 32, ), 'type' => 'text_textfield', 'weight' => 18, ), ); // Exported field_instance: 'commerce_product-product-field_wt' $field_instances['commerce_product-product-field_wt'] = array( 'bundle' => 'product', 'default_value' => NULL, 'deleted' => 0, 'description' => 'Вес Брутто коробка (кг)(16.00) ', 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'text', 'settings' => array(), 'type' => 'text_default', 'weight' => 14, ), ), 'entity_type' => 'commerce_product', 'field_name' => 'field_wt', 'label' => 'WT', 'required' => 0, 'settings' => array( 'text_processing' => 0, 'user_register_form' => FALSE, ), 'widget' => array( 'active' => 1, 'module' => 'text', 'settings' => array( 'size' => 32, ), 'type' => 'text_textfield', 'weight' => 17, ), ); // Translatables // Included for use with string extractors like potx. t('% Скидки'); t('ACTNAME'); t('ACTPRC'); t('Article'); t('BRAND'); t('Category product'); t('DISCNT'); t('Image product'); t('LS'); t('MATNAME'); t('PMOPT'); t('PQTY'); t('Price'); t('RUB1'); t('RUB2'); t('RUB3'); t('RUB4'); t('UM'); t('VOL'); t('WT'); t('Акция'); t('Артикул'); t('В наличие (шт)'); t('Вес Брутто коробка (кг)(16.00) '); t('Категория товара'); t('Код рубр.1 1-й уровень вложения (пример: TCODE="009" TNAME="Новогодний ассортимент" )'); t('Код рубр.2 2-й уровень вложения (пример: PCODE="036 " PNAME="Мягкая игрушка новогодняя" )'); t('Код рубр.3 3-й уровень вложения (пример: PARTNO="0175 " PARTNAME="Мягкая игрушка")'); t('Код рубр.4 4-й уровень вложения (пример: CODE="0175 " NAME="Мягкие игрушки (новогодние)")'); t('Материал'); t('Объем упаковки (м3)(.1250)'); t('Скидка'); t('кол-во в упак'); t('<NAME>'); t('<NAME>'); return $field_instances; } <file_sep>/ens/ens.features.field_base.inc <?php /** * @file * ens.features.field_base.inc */ /** * Implements hook_field_default_field_bases(). */ function ens_field_default_field_bases() { $field_bases = array(); // Exported field_base: 'commerce_price' $field_bases['commerce_price'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array( 0 => 'commerce_product', ), 'field_name' => 'commerce_price', 'indexes' => array( 'currency_price' => array( 0 => 'amount', 1 => 'currency_code', ), ), 'locked' => 1, 'module' => 'commerce_price', 'settings' => array(), 'translatable' => 0, 'type' => 'commerce_price', ); // Exported field_base: 'field_actname' $field_bases['field_actname'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_actname', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 255, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_actprc' $field_bases['field_actprc'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_actprc', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_article' $field_bases['field_article'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_article', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_brand' $field_bases['field_brand'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_brand', 'indexes' => array( 'tid' => array( 0 => 'tid', ), ), 'locked' => 0, 'module' => 'taxonomy', 'settings' => array( 'allowed_values' => array( 0 => array( 'vocabulary' => 'brands', 'parent' => 0, ), ), ), 'translatable' => 0, 'type' => 'taxonomy_term_reference', ); // Exported field_base: 'field_category_product' $field_bases['field_category_product'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_category_product', 'indexes' => array( 'tid' => array( 0 => 'tid', ), ), 'locked' => 0, 'module' => 'taxonomy', 'settings' => array( 'allowed_values' => array( 0 => array( 'vocabulary' => 'catalog', 'parent' => 0, ), ), ), 'translatable' => 0, 'type' => 'taxonomy_term_reference', ); // Exported field_base: 'field_code' $field_bases['field_code'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_code', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'label' => 'CODE', 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_discnt' $field_bases['field_discnt'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_discnt', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_image' $field_bases['field_image'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_image', 'indexes' => array( 'fid' => array( 0 => 'fid', ), ), 'locked' => 0, 'module' => 'image', 'settings' => array( 'default_image' => FALSE, 'uri_scheme' => 'public', ), 'translatable' => 0, 'type' => 'image', ); // Exported field_base: 'field_image_product' $field_bases['field_image_product'] = array( 'active' => 1, 'cardinality' => -1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_image_product', 'indexes' => array( 'fid' => array( 0 => 'fid', ), ), 'locked' => 0, 'module' => 'image', 'settings' => array( 'default_image' => 0, 'uri_scheme' => 'public', ), 'translatable' => 0, 'type' => 'image', ); // Exported field_base: 'field_ls' $field_bases['field_ls'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_ls', 'indexes' => array(), 'locked' => 0, 'module' => 'number', 'settings' => array(), 'translatable' => 0, 'type' => 'number_integer', ); // Exported field_base: 'field_matname' $field_bases['field_matname'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_matname', 'indexes' => array( 'tid' => array( 0 => 'tid', ), ), 'locked' => 0, 'module' => 'taxonomy', 'settings' => array( 'allowed_values' => array( 0 => array( 'vocabulary' => 'material', 'parent' => 0, ), ), ), 'translatable' => 0, 'type' => 'taxonomy_term_reference', ); // Exported field_base: 'field_partno' $field_bases['field_partno'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_partno', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'label' => 'PARTNO', 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_pcode' $field_bases['field_pcode'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_pcode', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'label' => 'PCODE', 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_pmopt' $field_bases['field_pmopt'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_pmopt', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_pqty' $field_bases['field_pqty'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_pqty', 'indexes' => array(), 'locked' => 0, 'module' => 'number', 'settings' => array(), 'translatable' => 0, 'type' => 'number_integer', ); // Exported field_base: 'field_rub1' $field_bases['field_rub1'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_rub1', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_rub2' $field_bases['field_rub2'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_rub2', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_rub3' $field_bases['field_rub3'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_rub3', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_rub4' $field_bases['field_rub4'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_rub4', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_tags' $field_bases['field_tags'] = array( 'active' => 1, 'cardinality' => -1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_tags', 'indexes' => array( 'tid' => array( 0 => 'tid', ), ), 'locked' => 0, 'module' => 'taxonomy', 'settings' => array( 'allowed_values' => array( 0 => array( 'vocabulary' => 'tags', 'parent' => 0, ), ), ), 'translatable' => 0, 'type' => 'taxonomy_term_reference', ); // Exported field_base: 'field_tcode' $field_bases['field_tcode'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_tcode', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'label' => 'TCODE', 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_um' $field_bases['field_um'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_um', 'indexes' => array(), 'locked' => 0, 'module' => 'number', 'settings' => array(), 'translatable' => 0, 'type' => 'number_integer', ); // Exported field_base: 'field_vol' $field_bases['field_vol'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_vol', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); // Exported field_base: 'field_wt' $field_bases['field_wt'] = array( 'active' => 1, 'cardinality' => 1, 'deleted' => 0, 'entity_types' => array(), 'field_name' => 'field_wt', 'indexes' => array( 'format' => array( 0 => 'format', ), ), 'locked' => 0, 'module' => 'text', 'settings' => array( 'max_length' => 32, ), 'translatable' => 0, 'type' => 'text', ); return $field_bases; }
969b0b667accfbe58db385070fd8aecd5acd85d9
[ "PHP" ]
2
PHP
dashiwa/garbage_2
5f46e7f2fe6f1155656a74dee97adfc58279a2bf
e8188394eb19a9947ae35a7a32abc3bbc95207c7
refs/heads/master
<repo_name>mattdavey/EuronextClone<file_sep>/src/main/java/com/euronextclone/fix/client/OrderBuilder.java package com.euronextclone.fix.client; import quickfix.field.*; import quickfix.fix42.NewOrderSingle; import java.util.Date; import java.util.UUID; /** * Created with IntelliJ IDEA. * User: eprystupa * Date: 7/25/12 * Time: 10:02 PM */ public class OrderBuilder { private String symbol; private char orderType; private double quantity; private char side; private double price; public OrderBuilder withSymbol(String symbol) { this.symbol = symbol; return this; } public OrderBuilder withOrderType(char orderType) { this.orderType = orderType; return this; } public OrderBuilder withQuantity(double quantity) { this.quantity = quantity; return this; } public OrderBuilder at(double price) { this.price = price; return this; } public NewOrderSingle buy() { this.side = Side.BUY; return build(); } public NewOrderSingle sell() { this.side = Side.SELL; return build(); } private NewOrderSingle build() { final NewOrderSingle order = new NewOrderSingle( new ClOrdID(UUID.randomUUID().toString()), new HandlInst(HandlInst.AUTOMATED_EXECUTION_ORDER_PUBLIC), new Symbol(symbol), new Side(side), new TransactTime(new Date()), new OrdType(orderType)); order.set(new OrderQty(quantity)); order.set(new Price(price)); return order; } } <file_sep>/src/test/java/com/euronextclone/MatchingUnitStepDefinitions.java package com.euronextclone; import com.euronextclone.ordertypes.*; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import cucumber.annotation.en.Given; import cucumber.annotation.en.Then; import cucumber.annotation.en.When; import cucumber.table.DataTable; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static junit.framework.Assert.assertEquals; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class MatchingUnitStepDefinitions { private final MatchingUnit matchingUnit; private final List<Trade> generatedTrades; public MatchingUnitStepDefinitions(World world) { matchingUnit = world.getMatchingUnit(); generatedTrades = world.getGeneratedTrades(); } @Given("^that trading mode for security is \"([^\"]*)\" and phase is \"([^\"]*)\"$") public void that_trading_mode_for_security_is_and_phase_is(TradingMode tradingMode, TradingPhase phase) throws Throwable { matchingUnit.setTradingMode(tradingMode); matchingUnit.setTradingPhase(phase); } @Given("^that reference price is ([0-9]*\\.?[0-9]+)$") public void that_reference_price_is_(double price) throws Throwable { matchingUnit.setReferencePrice(price); } @Given("^the following orders are submitted in this order:$") public void the_following_orders_are_submitted_in_this_order(DataTable orderTable) throws Throwable { final List<OrderEntryRow> orderRows = orderTable.asList(OrderEntryRow.class); for (OrderEntryRow orderRow : orderRows) { matchingUnit.addOrder(new OrderEntry(orderRow.side, orderRow.broker, orderRow.quantity, orderRow.getOrderType())); } } @When("^class auction completes$") public void class_auction_completes() throws Throwable { matchingUnit.auction(); } @Then("^the calculated IMP is:$") public void the_calculated_IMP_is(List<Double> imp) { assertThat(matchingUnit.getIndicativeMatchingPrice(), is(imp.get(0))); } @Then("^the following trades are generated:$") public void the_following_trades_are_generated(DataTable expectedTradesTable) throws Throwable { final List<TradeRow> expectedTrades = expectedTradesTable.asList(TradeRow.class); final List<TradeRow> actualTrades = FluentIterable.from(generatedTrades).transform(TradeRow.FROM_TRADE).toImmutableList(); assertEquals(expectedTrades, actualTrades); generatedTrades.clear(); } @Then("^no trades are generated$") public void no_trades_are_generated() throws Throwable { List<TradeRow> actualTrades = FluentIterable.from(generatedTrades).transform(TradeRow.FROM_TRADE).toImmutableList(); List<TradeRow> empty = new ArrayList<TradeRow>(); assertEquals(empty, actualTrades); } @Then("^the book is empty$") public void the_book_is_empty() throws Throwable { final List<OrderBookRow> actualBuy = FluentIterable.from(matchingUnit.getOrders(OrderSide.Buy)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList(); final List<OrderBookRow> actualSell = FluentIterable.from(matchingUnit.getOrders(OrderSide.Sell)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList(); assertEquals(new ArrayList<OrderBookRow>(), actualBuy); assertEquals(new ArrayList<OrderBookRow>(), actualSell); } @Then("^the book looks like:$") public void the_book_looks_like(DataTable expectedBooks) throws Throwable { final List<String> headerColumns = new ArrayList<String>(expectedBooks.raw().get(0)); final int columns = headerColumns.size(); final int sideSize = columns / 2; for (int i = 0; i < columns; i++) { headerColumns.set(i, (i < sideSize ? "Buy " : "Sell ") + headerColumns.get(i)); } final List<List<String>> raw = new ArrayList<List<String>>(); raw.add(headerColumns); final List<List<String>> body = expectedBooks.raw().subList(1, expectedBooks.raw().size()); raw.addAll(body); final DataTable montageTable = expectedBooks.toTable(raw); final List<MontageRow> rows = montageTable.asList(MontageRow.class); final List<OrderBookRow> expectedBids = FluentIterable.from(rows).filter(MontageRow.NON_EMPTY_BID).transform(MontageRow.TO_TEST_BID).toImmutableList(); final List<OrderBookRow> expectedAsks = FluentIterable.from(rows).filter(MontageRow.NON_EMPTY_ASK).transform(MontageRow.TO_TEST_ASK).toImmutableList(); final List<OrderBookRow> actualBuy = FluentIterable.from(matchingUnit.getOrders(OrderSide.Buy)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList(); final List<OrderBookRow> actualSell = FluentIterable.from(matchingUnit.getOrders(OrderSide.Sell)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList(); assertEquals(expectedBids, actualBuy); assertEquals(expectedAsks, actualSell); } private static class MontageRow { private String buyBroker; private Integer buyQuantity; private String buyPrice; private String sellBroker; private Integer sellQuantity; private String sellPrice; public static final Predicate<? super MontageRow> NON_EMPTY_BID = new Predicate<MontageRow>() { @Override public boolean apply(final MontageRow input) { return input.buyBroker != null && !"".equals(input.buyBroker); } }; public static final Function<? super MontageRow, OrderBookRow> TO_TEST_BID = new Function<MontageRow, OrderBookRow>() { @Override public OrderBookRow apply(final MontageRow input) { final OrderBookRow orderRow = new OrderBookRow(); orderRow.side = OrderSide.Buy; orderRow.broker = input.buyBroker; orderRow.price = input.buyPrice; orderRow.quantity = input.buyQuantity; return orderRow; } }; public static final Function<? super MontageRow, OrderBookRow> TO_TEST_ASK = new Function<MontageRow, OrderBookRow>() { @Override public OrderBookRow apply(final MontageRow input) { final OrderBookRow orderRow = new OrderBookRow(); orderRow.side = OrderSide.Sell; orderRow.broker = input.sellBroker; orderRow.price = input.sellPrice; orderRow.quantity = input.sellQuantity; return orderRow; } }; public static final Predicate<? super MontageRow> NON_EMPTY_ASK = new Predicate<MontageRow>() { @Override public boolean apply(final MontageRow input) { return input.sellBroker != null && !"".equals(input.sellBroker); } }; } private static class TradeRow { private String buyingBroker; private String sellingBroker; private int quantity; private double price; public static final Function<? super Trade, TradeRow> FROM_TRADE = new Function<Trade, TradeRow>() { @Override public TradeRow apply(Trade input) { TradeRow tradeRow = new TradeRow(); tradeRow.setBuyingBroker(input.getBuyBroker()); tradeRow.setPrice(input.getPrice()); tradeRow.setQuantity(input.getQuantity()); tradeRow.setSellingBroker(input.getSellBroker()); return tradeRow; } }; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TradeRow tradeRow = (TradeRow) o; if (Double.compare(tradeRow.price, price) != 0) return false; if (quantity != tradeRow.quantity) return false; if (!buyingBroker.equals(tradeRow.buyingBroker)) return false; if (!sellingBroker.equals(tradeRow.sellingBroker)) return false; return true; } @Override public int hashCode() { int result; long temp; result = buyingBroker.hashCode(); result = 31 * result + sellingBroker.hashCode(); result = 31 * result + quantity; temp = price != +0.0d ? Double.doubleToLongBits(price) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public String toString() { return "TradeRow{" + "buyingBroker='" + buyingBroker + '\'' + ", sellingBroker='" + sellingBroker + '\'' + ", quantity=" + quantity + ", price=" + price + '}'; } public void setBuyingBroker(String buyingBroker) { this.buyingBroker = buyingBroker; } public void setSellingBroker(String sellingBroker) { this.sellingBroker = sellingBroker; } public void setQuantity(int quantity) { this.quantity = quantity; } public void setPrice(double price) { this.price = price; } } private static class OrderEntryRow { private static final Pattern PEG = Pattern.compile("Peg(?:\\[(.+)\\])?", Pattern.CASE_INSENSITIVE); private String broker; private OrderSide side; private int quantity; private String price; public OrderType getOrderType() { Matcher peg = PEG.matcher(price); if (peg.matches()) { String limit = peg.group(1); return limit != null ? new PegWithLimit(Double.parseDouble(limit)) : new Peg(); } if ("MTL".compareToIgnoreCase(price) == 0) { return new MarketToLimit(); } if ("MO".compareToIgnoreCase(price) == 0) { return new Market(); } return new Limit(Double.parseDouble(price)); } } private static class OrderBookRow { private String broker; private OrderSide side; private int quantity; private String price; public static Function<? super Order, OrderBookRow> FROM_Order(final MatchingUnit matchingUnit) { return new Function<Order, OrderBookRow>() { @Override public OrderBookRow apply(final Order order) { final OrderSide side = order.getSide(); final OrderType orderType = order.getOrderType(); final Double bestLimit = matchingUnit.getBestLimit(side); final OrderBookRow orderRow = new OrderBookRow(); orderRow.broker = order.getBroker(); orderRow.side = order.getSide(); Double price = orderType.price(side, matchingUnit.getBestLimit(side)); orderRow.price = orderType.displayPrice(price); orderRow.quantity = order.getQuantity(); return orderRow; } }; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OrderBookRow orderRow = (OrderBookRow) o; if (quantity != orderRow.quantity) return false; if (!broker.equals(orderRow.broker)) return false; if (price != null ? !price.equals(orderRow.price) : orderRow.price != null) return false; if (side != orderRow.side) return false; return true; } @Override public int hashCode() { int result = broker.hashCode(); result = 31 * result + side.hashCode(); result = 31 * result + quantity; result = 31 * result + (price != null ? price.hashCode() : 0); return result; } @Override public String toString() { return "OrderBookRow{" + "broker='" + broker + '\'' + ", side=" + side + ", quantity=" + quantity + ", price=" + price + '}'; } } }<file_sep>/script/rt-linux/build-rt-kernel #!/bin/bash EC2_KEY=~/.ssh/[your_key].pem . ./build-utils echo 'Spawning new ec2 instance...' EC2_HOST=`spawn-instance "matching-engine" 20 m1.xlarge` [ $? != 0 ] && echo 'spawning ec2 instance failed' && exit 1 echo "Copying installation scripts to ${EC2_HOST}..." scp -i ${EC2_KEY} * .config root@${EC2_HOST}:/root/ >> /dev/null 2>&1 echo "Installing ${EC2_HOST}..." ssh -i ${EC2_KEY} root@${EC2_HOST} './install-rt-kernel' [ $? != 0 ] && echo 'installing ec2 instance failed' && exit 1 echo 'Build is done.' <file_sep>/docs/SettingUpDevEnvironment.md # Setting up development environment ## Prerequisites The only prerequisite required is that your system has [0MQ library](http://www.zeromq.org/) built and installed. 0MQ is a native dependecy used for messaging and is not automatically resolved by Maven build. Detailed instructions on how to build and install 0MQ on your system are available on [ZeroMQ site](http://www.zeromq.org/intro:get-the-software). ## Build First use [git](http://git-scm.com/) to clone this repo: git clone https://github.com/mattdavey/EuronextClone.git cd EuronextClone EuronextClone is built with [Maven](http://maven.apache.org/). mvn clean install The above will build the prototype and run all unit tests (cucumber-jvm over JUnit runner). ## Run There are currently two application available in the prototype: [FIX Server](#fix-server) and [FIX client](#fix-client). You can run a sinle copy of FIX server and one or more copies of FIX Client. This is changing soon though, so check this page often. We are moving to architecture where multiple FIX Servers may run, and we are moving to architecture where matching engine (ME) is a separate from FIX Server, and you can run multiple copies of those too. ### FIX Server FIX Server entry point is located at [FixServerApp](../src/main/java/com/euronextclone/fix/server/FixServerApp.java). FIX Server is preconfigured to accept connections from BROKER-A and BROKER-B clients. (See [FixServer.cfg](../src/main/resources/FixServer.cfg)) To run FIX Server using Maven: mvn exec:exec -Prun-fix-server This assumes that native 0MQ library is available at **/usr/local/lib** unless you have overriden its location using **zmq.library.path** environment variable. If you are running FIX Server manually or from your favorite IDE make sure that **-Djava.library.path=...** is set to the location where you have installed 0MQ library to. ### FIX Client FIX Client entry point is located at [FixClientApp](../src/main/java/com/euronextclone/fix/client/FixClientApp.java). To run FIX Client using Maven (as broker A): mvn exec:exec -Prun-fix-client-a To run FIX Client using Maven (as broker B): mvn exec:exec -Prun-fix-client-b If you running FIX Client manually or from your favorite IDE then you can pass the following command line arguments: **--broker=BROKER** The broker argument configures the FIX client for a specific broker configuration. For example, passing **--broker=A** uses [FixBrokerA.cfg](../src/main/resources/FixBrokerA.cfg) configuration. And passing **--broker=B** uses [FixBrokerB.cfg](../src/main/resources/FixBrokerB.cfg) configuration. You can start multiple copies of FIX Client, with different **"--broker"** configured. When the FIX client starts it is ready to accept user's input. * typing "**q**" terminates the FIX Client * typing "**h**" lists all available commands The following commands are currently supported: #### Place Limit Order buy MSFT 10@34 #### Place Market Order sell MSFT 5 <file_sep>/src/main/java/com/euronextclone/fix/client/commands/PlaceLimitOrder.java package com.euronextclone.fix.client.commands; import com.euronextclone.fix.client.FixClient; import com.euronextclone.fix.client.OrderBuilder; import quickfix.SessionNotFound; import quickfix.field.OrdType; import quickfix.fix42.NewOrderSingle; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created with IntelliJ IDEA. * User: eprystupa * Date: 8/1/12 * Time: 7:38 PM */ public class PlaceLimitOrder implements ClientCommand { private static final Pattern INSTRUCTION = Pattern.compile("^(Buy|Sell) (\\S+) (\\d+)@(\\d+)$", Pattern.CASE_INSENSITIVE); @Override public String name() { return "Place limit order"; } @Override public Pattern pattern() { return INSTRUCTION; } @Override public void execute(final FixClient client, final Matcher input) throws SessionNotFound { if (!input.matches()) { throw new RuntimeException("Bad input for place limit order command"); } final String side = input.group(1); final String symbol = input.group(2); final String quantity = input.group(3); final String price = input.group(4); final OrderBuilder orderBuilder = new OrderBuilder() .withSymbol(symbol) .withOrderType(OrdType.LIMIT) .withQuantity(Double.parseDouble(quantity)) .at(Double.parseDouble(price)); final NewOrderSingle order = side.compareToIgnoreCase("Buy") == 0 ? orderBuilder.buy() : orderBuilder.sell(); client.submitOrder(order); } } <file_sep>/src/main/java/com/euronextclone/framework/Action.java package com.euronextclone.framework; /** * Created with IntelliJ IDEA. * User: eprystupa * Date: 8/6/12 * Time: 8:39 AM */ public interface Action<T> { void invoke(final T t); } <file_sep>/src/test/java/com/euronextclone/World.java package com.euronextclone; import cucumber.annotation.Before; import hu.akarnokd.reactive4java.reactive.Observer; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; public class World { private final List<Trade> generatedTrades = new ArrayList<Trade>(); private final MatchingUnit matchingUnit = new MatchingUnit("MSFT"); public List<Trade> getGeneratedTrades() { return generatedTrades; } public MatchingUnit getMatchingUnit() { return matchingUnit; } @Before public void setUp() { matchingUnit.register(new Observer<Trade>() { @Override public void next(Trade trade) { generatedTrades.add(trade); } @Override public void error(@Nonnull Throwable throwable) { } @Override public void finish() { } }); } } <file_sep>/src/main/java/com/euronextclone/fix/server/FixServer.java package com.euronextclone.fix.server; import com.euronextclone.*; import com.euronextclone.fix.FixAdapter; import com.euronextclone.messaging.Publisher; import com.euronextclone.ordertypes.Limit; import com.euronextclone.ordertypes.Market; import hu.akarnokd.reactive4java.reactive.Observer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import quickfix.*; import quickfix.field.*; import quickfix.fix42.ExecutionReport; import quickfix.fix42.NewOrderSingle; import javax.annotation.Nonnull; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class FixServer extends FixAdapter implements Observer<Trade> { private static Logger logger = LoggerFactory.getLogger(FixServer.class); private final SocketAcceptor socketAcceptor; private Map<String, SessionID> sessionByBroker; // TODO: this is temporary. Matching units will be outside of FIX server, likely in a different process private final MatchingUnit matchingUnit; // TODO: this is temporary until symbol is added to OrderEntry private final Symbol symbol = new Symbol("MSFT"); private final Publisher orderPublisher; // TODO: to correctly route execution reports to relevant party looks like I need: // a) a mapping from OrderId to Broker (TargetCompID) // b) a mapping from Broker (TargetCompId) to SessionID public FixServer(final SessionSettings settings, final Publisher orderPublisher) throws ConfigError { this.orderPublisher = orderPublisher; MessageStoreFactory messageStoreFactory = new FileStoreFactory(settings); SLF4JLogFactory logFactory = new SLF4JLogFactory(settings); MessageFactory messageFactory = new DefaultMessageFactory(); socketAcceptor = new SocketAcceptor(this, messageStoreFactory, settings, logFactory, messageFactory); sessionByBroker = new HashMap<String, SessionID>(); matchingUnit = new MatchingUnit("MSFT"); matchingUnit.register(this); matchingUnit.setTradingMode(TradingMode.Continuous); matchingUnit.setTradingPhase(TradingPhase.CoreContinuous); } public void start() throws ConfigError { socketAcceptor.start(); } public void stop() { socketAcceptor.stop(); } @Override public void onCreate(SessionID sessionId) { sessionByBroker.put(sessionId.getTargetCompID(), sessionId); } @Override public void onMessage(NewOrderSingle order, SessionID sessionID) throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue { final String broker = sessionID.getTargetCompID(); OrderEntry orderEntry = convertToOrderEntry(order, broker); acceptOrder(orderEntry); final String symbol = order.getSymbol().getValue(); orderPublisher.publish(symbol, orderEntry, OrderEntry.class); // TODO: this is going away soon when subscribe is ready on the matching engine side matchingUnit.addOrder(orderEntry); } @Override public void next(Trade trade) { try { sendExecutionReport(trade, new Side(Side.BUY)); sendExecutionReport(trade, new Side(Side.SELL)); } catch (SessionNotFound sessionNotFound) { logger.error(sessionNotFound.getMessage(), sessionNotFound); } } @Override public void error(@Nonnull Throwable throwable) { throw new RuntimeError(throwable); } @Override public void finish() { // Nothing to do } private OrderEntry convertToOrderEntry(NewOrderSingle orderSingle, String broker) throws FieldNotFound { OrderSide side = orderSingle.getSide().getValue() == Side.BUY ? OrderSide.Buy : OrderSide.Sell; OrderType orderType = null; switch (orderSingle.getOrdType().getValue()) { case OrdType.MARKET: orderType = new Market(); break; case OrdType.LIMIT: orderType = new Limit(orderSingle.getPrice().getValue()); break; } return new OrderEntry( side, broker, (int) orderSingle.getOrderQty().getValue(), orderType); } private ExecutionReport buildExecutionReport(final String orderId, final ExecTransType execTransType, final ExecType execType, final OrdStatus ordStatus, final Side side) { return new ExecutionReport( new OrderID(orderId), generateExecId(), execTransType, execType, ordStatus, symbol, side, new LeavesQty(), new CumQty(), new AvgPx()); } private void acceptOrder(final OrderEntry orderEntry) { final String broker = orderEntry.getBroker(); final SessionID sessionID = sessionByBroker.get(broker); if (sessionID != null) { final Side side = new Side(orderEntry.getSide() == OrderSide.Buy ? Side.BUY : Side.SELL); final ExecutionReport report = buildExecutionReport( orderEntry.getOrderId(), new ExecTransType(ExecTransType.NEW), new ExecType(ExecType.NEW), new OrdStatus(OrdStatus.NEW), side); sendToTarget(report, sessionID); } } private boolean sendToTarget(ExecutionReport report, SessionID sessionID) { try { return Session.sendToTarget(report, sessionID); } catch (SessionNotFound sessionNotFound) { throw new RuntimeError(sessionNotFound); } } private void sendExecutionReport(Trade trade, Side side) throws SessionNotFound { final boolean buy = side.getValue() == Side.BUY; final String orderId = buy ? trade.getBuyOrderId() : trade.getSellOrderId(); final String broker = buy ? trade.getBuyBroker() : trade.getSellBroker(); final SessionID sessionID = sessionByBroker.get(broker); if (sessionID != null) { ExecutionReport executionReport = new ExecutionReport( new OrderID(orderId), generateExecId(), new ExecTransType(ExecTransType.STATUS), new ExecType(ExecType.PARTIAL_FILL), new OrdStatus(OrdStatus.PARTIALLY_FILLED), symbol, side, new LeavesQty(), new CumQty(), new AvgPx()); executionReport.set(new LastShares(trade.getQuantity())); executionReport.set(new LastPx(trade.getPrice())); sendToTarget(executionReport, sessionID); } } private ExecID generateExecId() { return new ExecID(UUID.randomUUID().toString()); } } <file_sep>/script/rt-linux/install-rt-kernel #!/bin/bash LOG=/var/log/matching-engine-install-rt-kernel.log KERNEL_VERSION='2.6.33.9' KERNEL_SOURCE="linux-${KERNEL_VERSION}" RT_PATCH_REV='31' echo 'Resizing the root device...' resize2fs /dev/xvde1 >> $LOG 2>&1 [ $? != 0 ] && echo 'resizing root device failed' && exit 1 echo 'Installing gcc...' yum -y install gcc >> $LOG 2>&1 [ $? != 0 ] && echo 'yum gcc failed' && exit 1 echo 'Downloding kernel...' wget http://www.kernel.org/pub/linux/kernel/v2.6/longterm/v2.6.33/linux-${KERNEL_VERSION}.tar.bz2 >> $LOG 2>&1 [ $? != 0 ] && echo 'downloading linux kernel sources failed' && exit 1 echo 'Downloding RT kernel patch...' wget http://www.kernel.org/pub/linux/kernel/projects/rt/2.6.33/patch-${KERNEL_VERSION}-rt${RT_PATCH_REV}.bz2 >> $LOG 2>&1 [ $? != 0 ] && echo 'downloading linux kernel RT patch failed' && exit 1 echo 'Patching the kernel...' tar xfj linux-${KERNEL_VERSION}.tar.bz2 >> $LOG 2>&1 [ $? != 0 ] && echo 'un-tar on linux kernel sources failed' && exit 1 cd ${KERNEL_SOURCE} >> $LOG 2>&1 [ $? != 0 ] && echo 'cd to linux kernel sources failed' && exit 1 bzcat ../patch-${KERNEL_VERSION}-rt${RT_PATCH_REV}.bz2 | patch -p1 >> $LOG 2>&1 [ $? != 0 ] && echo 'patching linux kernel sources with RT failed' && exit 1 echo 'Deploying kernel config...' cp ../.config . >> $LOG 2>&1 [ $? != 0 ] && echo 'Deploying kernel config failed' && exit 1 echo 'Building and installing the kernel...' make >> $LOG 2>&1 [ $? != 0 ] && echo 'Building the kernel failed' && exit 1 make modules >> $LOG 2>&1 [ $? != 0 ] && echo 'Building the modules failed' && exit 1 make modules_install >> $LOG 2>&1 [ $? != 0 ] && echo 'Installing the modules failed' && exit 1 make install >> $LOG 2>&1 [ $? != 0 ] && echo 'Installing the kernel failed' && exit 1 cp .config /boot/config-${KERNEL_VERSION}-rt${RT_PATCH_REV} >> $LOG 2>&1 [ $? != 0 ] && echo 'Installing the kernel config failed' && exit 1 echo 'Done installing.' <file_sep>/src/main/java/com/euronextclone/engine/MatchingEngine.java package com.euronextclone.engine; import com.euronextclone.MatchingUnit; import com.euronextclone.OrderEntry; import com.euronextclone.OrderSide; import com.euronextclone.ordertypes.Limit; import com.lmax.disruptor.*; import com.lmax.disruptor.dsl.Disruptor; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Matching Engine will contain 1 or more matching units. * * Engine is responsible for listing to incoming requests, journal the requests (orderEntry), * replicate to slave Matching engine and then submitting request to Matching Unit for processing * * Engine also needs to heat-beat so slave can promote to master if required * * Engine will also handle networking - ZeroMQ */ public class MatchingEngine { private final static int RING_SIZE = 1024 * 8; private final ExecutorService EXECUTOR = Executors.newFixedThreadPool(3); private final RingBuffer<ValueEvent> ringBuffer; private final MatchingUnit matchingUnit; final EventHandler<ValueEvent> journalHandler = new EventHandler<ValueEvent>() { public void onEvent(final ValueEvent event, final long sequence, final boolean endOfBatch) throws Exception { System.out.println(String.format("Journal %s", event.getValue())); } }; final EventHandler<ValueEvent> replicatorHandler = new EventHandler<ValueEvent>() { public void onEvent(final ValueEvent event, final long sequence, final boolean endOfBatch) throws Exception { System.out.println(String.format("Replicator %s", event.getValue())); } }; final EventHandler<ValueEvent> matchingUnitHandler = new EventHandler<ValueEvent>() { public void onEvent(final ValueEvent event, final long sequence, final boolean endOfBatch) throws Exception { System.out.println(String.format("Process %s", event.getValue())); matchingUnit.addOrder(event.getValue()); } }; private final Disruptor<ValueEvent> disruptor; public MatchingEngine(final String instrument) { matchingUnit = new MatchingUnit(instrument); disruptor = new Disruptor<ValueEvent>(ValueEvent.EVENT_FACTORY, EXECUTOR, new SingleThreadedClaimStrategy(RING_SIZE), new SleepingWaitStrategy()); disruptor.handleEventsWith(journalHandler, replicatorHandler).then(matchingUnitHandler); ringBuffer = disruptor.start(); } public void publish(final int num) { // Publishers claim events in sequence long sequence = ringBuffer.next(); ValueEvent event = ringBuffer.get(sequence); event.setValue(new OrderEntry(OrderSide.Buy, "A", num, new Limit(num))); // this could be more complex with multiple fields ringBuffer.publish(sequence); } public static void main(String args[]) { final MatchingEngine engine = new MatchingEngine("MSFT"); engine.publish(1234); engine.publish(1235); System.out.println("[Enter] q to exit"); Scanner scanner = new Scanner(System.in); while (!scanner.nextLine().trim().equals("q")) System.out.println("[Enter] q to exit"); engine.halt(); System.out.println("Exiting..."); } private void halt() { disruptor.halt(); disruptor.shutdown(); } } <file_sep>/src/main/java/com/euronextclone/fix/client/FixClientApp.java package com.euronextclone.fix.client; import com.euronextclone.fix.client.commands.ClientCommand; import com.euronextclone.fix.client.commands.PlaceLimitOrder; import com.euronextclone.fix.client.commands.PlaceMarketOrder; import com.lmax.disruptor.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import quickfix.ConfigError; import quickfix.SessionNotFound; import quickfix.SessionSettings; import quickfix.field.ExecType; import quickfix.field.Side; import quickfix.fix42.ExecutionReport; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created with IntelliJ IDEA. * User: eprystupa * Date: 7/24/12 * Time: 8:24 PM */ public class FixClientApp { private static Logger logger = LoggerFactory.getLogger(FixClientApp.class); private static List<ClientCommand> commands = new ArrayList<ClientCommand>(); public static void main(String args[]) { commands.add(new PlaceLimitOrder()); commands.add(new PlaceMarketOrder()); try { final String broker = getBroker(args, "A"); final FixClient client = createClient(broker); Scanner scanner = new Scanner(System.in); System.out.println("Enter [q] to exit, or [h] to list commands"); while (true) { System.out.print("Broker " + broker + "> "); final String command = scanner.nextLine().trim(); if (command.equals("q")) { break; } if (command.equals("h")) { listCommands(); continue; } for (ClientCommand clientCommand : commands) { final Matcher matcher = clientCommand.pattern().matcher(command); if (matcher.matches()) { clientCommand.execute(client, matcher); break; } } } System.out.println("Exiting..."); client.stop(); } catch (ConfigError configError) { logger.error(configError.getMessage(), configError); } catch (SessionNotFound sessionNotFound) { logger.error(sessionNotFound.getMessage(), sessionNotFound); } } private static String getBroker(String[] args, String defaultBroker) { // TODO: replace with some Java library for command arg parsing String result = defaultBroker; for (String arg : args) { final Matcher matcher = Pattern.compile("--broker=(\\S)").matcher(arg); if (matcher.matches()) { result = matcher.group(1); } } return result; } private static void listCommands() { for (ClientCommand command : commands) { System.out.println(command.name() + ":\t" + command.pattern().pattern()); } } private static FixClient createClient(final String broker) throws ConfigError { final InputStream config = FixClientApp.class.getClassLoader().getResourceAsStream("FixBroker" + broker + ".cfg"); final FixClient client = new FixClient(new SessionSettings(config)); client.start(); client.handleExecutions(new EventHandler<ExecutionReport>() { @Override public void onEvent(ExecutionReport report, long sequence, boolean endOfBatch) throws Exception { String orderId = report.getOrderID().getValue(); String side = report.getSide().getValue() == Side.BUY ? "bought" : "sold"; ExecType execType = report.getExecType(); String symbol = report.getSymbol().getValue(); if (execType.getValue() == ExecType.NEW) { logger.debug("Order {} accepted", orderId); } else { double tradeQty = report.getLastShares().getValue(); double tradePrice = report.getLastPx().getValue(); logger.debug("Broker {} {} {} shares of {} at {}", new Object[]{broker, side, tradeQty, symbol, tradePrice}); } } }); return client; } } <file_sep>/docs/Fix to Matching Cluster Architecture.md # FIX to Matching Engine Cluster Architecture ## Notes * The following architecture diagram does not capture high availability and/or failover aspect of the overall design; only the main messaging flow is presented * FIX server communicates with the clients over standard FIX protocol (clients not shown on the diagram) * Each FIX server is responsoble for a configured subset of clients (brokers) * When orders come in over FIX from brokers they are published using multicast with the instrument name as the topic (routing key) * Each FIX server subscribes for execution updates related to its subset of brokers and relays them over FIX to the clients * Each matching engine (ME) is responsible for its range of instruments (configured statically or dynamically) * Each ME subscribes for order events related to its range of instruments on a multicast channel, published to by the FIX servers. Orders and other instructions are then routed (based on instrument) to their respective matching unit (MU) for execution/processing. * When trades and other events are generated by MU they are published by ME using multicast with the affected broker as the topic (routing key) ## Diagram ![FIX to Matching Engine Flows over 0MQ](https://github.com/mattdavey/EuronextClone/raw/master/assets/FIXToMatchingEngineFlows0MQ.png)<file_sep>/README.md # Euronext Clone Inspired by github Price-Time Matching [Engine](https://gist.github.com/2855852), based on Euronext documentation publically available, and the madness of too many years in finance: * [The Peg Orders](http://www.euronext.com/fic/000/041/609/416094.pdf) * [Pure Market Order](http://www3.production.euronext.com/fic/000/041/480/414808.pdf) * [Auction](http://www.nyse.com/pdfs/5653_NYSEArca_Auctions.pdf) * [The Market to limit order](http://www3.production.euronext.com/fic/000/041/480/414806.pdf) * [Trading](https://europeanequities.nyx.com/en/trading/continuous-trading-process) * [The Stop Order](http://www3.production.euronext.com/fic/000/041/480/414809.pdf) * [Stop Order](http://www.euronext.com/fic/000/010/550/105509.pdf) * [IMP/TOP calculation](http://www.asx.com.au/products/calculate-open-close-prices.htm) ## Quick Links [Setting up dev environment](https://github.com/mattdavey/EuronextClone/blob/master/docs/SettingUpDevEnvironment.md) [FIX to matching eninge flows over 0MQ](https://github.com/mattdavey/EuronextClone/blob/master/docs/Fix%20to%20Matching%20Cluster%20Architecture.md) ## History The project initially started in the distant past as a Proof Of Concept (PoC) (see below) mainly aimed at attempting to model the data flows of a matching server in Java. Over time, work and thought has been put in to add ancillary services around the core order book with the aim of moving towards the high level architecture detailed below, offering Master/Slave with heart-beating from a resiliance perspective. It is hoped that at some point in the future performance numbers can be provided on suitable hardware to allow appropriate tuning and improve the architecture from a latency perspective. ## Proof Of Concept (PoC) Primarily this PoC architecture is aimed at joining all the dots together to ensure a client can submit an FIX order, and receive appropriate ExecutionReports ![Basic](https://github.com/mattdavey/EuronextClone/raw/master/assets/basic.jpg) ## High Level Architecture The architecture below is based on the [LMAX](http://martinfowler.com/articles/lmax.html) architecture, but leveraging ZeroMQ instead of [Informatica](http://www.informatica.com/us/products/messaging/) Ultra Messaging. Further reading available [here](http://mdavey.wordpress.com/2012/08/01/financial-messaging-zeromq-random-reading/) ![Basic](https://github.com/mattdavey/EuronextClone/raw/master/assets/complex.jpg). <file_sep>/src/main/java/com/euronextclone/TradingMode.java package com.euronextclone; /** * Created with IntelliJ IDEA. * User: eprystupa * Date: 7/19/12 * Time: 7:24 AM */ public enum TradingMode { ByAuction, Continuous } <file_sep>/src/main/java/com/euronextclone/OrderType.java package com.euronextclone; public interface OrderType { boolean acceptsMarketPrice(); boolean providesLimit(); double getLimit(); boolean canPegLimit(); boolean convertsToLimit(); Double price(OrderSide side, final Double bestLimit); String displayPrice(Double price); } <file_sep>/src/main/java/com/euronextclone/MatchingUnit.java package com.euronextclone; import com.euronextclone.ordertypes.Limit; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import com.google.common.collect.Lists; import hu.akarnokd.reactive4java.reactive.DefaultObservable; import hu.akarnokd.reactive4java.reactive.Observable; import hu.akarnokd.reactive4java.reactive.Observer; import javax.annotation.Nonnull; import java.io.Closeable; import java.util.*; public class MatchingUnit implements Observable<Trade> { private final OrderBook buyOrderBook; private final OrderBook sellOrderBook; private TradingPhase tradingPhase = TradingPhase.CoreContinuous; private TradingMode tradingMode = TradingMode.Continuous; private Double referencePrice; private Double indicativeMatchingPrice; /** * The observable helper. */ private final DefaultObservable<Trade> notifier = new DefaultObservable<Trade>(); private final String instrument; public MatchingUnit(String instrument) { this.instrument = instrument; buyOrderBook = new OrderBook(); sellOrderBook = new OrderBook(); } public void setReferencePrice(Double referencePrice) { this.referencePrice = referencePrice; } public Double getIndicativeMatchingPrice() { final List<Double> eligiblePrices = getListOfEligiblePrices(); final List<Integer> cumulativeBuy = getCumulativeQuantity(eligiblePrices, buyOrderBook, OrderSide.Buy); final List<Integer> cumulativeSell = getCumulativeQuantity(eligiblePrices, sellOrderBook, OrderSide.Sell); final List<VolumeAtPrice> totalTradeableVolume = getTotalTradeableVolume(eligiblePrices, cumulativeBuy, cumulativeSell); final List<VolumeAtPrice> maximumExecutableVolume = determineMaximumExecutableValue(totalTradeableVolume); if (maximumExecutableVolume.size() == 1) { return maximumExecutableVolume.get(0).price; } final List<VolumeAtPrice> minimumSurplus = establishMinimumSurplus(maximumExecutableVolume); if (minimumSurplus.size() == 1) { return minimumSurplus.get(0).price; } final Optional<Double> pressurePrice = ascertainWhereMarketPressureExists(minimumSurplus); if (pressurePrice.isPresent()) { return pressurePrice.get(); } return consultReferencePrice(minimumSurplus); } private double consultReferencePrice(List<VolumeAtPrice> minimumSurplus) { final FluentIterable<VolumeAtPrice> minimumSurplusIterable = FluentIterable.from(minimumSurplus); if (!minimumSurplus.isEmpty()) { double minPotentialPrice; double maxPotentialPrice; if (minimumSurplusIterable.allMatch(VolumeAtPrice.NO_PRESSURE)) { minPotentialPrice = minimumSurplusIterable.first().get().price; maxPotentialPrice = minimumSurplusIterable.last().get().price; } else { minPotentialPrice = minimumSurplusIterable.filter(VolumeAtPrice.BUYING_PRESSURE).last().get().price; maxPotentialPrice = minimumSurplusIterable.filter(VolumeAtPrice.SELLING_PRESSURE).first().get().price; } if (referencePrice == null) { return minPotentialPrice; } if (referencePrice >= maxPotentialPrice) { return maxPotentialPrice; } if (referencePrice <= minPotentialPrice) { return minPotentialPrice; } } return referencePrice; } private List<VolumeAtPrice> establishMinimumSurplus(List<VolumeAtPrice> maximumExecutableVolume) { if (maximumExecutableVolume.isEmpty()) { return maximumExecutableVolume; } final int minSurplus = Collections.min(maximumExecutableVolume, VolumeAtPrice.ABSOLUTE_SURPLUS_COMPARATOR).getAbsoluteSurplus(); FluentIterable<VolumeAtPrice> minSurplusOnly = FluentIterable.from(maximumExecutableVolume).filter(new Predicate<VolumeAtPrice>() { @Override public boolean apply(VolumeAtPrice input) { return input.getAbsoluteSurplus() == minSurplus; } }); return minSurplusOnly.toImmutableList(); } private List<VolumeAtPrice> determineMaximumExecutableValue(List<VolumeAtPrice> totalTradeableVolume) { if (totalTradeableVolume.isEmpty()) { return totalTradeableVolume; } final int maxVolume = Collections.max(totalTradeableVolume, VolumeAtPrice.TRADEABLE_VOLUME_COMPARATOR).getTradeableVolume(); FluentIterable<VolumeAtPrice> maxVolumeOnly = FluentIterable.from(totalTradeableVolume).filter(new Predicate<VolumeAtPrice>() { @Override public boolean apply(VolumeAtPrice input) { return input.getTradeableVolume() == maxVolume; } }); return maxVolumeOnly.toImmutableList(); } public void setTradingMode(TradingMode tradingMode) { this.tradingMode = tradingMode; } public void setTradingPhase(TradingPhase tradingPhase) { this.tradingPhase = tradingPhase; } private static class VolumeAtPrice { private double price; private int buyVolume; private int sellVolume; public VolumeAtPrice(double price, int buyVolume, int sellVolume) { this.price = price; this.buyVolume = buyVolume; this.sellVolume = sellVolume; } public int getTradeableVolume() { return Math.min(buyVolume, sellVolume); } public int getSurplus() { return buyVolume - sellVolume; } public int getAbsoluteSurplus() { return Math.abs(getSurplus()); } public static final Comparator<VolumeAtPrice> TRADEABLE_VOLUME_COMPARATOR = new Comparator<VolumeAtPrice>() { @Override public int compare(VolumeAtPrice volumeAtPrice1, VolumeAtPrice volumeAtPrice2) { Integer tradeableVolume1 = volumeAtPrice1.getTradeableVolume(); Integer tradeableVolume2 = volumeAtPrice2.getTradeableVolume(); return tradeableVolume1.compareTo(tradeableVolume2); } }; public static final Comparator<VolumeAtPrice> ABSOLUTE_SURPLUS_COMPARATOR = new Comparator<VolumeAtPrice>() { @Override public int compare(VolumeAtPrice volumeAtPrice1, VolumeAtPrice volumeAtPrice2) { Integer surplus1 = volumeAtPrice1.getAbsoluteSurplus(); Integer surplus2 = volumeAtPrice2.getAbsoluteSurplus(); return surplus1.compareTo(surplus2); } }; public static Predicate<? super VolumeAtPrice> BUYING_PRESSURE = new Predicate<VolumeAtPrice>() { @Override public boolean apply(final VolumeAtPrice input) { return input.getSurplus() > 0; } }; public static Predicate<? super VolumeAtPrice> SELLING_PRESSURE = new Predicate<VolumeAtPrice>() { @Override public boolean apply(final VolumeAtPrice input) { return input.getSurplus() < 0; } }; public static Predicate<? super VolumeAtPrice> NO_PRESSURE = new Predicate<VolumeAtPrice>() { @Override public boolean apply(final VolumeAtPrice input) { return input.getSurplus() == 0; } }; } private Optional<Double> ascertainWhereMarketPressureExists(List<VolumeAtPrice> minimumSurplus) { if (!minimumSurplus.isEmpty()) { final FluentIterable<VolumeAtPrice> minimumSurplusIterable = FluentIterable.from(minimumSurplus); final boolean buyingPressure = minimumSurplusIterable.allMatch(VolumeAtPrice.BUYING_PRESSURE); if (buyingPressure) { return Optional.of(minimumSurplusIterable.last().get().price); } final boolean sellingPressure = minimumSurplusIterable.allMatch(VolumeAtPrice.SELLING_PRESSURE); if (sellingPressure) { return Optional.of(minimumSurplusIterable.first().get().price); } } return Optional.absent(); } private List<Integer> getCumulativeQuantity( final List<Double> eligiblePrices, final OrderBook book, final OrderSide side) { final List<Integer> quantities = new ArrayList<Integer>(eligiblePrices.size()); final Iterable<Double> priceIterable = side == OrderSide.Sell ? eligiblePrices : Lists.reverse(eligiblePrices); final ListIterator<Order> current = book.getOrders().listIterator(); int cumulative = 0; for (final double price : priceIterable) { while (current.hasNext()) { final Order order = current.next(); final OrderType orderType = order.getOrderType(); Double orderPrice = orderType.price(side, book.getBestLimit()); if (canTrade(side, orderPrice, price)) { cumulative += order.getQuantity(); } else { current.previous(); break; } } quantities.add(cumulative); } return side == OrderSide.Sell ? quantities : Lists.reverse(quantities); } private boolean canTrade(OrderSide orderSide, Double orderPrice, double testPrice) { if (orderPrice == null) { return true; } if (orderSide == OrderSide.Buy) { return testPrice <= orderPrice; } return testPrice >= orderPrice; } private List<VolumeAtPrice> getTotalTradeableVolume( final List<Double> eligiblePrices, final List<Integer> cumulativeBuy, final List<Integer> cumulativeSell) { final List<VolumeAtPrice> tradeableVolume = new ArrayList<VolumeAtPrice>(); final Iterator<Double> priceIterator = eligiblePrices.iterator(); final Iterator<Integer> buy = cumulativeBuy.iterator(); final Iterator<Integer> sell = cumulativeSell.iterator(); while (priceIterator.hasNext()) { final double price = priceIterator.next(); final int buyVolume = buy.next(); final int sellVolume = sell.next(); tradeableVolume.add(new VolumeAtPrice(price, buyVolume, sellVolume)); } return tradeableVolume; } private List<Double> getListOfEligiblePrices() { final TreeSet<Double> prices = new TreeSet<Double>(); if (referencePrice != null) { prices.add(referencePrice); } prices.addAll(getLimitPrices(buyOrderBook)); prices.addAll(getLimitPrices(sellOrderBook)); return new ArrayList<Double>(prices); } private Collection<? extends Double> getLimitPrices(final OrderBook book) { return FluentIterable.from(book.getOrders()).filter(new Predicate<Order>() { @Override public boolean apply(Order input) { return input.getOrderType().providesLimit(); } }).transform(new Function<Order, Double>() { @Override public Double apply(Order input) { return input.getOrderType().getLimit(); } }).toImmutableSet(); } public void auction() { tradingPhase = TradingPhase.CoreAuction; indicativeMatchingPrice = getIndicativeMatchingPrice(); while (!buyOrderBook.getOrders().isEmpty()) { if (!tryMatchOrder(buyOrderBook.getOrders().get(0))) { break; } } upgradeMarketToLimitOrders(buyOrderBook); upgradeMarketToLimitOrders(sellOrderBook); } private void upgradeMarketToLimitOrders(OrderBook orderBook) { if (tradingMode == TradingMode.Continuous) { List<Order> orders = orderBook.getOrders(); List<Order> mtlOrders = FluentIterable.from(orders).filter(new Predicate<Order>() { @Override public boolean apply(Order input) { return input.getOrderType().convertsToLimit(); } }).toImmutableList(); orders.removeAll(mtlOrders); for (Order mtlOrder : mtlOrders) { Order limit = mtlOrder.convertTo(new Limit(indicativeMatchingPrice)); orderBook.add(limit); } } } public List<Order> getOrders(final OrderSide side) { return getBook(side).getOrders(); } public void addOrder(final OrderEntry orderEntry) { final Order order = new Order(orderEntry.getOrderId(), orderEntry.getBroker(), orderEntry.getQuantity(), orderEntry.getOrderType(), orderEntry.getSide()); final OrderSide side = orderEntry.getSide(); boolean topOfTheBook = getBook(side).add(order) == 0; if (tradingPhase == TradingPhase.CoreContinuous && topOfTheBook) { tryMatchOrder(order); } } private boolean tryMatchOrder(final Order newOrder) { final OrderSide side = newOrder.getSide(); final OrderBook book = getBook(side); final int startQuantity = newOrder.getQuantity(); final OrderBook counterBook = getCounterBook(side); Double newOrderPrice = newOrder.getOrderType().providesLimit() ? newOrder.getOrderType().getLimit() : null; List<Order> toRemove = new ArrayList<Order>(); List<Order> toAdd = new ArrayList<Order>(); Order currentOrder = newOrder; for (final Order order : counterBook.getOrders()) { // Determine the price at which the trade happens final Double bookOrderPrice = order.getOrderType().price(order.getSide(), counterBook.getBestLimit()); Double tradePrice = determineTradePrice(newOrderPrice, bookOrderPrice, order.getSide(), counterBook.getBestLimit()); if (tradePrice == null) { break; } if (tradingPhase == TradingPhase.CoreAuction) { tradePrice = indicativeMatchingPrice; } // Determine the amount to trade int tradeQuantity = determineTradeQuantity(currentOrder, order); // Trade currentOrder.decrementQuantity(tradeQuantity); order.decrementQuantity(tradeQuantity); generateTrade(currentOrder, order, tradeQuantity, tradePrice); if (order.getQuantity() == 0) { toRemove.add(order); } else { if (order.getOrderType().convertsToLimit()) { toRemove.add(order); toAdd.add(order.convertTo(new Limit(tradePrice))); } break; } if (currentOrder.getQuantity() == 0) { break; } if (currentOrder.getOrderType().convertsToLimit()) { book.remove(currentOrder); currentOrder = currentOrder.convertTo(new Limit(tradePrice)); book.add(currentOrder); newOrderPrice = tradePrice; } } counterBook.removeAll(toRemove); for (Order order : toAdd) { counterBook.add(order); } if (currentOrder.getQuantity() == 0) { book.remove(currentOrder); } return startQuantity != currentOrder.getQuantity(); } private void generateTrade(final Order newOrder, final Order order, final int tradeQuantity, final double price) { Order buyOrder = newOrder.getSide() == OrderSide.Buy ? newOrder : order; Order sellOrder = newOrder == buyOrder ? order : newOrder; notifier.next(new Trade( buyOrder.getOrderId(), buyOrder.getBroker(), sellOrder.getOrderId(), sellOrder.getBroker(), tradeQuantity, price)); } private int determineTradeQuantity(Order newOrder, Order order) { return Math.min(newOrder.getQuantity(), order.getQuantity()); } private Double determineTradePrice(Double newOrderPrice, Double counterBookOrderPrice, OrderSide counterBookSide, Double counterBookBestLimit) { if (newOrderPrice == null && counterBookOrderPrice == null) { if (counterBookBestLimit != null) { return counterBookBestLimit; } return referencePrice; } if (newOrderPrice == null) { return counterBookOrderPrice; } if (counterBookOrderPrice == null) { return tryImprovePrice(newOrderPrice, counterBookSide, counterBookBestLimit); } if (counterBookSide == OrderSide.Buy && counterBookOrderPrice >= newOrderPrice) { return counterBookOrderPrice; } if (counterBookSide == OrderSide.Sell && counterBookOrderPrice <= newOrderPrice) { return counterBookOrderPrice; } return null; // Can't trade } private double tryImprovePrice(double price, OrderSide counterBookSide, Double counterBookBestLimit) { if (counterBookBestLimit == null) { return price; // can't improve, not best limit in counter book } if (counterBookSide == OrderSide.Buy && counterBookBestLimit > price) { return counterBookBestLimit; } if (counterBookSide == OrderSide.Sell && counterBookBestLimit < price) { return counterBookBestLimit; } return price; // can't improve } public Double getBestLimit(final OrderSide side) { return side != OrderSide.Buy ? sellOrderBook.getBestLimit() : buyOrderBook.getBestLimit(); } @Nonnull public Closeable register(@Nonnull Observer<? super Trade> observer) { return notifier.register(observer); } private OrderBook getBook(final OrderSide side) { return side != OrderSide.Buy ? sellOrderBook : buyOrderBook; } private OrderBook getCounterBook(final OrderSide side) { return side != OrderSide.Buy ? buyOrderBook : sellOrderBook; } }<file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mattdavey.matching</groupId> <artifactId>EuronextClone</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>Euronext Clone</name> <properties> <cucumber-jvm.version>1.0.11</cucumber-jvm.version> <zmq.library.path>env.zmq.library.path</zmq.library.path> </properties> <dependencies> <dependency> <groupId>reactive4java</groupId> <artifactId>reactive4java</artifactId> <version>0.96.2</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>12.0.1</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>${cucumber-jvm.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-picocontainer</artifactId> <version>${cucumber-jvm.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>${cucumber-jvm.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <version>1.3</version> <scope>test</scope> </dependency> <!-- QuickFIX/J dependencies --> <dependency> <groupId>org.quickfixj</groupId> <artifactId>quickfixj-core</artifactId> <version>1.5.2</version> </dependency> <dependency> <groupId>org.quickfixj</groupId> <artifactId>quickfixj-msg-fix42</artifactId> <version>1.5.2</version> </dependency> <dependency> <groupId>org.apache.mina</groupId> <artifactId>mina-core</artifactId> <version>1.1.0</version> </dependency> <!-- logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.3</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.0</version> <scope>runtime</scope> </dependency> <!-- LMAX disruptor --> <dependency> <groupId>com.googlecode.disruptor</groupId> <artifactId>disruptor</artifactId> <version>2.10.1</version> </dependency> <!-- 0MQ --> <dependency> <groupId>jzmq</groupId> <artifactId>jzmq</artifactId> <version>3.3.0</version> </dependency> <!-- Protocol buffers --> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-runtime</artifactId> <version>1.0.7</version> </dependency> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-core</artifactId> <version>1.0.7</version> </dependency> </dependencies> <repositories> <!-- local repo magic --> <repository> <id>local-libs</id> <url>file://${basedir}/libs</url> </repository> </repositories> <profiles> <profile> <id>default-zmq-library-path</id> <activation> <property> <name>!zmq.library.path</name> </property> </activation> <properties> <zmq.library.path>/usr/local/lib</zmq.library.path> </properties> </profile> <profile> <id>run-fix-server</id> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <goals> <goal>exec</goal> </goals> </execution> </executions> <configuration> <executable>java</executable> <arguments> <argument>-classpath</argument> <classpath/> <argument>-Djava.library.path=${zmq.library.path}</argument> <argument>com.euronextclone.fix.server.FixServerApp</argument> </arguments> </configuration> </plugin> </plugins> </build> </profile> <profile> <id>run-fix-client-a</id> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <goals> <goal>exec</goal> </goals> </execution> </executions> <configuration> <executable>java</executable> <arguments> <argument>-classpath</argument> <classpath/> <argument>com.euronextclone.fix.client.FixClientApp</argument> <argument>--broker=A</argument> </arguments> </configuration> </plugin> </plugins> </build> </profile> <profile> <id>run-fix-client-b</id> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <goals> <goal>exec</goal> </goals> </execution> </executions> <configuration> <executable>java</executable> <arguments> <argument>-classpath</argument> <classpath/> <argument>com.euronextclone.fix.client.FixClientApp</argument> <argument>--broker=B</argument> </arguments> </configuration> </plugin> </plugins> </build> </profile> </profiles> </project> <file_sep>/script/rt-linux/build-utils #!/bin/bash function create-group { GROUP=$1 DESCRIPTION=$2 ec2-create-group "${GROUP}" -d "${DESCRIPTION}" ec2-authorize "${GROUP}" -P tcp -p 22 -s 0.0.0.0/0 } function spawn-instance { SECURITY_GROUPS=$1 for group in ${SECURITY_GROUPS}; do GRP_OPTIONS="${GRP_OPTIONS} -g ${group}" done ROOT_DEVICE_SIZE=$2 INSTANCE_TYPE=${3:-t1.micro} RESERVATION=`ec2-run-instances ami-41d00528 ${GRP_OPTIONS} -t ${INSTANCE_TYPE} -k gsmarquee -b /dev/sda1=:${ROOT_DEVICE_SIZE}:true \ | grep INSTANCE` [ $? != 0 ] && echo 'ec2-run-instances failed' >&2 && return 1 INSTANCE=`echo "${RESERVATION}" | awk '{print $2}'` while [[ -z "${EC2_HOST}" ]]; do EC2_HOST=`ec2-describe-instances ${INSTANCE} --filter instance-state-name=running \ | grep '^INSTANCE' | awk '{print $4}'` [ $? != 0 ] && echo 'ec2-describe-instances failed' >&2 && return 1 done while [[ true ]]; do ssh -o StrictHostKeyChecking=no -i ~/.ssh/gsmarquee.pem root@${EC2_HOST} 'echo OK >> /dev/null' >> /dev/null 2>&1 [ $? = 0 ] && break sleep 1 done echo "${EC2_HOST}" return 0 } function get-instance-field { GROUP_NAME=$1 FIELD_POS=$2 ec2-describe-instances --show-empty-fields \ --filter instance-state-name=running \ --filter group-name=${GROUP_NAME} \ | grep INSTANCE | cut -f ${FIELD_POS} } function get-public-dns { SECURITY_GROUPS=$1 for group in ${SECURITY_GROUPS}; do get-instance-field ${group} 4 done | sort -u } function get-private-dns { SECURITY_GROUPS=$1 for group in ${SECURITY_GROUPS}; do get-instance-field ${group} 5 done | sort -u } function build-uri { HOSTS=$1 PORT=$2 PROTOCOL=$3 URI='' for host in ${HOSTS}; do if [[ -n ${URI} ]]; then URI=${URI}", "; fi URI=$URI$PROTOCOL${host} if [[ -n ${PORT} ]]; then URI=${URI}:${PORT}; fi done echo ${URI} } <file_sep>/src/main/java/com/euronextclone/ordertypes/MarketToLimit.java package com.euronextclone.ordertypes; import com.euronextclone.OrderSide; import com.euronextclone.OrderType; /** * Created with IntelliJ IDEA. * User: eprystupa * Date: 7/20/12 * Time: 2:33 PM */ public class MarketToLimit implements OrderType { @Override public boolean acceptsMarketPrice() { return true; } @Override public boolean providesLimit() { return false; } @Override public double getLimit() { throw new RuntimeException("MTL orders do not provide limit"); } @Override public boolean canPegLimit() { return false; } @Override public boolean convertsToLimit() { return true; } @Override public Double price(OrderSide side, Double bestLimit) { return null; } @Override public String displayPrice(Double price) { return "MTL"; } }
b3bb9529cda6f89043ba503ed37ad562dc49d720
[ "Markdown", "Java", "Maven POM", "Shell" ]
19
Java
mattdavey/EuronextClone
0ae7d79a2c3832b8404d3f09709074c3f0df1657
de09106ca051f5a90d0ad476346842a0a8a08ca9
refs/heads/master
<repo_name>zhaijunhua/graduation<file_sep>/back-deve/nodeServer/blogServer/models/sentences.js var mongoose = require('mongoose'); // 引入数据库 var Schema = mongoose.Schema; var sentencesSchema = new Schema({ 'sentenceContent': String, 'translate': String, 'author': String, 'category': String, 'addTime': Date },{ collection: 'sentences' }); module.exports = mongoose.model('Sentence', sentencesSchema);<file_sep>/back-deve/nodeServer/blogServer/routes/score.js var express = require('express'); var router = express(); //获取路由 var mysql = require('mysql'); var dbConfig = require('../database/DBConfig'); var pool = mysql.createPool( dbConfig.mysql ); var sql = 'SELECT *,(select Count(*) from studentScore WHERE student_number = ?) as count FROM studentScore WHERE student_number = ? LIMIT ?, ?'; var sqlYear = `SELECT *, ( SELECT Count(*) FROM studentScore WHERE student_number = ? AND schoolYear = ? ) AS count FROM studentScore WHERE student_number = ? AND schoolYear = ? LIMIT ?, ?` var sql2 = 'SELECT * FROM CompreScore WHERE student_number = ?'; var connection = mysql.createConnection(dbConfig.mysql); connection.connect(); var responseJSON = function (res, ret) {   if(typeof ret === 'undefined') {       res.json({code:'500', msg: '操作失败'});   } else {     res.json(ret);   } }; router.get('/getScore', function(req, res, next) { pool.getConnection(function(err, connection) { let param = req.query || req.params; let studentNumber = param.studentNumber; let rows = parseInt(param.rows); let page = parseInt(param.page-1); let year = param.year; console.log('年' + year); if(!year || year == 'undefined' || year == '') { console.log('1112'); connection.query(sql,[studentNumber,studentNumber,(rows-1)*page,rows], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) } else { console.log('2222'); connection.query(sqlYear,[studentNumber, year, studentNumber, year, (rows-1)*page,rows], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) } }) }) router.get('/getCompreScore', function(req, res, next) { pool.getConnection(function(err, connection) { var param = req.query; console.log(param); connection.query(sql2,param.student_number, function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }) connection.end(); module.exports = router;<file_sep>/back-deve/nodeServer/blogServer/routes/personal.js var express = require('express'); var router = express(); //获取路由 var mysql = require('mysql'); var dbConfig = require('../database/DBConfig'); var pool = mysql.createPool( dbConfig.mysql ); //使用DBConfig中配置信息创建一个MySQL连接池 var sql = 'SELECT * FROM studentmanage'; var sql2 = 'SELECT * FROM studentmanage where student_number = ?'; var connection = mysql.createConnection(dbConfig.mysql); connection.connect(); var connection = mysql.createConnection(dbConfig.mysql); connection.connect(); var responseJSON = function (res, ret) {   if(typeof ret === 'undefined') {       res.json({code:'500', msg: '操作失败'});   } else {     res.json(ret);   } }; router.get('/studentMess',function(req, res, next) { res.send(str); }); router.get('/getInfoById', function(req, res, next) { pool.getConnection(function(err, connection) { let param = req.query; connection.query(sql2, [param.studentNumber],function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }); connection.end(); module.exports = router; // 必须进行输出 <file_sep>/back-deve/nodeServer/blogServer/models/blogs.js var mongoose = require('mongoose'); // 引入数据库 var Schema = mongoose.Schema; var blogMessageSchema = new Schema({ "blogTitle": String, "blogTime": { type: Date, default: Date.now() }, "blogContent": String, "category": String, "introduce": String }, { collection: 'blogMessage' }); module.exports = mongoose.model('Blog', blogMessageSchema); <file_sep>/back-deve/nodeServer/blogServer/routes/messageboard.js var express = require('express'); var router = express(); var mongoose = require('mongoose'); var Leavemessage = require('../models/messageboard'); mongoose.connect('mongodb://127.0.0.1:27017/blogs'); mongoose.connection.on("connected", function() { console.log("MongoDB Connect Success"); }); mongoose.connection.on("error", function() { console.log("MongoDB connect Filed"); }) mongoose.connection.on("disconnected", function() { console.log("MongoDB connect disconnected"); }); router.post('/write', function(req, res, next){ let newMessage = new Leavemessage({ leavecontent: req.body.leavecontent, leaveperson: req.body.leaveperson, date: req.body.date ? new Date():new Date(parseInt(req.body.date)) }); newMessage.save(function(err,doc) { if (err) { return res.json({ status: '0', msg: err.message }); } res.json({ status: '1', data: doc }); }); }); router.get('/getleaveMessage', function(req, res, next) { // var page = req.param('page'); // let pageSize = parseInt(req.param('pageSize')); // let skip = (page-1) * pageSize; // let params = {}; // let message = Leavemessage.find(params).skip(params).skip(skip).limit(pageSize); Leavemessage.find({}, function(err, doc){ if (err) { res.json({ status: '0', msg: err.message }); } else { res.json({ status: '1', msg: 'success', result: { count: doc.length, list: doc } }) } }) }); router.post('/deleteLeave', function(req, res, next){ var id = req.body.id; var findId = mongoose.Types.ObjectId(id); var param = { _id: findId }; Leavemessage.findOneAndRemove(param, function(err, doc) { if(err) { res.json({ status: '00000', msg: err.message }); } else { res.json({ status: '10001', msg: 'success', result: doc }); } }); }); module.exports = router;<file_sep>/back-deve/nodeServer/blogServer/routes/getOthers.js var express = require('express'); var router = express(); //获取路由 var mysql = require('mysql'); var dbConfig = require('../database/DBConfig'); var pool = mysql.createPool( dbConfig.mysql ); var connection = mysql.createConnection(dbConfig.mysql); connection.connect(); var responseJSON = function (res, ret) {   if(typeof ret === 'undefined') {       res.json({code:'500', msg: '操作失败'});   } else {     res.json(ret);   } }; router.get('/getYear', function(req, res, next) { let yearSql = 'select schoolYear from studentscore WHERE student_number = ? GROUP BY schoolYear'; pool.getConnection(function(err, connection) { let param = req.query || req.params; let studentNumber = param.studentNumber; connection.query(yearSql,[studentNumber], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }) router.get('/getAcademy', function(req, res, next) { let acaSql = `select * from academylist`; pool.getConnection(function(err, connection) { connection.query(acaSql, function(err,result) { if(result) { let acalist = [] for(var i=0;len=result.length,i<len;i++){ result[i]["children"]=[]; acalist.push(JSON.parse(JSON.stringify(result[i]))); } connection.query(`select * from majorlist`, function(err, result1) { if(result1) { let acaTreeList = JSON.parse(JSON.stringify(acalist)); let majorlist = result1; console.log(acalist); for(var i=0; i< acalist.length; i++) { var a = acalist[i].id; for(var j =0; j <majorlist.length; j++) { console.log("liceng" + a); if(majorlist[j].acaId == a) { console.log(majorlist[j]); acaTreeList[i]['children'].push(majorlist[j]); } } } console.log(acaTreeList); dataRes = { code:200, data: acaTreeList }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) } else { responseJSON(res, err); connection.release(); } }) }) }) router.get('/getmajor', function(req, res, next) { let yearSql = `select * from majorlist`; pool.getConnection(function(err, connection) { connection.query(yearSql, function(err,result) { if(result) { let result1 =JSON.parse(JSON.stringify(result)); let resultData = buildTree(result1); dataRes = { code:200, data: resultData }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }); router.post('/addAcademy', function(req, res, next) { let addsql = 'insert into academylist (student_academy) values(?)' var param = req.body; pool.getConnection(function(err, connection) { connection.query(addsql, [param.student_academy], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }); router.post('/deleteAcademy', function(req, res, next) { var param = req.body; pool.getConnection(function(err, connection) { connection.query(sql2, [param.student_academy], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }); connection.end(); module.exports = router;<file_sep>/back-deve/nodeServer/blogServer/models/messageboard.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var messageabordSchema = new Schema({ leavecontent: String, leaveperson: String, date: Date }, { collection: 'leavemessage' }); module.exports = mongoose.model('Leavemessage', messageabordSchema);<file_sep>/back-deve/nodeServer/blogServer/dataBase/DBConfig.js module.exports = { mysql: { host:'127.0.0.1', port:'3306', user:'root', password:'<PASSWORD>', database:'assessmentsystem' } }<file_sep>/back-deve/nodeServer/blogServer/dataBase/querySql.js var sql = {};<file_sep>/back-deve/nodeServer/blogServer/routes/getRankMsg.js var express = require('express'); var router = express(); //获取路由 var mysql = require('mysql'); var dbConfig = require('../database/DBConfig'); var pool = mysql.createPool( dbConfig.mysql ); // var sql = 'select * from scorerank where student_number = ?'; var sql = 'SELECT b.* FROM (SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r,(SELECT * FROM scorerank ORDER BY avgScore DESC) AS t) AS b WHERE b.student_number = ?'; var sql2 = `SELECT b.* FROM ( SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r, ( SELECT scorerank.student_number,(scorerank.avgScore * 0.7 + comprescore.compreScore*0.3) as finalA FROM scorerank,comprescore GROUP BY scorerank.student_number ORDER BY finalA DESC ) AS t ) AS b WHERE b.student_number = ?`; var avgRankSql = `SELECT b.* FROM ( SELECT t.*, @ranknum := @ranknum + 1 AS ranknum FROM (SELECT @ranknum := 0) r, ( SELECT scorerank.avgScore, scorerank.student_number, scorerank.student_grade, studentmanage.student_major FROM scorerank,studentmanage WHERE studentmanage.student_major = ? and scorerank.student_grade = ? GROUP BY scorerank.student_number ORDER BY avgScore DESC ) AS t ) AS b WHERE b.student_number = ?`; // 成绩总排名 // 综合排名 var finalRankSql = `SELECT b.* FROM ( SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r, ( SELECT scorerank.student_number,(scorerank.avgScore * 0.7 + comprescore.compreScore*0.3) as finalA FROM scorerank,comprescore,studentmanage WHERE studentmanage.student_major = ? and scorerank.student_grade = ? GROUP BY scorerank.student_number ORDER BY finalA DESC ) AS t ) AS b WHERE b.student_number = 2016210973`; var connection = mysql.createConnection(dbConfig.mysql); connection.connect(); var responseJSON = function (res, ret) {   if(typeof ret === 'undefined') {       res.json({code:'500', msg: '操作失败'});   } else {     res.json(ret);   } }; router.get('/getRank', function(req, res, next) { pool.getConnection(function(err, connection) { var param = req.query; connection.query(sql,param.number, function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }); router.get('/getAvgRank', function(req, res, next) { pool.getConnection(function(err, connection) { let param = req.query; let studentMajor = param.studentMajor; let studentGrade = param.studentGrade; let studentNumber = param.studentNumber; connection.query(avgRankSql,[studentMajor, studentGrade, studentNumber], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }) // 获得综合排名 router.get('/finalRankSql', function(req, res, next) { pool.getConnection(function(err, connection) { let param = req.query; let studentMajor = param.studentMajor; let studentGrade = param.studentGrade; let studentNumber = param.studentNumber; connection.query(avgRankSql,[studentMajor, studentGrade, studentNumber], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }); connection.end(); module.exports = router;<file_sep>/back-deve/nodeServer/blogServer/routes/addApply.js var express = require('express'); var router = express(); //获取路由 var mysql = require('mysql'); var dbConfig = require('../database/DBConfig'); var pool = mysql.createPool( dbConfig.mysql ); // var sql = 'select * from scorerank where student_number = ?'; var sql = 'INSERT INTO qualitypoint (student_number, schoolYear ,student_name, for_reason, add_score) VALUES (?, ?, ?, ?, ?)'; var sql2 = 'INSERT INTO applylist (student_number, student_name, schoolYear, apply_reason, student_major, award_type) VALUES (?, ?, ?, ?, ?, ?)'; var connection = mysql.createConnection(dbConfig.mysql); connection.connect(); var responseJSON = function (res, ret) {   if(typeof ret === 'undefined') {       res.json({code:'500', msg: '操作失败'});   } else {     res.json(ret);   } }; router.post('/addScoreApply', function(req, res, next) { var param = req.body; console.log(param.studentNumber); pool.getConnection(function(err, connection) { connection.query(sql, [param.studentNumber, param.schoolYear, param.studentName, param.reason, param.addScore], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }); router.post('/addAwardApply', function(req, res, next) { var param = req.body; pool.getConnection(function(err, connection) { connection.query(sql2, [param.studentNumber, param.studentName, param.schoolYear, param.reason, param.studentMajor, param.awardType ], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }); router.post('/updateScoreApply', function(req, res, next) { let updateSql = `UPDATE qualitypoint SET apply_status = ? WHERE id = ?` var param = req.body; let status = param.status; let applyId = param.applyId; pool.getConnection(function(err, connection) { connection.query(updateSql, [status, applyId], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) }) }); // 不通过插入另一个表中 router.post('/addUnSApply', function(req, res, next) { let insertSql = 'insert into unqualitypoint select * from qualitypoint where id = ?;' var param = req.body; let unSapplyId = param.applyId; pool.getConnection(function(err, connection) { connection.query(insertSql, [unSapplyId], function(err,result) { if(result) { connection.query('delete from qualitypoint where id=?;', [unSapplyId], function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) } else { responseJSON(res, err); connection.release(); } }) }) }); // 综合素质通过审批放入另外一张表x router.post('/addInSApply', function(req, res, next) { let insertSql = `insert into inqualitypoint select * from qualitypoint where id = ?;` var param = req.body; let applyId = param.applyId; pool.getConnection(function(err, connection) { connection.query(insertSql, applyId, function(err,result) { if(result) { connection.query('delete from qualitypoint where id=?;', applyId, function(err,result) { if(result) { dataRes = { code:200, data: result }; responseJSON(res, dataRes); connection.release(); } else { responseJSON(res, err); connection.release(); } }) } else { responseJSON(res, err); connection.release(); } }) }) }); connection.end(); module.exports = router;<file_sep>/back-deve/nodeServer/blogServer/routes/users.js var express = require('express'); var router = express(); //获取路由 var mongoose = require('mongoose'); var User = require('../models/users'); var Personal = require('../models/aboutme'); mongoose.connect('mongodb://127.0.0.1:27017/blogs'); mongoose.connection.on("connected", function() { console.log("MongoDB Connect Success"); }); mongoose.connection.on("error", function() { console.log("MongoDB connect Filed"); }) mongoose.connection.on("disconnected", function() { console.log("MongoDB connect disconnected"); }); // 登录接口 router.post('/login',function(req,res,next){ var param = { userName: req.body.userName, userPwd: <PASSWORD> } User.findOne(param, function(err,doc) { if(err) { res.json({ // 报错 status: '1', msg: err.message // 直接报错 }); } else { res.cookie('userId', doc.userId, { // signed: true, // 加密 path: '/', // 将登陆获取的值=cookie值保存 maxAge: 1000*60*60 // cookie保存时间,这里是一个小时 }); console.log(req.headers.cookie); // req.session.user = doc; // session可以实时拿到用户信息 if(doc) { // 使用cookie res.json({ status: '0', msg: '', result: doc.userName }); } } }) }); // 登出接口 router.post('/logout', function(req, res, next) { res.cookie('userId', '', { path: '/', maxAge: -1 }); res.json({ status: '0', msg: '', result: '' }); }); // 获取个人信息 router.get('/personalmessage', function(req, res, next) { Personal.find({}, function(err, data) { if(err) { res.json({ status: '00000', msg: err.message, result: 'ERROR' }); } else { res.json({ status: '10001', msg: 'success', result: data }) } }) }); // 修改个人信息 router.post('/editMessage', function(req, res, next){ let userId = req.body.id; let id = mongoose.Types.ObjectId(userId); let resume = req.body.resume; let param = { _id: id }; let data = { resume: resume } Personal.findOneAndUpdate(param, data, function(err, data){ if(err) { res.json({ status: '000000', msg: err.message, result: 'error' }); } else { res.json({ status: '10001', message: 'success', result: data }); } }); }); module.exports = router;
fb0e20e44fdaa6d0603704effb1b775beb78d225
[ "JavaScript" ]
12
JavaScript
zhaijunhua/graduation
98062a9ba1a2f12bface5f9e82c07711907f991c
da21058a4508c3f530439848049a0867fb513a5a
refs/heads/master
<repo_name>SayaniG371/CiphX<file_sep>/CipheringAlgos/Homophonic.py import random key_table={'A':['D','9'],'B':'X','C':'S','D':'F','E':['Z','7','2','1'],'F':'E','G':'H','H':'C','I':['V','3'],'J':'I','K':'T','L':'P','M':'G','N':['A','5'],'O':['Q','0'],'P':'L','Q':'K','R':'J','S':['R','4'],'T':['U','6'],'U':'O','V':'W','W':'M','X':'Y','Y':'B','Z':'N'} def encrypt(msg): enc="" for i in msg: if i in key_table: if isinstance(key_table[i], list): enc+=random.choice(key_table[i]) else: enc+=key_table[i] else: enc+=i return enc def decrypt(msg): dec="" for i in msg: if i.isalnum(): k=0 for j in key_table.values(): if i in j: break k+=1 dec+=chr(65+k) else: dec+=i return dec <file_sep>/CipheringAlgos/VigenereAutokey.py chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def Enc(strn, key): # Encrypting process if strn.isupper(): # Creating key upto message length i = 0 while len(key) != len(strn): key += strn[i] i += 1 # encryption st = "" for i in range(len(strn)): if strn[i] not in chars: st += strn[i] continue s = ((ord(strn[i]) + ord(key[i])) % 26) + ord('A') st += chr(s) return st if strn.islower(): strn = strn.upper() key = key.upper() # Creating key upto message length i = 0 while len(key) != len(strn): key += strn[i] i += 1 # encryption st = "" for i in range(len(strn)): if strn[i] not in chars: st += strn[i] continue s = ((ord(strn[i]) + ord(key[i])) % 26) + ord('A') st += chr(s) st = st.lower() return st def Dec(strn, key): # Decryption process if strn.isupper(): # Creating key i = 0 while len(key) != len(strn): key += chr(((ord(strn[i]) - ord(key[i])) % 26) + ord('A')) i += 1 # decryption st = "" for i in range(len(strn)): if strn[i] not in chars: st += strn[i] continue s = ((ord(strn[i]) - ord(key[i]) + 26) % 26) + ord('A') st += chr(s) return st if strn.islower(): strn = strn.upper() key = key.upper() # Creating key i = 0 while len(key) != len(strn): key += chr(((ord(strn[i]) - ord(key[i])) % 26) + ord('A')) i += 1 # decryption st = "" for i in range(len(strn)): if strn[i] not in chars: st += strn[i] continue s = ((ord(strn[i]) - ord(key[i]) + 26) % 26) + ord('A') st += chr(s) st = st.lower() return st <file_sep>/CipheringAlgos/Vigenere.py chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def Enc(txt, k): # transforming key to length of message ls = "" i = 0 while len(ls) != len(txt): ls += k[i] if i == len(k) - 1: i = 0 continue i += 1 # Encrypting the message if txt.isupper(): st = "" for i in range(len(txt)): if txt[i] not in chars: st += txt[i] continue s = ((ord(txt[i]) + ord(ls[i])) % 26) + ord('A') st += chr(s) return st if txt.islower(): txt = txt.upper() ls = ls.upper() st = "" for i in range(len(txt)): if txt[i] not in chars: st += txt[i] continue s = ((ord(txt[i]) + ord(ls[i])) % 26) + ord('a') st += chr(s) st = st.lower() return st def Dec(txt, k): # transforming key to length of message ls = "" i = 0 while len(ls) != len(txt): ls += k[i] if i == len(k) - 1: i = 0 continue i += 1 # Decrypting the message if txt.isupper(): st = "" for i in range(len(txt)): if txt[i] not in chars: st += txt[i] continue s = ((ord(txt[i]) - ord(ls[i]) + 26) % 26) + ord('A') st += chr(s) return st if txt.islower(): txt = txt.upper() ls = ls.upper() st = "" for i in range(len(txt)): if txt[i] not in chars: st += txt[i] continue s = ((ord(txt[i]) - ord(ls[i]) + 26) % 26) + ord('a') st += chr(s) st = st.lower() return st <file_sep>/CipheringAlgos/Caesar.py def enc(s,k): e="" for letter in s: if letter.isupper(): e+= chr((ord(letter) + k-65) % 26 + 65) else: e += chr((ord(letter) + k - 97) % 26 + 97) return e def dec(s,k): d="" for letter in s: if letter.isupper(): d+= chr((ord(letter) + (26-k)-65) % 26 + 65) else: d+= chr((ord(letter) + (26-k) - 97) % 26 + 97) return d <file_sep>/CipheringAlgos/AtbashCipher.py ''' Atbash cipher is a substitution cipher with just one specific key where all the letters are reversed that is A to Z and Z to A. It was originally used to encode the Hebrew alphabets but it can be modified to encode any alphabet. Atbash Table = {'A' : 'Z', 'B' : 'Y', 'C' : 'X', 'D' : 'W', 'E' : 'V', 'F' : 'U', 'G' : 'T', 'H' : 'S', 'I' : 'R', 'J' : 'Q', 'K' : 'P', 'L' : 'O', 'M' : 'N', 'N' : 'M', 'O' : 'L', 'P' : 'K', 'Q' : 'J', 'R' : 'I', 'S' : 'H', 'T' : 'G', 'U' : 'F', 'V' : 'E', 'W' : 'D', 'X' : 'C', 'Y' : 'B', 'Z' : 'A'} You may use the following table but here I've used a different approach. My approach is mostly based on the fact that each character has its own counterpart at the opposite end. So, what I did was that find the middle point the character set and just calculated the difference to obtain the counterpart. Like: A <-------------- M , N --------------> Z 65<--------------77, 78 --------------> 90 Given character be G (71) So 71-78 gives -7 And 77-(-7) = 77+7 = 84 ,i.e, T ''' #The funtion to encrypt and decrypt. def Atbashconvert(string): #Initializing the output string. result = '' #For loop for iterating through each character in given string. for c in string: #Checks if the character is in Upper case if c.isupper(): #Converting the character to its counterpart. result += chr(77 - (ord(c)-78)) #---------------------------------------------------------------- #result += chr(155 - ord(c)) <--------------------Shorter #Checks if the character is in Lower case. elif c.islower(): #Converting the character to its counterpart. result += chr(109 - (ord(c)-110)) #---------------------------------------------------------------- #result += chr(219 - ord(c)) <---------------------Shorter else: #If the character is not an alphabet the we do not alter the character. result += c #Returning the result. return result ''' #The Driver Code t = "" while t != "exit": print("Enter the Message:") message = input() converted = convert(message) #converts the message print(converted) print("Want to use again? Press 'Yes'. Or Press 'exit' to end process.") t = input().lower() # converts the input to lowercase to avoid typos. '''<file_sep>/CiphX.py from tkinter import * from PIL import ImageTk, Image from CipheringAlgos import Caesar from CipheringAlgos import VigenereAutokey from CipheringAlgos import Vigenere from CipheringAlgos import PlayFair from CipheringAlgos.AtbashCipher import Atbashconvert from CipheringAlgos import beaufortC from CipheringAlgos import beaufortautokeyC from CipheringAlgos import Homophonic from CipheringAlgos import columnerC root = Tk() root.title("CiphX") root.iconbitmap('disneyland.ico') root.geometry("2000x2000") root.bind('<Escape>', lambda event: root.state('normal')) root.bind('<F11>', lambda event: root.state('zoomed')) filename = PhotoImage(file="T2.png") background_label = Label(root, image=filename) background_label.place(x=0, y=0, relwidth=1, relheight=1) global im1 im1 = ImageTk.PhotoImage(Image.open("ebtn.png")) global im2 im2 = ImageTk.PhotoImage(Image.open("dbtn.png")) # Welcome msg l1 = Label(root, padx=30, text="Welcome To CiphX !", font=("Helvetica", 60)) l1.place(x=700, y=100, anchor="center") k1 = Label(root, padx=5, text="Press F11 : FullScreen", bg="Lightyellow", font=("Helvetica", 10)) k1.place(x=950, y=160) k2 = Label(root, padx=5, text="Press ESC : NormalScreen", bg="Lightyellow", font=("Helvetica", 10)) k2.place(x=1100, y=160) # Select Ciphering Method def sel(): s = clicked.get() if s == "Caesar Cipher": # Caesar cipher et = Toplevel() et.title("Caesar Cipher") et.iconbitmap('disneyland.ico') et.configure(bg="Pink") et.geometry("2000x2000") et.bind('<Home>', lambda event: et.state('normal')) et.bind('<F12>', lambda event: et.state('zoomed')) def Encode(): txt = ent1.get() key = int(ent2.get()) st = Caesar.enc(txt, key) global lbl lbl = Label(et, text="Ciphered Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Decode(): txt = ent1.get() key = int(ent2.get()) st = Caesar.dec(txt, key) global lbl lbl = Label(et, text="Original Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Ref(): ent1.delete(0, END) ent2.delete(0, END) lbl.destroy() def Back(): et.destroy() lb = Label(et, padx=30, text="CAESAR CIPHER", font=("Helvetica", 40)) lb.place(x=700, y=50, anchor="center") k1 = Label(et, padx=10, text="Press F12 : FullScreen", bg="Lightyellow", font=("Helvetica", 10)) k1.place(x=600, y=100, anchor="center") k2 = Label(et, padx=10, text="Press Home : NormalScreen", bg="Lightyellow", font=("Helvetica", 10)) k2.place(x=800, y=100, anchor="center") lb1 = Label(et, padx=30, text="Enter Message : ", font=("Helvetica", 20)) lb1.place(x=700, y=150, anchor="center") ent1 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent1.configure(font=("Helvetica", 20)) ent1.place(x=700, y=200, anchor="center") lb2 = Label(et, padx=30, text="Enter KEY : ", font=("Helvetica", 20)) lb2.place(x=700, y=250, anchor="center") ent2 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent2.configure(font=("Helvetica", 20)) ent2.place(x=700, y=300, anchor="center") # Create Button btn1 = Button(et, borderwidth=0, padx=20, pady=20, command=Encode) btn1.configure(font=("Helvetica", 20), image=im1, bg="Pink") btn1.place(x=500, y=400, anchor="center") btn2 = Button(et, borderwidth=0, padx=20, pady=20, command=Decode) btn2.configure(font=("Helvetica", 20), image=im2, bg="Pink") btn2.place(x=900, y=400, anchor="center") btn3 = Button(et, text="REFRESH", borderwidth=0, padx=50, pady=10, command=Ref) btn3.configure(font=("Helvetica", 10)) btn3.place(x=600, y=600, anchor="center") btn4 = Button(et, text="BACK TO HOMESCREEN", borderwidth=0, padx=10, pady=10, command=Back) btn4.configure(font=("Helvetica", 10)) btn4.place(x=800, y=600, anchor="center") if s == "Vigenere Cipher": # Vigenere cipher et = Toplevel() et.title("Vigenere Cipher") et.iconbitmap('disneyland.ico') et.configure(bg="Pink") et.geometry("2000x2000") et.bind('<Home>', lambda event: et.state('normal')) et.bind('<F12>', lambda event: et.state('zoomed')) def Encode(): txt = ent1.get() k = ent2.get() st = Vigenere.Enc(txt, k) global lbl lbl = Label(et, text="Ciphered Message : "+st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Decode(): txt = ent1.get() k = ent2.get() st = Vigenere.Dec(txt, k) global lbl lbl = Label(et, text="Original Message : "+st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Ref(): ent1.delete(0, END) ent2.delete(0, END) lbl.destroy() def Back(): et.destroy() lb = Label(et, padx=30, text="VIGENERE CIPHER", font=("Helvetica", 40)) lb.place(x=700, y=50, anchor="center") k1 = Label(et, padx=10, text="Press F12 : FullScreen", bg="Lightyellow", font=("Helvetica", 10)) k1.place(x=600, y=100, anchor="center") k2 = Label(et, padx=10, text="Press Home : NormalScreen", bg="Lightyellow", font=("Helvetica", 10)) k2.place(x=800, y=100, anchor="center") lb1 = Label(et, padx=30, text="Enter Message : ", font=("Helvetica", 20)) lb1.place(x=700, y=150, anchor="center") ent1 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent1.configure(font=("Helvetica", 20)) ent1.place(x=700, y=200, anchor="center") lb2 = Label(et, padx=30, text="Enter KEY : ", font=("Helvetica", 20)) lb2.place(x=700, y=250, anchor="center") ent2 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent2.configure(font=("Helvetica", 20)) ent2.place(x=700, y=300, anchor="center") # Create Button btn1 = Button(et, borderwidth=0, padx=20, pady=20, command=Encode) btn1.configure(font=("Helvetica", 20), image=im1, bg="Pink") btn1.place(x=500, y=400, anchor="center") btn2 = Button(et, borderwidth=0, padx=20, pady=20, command=Decode) btn2.configure(font=("Helvetica", 20), image=im2, bg="Pink") btn2.place(x=900, y=400, anchor="center") btn3 = Button(et, text="REFRESH", borderwidth=0, padx=50, pady=10, command=Ref) btn3.configure(font=("Helvetica", 10)) btn3.place(x=600, y=600, anchor="center") btn4 = Button(et, text="BACK TO HOMESCREEN", borderwidth=0, padx=10, pady=10, command=Back) btn4.configure(font=("Helvetica", 10)) btn4.place(x=800, y=600, anchor="center") if s == "Vigenere Autokey Cipher": # Vigenere Autokey cipher et = Toplevel() et.title("Vigenere Autokey Cipher") et.iconbitmap('disneyland.ico') et.configure(bg="Pink") et.geometry("2000x2000") et.bind('<Home>', lambda event: et.state('normal')) et.bind('<F12>', lambda event: et.state('zoomed')) def Encode(): txt = ent1.get() key = ent2.get() st = VigenereAutokey.Enc(txt, key) global lbl lbl = Label(et, text="Ciphered Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Decode(): txt = ent1.get() key = ent2.get() st = VigenereAutokey.Dec(txt, key) global lbl lbl = Label(et, text="Original Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Ref(): ent1.delete(0, END) ent2.delete(0, END) lbl.destroy() def Back(): et.destroy() lb = Label(et, padx=30, text="VIGENERE AUTOKEY CIPHER", font=("Helvetica", 40)) lb.place(x=700, y=50, anchor="center") k1 = Label(et, padx=10, text="Press F12 : FullScreen", bg="Lightyellow", font=("Helvetica", 10)) k1.place(x=600, y=100, anchor="center") k2 = Label(et, padx=10, text="Press Home : NormalScreen", bg="Lightyellow", font=("Helvetica", 10)) k2.place(x=800, y=100, anchor="center") lb1 = Label(et, padx=30, text="Enter Message : ", font=("Helvetica", 20)) lb1.place(x=700, y=150, anchor="center") ent1 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent1.configure(font=("Helvetica", 20)) ent1.place(x=700, y=200, anchor="center") lb2 = Label(et, padx=30, text="Enter KEY : ", font=("Helvetica", 20)) lb2.place(x=700, y=250, anchor="center") ent2 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent2.configure(font=("Helvetica", 20)) ent2.place(x=700, y=300, anchor="center") # Create Button btn1 = Button(et, borderwidth=0, padx=20, pady=20, command=Encode) btn1.configure(font=("Helvetica", 20), image=im1, bg="Pink") btn1.place(x=500, y=400, anchor="center") btn2 = Button(et, borderwidth=0, padx=20, pady=20, command=Decode) btn2.configure(font=("Helvetica", 20), image=im2, bg="Pink") btn2.place(x=900, y=400, anchor="center") btn3 = Button(et, text="REFRESH", borderwidth=0, padx=50, pady=10, command=Ref) btn3.configure(font=("Helvetica", 10)) btn3.place(x=600, y=600, anchor="center") btn4 = Button(et, text="BACK TO HOMESCREEN", borderwidth=0, padx=10, pady=10, command=Back) btn4.configure(font=("Helvetica", 10)) btn4.place(x=800, y=600, anchor="center") if s == "PlayFair Cipher": # PlayFair cipher et = Toplevel() et.title("PlayFair Cipher") et.iconbitmap('disneyland.ico') et.configure(bg="Pink") et.geometry("2000x2000") et.bind('<Home>', lambda event: et.state('normal')) et.bind('<F12>', lambda event: et.state('zoomed')) def Encode(): strn = ent1.get() key = ent2.get() msg = PlayFair.Enc(strn, key) global lbl lbl = Label(et, text="Ciphered Message : "+msg, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Decode(): strn = ent1.get() key = ent2.get() msg = PlayFair.Dec(strn, key) global lbl lbl = Label(et, text="Original Message : "+msg, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Ref(): ent1.delete(0, END) ent2.delete(0, END) lbl.destroy() def Back(): et.destroy() lb = Label(et, padx=30, text="PLAYFAIR CIPHER", font=("Helvetica", 40)) lb.place(x=700, y=50, anchor="center") k1 = Label(et, padx=10, text="Press F12 : FullScreen", bg="Lightyellow", font=("Helvetica", 10)) k1.place(x=600, y=100, anchor="center") k2 = Label(et, padx=10, text="Press Home : NormalScreen", bg="Lightyellow", font=("Helvetica", 10)) k2.place(x=800, y=100, anchor="center") lb1 = Label(et, padx=30, text="Enter Message : (UPPERCASE)", font=("Helvetica", 20)) lb1.place(x=700, y=150, anchor="center") ent1 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent1.configure(font=("Helvetica", 20)) ent1.place(x=700, y=200, anchor="center") lb2 = Label(et, padx=30, text="Enter KEY : (UPPERCASE)", font=("Helvetica", 20)) lb2.place(x=700, y=250, anchor="center") ent2 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent2.configure(font=("Helvetica", 20)) ent2.place(x=700, y=300, anchor="center") # Create Button btn1 = Button(et, borderwidth=0, padx=20, pady=20, command=Encode) btn1.configure(font=("Helvetica", 20), image=im1, bg="Pink") btn1.place(x=500, y=400, anchor="center") btn2 = Button(et, borderwidth=0, padx=20, pady=20, command=Decode) btn2.configure(font=("Helvetica", 20), image=im2, bg="Pink") btn2.place(x=900, y=400, anchor="center") btn3 = Button(et, text="REFRESH", borderwidth=0, padx=50, pady=10, command=Ref) btn3.configure(font=("Helvetica", 10)) btn3.place(x=600, y=600, anchor="center") btn4 = Button(et, text="BACK TO HOMESCREEN", borderwidth=0, padx=10, pady=10, command=Back) btn4.configure(font=("Helvetica", 10)) btn4.place(x=800, y=600, anchor="center") if s == "Atbash Cipher": # Atbash cipher et = Toplevel() et.title("Atbash Cipher") et.iconbitmap('disneyland.ico') et.configure(bg="Pink") et.geometry("2000x2000") et.bind('<Home>', lambda event: et.state('normal')) et.bind('<F12>', lambda event: et.state('zoomed')) def Encode(): txt = ent1.get() st = Atbashconvert(txt) global lbl lbl = Label(et, text="Ciphered Message : "+st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Decode(): txt = ent1.get() st = Atbashconvert(txt) global lbl lbl = Label(et, text="Original Message : "+st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Ref(): ent1.delete(0, END) lbl.destroy() def Back(): et.destroy() lb = Label(et, padx=30, text="ATBASH CIPHER", font=("Helvetica", 40)) lb.place(x=700, y=50, anchor="center") k1 = Label(et, padx=10, text="Press F12 : FullScreen", bg="Lightyellow", font=("Helvetica", 10)) k1.place(x=600, y=100, anchor="center") k2 = Label(et, padx=10, text="Press Home : NormalScreen", bg="Lightyellow", font=("Helvetica", 10)) k2.place(x=800, y=100, anchor="center") lb1 = Label(et, padx=30, text="Enter Message :", font=("Helvetica", 20)) lb1.place(x=700, y=150, anchor="center") ent1 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent1.configure(font=("Helvetica", 20)) ent1.place(x=700, y=200, anchor="center") # Create Button btn1 = Button(et, borderwidth=0, padx=20, pady=20, command=Encode) btn1.configure(font=("Helvetica", 20), image=im1, bg="Pink") btn1.place(x=500, y=400, anchor="center") btn2 = Button(et, borderwidth=0, padx=20, pady=20, command=Decode) btn2.configure(font=("Helvetica", 20), image=im2, bg="Pink") btn2.place(x=900, y=400, anchor="center") btn3 = Button(et, text="REFRESH", borderwidth=0, padx=50, pady=10, command=Ref) btn3.configure(font=("Helvetica", 10)) btn3.place(x=600, y=600, anchor="center") btn4 = Button(et, text="BACK TO HOMESCREEN", borderwidth=0, padx=10, pady=10, command=Back) btn4.configure(font=("Helvetica", 10)) btn4.place(x=800, y=600, anchor="center") if s == "Beaufort Cipher": # Beaufort cipher et = Toplevel() et.title("Beaufort Cipher") et.iconbitmap('disneyland.ico') et.configure(bg="Pink") et.geometry("2000x2000") et.bind('<Home>', lambda event: et.state('normal')) et.bind('<F12>', lambda event: et.state('zoomed')) def Encode(): txt = ent1.get() key = ent2.get() st = beaufortC.beaufortconvert(txt, key) global lbl lbl = Label(et, text="Ciphered Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Decode(): txt = ent1.get() key = ent2.get() st = beaufortC.beaufortconvert(txt, key) global lbl lbl = Label(et, text="Original Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Ref(): ent1.delete(0, END) ent2.delete(0, END) lbl.destroy() def Back(): et.destroy() lb = Label(et, padx=30, text="BEAUFORT CIPHER", font=("Helvetica", 40)) lb.place(x=700, y=50, anchor="center") k1 = Label(et, padx=10, text="Press F12 : FullScreen", bg="Lightyellow", font=("Helvetica", 10)) k1.place(x=600, y=100, anchor="center") k2 = Label(et, padx=10, text="Press Home : NormalScreen", bg="Lightyellow", font=("Helvetica", 10)) k2.place(x=800, y=100, anchor="center") lb1 = Label(et, padx=30, text="Enter Message : ", font=("Helvetica", 20)) lb1.place(x=700, y=150, anchor="center") ent1 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent1.configure(font=("Helvetica", 20)) ent1.place(x=700, y=200, anchor="center") lb2 = Label(et, padx=30, text="Enter KEY : ", font=("Helvetica", 20)) lb2.place(x=700, y=250, anchor="center") ent2 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent2.configure(font=("Helvetica", 20)) ent2.place(x=700, y=300, anchor="center") # Create Button btn1 = Button(et, borderwidth=0, padx=20, pady=20, command=Encode) btn1.configure(font=("Helvetica", 20), image=im1, bg="Pink") btn1.place(x=500, y=400, anchor="center") btn2 = Button(et, borderwidth=0, padx=20, pady=20, command=Decode) btn2.configure(font=("Helvetica", 20), image=im2, bg="Pink") btn2.place(x=900, y=400, anchor="center") btn3 = Button(et, text="REFRESH", borderwidth=0, padx=50, pady=10, command=Ref) btn3.configure(font=("Helvetica", 10)) btn3.place(x=600, y=600, anchor="center") btn4 = Button(et, text="BACK TO HOMESCREEN", borderwidth=0, padx=10, pady=10, command=Back) btn4.configure(font=("Helvetica", 10)) btn4.place(x=800, y=600, anchor="center") if s == "Beaufort Autokey Cipher": # Beaufort Autokey cipher et = Toplevel() et.title("Beaufort Autokey Cipher") et.iconbitmap('disneyland.ico') et.configure(bg="Pink") et.geometry("2000x2000") et.bind('<Home>', lambda event: et.state('normal')) et.bind('<F12>', lambda event: et.state('zoomed')) def Encode(): txt = ent1.get() key = ent2.get() st = beaufortautokeyC.encrypt(txt, key) global lbl lbl = Label(et, text="Ciphered Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Decode(): txt = ent1.get() key = ent2.get() st = beaufortautokeyC.decrypt(txt, key) global lbl lbl = Label(et, text="Original Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Ref(): ent1.delete(0, END) ent2.delete(0, END) lbl.destroy() def Back(): et.destroy() lb = Label(et, padx=30, text="BEAUFORT AUTOKEY CIPHER", font=("Helvetica", 40)) lb.place(x=700, y=50, anchor="center") k1 = Label(et, padx=10, text="Press F12 : FullScreen", bg="Lightyellow", font=("Helvetica", 10)) k1.place(x=600, y=100, anchor="center") k2 = Label(et, padx=10, text="Press Home : NormalScreen", bg="Lightyellow", font=("Helvetica", 10)) k2.place(x=800, y=100, anchor="center") lb1 = Label(et, padx=30, text="Enter Message : ", font=("Helvetica", 20)) lb1.place(x=700, y=150, anchor="center") ent1 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent1.configure(font=("Helvetica", 20)) ent1.place(x=700, y=200, anchor="center") lb2 = Label(et, padx=30, text="Enter KEY : ", font=("Helvetica", 20)) lb2.place(x=700, y=250, anchor="center") ent2 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent2.configure(font=("Helvetica", 20)) ent2.place(x=700, y=300, anchor="center") # Create Button btn1 = Button(et, borderwidth=0, padx=20, pady=20, command=Encode) btn1.configure(font=("Helvetica", 20), image=im1, bg="Pink") btn1.place(x=500, y=400, anchor="center") btn2 = Button(et, borderwidth=0, padx=20, pady=20, command=Decode) btn2.configure(font=("Helvetica", 20), image=im2, bg="Pink") btn2.place(x=900, y=400, anchor="center") btn3 = Button(et, text="REFRESH", borderwidth=0, padx=50, pady=10, command=Ref) btn3.configure(font=("Helvetica", 10)) btn3.place(x=600, y=600, anchor="center") btn4 = Button(et, text="BACK TO HOMESCREEN", borderwidth=0, padx=10, pady=10, command=Back) btn4.configure(font=("Helvetica", 10)) btn4.place(x=800, y=600, anchor="center") if s == "Homophonic Substitution Cipher": # Homophonic Substitution cipher et = Toplevel() et.title("Homophonic Substitution Cipher") et.iconbitmap('disneyland.ico') et.configure(bg="Pink") et.geometry("2000x2000") et.bind('<Home>', lambda event: et.state('normal')) et.bind('<F12>', lambda event: et.state('zoomed')) def Encode(): txt = ent1.get() st = Homophonic.encrypt(txt) global lbl lbl = Label(et, text="Ciphered Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Decode(): txt = ent1.get() st = Homophonic.decrypt(txt) global lbl lbl = Label(et, text="Original Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Ref(): ent1.delete(0, END) ent2.delete(0, END) lbl.destroy() def Back(): et.destroy() lb = Label(et, padx=30, text="HOMOPHONIC SUBSTITUTION CIPHER", font=("Helvetica", 40)) lb.place(x=700, y=50, anchor="center") k1 = Label(et, padx=10, text="Press F12 : FullScreen", bg="Lightyellow", font=("Helvetica", 10)) k1.place(x=600, y=100, anchor="center") k2 = Label(et, padx=10, text="Press Home : NormalScreen", bg="Lightyellow", font=("Helvetica", 10)) k2.place(x=800, y=100, anchor="center") lb1 = Label(et, padx=30, text="Enter Message : (UPPERCASE)", font=("Helvetica", 20)) lb1.place(x=700, y=150, anchor="center") ent1 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent1.configure(font=("Helvetica", 20)) ent1.place(x=700, y=200, anchor="center") # Create Button btn1 = Button(et, borderwidth=0, padx=20, pady=20, command=Encode) btn1.configure(font=("Helvetica", 20), image=im1, bg="Pink") btn1.place(x=500, y=400, anchor="center") btn2 = Button(et, borderwidth=0, padx=20, pady=20, command=Decode) btn2.configure(font=("Helvetica", 20), image=im2, bg="Pink") btn2.place(x=900, y=400, anchor="center") btn3 = Button(et, text="REFRESH", borderwidth=0, padx=50, pady=10, command=Ref) btn3.configure(font=("Helvetica", 10)) btn3.place(x=600, y=600, anchor="center") btn4 = Button(et, text="BACK TO HOMESCREEN", borderwidth=0, padx=10, pady=10, command=Back) btn4.configure(font=("Helvetica", 10)) btn4.place(x=800, y=600, anchor="center") if s == "Columner Transposition Cipher": # Columner Transposition cipher et = Toplevel() et.title("Columner Transposition Cipher") et.iconbitmap('disneyland.ico') et.configure(bg="Pink") et.geometry("2000x2000") et.bind('<Home>', lambda event: et.state('normal')) et.bind('<F12>', lambda event: et.state('zoomed')) def Encode(): txt = ent1.get() key = ent2.get() st = columnerC.encrypt(txt, key) global lbl lbl = Label(et, text="Ciphered Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Decode(): txt = ent1.get() key = ent2.get() st = columnerC.decrypt(txt, key) global lbl lbl = Label(et, text="Original Message : " + st, font=("Helvetica", 25)) lbl.place(x=700, y=500, anchor="center") def Ref(): ent1.delete(0, END) ent2.delete(0, END) lbl.destroy() def Back(): et.destroy() lb = Label(et, padx=30, text="COLUMNER TRANSPOSITION CIPHER", font=("Helvetica", 40)) lb.place(x=700, y=50, anchor="center") k1 = Label(et, padx=10, text="Press F12 : FullScreen", bg="Lightyellow", font=("Helvetica", 10)) k1.place(x=600, y=100, anchor="center") k2 = Label(et, padx=10, text="Press Home : NormalScreen", bg="Lightyellow", font=("Helvetica", 10)) k2.place(x=800, y=100, anchor="center") lb1 = Label(et, padx=30, text="Enter Message : ", font=("Helvetica", 20)) lb1.place(x=700, y=150, anchor="center") ent1 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent1.configure(font=("Helvetica", 20)) ent1.place(x=700, y=200, anchor="center") lb2 = Label(et, padx=30, text="Enter KEY : ", font=("Helvetica", 20)) lb2.place(x=700, y=250, anchor="center") ent2 = Entry(et, width=20, background="Skyblue", borderwidth=3) ent2.configure(font=("Helvetica", 20)) ent2.place(x=700, y=300, anchor="center") # Create Button btn1 = Button(et, borderwidth=0, padx=20, pady=20, command=Encode) btn1.configure(font=("Helvetica", 20), image=im1, bg="Pink") btn1.place(x=500, y=400, anchor="center") btn2 = Button(et, borderwidth=0, padx=20, pady=20, command=Decode) btn2.configure(font=("Helvetica", 20), image=im2, bg="Pink") btn2.place(x=900, y=400, anchor="center") btn3 = Button(et, text="REFRESH", borderwidth=0, padx=50, pady=10, command=Ref) btn3.configure(font=("Helvetica", 10)) btn3.place(x=600, y=600, anchor="center") btn4 = Button(et, text="BACK TO HOMESCREEN", borderwidth=0, padx=10, pady=10, command=Back) btn4.configure(font=("Helvetica", 10)) btn4.place(x=800, y=600, anchor="center") def Close(): root.destroy() clicked = StringVar() clicked.set("Caesar Cipher") lb = Label(root, padx=10, text="Choose The Ciphering Method :", font=("Helvetica", 25), background="Pink") lb.place(x=480, y=300, anchor="center") dd = OptionMenu(root, clicked, "Caesar Cipher", "Vigenere Cipher", "Vigenere Autokey Cipher", "PlayFair Cipher", "Atbash Cipher", "Beaufort Cipher", "Beaufort Autokey Cipher", "Homophonic Substitution Cipher", "Columner Transposition Cipher") dd.configure(font=("Helvetica", 25), bg="Skyblue", width=27) dd.place(x=1000, y=300, anchor="center") b1 = Button(root, width=10, text="Select", command=sel) b1.configure(font=("Helvetica", 25)) b1.place(x=700, y=400, anchor="center") b2 = Button(root, width=20, text="Close Window", command=Close) b2.configure(font=("Helvetica", 15)) b2.place(x=700, y=500, anchor="center") root.mainloop() <file_sep>/README.md # CIPHX : CIPHERING APP #### We have created a ciphering app that will encrypt and decrypt messages. You can choose any ciphering method among CAESAR CIPHER, ATBASH CIPHER, VIGENERE CIPHER, BEAUFORT CIPHER, PLAYFAIR CIPHER, COLUMNER TRANSPOSITION CIPHER and many more. ## How to access the app: ### 1. Clone or Download the files of this repo ### 2. Open the file name main.py in your device ### 3. Run it, and the app will launch ## How to use the app: ### 1. After launching the app, You will see a dropdown option onscreen in which you can select the method of ciphering. To complete the selection of choice, click the `SELECT` button onscreen. ### Use `F11` on keyboard for fullscreen view ### Use `ESC` on the keyboard for standard screen view ### 2. Click `Close Window` onscreen to close the app ### 3. After you select the ciphering method, a new window opens up where you can enter your message and key, according to the ciphering method. ### 4. Enter the message you want to encode or decode and key(if required), then press the `ENCODE` or `DECODE` button according to your choice. ### You will see the encoded or decoded message pop up ### Press the `REFRESH` button after encoding or decoding each time. ### Press the `BACK TO HOMESCREEN` button to go back to the main screen. ### Press `F12` on keyboard for fullscreen view ### Press `Home` on the keyboard for standard screen view ## Ciphering Methods Available: 1. **Caesar Cipher** 2. **Vigenere Cipher** 3. **Vigenere Autokey Cipher** 4. **PlayFair Cipher** 5. **Atbash Cipher** 6. **Beaufort Cipher** 7. **Beaufort Autokey Cipher** 8. **Homophonic Substitution Cipher** 9. **Columner Transposition Cipher** <file_sep>/CipheringAlgos/PlayFair.py # Encoding function for PlayFair Cipher def Enc(strn, inp): # Index returning function def iret(ch, k): li = [] for i in range(5): for j in range(5): if ch == k[i][j]: li.append(i) li.append(j) break return li # Creating square key li = list(inp) chars = "ABCDEFGHIKLMNOPQRSTUVWXYZ" j = 0 l = [] lis = [] lis.extend(li) while j != 25: ch = chars[j] if ch not in li: lis.append(ch) j += 1 j = 0 i = 0 lu = [] while j != 25: lu.append(lis[j]) if i == 4: l.append(lu) i = 0 lu = [] j += 1 continue i += 1 j += 1 k = l # Encrypting the message if (len(strn) % 2) != 0: strn += "Z" m = 0 for ch in strn: if ch == "J": strn.replace("I", m) m += 1 li = [] lis = [] j = 0 i = 0 while j != len(strn): li.append(strn[j]) j += 1 if i == 1: lis.append(li) i = 0 li = [] continue i += 1 msg = "" for c in range(len(lis)): x = iret(lis[c][0], k) r1 = x[0] c1 = x[1] y = iret(lis[c][1], k) r2 = y[0] c2 = y[1] if c1 == c2: msg = msg + k[(r1 + 1) % 5][c1] + k[(r2 + 1) % 5][c2] elif r1 == r2: msg = msg + k[r1][(c1 + 1) % 5] + k[r2][(c2 + 1) % 5] else: msg = msg + k[r1][c2] + k[r2][c1] return msg # Decoding Function for PlayFair Ciphering def Dec(strn, inp): # Index returning function def iret(ch, k): li = [] for i in range(5): for j in range(5): if ch == k[i][j]: li.append(i) li.append(j) break return li # Creating square key li = list(inp) chars = "ABCDEFGHIKLMNOPQRSTUVWXYZ" j = 0 l = [] lis = [] lis.extend(li) while j != 25: ch = chars[j] if ch not in li: lis.append(ch) j += 1 j = 0 i = 0 lu = [] while j != 25: lu.append(lis[j]) if i == 4: l.append(lu) i = 0 lu = [] j += 1 continue i += 1 j += 1 k = l # Decrypting the message li = [] lis = [] j = 0 i = 0 while j != len(strn): li.append(strn[j]) j += 1 if i == 1: lis.append(li) i = 0 li = [] continue i += 1 msg = "" for c in range(len(lis)): x = iret(lis[c][0], k) r1 = x[0] c1 = x[1] y = iret(lis[c][1], k) r2 = y[0] c2 = y[1] if c1 == c2: msg = msg + k[(r1 - 1) % 5][c1] + k[(r2 - 1) % 5][c2] elif r1 == r2: msg = msg + k[r1][(c1 - 1) % 5] + k[r2][(c2 - 1) % 5] else: msg = msg + k[r1][c2] + k[r2][c1] if msg[-1] == "Z": msg = msg[:-1] return msg
130c5753cd6fb20fbe0f9fc39c16b759a7ca60ef
[ "Markdown", "Python" ]
8
Python
SayaniG371/CiphX
7bf15192a2a6fd967b8c6a317687f955c6547d92
678e9acfcbfe49589820566b40fc86d98ef542ed
refs/heads/master
<repo_name>jazzbre/BeefLangAndroidTester<file_sep>/BeefProject/BeefProj.toml FileVersion = 1 [Project] Name = "BeefProject" StartupObject = "BeefProject.Program" <file_sep>/app/src/main/cpp/CMakeLists.txt cmake_minimum_required(VERSION 3.4.1) message("Generating for Android ABI ${ANDROID_ABI} in '${CMAKE_SOURCE_DIR}'...") set(BEEF_PROJECT_PATH "${CMAKE_SOURCE_DIR}/../../../..") if (${ANDROID_ABI} STREQUAL "arm64-v8a") set(BEEF_ARCH "Debug_aarch64-none-linux-android23") elseif (${ANDROID_ABI} STREQUAL "armeabi-v7a") set(BEEF_ARCH "Debug_armv7-none-linux-androideabi23") elseif (${ANDROID_ABI} STREQUAL "x86_64") set(BEEF_ARCH "Debug_x86_64-none-linux-android23") elseif (${ANDROID_ABI} STREQUAL "x86") set(BEEF_ARCH "/Debug_i686-none-linux-android23") endif() add_library( native-lib SHARED native-lib.cpp ) target_link_libraries( native-lib log ${BEEF_PROJECT_PATH}/BeefProject/build/${BEEF_ARCH}/BeefProject/BeefProject.a ${BEEF_PROJECT_PATH}/BeefLibs/${ANDROID_ABI}/libBeefRT_d.a ${BEEF_PROJECT_PATH}/BeefLibs/${ANDROID_ABI}/libffi.a ) <file_sep>/BeefProject/BeefSpace_User.toml FileVersion = 1 LastConfig = "Debug" LastPlatform = "Win64" RecentFilesList = ["src\\Program.bf", "src\\LinkIssue\\Color.bf", "src\\LinkIssue\\JSON\\Types\\JSONArray.bf", "src\\LinkIssue\\LinkIssue.bf", "src\\LinkIssue\\Bounds2.bf"] [MainWindow] X = 0 Y = 0 Width = 662 Height = 426 ShowKind = "Maximized" [MainDockingFrame] Type = "DockingFrame" SplitType = 2 [[MainDockingFrame.DockedWidgets]] RequestedWidth = 358.0 RequestedHeight = 208.0 SizePriority = 208.0 Type = "DockingFrame" SplitType = 1 [[MainDockingFrame.DockedWidgets.DockedWidgets]] RequestedWidth = 930.0 RequestedHeight = 208.0 Type = "TabbedView" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] Active = true TabLabel = "Workspace" TabWidth = 112.5 Type = "ProjectPanel" [[MainDockingFrame.DockedWidgets.DockedWidgets]] IsFillWidget = true Permanent = true RequestedWidth = 150.0 RequestedHeight = 150.0 SizePriority = 150.0 DefaultDocumentsTabbedView = true Type = "TabbedView" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] TabLabel = "Color.bf" TabWidth = 84.0 Type = "SourceViewPanel" FilePath = "src\\LinkIssue\\Color.bf" ProjectName = "BeefProject" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] TabLabel = "JSONArray.bf" TabWidth = 115.0 Type = "SourceViewPanel" FilePath = "src\\LinkIssue\\JSON\\Types\\JSONArray.bf" CursorPos = 166 ProjectName = "BeefProject" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] TabLabel = "LinkIssue.bf" TabWidth = 106.5 Type = "SourceViewPanel" FilePath = "src\\LinkIssue\\LinkIssue.bf" CursorPos = 54 ProjectName = "BeefProject" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] TabLabel = "Bounds2.bf" TabWidth = 104.5 Type = "SourceViewPanel" FilePath = "src\\LinkIssue\\Bounds2.bf" ProjectName = "BeefProject" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] Active = true TabLabel = "Program.bf" TabWidth = 103.5 Type = "SourceViewPanel" FilePath = "src\\Program.bf" CursorPos = 1680 VertPos = 2131.0 ProjectName = "BeefProject" [[MainDockingFrame.DockedWidgets]] RequestedWidth = 260.0 RequestedHeight = 675.0 Type = "DockingFrame" SplitType = 1 [[MainDockingFrame.DockedWidgets.DockedWidgets]] RequestedWidth = 260.0 RequestedHeight = 260.0 SizePriority = 0.4648071 Type = "TabbedView" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] TabLabel = "Memory" TabWidth = 98.5 Type = "MemoryPanel" AutoResize = "Auto_Mul8" RequestedWidth = 300.0 [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] Active = true TabLabel = "Watch" TabWidth = 86.0 Type = "WatchPanel" Columns = [{Width = 571.0}, {Width = 1210.0}, {Width = 200.0}] Items = [""] [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] TabLabel = "Auto" TabWidth = 78.0 Type = "AutoWatchPanel" Columns = [{Width = 588.0}, {Width = 679.0}, {Width = 200.0}] [[MainDockingFrame.DockedWidgets.DockedWidgets]] RequestedWidth = 260.0 RequestedHeight = 260.0 SizePriority = 0.5351929 Type = "TabbedView" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] TabLabel = "Find Results" TabWidth = 118.5 Type = "FindResultsPanel" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] TabLabel = "Threads" TabWidth = 95.5 Type = "ThreadPanel" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] TabLabel = "Call Stack" TabWidth = 104.0 Type = "CallStackPanel" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] TabLabel = "Immediate" TabWidth = 111.0 Type = "ImmediatePanel" [[MainDockingFrame.DockedWidgets.DockedWidgets.Tabs]] Active = true TabLabel = "Output" TabWidth = 91.5 Type = "OutputPanel" <file_sep>/settings.gradle include ':app' rootProject.name = "BeefLangAndroidTester"<file_sep>/BeefProject/BeefSpace.toml FileVersion = 1 Projects = {BeefProject = {Path = "."}} [Workspace] StartupProject = "BeefProject" <file_sep>/app/src/main/cpp/native-lib.cpp #include <jni.h> #include <android/log.h> #include <string> extern "C" void BeefMain(int argc, char** argv); extern "C" JNIEXPORT void JNICALL Java_com_beeflang_tester_MainActivity_nativeBeefMain(JNIEnv*, jobject) { BeefMain(0, nullptr); } struct Bounds { double l, b, r, t; }; extern "C" void* cpBoxShapeNew2(void* handle, Bounds bounds, double radius) { __android_log_print(ANDROID_LOG_INFO, "BEEFJNI", "cpBoxShapeNew2 %p, (%f %f %f), %f", handle, bounds.l, bounds.b, bounds.r, bounds.t, radius); return handle; } struct Vec2 { float x, y; }; enum class Cond : uint32_t { SomeShit = 7 }; extern "C" void* imguiSetNextWindowPos(Vec2 pos, Cond cond, Vec2 pivot) { __android_log_print(ANDROID_LOG_INFO, "BEEFJNI", "imguiSetNextWindowPos (%f %f), %d, (%f %f)", pos.x, pos.y, cond, pivot.x, pivot.y); return (void*)0x1234; }
1ff062029e478677cf9c303270f86157f232e406
[ "TOML", "CMake", "C++", "Gradle" ]
6
TOML
jazzbre/BeefLangAndroidTester
6418ede2bd2ac86a9d66f070a45643c908420a0a
3f818167ddad7246bbdb68df88f700d483771db4
refs/heads/master
<repo_name>kjwilsondev/pizza-box-api<file_sep>/app/main/model/cleaner.py from .. import db, flask_bcrypt import datetime from app.main.model.blacklist import BlacklistToken from ..config import key import jwt class Cleaner(db.Model): __tablename__ = "cleaner" id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(100)) num_boxes = db.Column(db.Integer) # num boxes currently on cleaner def __repr__(self): return "<Cleaner '{}'>".format(self.id)<file_sep>/app/main/model/restaurant.py from .. import db import datetime class Restaurant(db.Model): __tablename__ = "restaurant" id = db.Column(db.Integer, primary_key=True, autoincrement=True) public_id = db.Column(db.String(100), unique=True) name = db.Column(db.String(100)) num_boxes = db.Column(db.Integer) # num boxes currently on restaurant def __repr__(self): return "<Restaurant '{}'>".format(self.id)<file_sep>/app/main/service/box_service.py import uuid import datetime from app.main import db from app.main.model.box import Box def save_new_box(data): box = Box.query.filter_by(public_id=data['public_id']).first() if not box: new_box = Box( id=str(uuid.uuid4()), public_id=str(uuid.uuid4()), trips=data['trips'], registered_on=datetime.datetime.utcnow() ) save_changes(new_box) return new_box else: response_object = { 'status': 'fail', 'message': 'An error occurred', } return response_object, 409 def get_all_boxes(): return Box.query.all() def get_a_box(public_id): return Box.query.filter_by(public_id=public_id).first() def get_box_driver(public_id): box_driver = Box.query.filter_by(public_id=public_id).first() return box_driver.driver def save_changes(data): # commits the changes to database db.session.add(data) db.session.commit() <file_sep>/app/main/service/driver_service.py import uuid import datetime from app.main import db from app.main.model.driver import Driver def save_new_driver(data): driver = Driver.query.filter_by(email=data['email']).first() if not driver: new_driver = Driver( public_id=str(uuid.uuid4()), email=data['email'], username=data['username'], password=data['<PASSWORD>'], registered_on=datetime.datetime.utcnow() ) save_changes(new_driver) response_object = { 'status': 'success', 'message': 'Successfully registered.' } return response_object, 201 else: response_object = { 'status': 'fail', 'message': 'Driver already exists. Please Log in.', } return response_object, 409 def get_all_drivers(): return Driver.query.all() def get_a_driver(public_id): return Driver.query.filter_by(public_id=public_id).first() def save_changes(data): db.session.add(data) db.session.commit()<file_sep>/migrations/versions/121fba6dfadf_added_order_restaurant_and_cleaner_.py """added order, restaurant, and cleaner models Revision ID: <PASSWORD> Revises: <PASSWORD> Create Date: 2019-12-07 21:28:21.560162 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<PASSWORD>' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('cleaner', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('name', sa.String(length=100), nullable=True), sa.Column('num_boxes', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('driver', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('email', sa.String(length=255), nullable=False), sa.Column('registered_on', sa.DateTime(), nullable=False), sa.Column('admin', sa.Boolean(), nullable=False), sa.Column('public_id', sa.String(length=100), nullable=True), sa.Column('username', sa.String(length=50), nullable=True), sa.Column('password_hash', sa.String(length=100), nullable=True), sa.Column('num_boxes', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email'), sa.UniqueConstraint('public_id'), sa.UniqueConstraint('username') ) op.create_table('order', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('grubhub_user', sa.Integer(), nullable=True), sa.Column('grubhub_driver', sa.Integer(), nullable=True), sa.Column('restaurant', sa.Integer(), nullable=True), sa.Column('boxes_given', sa.Integer(), nullable=True), sa.Column('boxes_owed', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('restaurant', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('name', sa.String(length=100), nullable=True), sa.Column('num_boxes', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.drop_table('Driver') op.add_column('user', sa.Column('grubhub_id', sa.Integer(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('user', 'grubhub_id') op.create_table('Driver', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('email', sa.VARCHAR(length=255), nullable=False), sa.Column('registered_on', sa.DATETIME(), nullable=False), sa.Column('admin', sa.BOOLEAN(), nullable=False), sa.Column('public_id', sa.VARCHAR(length=100), nullable=True), sa.Column('username', sa.VARCHAR(length=50), nullable=True), sa.Column('password_hash', sa.VARCHAR(length=100), nullable=True), sa.Column('destination', sa.VARCHAR(length=100), nullable=True), sa.Column('num_boxes', sa.INTEGER(), nullable=True), sa.CheckConstraint('admin IN (0, 1)'), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email'), sa.UniqueConstraint('public_id'), sa.UniqueConstraint('username') ) op.drop_table('restaurant') op.drop_table('order') op.drop_table('driver') op.drop_table('cleaner') # ### end Alembic commands ### <file_sep>/app/main/model/box.py from .. import db, flask_bcrypt import datetime from app.main.model.blacklist import BlacklistToken from ..config import key import jwt # Box class inherits from db.Model class which declares the class as a model for sqlalchemy class Box(db.Model): """ Box Model for storing box related details """ __tablename__ = "box" id = db.Column(db.Integer, primary_key=True, autoincrement=True) registered_on = db.Column(db.DateTime, nullable=False) trips = db.Column(db.Integer) # number of trips box has made driver = db.Column(db.String, nullable=True) # TODO: Chain Restaurant = String # TODO: Number of Trips = Integer # TODO: Recent Users = array(queue) of last 5 users # TODO: Material (assuming there are many types of boxes): String public_id = db.Column(db.String(100), unique=True) def __repr__(self): return "<Box '{}'>".format(self.id) <file_sep>/Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] alembic = "==1.3.1" anaconda-client = "==1.2.2" aniso8601 = "==8.0.0" astroid = "==2.2.5" atomicwrites = "==1.3.0" attrs = "==19.1.0" bcrypt = "==3.1.7" cachetools = "==3.1.0" certifi = "==2019.3.9" cffi = "==1.13.2" chardet = "==3.0.4" click = "==7.0" clyent = "==1.2.1" envparse = "==0.2.0" flask-restplus = "==0.13.0" google-api-python-client = "==1.7.8" google-auth = "==1.6.3" google-auth-httplib2 = "==0.0.3" google-auth-oauthlib = "==0.2.0" gunicorn = "==20.0.4" h5py = "==2.10.0" httplib2 = "==0.12.1" idna = "==2.8" importlib-metadata = "==0.23" isort = "==4.3.15" itsdangerous = "==1.1.0" jsonschema = "==3.2.0" lazy-object-proxy = "==1.3.1" mccabe = "==0.6.1" more-itertools = "==7.0.0" numpy = "==1.17.3" oauthlib = "==3.0.1" pbr = "==5.4.3" pluggy = "==0.9.0" psycopg2 = "==2.8.3" py = "==1.8.0" pyasn1 = "==0.4.5" pyasn1-modules = "==0.2.4" pycparser = "==2.19" pylint = "==2.3.1" pyrsistent = "==0.15.5" pytest = "==4.4.0" python-dateutil = "==2.8.1" python-dotenv = "==0.10.3" python-editor = "==1.0.4" pytz = "==2019.3" requests = "==2.21.0" requests-oauthlib = "==1.2.0" rsa = "==4.0" scipy = "==1.3.1" six = "==1.13.0" stevedore = "==1.31.0" typed-ast = "==1.3.1" uritemplate = "==3.0.0" urlfetch = "==1.1.1" urllib3 = "==1.24.1" virtualenv = "==16.4.3" virtualenv-clone = "==0.5.3" virtualenvwrapper = "==4.8.4" wrapt = "==1.11.1" zipp = "==0.6.0" Flask = "==1.1.1" Flask-Bcrypt = "==0.7.1" Flask-Cors = "==3.0.8" Flask-Migrate = "==2.5.2" Flask-Script = "==2.0.6" Flask-SQLAlchemy = "==2.4.1" Flask-Testing = "==0.7.1" Jinja2 = "==2.10.1" Keras = "==2.3.1" Keras-Applications = "==1.0.8" Keras-Preprocessing = "==1.1.0" Mako = "==1.1.0" MarkupSafe = "==1.1.1" Pillow = "==6.1.0" PyJWT = "==1.7.1" PyYAML = "==5.1.2" SQLAlchemy = "==1.3.11" Werkzeug = "==0.15.6" psycopg2-binary = "==2.8.4" [requires] python_version = "3.7" <file_sep>/app/main/controller/restaurant_controller.py from flask import request from flask_restplus import Resource from ..util.dto import RestaurantDto from ..util.decorator import token_required, admin_token_required from ..service.restaurant_service import save_new_restaurant, get_all_restaurants, get_a_restaurant from functools import wraps api = RestaurantDto.api _restaurant = RestaurantDto.restaurant @api.route('/') class RestaurantList(Resource): @api.doc('list_of_registered_restaurants', security='apiKey') # TODO: @admin_token_required @api.marshal_list_with(_restaurant, envelope='data') def get(self): """List all registered restaurants""" return get_all_restaurants() @api.doc('create a new restaurant') @api.response(201, 'Restaurant successfully created.') @api.expect(_restaurant, validate=True) def post(self): """Creates a new Restaurant""" data = request.json return save_new_restaurant(data=data)<file_sep>/app/main/controller/driver_controller.py from flask import request from flask_restplus import Resource from ..util.dto import DriverDto from ..util.decorator import token_required, admin_token_required from ..service.driver_service import save_new_driver, get_all_drivers, get_a_driver from functools import wraps api = DriverDto.api _driver = DriverDto.driver @api.route('/') class DriverList(Resource): @api.doc('list_of_registered_drivers', security='apiKey') # TODO: @admin_token_required @api.marshal_list_with(_driver, envelope='data') def get(self): """List all registered drivers""" return get_all_drivers() @api.doc('create a new driver') @api.response(201, 'Driver successfully created.') @api.expect(_driver, validate=True) def post(self): """Creates a new Driver""" data = request.json return save_new_driver(data=data) # TODO: class Driver(Resource) @api.route('/driver') class Driver(Resource): @api.doc('get_a_driver', security='apiKey') # TODO: @admin_token_required @api.marshal_list_with(_driver, envelope='data') def get(self): """List all registered users""" return get_a_driver() <file_sep>/app/main/controller/box_controller.py from flask import request from flask_restplus import Resource from ..util.dto import BoxDto from ..util.decorator import token_required, admin_token_required from ..service.box_service import save_new_box, get_all_boxes, get_a_box from functools import wraps api = BoxDto.api _box = BoxDto.box @api.route('/boxes') class BoxList(Resource): @api.doc('list_of_registered_boxes', security='apiKey') @api.marshal_list_with(_box, envelope='data') # get all boxes def get(self): """List all registered boxes""" return get_all_boxes() @api.doc('create a new box') @api.response(201, 'Box successfully created.') @api.expect(_box, validate=True) # CREATE # create a box def post(self): """Creates a new Box """ data = request.json return save_new_box(data=data) @api.route('/<public_id>') @api.param('public_id', 'The Box identifier') @api.response(404, 'Box not found.') class Box(Resource): # READ # get a box @api.doc('get a box', security='apiKey') @api.marshal_with(_box) def get(self, public_id): """get a box given its identifier""" box = get_a_box(public_id) if not box: api.abort(404) else: return box # UPDATE # update box location @api.doc('update a box', security='apiKey') @api.marshal_with(_box) def update(self, public_id): """get a box given its identifier""" box = get_a_box(public_id) if not box: api.abort(404) else: db.session.update(box) db.session.commit() return redirect("/") # DESTROY # delete a box @api.doc('delete a box', security='apiKey') @api.marshal_with(_box) def delete(self, public_id): """get a box given its identifier""" box = get_a_box(public_id) if not box: api.abort(404) else: db.session.delete(box) db.session.commit() return redirect("/") # READ # get the box driver @api.route('/foodOrdered/<public_id>') @api.param('public_id', 'box driver') @api.doc('get the driver', security='apiKey') @api.marshal_with(_box) def get(self, public_id): """get a driver given its identifier""" driver = get_box_driver(public_id) if not driver: api.abort(404) else: return driver <file_sep>/app/main/model/order.py from .. import db, flask_bcrypt import datetime from app.main.model.blacklist import BlacklistToken from ..config import key import jwt class Order(db.Model): __tablename__ = "order" id = db.Column(db.Integer, primary_key=True, autoincrement=True) confirmation = db.Column(db.String(100), unique=True) grubhub_user = db.Column(db.Integer, unique=True, nullable=False) grubhub_driver = db.Column(db.Integer, unique=True, nullable=False) restaurant_id = db.Column(db.Integer) boxes_given = db.Column(db.Integer) boxes_owed = db.Column(db.Integer) def __repr__(self): return "<Order '{}'>".format(self.id)<file_sep>/app/main/util/dto.py from flask_restplus import Namespace, fields class AuthDto: api = Namespace('auth', description='authentication operations') user_auth = api.model('auth', { 'email': fields.String(required=True, description='The email address'), 'password': fields.String(required=True, description='The user password '), }) class UserDto: api = Namespace('user', description='user operations') user = api.model('user', { 'email': fields.String(required=True, description='user email address'), 'username': fields.String(required=True, description='user username'), 'password': fields.String(required=True, description='user password'), 'public_id': fields.String(description='user Identifier') }) class DriverDto: api = Namespace('driver', description='driver operations') driver = api.model('driver', { 'email': fields.String(required=True, description='driver email address'), 'username': fields.String(required=True, description='driver username'), 'password': fields.String(required=True, description='driver <PASSWORD>'), 'public_id': fields.String(description='driver Identifier'), 'num_boxes': fields.Integer(description='driver num of boxes') }) class RestaurantDto: api = Namespace('restaurant', description='restaurant operations') restaurant = api.model('restaurant', { 'name': fields.String(required=True, description='restaurant name'), 'num_boxes': fields.Integer(description='restaurant num of boxes') }) class CleanerDto: api = Namespace('cleaner', description='cleaner operations') cleaner = api.model('cleaner', { 'name': fields.String(required=True, description='cleaner name'), 'num_boxes': fields.Integer(description='cleaner num of boxes') }) class OrderDto: api = Namespace('order', description='order operations') order = api.model('order', { 'grubhub_user': fields.Integer(required=True, description='grubhub user id'), 'grubhub_driver': fields.Integer(required=True, description='grubhub driver id'), 'restaurant': fields.Integer(required=True, description='restaurant id'), 'boxes_given': fields.Integer(description='number of boxes being given'), 'boxes_owed': fields.Integer(description='number of boxes user owes') }) class BoxDto: api = Namespace('box', description='box operations') box = api.model('box', { 'id': fields.String(required=True, description='box ids'), 'registered_on': fields.String(required=True, description='registration'), 'trips': fields.String(required=False, description='trips'), 'driver': fields.String(required=False, description='driver'), 'public_id': fields.String(required=True, description='public id') }) <file_sep>/app/main/service/cleaner_service.py import uuid import datetime from app.main import db from app.main.model.cleaner import Cleaner def get_all_cleaners(): return Cleaner.query.all() def save_changes(data): # commits the changes to database db.session.add(data) db.session.commit()<file_sep>/app/__init__.py # app/__init__.py from flask_restplus import Api from flask import Blueprint from .main.controller.auth_controller import api as auth_ns from .main.controller.user_controller import api as user_ns from .main.controller.driver_controller import api as driver_ns from .main.controller.order_controller import api as order_ns from .main.controller.restaurant_controller import api as restaurant_ns from .main.controller.cleaner_controller import api as cleaner_ns blueprint = Blueprint('api', __name__) # TODO: Authorizations authorizations = { 'apikey': { 'type': 'apiKey', 'in': 'header', 'name': 'X-API-KEY' } } api = Api(blueprint, title='Re.Box Backend', version='1.0', authorizations=authorizations, description='the resuable food box api' ) api.add_namespace(auth_ns) api.add_namespace(user_ns, path='/user') api.add_namespace(driver_ns, path='/driver') api.add_namespace(order_ns, path='/order') api.add_namespace(restaurant_ns, path='/restaurant') api.add_namespace(cleaner_ns, path='/cleaner')<file_sep>/app/main/service/restaurant_service.py import uuid import datetime from app.main import db from app.main.model.restaurant import Restaurant def save_new_restaurant(restaurant): restaurant = Restaurant.query.filter_by(name=data['name']).first() if not restaurant: new_restaurant = Restaurant( public_id=str(uuid.uuid4()), name=data['name'], num_boxes=data['num_boxes'], restaurant_id=data['restaurant_id'] ) save_changes(new_restaurant) response_object = { 'status': 'success', 'message': 'Successfully registered restaurant.' } return response_object, 201 else: response_object = { 'status': 'fail', 'message': 'Restaurant already exists.', } return response_object, 409 def get_a_restaurant(name): return Restaurant.query.filter_by(name=name).first() def get_all_restaurants(): return Restaurant.query.all() def save_changes(data): # commits the changes to database db.session.add(data) db.session.commit()<file_sep>/app/main/controller/order_controller.py from flask import request from flask_restplus import Resource from ..util.dto import OrderDto from ..util.decorator import token_required, admin_token_required from ..service.order_service import save_new_order, get_all_orders, get_an_order from functools import wraps api = OrderDto.api _order = OrderDto.order @api.route('/') class OrderList(Resource): @api.doc('list_of_registered_orders', security='apiKey') # TODO: @admin_token_required @api.marshal_list_with(_order, envelope='data') def get(self): """List all registered orders""" return get_all_orders() @api.doc('create a new order') @api.response(201, 'Order successfully created.') @api.expect(_order, validate=True) def post(self): """Creates a new Order""" data = request.json return save_new_order(data=data)<file_sep>/app/main/service/order_service.py import uuid import datetime from app.main import db from app.main.model.order import Order def save_new_order(order): order = Order.query.filter_by(confirmation=data['confirmation']).first() if not order: new_order = Order( public_id=str(uuid.uuid4()), confirmation=data['confirmation'], grubhub_user=data['grubhub_user'], grubhub_driver=data['grubhub_driver'], restaurant_id=data['restaurant_id'], boxes_given=data['boxes_given'], boxes_owed=data['boxes_owed'], registered_on=datetime.datetime.utcnow() ) save_changes(new_order) response_object = { 'status': 'success', 'message': 'Successfully registered.' } return response_object, 201 else: response_object = { 'status': 'fail', 'message': 'Order already exists.', } return response_object, 409 def get_all_orders(): return Order.query.all() def get_an_order(confirmation): return Order.query.filter_by(confirmation=confirmation).first() def save_changes(data): # commits the changes to database db.session.add(data) db.session.commit()<file_sep>/app/main/controller/cleaner_controller.py from flask import request from flask_restplus import Resource from ..util.dto import CleanerDto from ..util.decorator import token_required, admin_token_required # from ..service.cleaner_service import save_new_cleaner, get_all_cleaners, get_a_cleaner from ..service.cleaner_service import get_all_cleaners from functools import wraps api = CleanerDto.api _cleaner = CleanerDto.cleaner @api.route('/') class CleanerList(Resource): @api.doc('list_of_registered_cleaners', security='apiKey') # TODO: @admin_token_required @api.marshal_list_with(_cleaner, envelope='data') def get(self): """List all registered cleaners""" return get_all_cleaners() # TODO: Create save new cleaner function # @api.doc('create a new cleaner') # @api.response(201, 'Cleaner successfully created.') # @api.expect(_cleaner, validate=True) # def post(self): # """Creates a new User """ # data = request.json # return save_new_cleaner(data=data)
5aedfaf2712d3461ac2af6604a24069d7ec0c0e0
[ "TOML", "Python" ]
18
Python
kjwilsondev/pizza-box-api
d8990dd6bd510c3417eee43afd1fd2a2c3757425
1d6f6b59bf57bc71e33022d580b6cc82d2b282fc
refs/heads/master
<file_sep>package CRUD.service; /** * Created by sanzhar on 8/23/16. */ import CRUD.User; import java.util.List; public interface UserService { void addUser(User user); void updateUser(User user); void removeUser(int id); User getUser(int id); List<User> getUsers(Long page); List<User> getUsers(String name); List<User> getAdmins(); } <file_sep>CRUD project This is test project for JavaRush.ru It is a simple CRUD application that stores information of Users (ID, Name,age, IsAdmin and date) Project build * Maven; Server * Apache Tomcat 7; Database * MySql * Name:users_db * Table:User, * username= "root", password="<PASSWORD>"; For additional dependency information please read pom.xml file
6f6a66b4cc3b1942187a499ccc18982d00b52d2d
[ "Markdown", "Java" ]
2
Java
satybS/CrudProjectJavaRush
d50aca0d8e78079acea5280a7f5627e6964fb0da
2135d78331a871dedfba62959b3b69cacec2e303
refs/heads/master
<repo_name>vmp6syu/yuntech_Driver_course<file_sep>/week7/select.c #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> int main() { //int fds; int ret; char buf[100]; int timecount; int maxfd; fd_set rfds;//set listen struct timeval tv;//set wating time,0不等待,NULL一直等待。 FD_ZERO(&rfds);//清空集合 timecount = 0; while(1) { FD_SET(STDIN_FILENO, &rfds);//put keyboard input in maxfd = STDIN_FILENO + 1; tv.tv_sec = 5; tv.tv_usec = 0;//set wait time ret = select(maxfd, &rfds, NULL, NULL, &tv); if(ret<0) { printf("select error, process will eixt\n"); exit(0); } else if(FD_ISSET(STDIN_FILENO, &rfds))//test if have data { fgets(buf, 100, stdin); printf("You input is %s\n",buf); } else { timecount++; printf("\ntime out: %d\n", timecount); } } return 0; } <file_sep>/week2/hello.c #include<linux/module.h> #include<linux/init.h> #include<linux/sched.h> #include<linux/kernel.h> MODULE_LICENSE("Dual BSD/GPL"); static int hello_init(void) { printk(KERN_INFO"Hello World!\n"); printk("Process ID:%d\n",current->pid); //printk("Scheduling policy:= %d\n",); printk("over\n"); return 0; } static int hello_exit(void) { printk(KERN_INFO "driver unloaded\n"); } module_init(hello_init); module_exit(hello_exit); <file_sep>/week3_HW/abc.c #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/time.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #include<errno.h> #define DEVFILE "/dev/test" int open_file(char *filename) { int fd; fd=open(filename, O_RDWR); if(fd == -1){ perror("open"); } return (fd); } void close_file(int fd) { if(close(fd)!=0){ perror("close"); } } void read_file(int fd) { char *buf ; ssize_t ret; ret=read(fd,buf,sizeof(buf)); printf("%s",buf); perror("read"); printf("\n"); } void write_file(int fd,char *val) { ssize_t ret; ret=write(fd,val,sizeof(val)); printf("you enter:%s\n",val); if(ret <= 0) { perror("write"); } } int main(void) { int i; int fd; int mode; char *s; printf("1=read from device\n"); printf("2=write to device\n"); printf("chose mode:"); scanf("%d",&mode); fd=open_file(DEVFILE); switch(mode) { case 1: read_file(fd); break; case 2: printf("enter:"); scanf("%s",s); write_file(fd, s); break; default: printf("enter error"); } return 0; } <file_sep>/week7/aaa.c #include<stdio.h> #include<string.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <poll.h> int main(int argc , char *argv[]) { int fd; char buf[11]; int ret; struct pollfd fds; int retval; while(1) { do { fds.fd = fd; fds.events = POLLIN; retval = poll(&fds, 1, 5 * 1000); printf("retval:%d\n",retval); if (retval == -1) { perror("poll"); printf("123"); break; } if (retval) { memset((void *)buf,0,11); ret =read(fd,(void * )buf,10); printf("ret=%d\n",ret); if (ret != -1) { printf("buf=%s\n",buf); } break; } printf("timeout!!!\n"); } while (retval == 0); /* timeout elapsed */ } return 0; } <file_sep>/week2/Makefile PWD :=$(shell pwd) obj-m := hello.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) cleam <file_sep>/week7/aaa2.c #include<stdio.h> #include<string.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <poll.h> int main(int argc , char *argv[]) { int fd; fd_set rfds; struct timeval tv; char buf[11]; int ret; int retval; while(1) { do { FD_ZERO(&rfds); FD_SET(fd, &rfds); tv.tv_sec = 5; tv.tv_usec = 0; printf("select()...\n"); retval = select(fd + 1, &rfds, NULL, NULL, &tv); if (retval==-1) { perror("poll"); break; } if (retval) { break; } memset((void *)buf,0,11); ret =read(fd,(void * )buf,10); if(ret!=-1) { printf("ret=%d\n",ret); if (ret != -1) { printf("buf=%s\n",buf); } } else { printf("timeout\n"); } } while (retval == 0); /* timeout elapsed */ } return 0; } <file_sep>/week5/hello.c #include<linux/kernel.h> #include<unistd.h> #include<sys/syscall.h> #include<stdio.h> int main(){ long int sys = syscall(548); printf("sys_hello returned %ld\n",sys); return 0 ; } <file_sep>/devone.c #include<linux/init.h> #include<linux/module.h> #include<linux/types.h> #include<linux/kernel.h> #include<linux/fs.h> #include<linux/cdev.h> #include<linux/sched.h> #include<asm/current.h> #include<asm/uaccess.h> MODULE_LICENSE("Dual BSD/GPL"); #denfine DRIVER_NAME "devonw" static int devone_devs =1; static int devone_major = 0; module_param(devone_major , uint,0); static struct cdev devonw_cdev; struct devone_data{ unsigned char val; rwlock_t lock; }; ssize_t devone_write(struct file *filp,const char __user *buf,size_t count ,loff_t *f_pos) { struct devone_data 8p =filp->private_data; unsigned char val; int retval= 0; printk("%s:count %d pos %lld\n",__func__,count, *f_pos); if(count >=1){ if(copy_from_user(&val, &buf[0],1)){ retvail=-EFAULT; goto out; } write_lock(&p->lock); p->val=val; write_unlock(&p->lock); retval=count; } out: return (retval); } <file_sep>/week3_HW/test.c #include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/cdev.h> #include <linux/semaphore.h> #include <asm/uaccess.h> #include <linux/uaccess.h> //*1 Creat a structure for our test device struct test_device { char data[100]; struct semaphore sem; } virtual_device; //*2 To later register our device it needs a cdev object and some variables struct cdev *mcdev; //m stands 'my' int major_number; //store our major number int ret; //used to hold return values of functions dev_t dev_num; //hold major numbel that kernel give #define DEVICE_NAME "testdevice" //name --> appeas in /proc/devices //****************************************************************************************************** //*7 called on device_file open int device_open(struct inode *inode, struct file *filp){ //only allow one process to open this device by using a semaphore as mutual exclusve lock- mutex if(down_interruptible(&virtual_device.sem) !=0){ printk(KERN_ALERT "test: couldn't lock device during open"); return -1; } printk(KERN_INFO "test: open device"); return 0; } //****************************************************************************************************** //****************************************************************************************************** //*8 called when user want to get information from the device ssize_t device_read(struct file* filp, char* bufStoreData, size_t bufCount, loff_t* curOffset){ //take data from kernel space(device) to user space(process) printk(KERN_INFO "test: reading from device"); ret = copy_to_user(bufStoreData, virtual_device.data, bufCount); return ret; } //****************************************************************************************************** //****************************************************************************************************** //*9 called when user want to send information to the device ssize_t device_write(struct file* filp, const char* bufStoreData, size_t bufCount, loff_t* curOffset){ //send data from user kernel printk(KERN_INFO "test: writing to device"); ret=copy_from_user(virtual_device.data, bufStoreData, bufCount); return ret; } //****************************************************************************************************** //****************************************************************************************************** //*7 called upon user close int device_close(struct inode *inode, struct file *filp){ up(&virtual_device.sem); printk(KERN_INFO "test: close device"); return 0; } //****************************************************************************************************** //****************************************************************************************************** //*6 tell the kernel which functions to call when user operates on our device file struct file_operations fops = { .owner = THIS_MODULE, //prevent unloadind of this module when operations are in use .open = device_open, //points to the method to call when opening the device .release = device_close, //points to the method to call when closing the device .write = device_write, //points to the method to call when writing to the device .read = device_read //points to the method to call when reading from the device }; //****************************************************************************************************** //*3 register our device with the system: a teo process static int driver_entry(void){ //step 1 use dynamic allocation to assign our devicce ret = alloc_chrdev_region(&dev_num,0,1,DEVICE_NAME); if(ret<0){ printk(KERN_ALERT "test: failed to allocate amajor number"); return ret; //propagate error } major_number = MAJOR(dev_num); //extracts the major number and store our variable printk(KERN_INFO "test: major number is %d" ,major_number); printk(KERN_INFO "use \"mknod /dev/%s c %d 0\" for device file",DEVICE_NAME, major_number); //dmesg //step 2 mcdev = cdev_alloc(); //cerat our cdev structure, initialized our cdev mcdev->ops = &fops; mcdev->owner = THIS_MODULE; //that we creat cdev, we have to add it to kernel ret = cdev_add(mcdev, dev_num, 1); if(ret<0){ //check errors printk(KERN_ALERT "test: unable to add cdev to kernel"); return ret; } //*4 Initialize our semaphore sema_init(&virtual_device.sem,1); //initial value of one return 0; } static void driver_exit(void){ //*5 unregister everything in reverse order //a) cdev_del(mcdev); //b) unregister_chrdev_region(dev_num, 1); printk(KERN_ALERT "test: unloaded module"); } //inform the kernel where to start and stop with our module/driver module_init(driver_entry); module_exit(driver_exit);
dc463bde42b488daa76aab83d2e482addd1a0929
[ "C", "Makefile" ]
9
C
vmp6syu/yuntech_Driver_course
4674f9a52918cec605fa6d39da56bbdeb9693aaa
971512cbb7dfc3f0c74183fc86b56ede0874f3b5
refs/heads/master
<file_sep>public class SimHash { /** * Generate 64 bit simhash for a string * * @param s * @return */ public static long simHash64(String s) { long result = 0; int[] bitVector = new int[64]; String[] words = s.split("[\\s()\\-\\/]+"); for (String word : words) { if (word.isEmpty()) { continue; } long hash = fvnHash64(word); for (int i = 0; i < bitVector.length; i++) { bitVector[i] += (hash & 1) == 1 ? 1 : -1; hash = hash >> 1; } } for (int i = 0; i < bitVector.length; i++) { result = result << 1; if (bitVector[i] > 0) { result += 1; } } return result; } /** * Count different bits between two numbers * * @param a * @param b * @return */ public static int hammingDistance(long a, long b) { int dist = 0; a = a ^ b; while (a != 0) { a &= a - 1; dist++; } return dist; } /** * Generate 64 bit FVN hash for a string * @param s * @return */ public static long fvnHash64(String s) { long basis = 0xcbf29ce484222325L; long prime = 0x100000001b3L; for (int i = 0; i < s.length(); i++) { basis ^= s.charAt(i); basis *= prime; } return basis; } } <file_sep># simhash Java implementation of simhash algorithm
c76297add7575e4d9ebbb060e31196ea9a1277ad
[ "Markdown", "Java" ]
2
Java
haohany/simhash
fee03f314fbd32bd890a41eac1efd561e18c8343
eeccd9038d99ce977606cbc955171bbc06c5a5f7
refs/heads/master
<file_sep>const path = require('path'); const webpack = require('webpack'); const nodeEnv = process.env.NODE_ENV || 'development'; const isProd = nodeEnv === 'production'; console.log(`Building for environment: ${nodeEnv}`); const plugins = [ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity, filename: 'vendor.bundle.js' }), new webpack.optimize.DedupePlugin(), // expose buddybuild env vars. new webpack.EnvironmentPlugin([ "BUDDYBUILD_BUILD_NUMBER", "BUDDYBUILD_BRANCH" ]) ]; if (isProd) { plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: false, minimize: true, comments: false, mangle: false })); } module.exports = { devtool: isProd ? undefined : 'source-map', entry: { js: path.resolve(__dirname, 'app/app.ts'), vendor: [ path.normalize('es6-shim/es6-shim.min'), 'reflect-metadata', 'zone.js/dist/zone', 'ionic-angular' ] }, output: { path: path.resolve('www/build'), filename: 'app.bundle.js', pathinfo: false, publicPath: "/" }, module: { preLoaders: [{ test: /\.ts$/, loader: 'tslint' }], loaders: [{ test: /\.ts$/, loader: 'awesome-typescript', query: { doTypeCheck: false, resolveGlobs: false }, include: [path.resolve(__dirname, 'app')], exclude: /node_modules/ }, { test: /\.js$/, include: path.resolve('node_modules'), loader: 'strip-sourcemap' }, { test: /\.html$/, loader: 'html' }, { test: /\.json/, loader: 'json' }, { test: /.*\.(scss|css)$/i, loaders: [ 'style', 'css', 'sass' ] }, { test: /.*\.(gif|png|jpg|jpeg)$/i, loaders: [ 'file?hash=sha512&digest=hex&name=build/[hash].[ext]', 'image-webpack?{progressive:true, optimizationLevel: 1, interlaced: false, pngquant:{quality: "65-90", speed: 10}}' ] }, { test: /\.(eot|woff|ttf|svg|otf)$/, loader: 'url?limit=1000' }], noParse: [ /es6-shim/, /reflect-metadata/, /zone\.js(\/|\\)dist(\/|\\)zone-microtask/ ] }, tslint: { emitErrors: true }, resolve: { extensions: ['', '.js', '.ts'], modules: [ path.resolve(__dirname, 'app'), 'node_modules' ], alias: { assets: path.resolve(__dirname, 'app/assets'), components: path.resolve(__dirname, 'app/components'), models: path.resolve(__dirname, 'app/models'), pages: path.resolve(__dirname, 'app/pages'), pipes: path.resolve(__dirname, 'app/pipes'), services: path.resolve(__dirname, 'app/services'), utils: path.resolve(__dirname, 'app/utils') } }, plugins }; <file_sep>import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Observable } from 'rxjs/Observable'; import { Injectable } from 'angular2/core'; import { Http } from 'angular2/http'; const API_URL = (path = '') => `http://www.nhtsa.gov/webapi/api/SafetyRatings/${path}?format=json`; @Injectable() export class NHTSAService { constructor(private http: Http) { } getSafetyRatings() { let url = API_URL(); return this.http .get(url) .map(res => res.json()) .catch(this.handleError); } getModelYearDetails(modelYear) { let url = API_URL(`modelyear/${modelYear}`); return this.http .get(url) .map(res => res.json()) .catch(this.handleError); } getMakeDetails(modelYear, make) { let url = API_URL(`modelyear/${modelYear}/make/${make}`); return this.http .get(url) .map(res => res.json()) .catch(this.handleError); } getModelDetails(modelYear, make, model) { let url = API_URL(`modelyear/${modelYear}/make/${make}/model/${model}`); return this.http.get(url) .map(res => res.json()) .catch(this.handleError); } getVehicleDetails(vehicleId) { let url = API_URL(`VehicleId/${vehicleId}`); return this.http.get(url) .map(res => res.json()) .catch(this.handleError); } private handleError(error) { console.error('private handleError', error); if (error.json()) { return Observable.throw(error.json().error || 'Server error'); } } } <file_sep>import { App, Platform, Modal, NavController, Loading } from 'ionic-angular'; import { IndexView } from './pages/index/index.view'; import { NHTSAService } from './services/nhtsa.service'; @App({ template: `<ion-nav id="nav" [root]="indexView"></ion-nav>`, providers: [ NHTSAService ] }) export class NCAP { private indexView = IndexView; constructor( private platform: Platform, ) { this.platform = platform; this.platform.ready().then(() => { console.info('platform ready'); }); } } <file_sep>import {Pipe, PipeTransform} from 'angular2/core'; import * as titleCase from 'title-case'; const ignored = ['BMW', 'GMC', 'AWD', 'CX-3', 'CX-5', 'MX-5', 'CTS', ' DTS', ' ESCALADE', ' ESCALADE ESV', ' ESCALADE EXT', ' SRX', ' STS', ' XLR', ' F-150', ' F-250', ' F-350', ' CR-V', ' FCX', ' LR3', ' SQ5', ' TT', 'TTS']; @Pipe({ name: 'titlecase' }) export class TitleCasePipe implements PipeTransform { transform(value: string) { if (ignored.indexOf(value) === -1) { return titleCase(value); } else { return value; } } } <file_sep>import { Page, Modal, NavController, Loading } from 'ionic-angular'; import { NHTSAService } from '../../services/nhtsa.service'; import { MakeView } from '../make/make.view'; import * as template from './index.view.html'; @Page({ template }) export class IndexView { private modelYears = []; constructor( private nav: NavController, private nhtsa: NHTSAService ) { } /** * When page loads, get the Model Year information */ onPageLoaded() { this.nhtsa.getSafetyRatings().subscribe( (results) => { this.modelYears = results.Results; }, (error) => { console.log(error); }); } goToModelYear(year) { this.nav.push(MakeView, { year }); } }; <file_sep>import { Component, Input } from 'angular2/core'; import { IONIC_DIRECTIVES } from 'ionic-angular'; @Component({ selector: 'stars', directives: [IONIC_DIRECTIVES], template: ` <ionicon tertiary name="star" *ngFor="#times of repeatTimes"></ionicon> <small *ngIf="repeatTimes.length === 0">Not Rated</small> ` }) export class StarsDisplay { @Input() numberOfStars; private repeatTimes; ngOnInit() { const parsedNumber = parseInt(this.numberOfStars, 10) || 0; if (parsedNumber > 0) { this.repeatTimes = Array(parseInt(this.numberOfStars, 10)).fill().map((x, i) => i); } else { this.repeatTimes = []; } } } <file_sep>import { Page, Modal, NavController, NavParams, Loading } from 'ionic-angular'; import { NHTSAService } from '../../services/nhtsa.service'; import { StarsDisplay } from '../../components/stars/stars'; import * as template from './vehicle.view.html'; @Page({ directives: [ StarsDisplay ], template }) export class VehicleDetail { private vehicleId; private selectedVehicle; private loadingVehicle = true; constructor( private nav: NavController, private params: NavParams, private nhtsa: NHTSAService ) { this.vehicleId = this.params.get('vehicleId'); } /** * When page loads, get the available Makes for the model * year that we passed in the params. */ onPageLoaded(): void { this.nhtsa.getVehicleDetails(this.vehicleId).subscribe( (res) => { this.selectedVehicle = res.Results[0]; console.log(this.selectedVehicle); }, (error) => { console.log(error); }); } }; <file_sep>![No longer maintained](https://img.shields.io/badge/Maintenance-OFF-red.svg) ### [DEPRECATED] This repository is no longer maintained > While this project is fully functional, the dependencies are no longer up to date. You are still welcome to explore, learn, and use the code provided here. > > Modus is dedicated to supporting the community with innovative ideas, best-practice patterns, and inspiring open source solutions. Check out the latest [Modus Labs](https://labs.moduscreate.com?utm_source=github&utm_medium=readme&utm_campaign=deprecated) projects. [![Modus Labs](https://res.cloudinary.com/modus-labs/image/upload/h_80/v1531492623/labs/logo-black.png)](https://labs.moduscreate.com?utm_source=github&utm_medium=readme&utm_campaign=deprecated) --- # Framework Shootout - Ionic 2 App using Ionic 2 + Angular 2 ![app](https://cloud.githubusercontent.com/assets/289938/14546593/5a1d352c-025b-11e6-844c-ef0a83a44e62.gif) # Getting Started Make sure you have the ionic beta installed. Also make sure you have the [CORs Chrome Plugin](https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en) plugin installed to allow CORs from your browser. ```bash $ npm install -g ionic@beta ``` After the repo is cloned: ```bash $ npm install $ ionic state restore $ ionic serve ``` <file_sep>// get around TS warnings. declare var process: any; export const apiResource = (resource): string => { const activeUser = localStorage.getItem('activeUser'); if (activeUser) { const sessid = JSON.parse(localStorage.getItem('activeUser')).SessionID; return `https://stage.calamp-ts.com${resource}?sessid=${sessid}`; } else { return `https://stage.calamp-ts.com${resource}`; } }; export const BUILD_NUMBER = process.env.BUDDYBUILD_BUILD_NUMBER || 'Desktop'; export const BUILD_BRANCH = process.env.BUDDYBUILD_BRANCH || 'Desktop'; <file_sep>import { Page, Modal, NavController, NavParams, Loading } from 'ionic-angular'; import { NHTSAService } from '../../services/nhtsa.service'; import { ModelView } from '../model/model.view'; import { TitleCasePipe } from '../../pipes/titleCase.ts'; import * as template from './make.view.html'; @Page({ template, pipes: [ TitleCasePipe ] }) export class MakeView { private availableManufacturers = []; constructor( private nav: NavController, private params: NavParams, private nhtsa: NHTSAService ) {} /** * When page loads, get the available Makes for the model * year that we passed in the params. */ onPageLoaded(): void { const year = this.params.get('year').ModelYear; this.nhtsa.getModelYearDetails(year).subscribe( (res) => { this.availableManufacturers = res.Results; }, (error) => { console.log(error); }); } goToManufacturer(manufacturer) { console.log(manufacturer); this.nav.push(ModelView, { manufacturer }); } }; <file_sep>import { Page, Modal, NavController, NavParams, Loading } from 'ionic-angular'; import { NHTSAService } from '../../services/nhtsa.service'; import { VehicleDetail } from '../vehicle/vehicle.view'; import * as template from './trim.view.html'; @Page({ template }) export class TrimView { private vehicle; private availableVehicles = []; constructor( private nav: NavController, private params: NavParams, private nhtsa: NHTSAService ) { this.vehicle = this.params.get('vehicle'); } /** * When page loads, get the available Makes for the model * year that we passed in the params. */ onPageLoaded(): void { const { ModelYear, Make, Model } = this.params.get('vehicle'); console.log(ModelYear, Make, Model); this.nhtsa.getModelDetails(ModelYear, Make, Model).subscribe( (res) => { this.availableVehicles = res.Results; }, (error) => { console.log(error); }); } getVehicleDetails(vehicle) { this.nav.push(VehicleDetail, { vehicleId: vehicle.VehicleId }); console.log(vehicle); } };
3ba5c7e3005c3426706a7e0749ec0330d38dfff8
[ "JavaScript", "TypeScript", "Markdown" ]
11
JavaScript
isabella232/framework-shootout-ionic2
8e9a590e2014af8ae5cfa6693e252762e1f9ad84
10d695f274eede12a671649fe3ede59c9bfe6559
refs/heads/master
<repo_name>TimTosi/shuntingYard<file_sep>/src/operation/inf_mul.c /* ** inf_mul.c for Bistromathique in /home/tosi_t//TESTBASE ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Aug 13 15:34:51 2013 <NAME> ** Last update Sun Sep 8 22:39:07 2013 tim<NAME> */ #include <stdlib.h> #include "my_str.h" #include "operation.h" #include "uniform.h" #include "my_flags.h" static char _add_digit(char first_digit, char second_digit, char *base, t_add *add) { int i; int j; i = 0; j = 0; if (in_array(first_digit, base) != RETURN_FAILURE) while (first_digit != base[i]) ++i; if (in_array(second_digit, base) != RETURN_FAILURE) while (second_digit != base[j]) ++j; j += add->carry; add->carry = 0; while (j > 0) { ++i; --j; if (base[i] == '\0') { i = 0; add->carry += 1; } } return (base[i]); } static void _init_mul(char first_digit, char second_digit, char *base, int *j, int *buff) { *j = 0; *buff = 0; if (in_array(first_digit, base) != RETURN_FAILURE) while (first_digit != base[*buff]) ++(*buff); if (in_array(second_digit, base) != RETURN_FAILURE) while (second_digit != base[*j]) ++(*j); } static char _mul_digit(char first_digit, char second_digit, char *base, t_add *add) { int i; int j; int buff; int time; i = 0; _init_mul(first_digit, second_digit, base, &j, &buff); while (j > 0) { time = buff; while (time > 0) { ++i; --time; if (base[i] == '\0') { i = 0; add->carry2 += 1; } } --j; } return (base[i]); } static char *_set_sym(char *res, char *f_op, char *s_op, char *base) { if (((in_array(f_op[0], base) != RETURN_FAILURE) && (in_array(s_op[0], base) != RETURN_FAILURE)) || ((in_array(f_op[0], base) == RETURN_FAILURE) && (in_array(s_op[0], base) == RETURN_FAILURE))) return (res); else if (in_array(f_op[0], base) == RETURN_FAILURE) { res[0] = f_op[0]; return (res); } res[0] = s_op[0]; return (res); } char *inf_mul(char *f_op, char *s_op, char *base, char minus) { t_add add; char *res; int x; x = 0; if ((res = op_init(&add, f_op, s_op, base)) == NULL) return (NULL); while (add.j >= 0) { add.k = (my_strlen(res) - (1 + x)); add.i = (my_strlen(f_op) - 1); while (add.i >= 0) { res[add.k] = _add_digit(_mul_digit(f_op[add.i], s_op[add.j], base, &add), res[add.k], base, &add); --(add.i); --(add.k); add.carry += add.carry2; add.carry2 = 0; } res[add.k] = _add_digit(res[add.k], base[0], base, &add); ++x; --(add.j); } return (uniform_result(_set_sym(res, f_op, s_op, base), base, minus)); } <file_sep>/src/linked-list/push_back.c /* ** push_back.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sat Jul 27 19:40:53 2013 <NAME> ** Last update Fri Aug 16 14:21:59 2013 <NAME> */ #include <stdlib.h> #include "linked_list.h" #include "memory.h" #include "my_flags.h" const int push_back(t_linked_list *this, char *content) { t_content *tmp; if ((content == NULL) || (tmp = malloc(sizeof(*tmp))) == NULL) return (RETURN_FAILURE); tmp->content = content; tmp->next = NULL; tmp->prev = this->back; if (this->size == 0) this->front = tmp; else if (this->size == 1) { this->front = this->back; this->front->next = tmp; } else this->back->next = tmp; this->back = tmp; ++(this->size); return (RETURN_SUCCESS); } <file_sep>/inc/uniform.h /* ** uniform.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Sep 4 13:38:28 2013 <NAME> ** Last update Sun Sep 8 19:46:18 2013 tim<NAME>si */ #ifndef UNIFORM_H_ # define UNIFORM_H_ char *uniform_to_zero(char *base, char *origin); char *uniform_result(char *rest, char *base, char minus); char *uniform_sym(char *op1, char *op2, char *res, char minus); const int epure_sym(char *op1, char *op2, char **res1, char **res2, char minus); #endif /* !UNIFORM_H_ */ <file_sep>/src/parser/lexer/p_operand.c /* ** p_operand.c for Bistromathique in /home/tosi_t//BISTRO/src/parser/lexer ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Aug 8 13:46:35 2013 <NAME> ** Last update Sun Sep 8 21:48:57 2013 tim<NAME> */ #include <stdlib.h> #include "parser.h" #include "memory.h" #include "uniform.h" #include "my_str.h" #include "my_flags.h" const int p_operand(t_op *operation, int *i) { int j; j = 0; while ((in_array(operation->input[*i + j], operation->operands)) != RETURN_FAILURE) ++j; if ((push_back(operation->lexeme_list, my_strndup(&(operation->input[*i]), j))) == RETURN_FAILURE) return (RETURN_FAILURE); if ((operation->lexeme_list->back->content = uniform_result(operation->lexeme_list->back->content, operation->operands, operation->operators[3])) == NULL) return (RETURN_FAILURE); operation->lexeme_list->back->type = P_OPERAND; *i += j; return (RETURN_SUCCESS); } <file_sep>/src/operation/op_init.c /* ** op_init.c for Bistromathique in /home/tosi_t//BISTRO/src/operation ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Aug 15 02:15:48 2013 <NAME> ** Last update Sun Aug 18 15:25:22 2013 tim<NAME> */ #include <stdlib.h> #include "operation.h" #include "my_str.h" #include "memory.h" char *op_init(t_add *add, char *first_op, char *second_op, char *base) { char *result; add->carry = 0; add->carry2 = 0; add->i = my_strlen(first_op); add->j = my_strlen(second_op); add->k = (add->i > add->j ? add->i + 2 : add->j + 2); if ((result = malloc(sizeof(*result) * (add->k + 1))) == NULL) return (NULL); result[add->k] = '\0'; my_memset(result, base[0], add->k); --(add)->i; --(add)->j; --(add)->k; return (result); } <file_sep>/src/str/in_array.c /* ** in_array.c for Bistromathique in /home/tosi_t//BISTRO/src/str ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 23 14:23:11 2013 <NAME> ** Last update Tue Jul 23 14:25:11 2013 tim<NAME> */ #include "my_flags.h" const int in_array(char needle, char *heap) { int i; i = 0; while (heap[i] != '\0') { if (heap[i] == needle) return (i); ++i; } return (RETURN_FAILURE); } <file_sep>/src/parser/set_res.c /* ** set_res.c for Bistromathique in /home/tosi_t//BISTRO/src/operation ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Fri Aug 16 13:59:11 2013 <NAME> ** Last update Sun Sep 8 20:46:06 2013 timothe<NAME>si */ #include <stdlib.h> #include "parser.h" t_content *set_res(char *res, t_op *operation) { t_content *container; if ((container = malloc(sizeof(*container))) == NULL) return (NULL); container->content = res; if (((char *)(container->content))[0] == operation->operators[3]) container->type = N_OPERAND; else container->type = P_OPERAND; return (container); } <file_sep>/src/shunting-yard/output_rule.c /* ** output_rule.c for Bistromathique in /home/tosi_t//BISTRO/src/shunting-yard ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Aug 4 14:36:31 2013 <NAME> ** Last update Sun Aug 4 17:11:32 2013 tim<NAME> */ #include "shunting_yard.h" #include "my_flags.h" const int output_rule(t_op *operation, t_shunting *shunting) { while (shunting->operator_stack->size > 0) { if ((shunting->operator_stack->front->type == WP_OPERATOR) || (shunting->operator_stack->front->type == SP_OPERATOR)) push_back_elem(operation->postfix_notation, pop_front_elem(shunting->operator_stack)); else return (RETURN_FAILURE); } return (RETURN_SUCCESS); } <file_sep>/src/str/my_puterror.c /* ** my_puterror.c for Bistromathique in /home/tosi_t//BISTRO/src/str ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Jul 18 11:18:51 2013 <NAME> ** Last update Sun Sep 8 21:02:06 2013 tim<NAME> */ #include <unistd.h> #include "my_flags.h" #include "my_str.h" const int my_puterror(char *str) { (void) write(ERROR_OUTPUT, str, my_strlen(str)); return (RETURN_FAILURE); } <file_sep>/src/linked-list/push_back_elem.c /* ** push_back_elem.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 30 14:06:46 2013 <NAME> ** Last update Tue Jul 30 14:10:33 2013 <NAME> */ #include <stdlib.h> #include "linked_list.h" #include "my_flags.h" const int push_back_elem(t_linked_list *this, t_content *content) { content->next = NULL; content->prev = this->back; if (this->size == 0) this->front = content; else if (this->size == 1) { this->front = this->back; this->front->next = content; } else this->back->next = content; this->back = content; ++(this->size); return (RETURN_SUCCESS); } <file_sep>/src/param/check_param.c /* ** check_param.c for Bistromathique in /home/tosi_t//BISTRO/src/error ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Fri Jul 12 19:53:12 2013 <NAME> ** Last update Sun Sep 8 20:57:10 2013 timothee tosi */ #include "check_param.h" #include "my_flags.h" #include "my_str.h" static const int _check_param_nb(int param_nb, char *name) { if (param_nb != 4) { my_puterror("Usage : "); my_puterror(name); my_puterror(" base ops\"()+-*/%\" exp_len\n"); return (RETURN_FAILURE); } return (RETURN_SUCCESS); } static const int _check_size_read(char *str) { if ((is_number(str) == RETURN_FAILURE)) return (RETURN_FAILURE); return (RETURN_SUCCESS); } const int check_param(const int param_nb, char **param_tab) { if ((_check_param_nb(param_nb, param_tab[0]) == RETURN_FAILURE) || (check_op(param_tab) == RETURN_FAILURE) || (_check_size_read(param_tab[3]) == RETURN_FAILURE)) return (RETURN_FAILURE); return (RETURN_SUCCESS); } <file_sep>/inc/parser.h /* ** parser.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Mon Jul 22 10:36:38 2013 <NAME> ** Last update Fri Aug 16 14:18:05 2013 timothee tosi */ #ifndef PARSER_H_ # define PARSER_H_ # include "operation.h" typedef enum { L_BRACKET, R_BRACKET, SP_OPERATOR, WP_OPERATOR, P_OPERAND, N_OPERAND } token_id; typedef struct s_parser_rule { const int (*ptr_func)(t_op *operation, t_content **tmp); token_id id; } t_parser_rule; const int lexer(t_op *operation); const int parser(t_op *operation); const int l_bracket(t_op *operation, int *i); const int r_bracket(t_op *operation, int *i); const int sp_operator(t_op *operation, int *i); const int wp_operator(t_op *operation, int *i); const int p_operand(t_op *operation, int *i); const int n_operand(t_op *operation, int *i); const int parse_l_bracket(t_op *operation, t_content **tmp); const int parse_r_bracket(t_op *operation, t_content **tmp); const int parse_sp_operator(t_op *operation, t_content **tmp); const int parse_wp_operator(t_op *operation, t_content **tmp); const int parse_operand(t_op *operation, t_content **tmp); t_content *set_res(char *res, t_op *operation); #endif /* !PARSER_H_ */ <file_sep>/inc/my_str.h /* ** my_str.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Fri Jul 12 19:46:36 2013 <NAME> ** Last update Sun Sep 8 21:02:40 2013 tim<NAME> */ #ifndef MY_STR_H_ # define MY_STR_H_ const int is_number(char *str); const int in_array(char needle, char *heap); const int str_base_cmp(char *str1, char *str2, char *base); int my_getnbr(char *str); int my_strlen(char *str); char *my_strcpy(char *origin, char *dest); void my_putstr(char *str); const int my_puterror(char *str); #endif /* !MY_STR_H_ */ <file_sep>/inc/operation.h /* ** operation.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Jul 18 17:48:05 2013 <NAME> ** Last update Wed Sep 4 19:02:13 2013 tim<NAME> */ #ifndef OPERATION_H_ # define OPERATION_H_ # include "linked_list.h" typedef enum { ADDITION, SUBTRACTION, DIVISION, MULTIPLICATION, MODULO } operation_id; typedef struct s_op { char *operators; char *operands; char *input; t_content *infix_notation; t_linked_list *lexeme_list; t_linked_list *postfix_notation; int size_read; } t_op; typedef struct s_add { int carry; int carry2; int i; int j; int k; } t_add; char *op_init(t_add *add, char *first_op, char *second_op, char *base); char *inf_add(char *first_op, char *sec_op, char *base, char minus); char *inf_sub(char *first_op, char *sec_op, char *base, char minus); char *inf_mul(char *first_op, char *sec_op, char *base, char minus); char *inf_div(char *first_op, char *sec_op, char *base, char minus); char *set_dividend(char *divisor, char *base, char minus, int x); #endif /* !OPERATION_H_ */ <file_sep>/src/uniform/uniform_result.c /* ** set_div_rest.c for Bistromathique in /home/tosi_t//INF_DIV/src/misc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Aug 20 02:53:40 2013 <NAME> ** Last update Sun Sep 8 21:41:00 2013 tim<NAME> */ #include <stdlib.h> #include "uniform.h" static char *_set_final_rest(char *rest, char *final_rest, char minus, int i, char sym) { int j; j = 0; if (sym == minus) { final_rest[0] = minus; ++j; } while (rest[i] != '\0') { final_rest[j] = rest[i]; ++i; ++j; } final_rest[j] = '\0'; free(rest); return (final_rest); } char *uniform_result(char *rest, char *base, char minus) { char *final_rest; char sym; int i; int j; int k; i = 0; k = 0; sym = rest[0]; if (rest[0] == minus) ++k; while ((rest[i] == base[0]) || (rest[i] == minus)) ++i; if (rest[i] == '\0') return (uniform_to_zero(base, rest)); j = i; while (rest[i] != '\0') { ++i; ++k; } if ((final_rest = malloc(sizeof(*final_rest) * (k + 1))) == NULL) return (NULL); return (_set_final_rest(rest, final_rest, minus, j, sym)); } <file_sep>/src/linked-list/show_node.c /* ** show_node.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Jul 28 21:40:15 2013 <NAME> ** Last update Wed Aug 7 14:21:21 2013 <NAME> */ #include <stdlib.h> #include "linked_list.h" #include "my_str.h" void show_node(t_linked_list *list) { t_content *tmp; tmp = list->front; while (tmp != NULL) { my_putstr(tmp->content); my_putstr("\n"); tmp = tmp->next; } } <file_sep>/src/uniform/epure_sym.c /* ** epure_sym.c for Bistromathique in /home/tosi_t//BISTRO/src/uniform ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Sep 4 18:30:45 2013 <NAME> ** Last update Wed Sep 4 18:36:22 2013 tim<NAME> */ #include <stdlib.h> #include "memory.h" #include "my_flags.h" const int epure_sym(char *op1, char *op2, char **res1, char **res2, char minus) { if ((op1[0] == minus) && ((*res1 = my_strdup(&op1[1])) == NULL)) return (RETURN_FAILURE); else if ((*res1 = my_strdup(op1)) == NULL) return (RETURN_FAILURE); if ((op2[0] == minus) && ((*res2 = my_strdup(&op2[1])) == NULL)) return (RETURN_FAILURE); else if ((*res2 = my_strdup(op2)) == NULL) return (RETURN_FAILURE); return (RETURN_SUCCESS); } <file_sep>/src/operation/inf_mult.c /* ** inf_mult.c for Bistromathique in /home/tosi_t//BISTRO/src/operation ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sat Aug 10 18:53:36 2013 <NAME> ** Last update Sat Aug 10 19:12:06 2013 tim<NAME> */ #include "operation.h" #include "my_str.h" char *inf_mult(t_content *first_op, t_content *second_op, t_op *operation) { return ("18"); } <file_sep>/src/shunting_yard.c /* ** bistromathique.c for Bistromatique in /home/tosi_t//BISTRO/src ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Fri Jul 12 17:26:37 2013 <NAME> ** Last update Thu Aug 15 02:32:03 2013 <NAME> */ #include <stdlib.h> #include "my_flags.h" #include "check_param.h" #include "my_str.h" #include "operation.h" #include "parser.h" static const int struct_init(t_op *operation) { operation->infix_notation = NULL; if (((operation->lexeme_list = new_linked_list()) == NULL) || ((operation->postfix_notation = new_linked_list()) == NULL)) return (RETURN_FAILURE); return (RETURN_SUCCESS); } int main(int ac, char **av) { t_op operation; if ((struct_init(&operation) == RETURN_FAILURE) || (check_param(ac, av) == RETURN_FAILURE) || (get_param(&operation, av) == RETURN_FAILURE) || (parser(&operation) == RETURN_FAILURE)) { my_putstr("ECHEC\n"); return (EXIT_FAILURE); } return (EXIT_SUCCESS); } <file_sep>/src/str/my_putstr.c /* ** my_putstr.c for Bistromathique in /home/tosi_t//BISTRO/src/str ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Fri Jul 12 20:04:26 2013 <NAME> ** Last update Mon Jul 22 17:43:04 2013 tim<NAME> */ #include <unistd.h> #include "my_flags.h" #include "my_str.h" void my_putstr(char *str) { (void) write(STANDARD_OUTPUT, str, my_strlen(str)); } <file_sep>/src/operation/set_div.c /* ** set_div.c for Bistromathique in /home/tosi_t//BISTRO/src/operation ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Sep 4 14:07:35 2013 <NAME> ** Last update Sun Sep 8 22:25:39 2013 timothe<NAME> */ #include <stdlib.h> #include "shunting_yard.h" #include "uniform.h" #include "my_flags.h" #include "my_str.h" static const int _division_by_zero(char *divisor, char *base) { if (divisor[0] == base[0]) return (my_puterror("Division by zero\n")); return (RETURN_SUCCESS); } t_content *set_div(t_op *operation, t_shunting *stack) { t_content *op1; t_content *op2; char *op_cpy1; char *op_cpy2; t_content *sym; char *res; op2 = pop_front_elem(stack->operator_stack); op1 = pop_front_elem(stack->operator_stack); sym = pop_front_elem(operation->postfix_notation); if ((epure_sym(op1->content, op2->content, &op_cpy1, &op_cpy2, operation->operators[3]) == RETURN_FAILURE) || (_division_by_zero(op2->content, operation->operands) == RETURN_FAILURE)) return (NULL); res = inf_div(op_cpy1, op_cpy2, operation->operands, operation->operators[3]); free(op_cpy1); free(op_cpy2); if ((res = uniform_sym(op1->content, op2->content, res, operation->operators[3])) == NULL) return (NULL); free_node(op1); free_node(op2); free_node(sym); return (set_res(res, operation)); } <file_sep>/src/shunting-yard/infix_to_postfix.c /* ** infix_to_postfix.c for Bistromathique in /home/tosi_t/BISTRO/src/shunting-yard ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 30 09:36:54 2013 <NAME> ** Last update Sat Aug 10 12:18:09 2013 <NAME> */ #include <stdlib.h> #include "shunting_yard.h" #include "my_flags.h" #include "my_str.h" static const t_infix g_determine_rule[] = { {L_BRACKET, &left_parenthesis_rule}, {R_BRACKET, &right_parenthesis_rule}, {SP_OPERATOR, &operator_rule}, {WP_OPERATOR, &operator_rule}, {P_OPERAND, &operand_rule}, {N_OPERAND, &operand_rule}, {-1, NULL} }; static const int _determine_rule(t_op *operation, t_shunting *shunting) { int i; i = 0; while (g_determine_rule[i].id != -1) { if (g_determine_rule[i].id == shunting->infix->front->type) return (g_determine_rule[i].ptr_func(operation, shunting)); ++i; } return (RETURN_FAILURE); } static const int _shunting_init(t_shunting *shunting, t_op *operation) { shunting->infix = operation->lexeme_list; if ((shunting->operator_stack = new_linked_list()) == NULL) return (RETURN_FAILURE); return (RETURN_SUCCESS); } const int infix_to_postfix(t_op *operation) { t_shunting shunting; if (_shunting_init(&shunting, operation) == RETURN_FAILURE) return (RETURN_FAILURE); while (shunting.infix->size > 0) { if (_determine_rule(operation, &shunting) == RETURN_FAILURE) return (RETURN_FAILURE); } if (output_rule(operation, &shunting) == RETURN_FAILURE) return (RETURN_FAILURE); free(shunting.operator_stack); my_putstr("SHUNTING YARD RESULT :\n"); show_list(operation->postfix_notation); my_putstr("\n\n"); return (RETURN_SUCCESS); } <file_sep>/src/param/check_op.c /* ** check_op.c for Bistromathique in /home/tosi_t//BISTRO/src/param ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Mon Jul 22 09:05:42 2013 <NAME> ** Last update Mon Jul 22 17:40:36 2013 <NAME> */ #include "check_param.h" #include "my_flags.h" #include "my_str.h" static const int _check_strchr(char *str) { int i; int j; j = 0; while (str[j] != '\0') { i = 0; while (str[i] != '\0') { if ((i != j) && (str[i] == str[j])) { my_puterror("Error: Same character in base or operators.\n"); return (RETURN_FAILURE); } ++i; } ++j; } return (RETURN_SUCCESS); } static const int _check_operators(char *str) { if (my_strlen(str) < OPERATORS_NB) { my_puterror("Error: Not enough operators in arguments.\n"); return (RETURN_FAILURE); } else if (my_strlen(str) > OPERATORS_NB) { my_puterror("Error: Too much operators in arguments.\n"); return (RETURN_FAILURE); } return (RETURN_SUCCESS); } static const int _check_match(char *operand, char *operator) { int i; int j; j = 0; while (operand[j] != '\0') { i = 0; while (operator[i] != '\0') { if (operand[j] == operator[i]) { my_puterror("Error: Same character in "); my_puterror("operand string and operator string.\n"); return (RETURN_FAILURE); } ++i; } ++j; } return (RETURN_SUCCESS); } const int check_op(char **param_tab) { if ((_check_strchr(param_tab[1]) == RETURN_FAILURE) || (_check_strchr(param_tab[2]) == RETURN_FAILURE) || (_check_operators(param_tab[2]) == RETURN_FAILURE) || (_check_match(param_tab[1], param_tab[2]) == RETURN_FAILURE)) return (RETURN_FAILURE); return (RETURN_SUCCESS); } <file_sep>/src/parser/parser.c /* ** parser.c for Bistromathique in /home/tosi_t//BISTRO/src/parser ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 30 09:16:50 2013 <NAME> ** Last update Sun Sep 8 21:17:07 2013 timothe<NAME> */ #include <stdlib.h> #include "parser.h" #include "shunting_yard.h" #include "my_flags.h" #include "my_str.h" static t_parser_rule g_parser_rule[]= { {&parse_l_bracket, L_BRACKET}, {&parse_r_bracket, R_BRACKET}, {&parse_sp_operator, SP_OPERATOR}, {&parse_wp_operator, WP_OPERATOR}, {&parse_operand, P_OPERAND}, {&parse_operand, N_OPERAND}, {NULL, RETURN_FAILURE} }; static const int _parser_rule(t_op *operation, t_content **tmp) { int i; i = 0; while (g_parser_rule[i].id != RETURN_FAILURE) { if ((*tmp)->type == g_parser_rule[i].id) return (g_parser_rule[i].ptr_func(operation, tmp)); ++i; } return (RETURN_FAILURE); } const int parser(t_op *operation) { t_content *tmp; if (lexer(operation) == RETURN_FAILURE) return (RETURN_FAILURE); tmp = operation->lexeme_list->front; while (tmp != NULL) { if (_parser_rule(operation, &tmp) == RETURN_FAILURE) return (my_puterror(SYNTAXE_ERROR_MSG)); } if ((infix_to_postfix(operation) == RETURN_FAILURE) || (evaluate_postfix(operation) == RETURN_FAILURE)) return (RETURN_FAILURE); return (RETURN_SUCCESS); } <file_sep>/src/operation/inf_sub.c /* ** inf_sub.c for Bistromathique in ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Aug 13 15:34:51 2013 <NAME> ** Last update Fri Aug 16 23:18:24 2013 <NAME> */ #include <stdlib.h> #include "operation.h" #include "my_str.h" static char _sub_digit(char first_digit, char second_digit, char *base, t_add *add, char minus) { int i; int j; i = 0; j = 0; if (first_digit != minus) while (first_digit != base[i]) ++i; if (second_digit != minus) while (second_digit != base[j]) ++j; j += add->carry; add->carry = 0; while (j > 0) { if ((i == 0) && (j > 0)) { i = (my_strlen(base) - 1); add->carry += 1; } else --i; --j; } return (base[i]); } static int _swap_op(char **f_o, char **sec_o, char *first_op, char *sec_op, char *base) { int i; i = str_base_cmp(first_op, sec_op, base); if (i == -1) { *f_o = sec_op; *sec_o = first_op; return (1); } else { *f_o = first_op; *sec_o = sec_op; return (0); } } static void _handle_sign(char **result, int carry, char minus, char *first_op, char *sec_op) { if (((carry == 1) && (first_op[0] != minus) && (sec_op[0] != minus)) || ((carry == 0) && (first_op[0] == minus) && (sec_op[0] != minus)) || ((carry == 1) && (sec_op[0] == minus))) *result[0] = minus; } char *inf_sub(char *first_op, char *sec_op, char *base, char minus) { t_add add; char *first_o; char *sec_o; char *result; int carry; carry = _swap_op(&first_o, &sec_o, first_op, sec_op, base); if ((result = op_init(&add, first_o, sec_o, base)) == NULL) return (NULL); while ((add.i >= 0) || (add.j >= 0)) { if ((add.i >= 0) && (add.j >= 0)) result[add.k] = _sub_digit(first_o[add.i], sec_o[add.j], base, &add, minus); else if ((add.i >= 0) && (add.j < 0)) result[add.k] = _sub_digit(first_o[add.i], base[0], base, &add, minus); else result[add.k] = _sub_digit(base[0], sec_o[add.j], base, &add, minus); --(add).i; --(add).j; --(add).k; } _handle_sign(&result, carry, minus, first_op, sec_op); return (result); } <file_sep>/src/str/my_strcpy.c /* ** my_strcpy.c for Bistromathique in /home/tosi_t//INF_DIV/src ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Mon Aug 19 23:59:18 2013 <NAME> ** Last update Tue Aug 20 00:00:45 2013 timothee tosi */ char *my_strcpy(char *origin, char *dest) { int i; i = 0; while (origin[i] != '\0') { dest[i] = origin[i]; ++i; } return (dest); } <file_sep>/src/shunting-yard/evaluate_postfix.c /* ** evaluate_postfix.c for Bistromathique in /home/tosi_t//BISTRO/src/shunting-yard ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sat Aug 10 11:19:40 2013 <NAME> ** Last update Sun Sep 8 22:34:49 2013 <NAME> */ #include <stdlib.h> #include "shunting_yard.h" #include "my_str.h" #include "my_flags.h" static t_postfix g_tab_postfix[] = { {ADDITION, &set_sub_add}, {SUBTRACTION, &set_sub_add}, {DIVISION, &set_div}, {MULTIPLICATION, &set_mul}, {MODULO, &set_mod}, {RETURN_FAILURE, NULL} }; static const int _calc_elem(t_shunting *stack, t_op *operation) { int i; t_content *res; if (stack->operator_stack->size < 2) return (RETURN_FAILURE); i = 0; while (g_tab_postfix[i].id != RETURN_FAILURE) { if (g_tab_postfix[i].id == operation->postfix_notation->front->operator) { if ((res = g_tab_postfix[i].ptr_func(operation, stack)) == NULL) return (RETURN_FAILURE); push_front_elem(operation->postfix_notation, res); return (RETURN_SUCCESS); } ++i; } return (RETURN_FAILURE); } const int _check_type(t_shunting *stack, t_op *operation) { if (operation->postfix_notation->front->type >= P_OPERAND) return (push_front_elem(stack->operator_stack, pop_front_elem(operation->postfix_notation))); else return (_calc_elem(stack, operation)); } const int evaluate_postfix(t_op *operation) { t_shunting stack; if ((stack.operator_stack = new_linked_list()) == NULL) return (RETURN_FAILURE); if (operation->postfix_notation->size == 1) { my_putstr(operation->postfix_notation->front->content); my_putstr("\n"); free(stack.operator_stack); return (RETURN_SUCCESS); } while (operation->postfix_notation->size > 1) { if (_check_type(&stack, operation) == RETURN_FAILURE) return (RETURN_FAILURE); } if (_check_type(&stack, operation) == RETURN_FAILURE) return (RETURN_FAILURE); my_putstr(operation->postfix_notation->front->content); my_putstr("\n"); free(stack.operator_stack); return (RETURN_SUCCESS); } <file_sep>/src/operation/set_dividend.c /* ** set_dividend.c for Bistromathique in /home/tosi_t//INF_DIV/src/misc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Mon Sep 2 13:06:35 2013 <NAME> ** Last update Wed Sep 4 19:03:28 2013 tim<NAME> */ #include <stdlib.h> #include "operation.h" #include "uniform.h" static char *_int_to_base_digit(char *base, int x) { char *digit; if ((digit = malloc(sizeof(*digit) * 2)) == NULL) return (NULL); digit[0] = base[x]; digit[1] = '\0'; return (digit); } char *set_dividend(char *divisor, char *base, char minus, int x) { char *digit; char *new_divisor; if ((digit = _int_to_base_digit(base, x)) == NULL) return (NULL); if ((new_divisor = inf_mul(divisor, digit, base, minus)) == NULL) return (NULL); free(digit); if ((new_divisor = uniform_result(new_divisor, base, minus)) == NULL) return (NULL); return (new_divisor); } <file_sep>/src/operation/inf_div.c /* ** inf_div.c for Bistromathique in /home/tosi_t//TESTBASE ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Aug 13 15:34:51 2013 <NAME> ** Last update Sun Sep 8 19:49:02 2013 tim<NAME>si */ #include <stdlib.h> #include "operation.h" #include "uniform.h" #include "memory.h" #include "my_str.h" #include "my_flags.h" static char *_set_dividend(char *str, char digit, int n, char *base) { char *dividend; if ((my_strlen(str) == 1) && (str[0] == base[0])) { str[0] = digit; return (str); } n += my_strlen(str); if ((dividend = malloc(sizeof(*dividend) * (n + 1))) == NULL) return (NULL); dividend[n] = '\0'; dividend = my_strcpy(str, dividend); dividend[n - 1] = digit; free(str); return (dividend); } static char *_set_res(char *dividend, char *base) { char *res; if ((res = malloc(sizeof(*res) * (my_strlen(dividend) + 1))) == NULL) return (NULL); res[my_strlen(dividend)] = '\0'; my_memset(res, base[0], my_strlen(dividend)); return (res); } static char *_calc_div(char *dividend, char *divisor, char *base, char *res, char minus) { char *real_divisor; int x; x = 1; real_divisor = divisor; if ((str_base_cmp(dividend, divisor, base) == RETURN_FAILURE) || dividend[0] == base[0]) { res[0] = base[0]; return (uniform_result(dividend, base, minus)); } while ((str_base_cmp(dividend, real_divisor, base) != RETURN_FAILURE) && (str_base_cmp(dividend, real_divisor, base) != 0)) { ++x; if ((real_divisor = set_dividend(divisor, base, minus, x)) == NULL) return (NULL); } if (str_base_cmp(dividend, real_divisor, base) != 0) --x; *res = base[x]; if (((real_divisor = set_dividend(divisor, base, minus, x)) == NULL) || ((real_divisor = inf_sub(dividend, real_divisor, base, minus)) == NULL)) return (NULL); return (uniform_result(real_divisor, base, minus)); } char *inf_div(char *f_op, char *s_op, char *base, char minus) { char *res; char *dividend; int x; int y; if (str_base_cmp(f_op, s_op, base) == RETURN_FAILURE) return (uniform_to_zero(base, NULL)); x = my_strlen(s_op); y = 0; if (((dividend = my_strndup(f_op, x)) == NULL) || ((res = _set_res(f_op, base)) == NULL)) return (NULL); dividend = _calc_div(dividend, s_op, base, &res[y], minus); ++y; while (f_op[x] != '\0') { if (((dividend = _set_dividend(dividend, f_op[x], 1, base)) == NULL) || ((dividend = _calc_div(dividend, s_op, base, &res[y], minus)) == NULL)) return (NULL); ++x; ++y; } res[y] = '\0'; return (uniform_result(res, base, minus)); } <file_sep>/src/shunting-yard/operator_rule.c /* ** operator_rule.c for Bistromathique in /home/tosi_t//BISTRO/src/shunting-yard ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Aug 4 13:32:24 2013 <NAME> ** Last update Wed Aug 7 14:24:19 2013 <NAME> */ #include "shunting_yard.h" #include "my_flags.h" static const int _check_precedence(t_op *operation, t_shunting *shunting) { if ((shunting->operator_stack->front->type == WP_OPERATOR) && (shunting->infix->front->type == SP_OPERATOR)) { push_front_elem(shunting->operator_stack, pop_front_elem(shunting->infix)); return (RETURN_FAILURE); } push_back_elem(operation->postfix_notation, pop_front_elem(shunting->operator_stack)); return (RETURN_SUCCESS); } const int operator_rule(t_op *operation, t_shunting *shunting) { while ((shunting->operator_stack->size > 0) && ((shunting->operator_stack->front->type == WP_OPERATOR) || (shunting->operator_stack->front->type == SP_OPERATOR))) { if (_check_precedence(operation, shunting) == RETURN_FAILURE) return (RETURN_SUCCESS); } push_front_elem(shunting->operator_stack, pop_front_elem(shunting->infix)); return (RETURN_SUCCESS); } <file_sep>/src/linked-list/show_list.c /* ** show_list.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Jul 28 21:40:15 2013 <NAME> ** Last update Wed Aug 7 14:19:10 2013 <NAME> */ #include <stdlib.h> #include "linked_list.h" #include "my_str.h" void show_list(t_linked_list *list) { t_content *tmp; tmp = list->front; while (tmp != NULL) { my_putstr(tmp->content); tmp = tmp->next; } } <file_sep>/src/linked-list/push_front.c /* ** push_front.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sat Jul 27 19:56:14 2013 <NAME> ** Last update Fri Aug 16 14:22:53 2013 <NAME> */ #include <stdlib.h> #include "linked_list.h" #include "my_flags.h" const int push_front(t_linked_list *this, char *content) { t_content *tmp; if ((content == NULL) || (tmp = malloc(sizeof(*tmp))) == NULL) return (RETURN_FAILURE); tmp->content = content; tmp->prev = NULL; tmp->next = this->front; if (this->size == 0) this->back = tmp; else if (this->size == 1) { this->back = this->front; this->back->prev = tmp; } else this->front->prev = tmp; this->front = tmp; ++(this->size); return (RETURN_SUCCESS); } <file_sep>/src/linked-list/show_reverse_list.c /* ** show_reverse_list.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Aug 4 11:35:32 2013 <NAME> ** Last update Sun Aug 4 11:36:59 2013 <NAME> */ #include <stdlib.h> #include "linked_list.h" #include "my_str.h" void show_reverse_list(t_linked_list *list) { t_content *tmp; tmp = list->back; while (tmp != NULL) { my_putstr(tmp->content); tmp = tmp->prev; } } <file_sep>/src/shunting-yard/operand_rule.c /* ** operand_rule.c for Bistromathique in /home/tosi_t//BISTRO/src/shunting-yard ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Mon Aug 5 14:23:14 2013 <NAME> ** Last update Mon Aug 5 14:26:48 2013 tim<NAME> */ #include "shunting_yard.h" #include "my_flags.h" const int operand_rule(t_op *operation, t_shunting *shunting) { push_back_elem(operation->postfix_notation, pop_front_elem(shunting->infix)); return (RETURN_SUCCESS); } <file_sep>/src/parser/lexer/sp_operator.c /* ** sp_operator.c for Bistromathique in /home/tosi_t//BISTRO/src/parser/lexer ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Aug 8 13:25:58 2013 <NAME> ** Last update Sat Aug 10 12:36:20 2013 <NAME> */ #include "parser.h" #include "memory.h" #include "my_flags.h" static void _define_id(t_op *operation, int *i) { operation->lexeme_list->back->type = SP_OPERATOR; if (operation->input[*i] == operation->operators[4]) operation->lexeme_list->back->operator = DIVISION; else if (operation->input[*i] == operation->operators[5]) operation->lexeme_list->back->operator = MULTIPLICATION; else operation->lexeme_list->back->operator = MODULO; } const int sp_operator(t_op *operation, int *i) { if ((operation->input[*i] == operation->operators[4]) || (operation->input[*i] == operation->operators[5]) || (operation->input[*i] == operation->operators[6])) { if ((push_back(operation->lexeme_list, my_strndup(&(operation->input[*i]), 1))) == RETURN_FAILURE) return (RETURN_FAILURE); _define_id(operation, i); *i += 1; return (RETURN_SUCCESS); } return (RETURN_FAILURE); } <file_sep>/src/parser/lexer/wp_operator.c /* ** wp_operator.c for Bistromathique in /home/tosi_t//BISTRO/src/parser/lexer ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Aug 8 13:29:56 2013 <NAME> ** Last update Fri Aug 16 16:03:29 2013 <NAME> */ #include "parser.h" #include "memory.h" #include "my_str.h" #include "my_flags.h" static void _define_id(t_op *operation, int *i) { operation->lexeme_list->back->type = WP_OPERATOR; if (operation->input[*i] == operation->operators[2]) operation->lexeme_list->back->operator = ADDITION; else operation->lexeme_list->back->operator = SUBTRACTION; } const int wp_operator(t_op *operation, int *i) { if ((operation->input[*i] == operation->operators[2]) || (operation->input[*i] == operation->operators[3])) { if ((operation->input[*i] == operation->operators[3]) && ((in_array(operation->input[*i + 1], operation->operands)) != RETURN_FAILURE) && ((*i == 0) || (((in_array(operation->input[*i - 1], operation->operators)) != RETURN_FAILURE) && (operation->input[*i - 1] != operation->operators[1])))) return (n_operand(operation, i)); if ((push_back(operation->lexeme_list, my_strndup(&(operation->input[*i]), 1))) == RETURN_FAILURE) return (RETURN_FAILURE); _define_id(operation, i); *i += 1; return (RETURN_SUCCESS); } return (RETURN_FAILURE); } <file_sep>/src/operation/set_mod.c /* ** set_mod.c for Bistromathique in /home/tosi_t//BISTRO/src/operation ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Sep 4 18:04:04 2013 <NAME> ** Last update Sun Sep 8 22:23:03 2013 timothe<NAME> */ #include <stdlib.h> #include "shunting_yard.h" #include "uniform.h" #include "my_flags.h" #include "my_str.h" static void free_buffers(char **str1, char **str2, char **str3, char **str4) { free(*str1); free(*str2); free(*str3); free(*str4); } static char *modulo_operation(char *op1, char *op2, t_op *operation) { char *op_cpy1; char *op_cpy2; char *res1; char *res2; char *res3; if (op2[0] == operation->operands[0]) { my_puterror("Division by zero\n"); return (NULL); } if (epure_sym(op1, op2, &op_cpy1, &op_cpy2, operation->operators[3]) == RETURN_FAILURE) return (NULL); res1 = inf_div(op_cpy1, op_cpy2, operation->operands, operation->operators[3]); res2 = inf_mul(op_cpy2, res1, operation->operands, operation->operators[3]); res3 = inf_sub(op_cpy1, res2, operation->operands, operation->operators[3]); free_buffers(&op_cpy1, &op_cpy2, &res1, &res2); return (res3); } t_content *set_mod(t_op *operation, t_shunting *stack) { t_content *op1; t_content *op2; t_content *sym; char *res; op2 = pop_front_elem(stack->operator_stack); op1 = pop_front_elem(stack->operator_stack); sym = pop_front_elem(operation->postfix_notation); if ((res = modulo_operation(op1->content, op2->content, operation)) == NULL) return (NULL); if ((res = uniform_sym(op1->content, op2->content, res, operation->operators[3])) == NULL) return (NULL); free_node(op1); free_node(op2); free_node(sym); return (set_res(res, operation)); } <file_sep>/inc/shunting_yard.h /* ** shunting_yard.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 30 09:25:35 2013 <NAME> ** Last update Wed Sep 4 18:52:14 2013 timothee tosi */ #ifndef SHUNTING_YARD_H_ # define SHUNTING_YARD_H_ # include "parser.h" # include "operation.h" typedef struct s_shunting { t_linked_list *infix; t_linked_list *operator_stack; } t_shunting; typedef struct s_infix { token_id id; const int (*ptr_func)(t_op *operation, t_shunting *shunting); } t_infix; typedef struct s_postfix { operation_id id; t_content *(*ptr_func)(t_op *operation, t_shunting *stack); } t_postfix; const int operator_rule(t_op *operation, t_shunting *shunting); const int operand_rule(t_op *operation, t_shunting *shunting); const int left_parenthesis_rule(t_op *operation, t_shunting *shunting); const int right_parenthesis_rule(t_op *operation, t_shunting *shunting); const int output_rule(t_op *operation, t_shunting *shunting); const int infix_to_postfix(t_op *operation); const int evaluate_postfix(t_op *operation); t_content *set_sub_add(t_op *operation, t_shunting *stack); t_content *set_mul(t_op *operation, t_shunting *stack); t_content *set_div(t_op *operation, t_shunting *stack); t_content *set_mod(t_op *operation, t_shunting *stack); #endif /* !SHUNTING_YARD_H_ */ <file_sep>/src/str/str_base_cmp.c /* ** str_base_cmp.c for Bistromathique in ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Aug 14 22:13:30 2013 <NAME> ** Last update Fri Aug 16 23:17:05 2013 <NAME> */ #include "my_str.h" #include "my_flags.h" static const int _check_in_base(char c1, char c2, char *base) { int i; int j; i = 0; j = 0; while (base[i] != c1) ++i; while (base[j] != c2) ++j; if (c1 > c2) return (1); else if (c1 < c2) return (-1); return (0); } static const int _check_len(char *str1, char *str2) { int len1; int len2; len1 = my_strlen(str1); len2 = my_strlen(str2); if (len1 > len2) return (1); else if (len1 < len2) return (-1); return (0); } const int str_base_cmp(char *str1, char *str2, char *base) { int i; int j; int k; i = 0; j = 0; my_putstr(str2); if (in_array(str1[0], base) == RETURN_FAILURE) ++i; if (in_array(str2[0], base) == RETURN_FAILURE) ++j; if ((k = _check_len(&str1[i], &str2[j])) != 0) return (k); while (str1[i] && str2[j]) { if ((k = _check_in_base(str1[i], str2[j], base)) != 0) return (k); ++i; ++j; } if ((str1[i] != '\0') && (str2[j] == '\0')) return (1); else if ((str1[i] == '\0') && (str2[j] != '\0')) return (-1); return (0); } <file_sep>/src/parser/lexer/l_bracket.c /* ** l_bracket.c for Bistromathique in /home/tosi_t//BISTRO/src/parser/lexer ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Aug 8 13:14:13 2013 <NAME> ** Last update Thu Aug 8 14:45:11 2013 tim<NAME> */ #include "parser.h" #include "memory.h" #include "my_flags.h" const int l_bracket(t_op *operation, int *i) { if (operation->input[*i] == operation->operators[0]) { if ((push_back(operation->lexeme_list, my_strndup(&(operation->input[*i]), 1))) == RETURN_FAILURE) return (RETURN_FAILURE); operation->lexeme_list->back->type = L_BRACKET; *i += 1; return (RETURN_SUCCESS); } return (RETURN_FAILURE); } <file_sep>/inc/linked_list.h /* ** linked_list.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 23 16:05:34 2013 <NAME> ** Last update Fri Aug 16 15:41:07 2013 tim<NAME> */ #ifndef LINKED_LIST_H_ # define LINKED_LIST_H_ # include "content.h" typedef struct s_linked_list { unsigned int size; t_content *front; t_content *back; } t_linked_list; t_linked_list *new_linked_list(void); const int push_front(t_linked_list *list, char *content); const int push_front_elem(t_linked_list *this, t_content *content); const int push_back(t_linked_list *list, char *content); const int push_back_elem(t_linked_list *this, t_content *content); const int push_n(t_linked_list *list, char *content, int n); t_content *pop_front_elem(t_linked_list *list); void show_list(t_linked_list *list); void show_reverse_list(t_linked_list *list); void show_node(t_linked_list *list); void free_node(t_content *container); #endif /* !LINKED_LIST_H_ */ <file_sep>/src/shunting-yard/right_parenthesis_rule.c /* ** right_parenthesis_rule.c for Bistromathique in /home/tosi_t//BISTRO/src/shunting-yard ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Aug 4 17:27:43 2013 <NAME> ** Last update Sun Aug 4 17:33:23 2013 <NAME> */ #include "shunting_yard.h" #include "my_flags.h" const int right_parenthesis_rule(t_op *operation, t_shunting *shunting) { while (shunting->operator_stack->size > 0) { if (shunting->operator_stack->front->type == L_BRACKET) { pop_front_elem(shunting->operator_stack); pop_front_elem(shunting->infix); return (RETURN_SUCCESS); } push_back_elem(operation->postfix_notation, pop_front_elem(shunting->operator_stack)); } return (RETURN_FAILURE); } <file_sep>/Makefile ## Made by <NAME> NAME = shunting_yard CC = gcc RM = rm -f CFLAGS = -I./inc \ -Wall \ -Werror \ -pedantic SRC = src/shunting_yard.c \ src/param/check_param.c \ src/param/check_op.c \ src/param/get_param.c \ src/str/is_number.c \ src/str/in_array.c \ src/str/str_base_cmp.c \ src/str/my_getnbr.c \ src/str/my_strlen.c \ src/str/my_strcpy.c \ src/str/my_putstr.c \ src/str/my_puterror.c \ src/memory/my_strdup.c \ src/memory/my_strndup.c \ src/memory/my_memset.c \ src/linked-list/new_linked_list.c \ src/linked-list/push_front.c \ src/linked-list/push_front_elem.c \ src/linked-list/push_back.c \ src/linked-list/push_back_elem.c \ src/linked-list/push_n.c \ src/linked-list/pop_front_elem.c \ src/linked-list/show_list.c \ src/linked-list/show_node.c \ src/linked-list/show_reverse_list.c \ src/linked-list/free_node.c \ src/parser/parser.c \ src/parser/parse_l_bracket.c \ src/parser/parse_r_bracket.c \ src/parser/parse_sp_operator.c \ src/parser/parse_wp_operator.c \ src/parser/parse_operand.c \ src/parser/set_res.c \ src/parser/lexer/lexer.c \ src/parser/lexer/l_bracket.c \ src/parser/lexer/r_bracket.c \ src/parser/lexer/sp_operator.c \ src/parser/lexer/wp_operator.c \ src/parser/lexer/p_operand.c \ src/parser/lexer/n_operand.c \ src/uniform/uniform_to_zero.c \ src/uniform/uniform_result.c \ src/uniform/uniform_sym.c \ src/uniform/epure_sym.c \ src/shunting-yard/operator_rule.c \ src/shunting-yard/operand_rule.c \ src/shunting-yard/left_parenthesis_rule.c \ src/shunting-yard/right_parenthesis_rule.c \ src/shunting-yard/output_rule.c \ src/shunting-yard/infix_to_postfix.c \ src/shunting-yard/evaluate_postfix.c \ src/operation/op_init.c \ src/operation/inf_add.c \ src/operation/inf_sub.c \ src/operation/inf_mul.c \ src/operation/inf_div.c \ src/operation/set_sub_add.c \ src/operation/set_mul.c \ src/operation/set_div.c \ src/operation/set_dividend.c \ src/operation/set_mod.c OBJ = $(SRC:.c=.o) $(NAME): $(OBJ) $(CC) -o $(NAME) $(OBJ) all: $(NAME) clean: $(RM) $(OBJ) fclean: clean $(RM) $(NAME) re: fclean all .PHONY: all clean fclean re<file_sep>/src/memory/my_strndup.c /* ** my_strndup.c for Bistromathque in /home/tosi_t//BISTRO/src/memory ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 23 14:46:53 2013 <NAME> ** Last update Mon Jul 29 01:12:33 2013 <NAME> */ #include <stdlib.h> #include "my_str.h" char *my_strndup(char *original, int n) { char *duplicate; int i; i = 0; if ((duplicate = malloc(sizeof(*duplicate) * (n + 1))) == NULL) return (NULL); while ((original[i] != '\0') && i < n) { duplicate[i] = original[i]; ++i; } duplicate[i] = '\0'; return (duplicate); } <file_sep>/src/str/my_strlen.c /* ** my_strlen.c for Bistromathique in /home/tosi_t//BISTRO/src/str ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Fri Jul 12 19:35:30 2013 <NAME> ** Last update Thu Jul 18 15:46:21 2013 <NAME> */ int my_strlen(const char * str) { int i; i = 0; while (str[i]) ++i; return (i); } <file_sep>/src/parser/lexer/r_bracket.c /* ** r_bracket.c for Bistromathique in /home/tosi_t//BISTRO/src/parser/lexer ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Aug 8 13:23:32 2013 <NAME> ** Last update Thu Aug 8 14:45:39 2013 tim<NAME> */ #include "parser.h" #include "memory.h" #include "my_flags.h" const int r_bracket(t_op *operation, int *i) { if (operation->input[*i] == operation->operators[1]) { if ((push_back(operation->lexeme_list, my_strndup(&(operation->input[*i]), 1))) == RETURN_FAILURE) return (RETURN_FAILURE); operation->lexeme_list->back->type = R_BRACKET; *i += 1; return (RETURN_SUCCESS); } return (RETURN_FAILURE); } <file_sep>/inc/check_param.h /* ** param.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Mon Jul 22 09:15:56 2013 tim<NAME> ** Last update Mon Jul 22 17:38:42 2013 timothee tosi */ #ifndef PARAM_H_ # define PARAM_H_ # include "operation.h" # define OPERATORS_NB 7 const int check_param(const int param_nb, char **param_tab); const int check_op(char **param_tab); const int get_param(t_op *operation, char **av); #endif /* !PARAM_H_ */ <file_sep>/src/operation/inf_add.c /* ** inf_add.c for Bistromathique in ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Aug 13 15:34:51 2013 <NAME> ** Last update Sun Sep 8 22:35:50 2013 <NAME> */ #include <stdlib.h> #include "operation.h" static char _add_digit(char first_digit, char second_digit, char *base, t_add *add, char minus) { int i; int j; i = 0; j = 0; if (first_digit != minus) while (first_digit != base[i]) ++i; if (second_digit != minus) while (second_digit != base[j]) ++j; j += add->carry; add->carry = 0; while (j > 0) { ++i; --j; if (base[i] == '\0') { i = 0; add->carry += 1; } } return (base[i]); } char *inf_add(char *first_op, char *sec_op, char *base, char minus) { t_add add; char *result; if ((result = op_init(&add, first_op, sec_op, base)) == NULL) return (NULL); while ((add.i >= 0) || (add.j >= 0)) { if ((add.i >= 0) && (add.j >= 0)) result[add.k] = _add_digit(first_op[add.i], sec_op[add.j], base, &add, minus); else if ((add.i >= 0) && (add.j < 0)) result[add.k] = _add_digit(first_op[add.i], base[0], base, &add, minus); else result[add.k] = _add_digit(base[0], sec_op[add.j], base, &add, minus); --(add).i; --(add).j; --(add).k; } result[add.k] = _add_digit(base[0], base[0], base, &add, minus); if (first_op[0] == minus) result[0] = minus; return (result); } <file_sep>/src/linked-list/new_linked_list.c /* ** new_linked_list.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 23 16:04:59 2013 <NAME> ** Last update Sat Jul 27 20:33:54 2013 <NAME> */ #include <stdlib.h> #include "linked_list.h" t_linked_list *new_linked_list(void) { t_linked_list *linked_list; if ((linked_list = malloc(sizeof(*linked_list))) == NULL) return (NULL); linked_list->size = 0; linked_list->front = NULL; linked_list->back = NULL; return (linked_list); } <file_sep>/src/parser/lexer/lexer.c /* ** lexer.c for Bistromathique in /home/tosi_t//BISTRO/src/parser ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 23 15:32:16 2013 tim<NAME> ** Last update Sun Sep 8 21:14:31 2013 timothee tosi */ #include <stdlib.h> #include "parser.h" #include "memory.h" #include "my_flags.h" #include "my_str.h" static const int (*g_token_match[])(t_op *operation, int *i) = { &l_bracket, &r_bracket, &sp_operator, &wp_operator, &p_operand, NULL }; const int lexer(t_op *operation) { int i; int j; i = 0; if ((operation->lexeme_list = new_linked_list()) == NULL) return (RETURN_FAILURE); while (operation->input[i] != '\0') { j = 0; while (g_token_match[j](operation, &i) != RETURN_SUCCESS) { if (g_token_match[j] == NULL) return (my_puterror(SYNTAXE_ERROR_MSG)); ++j; } } my_putstr("LEXER RESULT :\n"); show_node(operation->lexeme_list); my_putstr("END\n"); return (RETURN_SUCCESS); } <file_sep>/src/linked-list/push_n.c /* ** push_n.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 23 16:04:09 2013 <NAME> ** Last update Sun Jul 28 23:28:30 2013 <NAME> */ #include <stdlib.h> #include "linked_list.h" #include "my_flags.h" #include "memory.h" static void add_node(t_linked_list **this, t_content **node, int n) { t_content *tmp; tmp = (*this)->front; while ((n-- > 0) && (tmp->next != NULL)) tmp = tmp->next; if (tmp == (*this)->back) { (*node)->prev = tmp; tmp->next = *node; (*this)->back = *node; } else { if (tmp == (*this)->front) (*this)->front = *node; else { tmp->prev->next = *node; (*node)->prev = tmp->prev; } (*node)->next = tmp; tmp->prev = *node; } } const int push_n(t_linked_list *this, char *content, int n) { t_content *tmp; if ((tmp = malloc(sizeof(*tmp))) == NULL) return (RETURN_FAILURE); tmp->content = content; tmp->next = NULL; tmp->prev = NULL; if (this->size == 0) { this->back = tmp; this->front = tmp; } else add_node(&this, &tmp, n); return (RETURN_SUCCESS); } <file_sep>/inc/memory.h /* ** memory.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Jul 18 18:02:54 2013 <NAME> ** Last update Thu Aug 15 02:20:30 2013 timothe<NAME>si */ #ifndef MEMORY_H_ # define MEMORY_H_ char *my_strdup(char *original); char *my_strndup(char *original, int n); void my_memset(char *array, int byte, int size); #endif /* !MEMORY_H_ */ <file_sep>/src/linked-list/push_front_elem.c /* ** push_front_elem.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 30 14:00:43 2013 <NAME> ** Last update Tue Jul 30 14:06:28 2013 <NAME> */ #include <stdlib.h> #include "linked_list.h" #include "my_flags.h" const int push_front_elem(t_linked_list *this, t_content *content) { content->prev = NULL; content->next = this->front; if (this->size == 0) this->back = content; else if (this->size == 1) { this->back = this->front; this->back->prev = content; } else this->front->prev = content; this->front = content; ++(this->size); return (RETURN_SUCCESS); } <file_sep>/src/parser/parse_r_bracket.c /* ** parse_r_bracket.c for Bistromathique in /home/tosi_t//BISTRO/src/parser ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Aug 8 15:12:09 2013 <NAME> ** Last update Thu Aug 8 20:36:50 2013 tim<NAME> */ #include <stdlib.h> #include "parser.h" #include "my_flags.h" const int parse_r_bracket(t_op *operation, t_content **tmp) { if (((*tmp)->prev == NULL) || ((*tmp)->prev->type == L_BRACKET) || ((*tmp)->prev->type == SP_OPERATOR) || ((*tmp)->prev->type == WP_OPERATOR) || (((*tmp)->next != NULL) && (((*tmp)->next->type == L_BRACKET) || ((*tmp)->next->type == N_OPERAND) || ((*tmp)->next->type == P_OPERAND)))) return (RETURN_FAILURE); *tmp = (*tmp)->next; return (RETURN_SUCCESS); } <file_sep>/src/memory/my_strdup.c /* ** my_strdup.c for Bistromathique in /home/tosi_t//BISTRO/src/memory ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Jul 18 17:57:03 2013 <NAME> ** Last update Tue Jul 23 14:48:11 2013 tim<NAME> */ #include <stdlib.h> #include "my_str.h" char *my_strdup(char *original) { char *duplicate; int i; i = 0; if ((duplicate = malloc(sizeof(*duplicate) * (my_strlen(original) + 1))) == NULL) return (NULL); while (original[i] != '\0') { duplicate[i] = original[i]; ++i; } duplicate[i] = '\0'; return (duplicate); } <file_sep>/src/uniform/uniform_sym.c /* ** uniform_sym.c for Bistromathqiue in /home/tosi_t//BISTRO/src/uniform ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Sep 4 17:27:49 2013 <NAME> ** Last update Wed Sep 4 18:02:51 2013 tim<NAME> */ #include <stdlib.h> #include "my_str.h" char *_set_new_res(char *origin, const int size, char minus) { int i; int j; char *new_res; if ((new_res = malloc(sizeof(*new_res) * (size + 1))) == NULL) return (NULL); new_res[0] = minus; new_res[size] = '\0'; i = 1; j = 0; while (origin[j]) { new_res[i] = origin[j]; ++j; ++i; } free(origin); return (new_res); } char *uniform_sym(char *op1, char *op2, char *res, char minus) { int res_size; if (((op1[0] == minus) && (op2[0] != minus)) || ((op1[0] != minus) && (op2[0] == minus))) { res_size = (my_strlen(res)) + 1; if ((res = _set_new_res(res, res_size, minus)) == NULL) return (NULL); } return (res); } <file_sep>/src/str/my_getnbr.c /* ** my_getnbr.c for Bistromathique in /home/tosi_t//BISTRO/src/str ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Mon Jul 22 10:44:20 2013 <NAME> ** Last update Tue Jul 23 09:44:24 2013 tim<NAME>si */ #include "my_str.h" /* nb negative, limit */ int my_getnbr(char *str) { int res; int i; int pow; i = my_strlen(str) - 1; res = 0; pow = 1; while (i >= 0) { res = res + ((str[i] - '0') * pow); --i; pow = pow * 10; } return (res); } <file_sep>/src/str/is_number.c /* ** is_number.c for Bistromathique in /home/tosi_t//BISTRO/src/str ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Jul 18 15:41:07 2013 <NAME> ** Last update Mon Jul 22 17:41:46 2013 tim<NAME> */ #include "my_flags.h" const int is_number(char *str) { int i; i = 0; while (str[i] != '\0') { if ((str[i] < '0') || (str[i] > '9')) return (RETURN_FAILURE); ++i; } return (RETURN_SUCCESS); } <file_sep>/src/linked-list/pop_front_elem.c /* ** pop_front_elem.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 30 15:44:35 2013 <NAME> ** Last update Tue Jul 30 17:33:26 2013 <NAME> */ #include <stdlib.h> #include "linked_list.h" t_content *pop_front_elem(t_linked_list *list) { t_content *tmp; if ((list == NULL) || (list->front == NULL)) return (NULL); tmp = list->front; if (list->size == 1) { list->front = NULL; list->back = NULL; } else if (list->size == 2) { list->front = list->back; list->back->prev = NULL; } else { list->front = list->front->next; list->front->prev = NULL; } --(list->size); tmp->prev = NULL; tmp->next = NULL; return (tmp); } <file_sep>/src/param/get_param.c /* ** get_param.c for Bistromathique in /home/tosi_t//BISTRO/src/param ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Jul 18 17:47:17 2013 <NAME> ** Last update Sun Sep 8 21:18:09 2013 timothe<NAME> */ #include <stdlib.h> #include <unistd.h> #include "operation.h" #include "my_str.h" #include "memory.h" #include "my_flags.h" static const int _check_input(t_op *operation) { int i; i = 0; while (operation->input[i] != '\0') { if (((in_array(operation->input[i], operation->operators)) == RETURN_FAILURE) && ((in_array(operation->input[i], operation->operands)) == RETURN_FAILURE)) return (my_puterror(SYNTAXE_ERROR_MSG)); ++i; } return (RETURN_SUCCESS); } static const int _get_input(t_op *operation) { if (((operation->input = malloc(sizeof(*(operation->input)) * (operation->size_read + 1))) == NULL)) return (RETURN_FAILURE); operation->input[operation->size_read] = '\0'; if (read(0, operation->input, operation->size_read) != operation->size_read) return (my_puterror("Could not read\n")); return (_check_input(operation)); } const int get_param(t_op *operation, char **av) { if ((operation->size_read = my_getnbr(av[3])) <= 0) return (my_puterror("Bad expr len\n")); if (((operation->operands = my_strdup(av[1])) == NULL) || ((operation->operators = my_strdup(av[2])) == NULL) || (_get_input(operation) == RETURN_FAILURE)) return (RETURN_FAILURE); return (RETURN_SUCCESS); } <file_sep>/inc/content.h /* ** content.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 23 10:14:01 2013 tim<NAME> ** Last update Sat Aug 10 12:31:21 2013 timothee tosi */ #ifndef CONTENT_H_ # define CONTENT_H_ typedef struct s_content { void *content; int type; int operator; struct s_content *next; struct s_content *prev; } t_content; #endif /* CONTENT_H_ */ <file_sep>/inc/my_flags.h /* ** my_flags.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Fri Jul 12 19:53:38 2013 tim<NAME> ** Last update Sun Sep 8 21:07:13 2013 timothee tosi */ #ifndef MY_FLAGS_H_ # define MY_FLAGS_H_ # define RETURN_SUCCESS 0 # define RETURN_FAILURE -1 # define STANDARD_OUTPUT 1 # define ERROR_OUTPUT 2 # define SYNTAXE_ERROR_MSG "syntax error" #endif /* !MY_FLAGS_H_ */ <file_sep>/src/uniform/uniform_to_zero.c /* ** uniform_to_zero.c for Bistromathique in /home/tosi_t//BISTRO/src/uniform ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Sep 4 13:36:30 2013 <NAME> ** Last update Sun Sep 8 20:26:16 2013 tim<NAME> */ #include <stdlib.h> #include "my_str.h" char *uniform_to_zero(char *base, char *origin) { char *res; if ((res = malloc(sizeof(*res) * 2)) == NULL) return (NULL); res[0] = base[0]; res[1] = '\0'; return (res); } <file_sep>/src/memory/my_memset.c /* ** my_memset.c for Bistromathique in /home/tosi_t//TESTBASE/src ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Aug 14 15:50:40 2013 <NAME> ** Last update Wed Aug 14 20:01:54 2013 tim<NAME> */ void my_memset(char *array, int byte, int size) { int i; i = 0; while (i < size) { array[i] = byte; ++i; } } <file_sep>/inc/circular_buffer.h /* ** circular_buffer.h for Bistromathique in /home/tosi_t//BISTRO/inc ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Jul 23 10:09:41 2013 <NAME> ** Last update Tue Jul 23 10:27:39 2013 timothe<NAME>si */ #ifndef CIRCULAR_BUFFER_H_ # define CIRCULAR_BUFFER_H_ typedef struct s_circular_buffer { unsigned int size; unsigned int free_cells; t_content *front; t_content *back; t_content *actual_pos; char *(*pop_from)(struct s_circular_buffer *this); const int (*push)(struct s_circular_buffer *this, char *content); void (*show)(struct s_stack *this); } t_cbuffer; t_cbuffer *new_cbuffer(unsigned int size); #endif /* CIRCULAR_BUFFER_H_ */ <file_sep>/src/operation/set_sub_add.c /* ** set_sub_add.c for Bistromathique in /home/tosi_t//BISTRO/src/operation ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Fri Aug 16 14:29:59 2013 <NAME> ** Last update Sun Sep 8 20:49:07 2013 timothee tosi */ #include <stdlib.h> #include "shunting_yard.h" #include "uniform.h" static const operation_id _select_sub_add(token_id op1, token_id op2, operation_id sym) { if (((op1 == op2) && (sym == ADDITION)) || ((op1 != op2) && (sym == SUBTRACTION))) return (ADDITION); return (SUBTRACTION); } t_content *set_sub_add(t_op *operation, t_shunting *stack) { t_content *op1; t_content *op2; t_content *sym; char *res; op2 = pop_front_elem(stack->operator_stack); op1 = pop_front_elem(stack->operator_stack); sym = pop_front_elem(operation->postfix_notation); if (_select_sub_add(op1->type, op2->type, sym->operator) == ADDITION) res = inf_add(op1->content, op2->content, operation->operands, operation->operators[3]); else res = inf_sub(op1->content, op2->content, operation->operands, operation->operators[3]); free_node(op1); free_node(op2); free_node(sym); if ((res = uniform_result(res, operation->operands, operation->operators[3])) == NULL) return (NULL); return (set_res(res, operation)); } <file_sep>/src/linked-list/free_node.c /* ** free_node.c for Bistromathique in /home/tosi_t//BISTRO/src/linked-list ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Fri Aug 16 15:37:59 2013 <NAME> ** Last update Fri Aug 16 15:40:32 2013 <NAME> */ #include <stdlib.h> #include "content.h" void free_node(t_content *container) { if (container != NULL) { if (container->content != NULL) free(container->content); free(container); } } <file_sep>/src/shunting-yard/left_parenthesis_rule.c /* ** left_parenthesis_rule.c for Bistromathique in /home/tosi_t//BISTRO/src/shunting-yard ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Aug 4 17:18:12 2013 <NAME> ** Last update Mon Aug 5 14:05:35 2013 <NAME> */ #include "shunting_yard.h" #include "my_flags.h" const int left_parenthesis_rule(t_op *operation, t_shunting *shunting) { push_front_elem(shunting->operator_stack, pop_front_elem(shunting->infix)); return (RETURN_SUCCESS); } <file_sep>/src/operation/set_mul.c /* ** set_mul.c for Bistromathique in /home/tosi_t//BISTRO/src/operation ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sat Aug 17 17:15:45 2013 <NAME> ** Last update Sun Sep 8 22:39:43 2013 tim<NAME> */ #include "shunting_yard.h" t_content *set_mul(t_op *operation, t_shunting *stack) { t_content *op1; t_content *op2; t_content *sym; char *res; op2 = pop_front_elem(stack->operator_stack); op1 = pop_front_elem(stack->operator_stack); sym = pop_front_elem(operation->postfix_notation); res = inf_mul(op1->content, op2->content, operation->operands, operation->operators[3]); free_node(op1); free_node(op2); free_node(sym); return (set_res(res, operation)); }
72843708cdaa271c369168a1f230d13b10eaa333
[ "C", "Makefile" ]
69
C
TimTosi/shuntingYard
1b93c863664980eda6733951c673f945a45db368
23c80e902ca7050591c1198711bc2d763ed91248
refs/heads/master
<repo_name>VolhvPorechja/SpringLearning<file_sep>/demo/src/main/resources/exceptions.properties common.fail=Sorry but this is fail!!<file_sep>/springcontext/src/main/java/org/volhvporechja/springcontext/Main.java package org.volhvporechja.springcontext; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; import org.volhvporechja.springcontext.beans.RestApi; @SpringBootApplication @EnableScheduling public class Main { public static void main(String[] args) { SpringApplication.run(RestApi.class, args); } } <file_sep>/demo/src/main/java/org/volhvporechja/demo/services/OffersService.java package org.volhvporechja.demo.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Service; import org.volhvporechja.demo.contracts.Offer; import javax.sql.DataSource; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class OffersService { private NamedParameterJdbcTemplate jdbc; private RowMapper<Offer> offerRowMapper = (rs, rowNum) -> { Offer result = new Offer(); result.setId(rs.getInt("id")); result.setName(rs.getString("name")); result.setEmail(rs.getString("email")); result.setText(rs.getString("text")); return result; }; @Autowired public void setDataSource(DataSource ds) { jdbc = new NamedParameterJdbcTemplate(ds); } public boolean createOffer(Offer offer) { BeanPropertySqlParameterSource param = new BeanPropertySqlParameterSource(offer); return jdbc.update("insert into Offers (name,email,text) values (:name,:email,:text)", param) == 1; } public List<Offer> getOffers() { return jdbc.query("select * from Offers", offerRowMapper); } public List<Offer> getOfferByName(String name) { MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("name", name); return jdbc.query("select * from Offers where name = :name", params, offerRowMapper); } } <file_sep>/demo-jsp/src/main/java/org/volhvporechja/demojsp/OffersRepository.java package org.volhvporechja.demojsp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import org.volhvporechja.demojsp.dao.Offer; import javax.sql.DataSource; import java.util.List; @Repository public class OffersRepository { private NamedParameterJdbcTemplate jdbc; private RowMapper<Offer> offerRowMapper = (rs, rowNum) -> { Offer result = new Offer(); result.setId(rs.getInt("id")); result.setName(rs.getString("name")); result.setEmail(rs.getString("email")); result.setText(rs.getString("text")); return result; }; @Autowired public void setDataSource(DataSource ds) { jdbc = new NamedParameterJdbcTemplate(ds); } public List<Offer> getOffers() { return jdbc.query("select * from Offers", offerRowMapper); } } <file_sep>/springcontext/src/main/java/org/volhvporechja/springcontext/beans/ScheduledTasks.java package org.volhvporechja.springcontext.beans; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.volhvporechja.springcontext.contracts.Quote; @Component public class ScheduledTasks { private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); Person person; @Autowired @Qualifier("OtherPerson") public void setPerson(Person person) { this.person = person; } @Scheduled(fixedRate = 5000) public void report() { log.info(person.toString()); } @Scheduled(fixedRate = 5000) public void reportQuote() { RestTemplate template = new RestTemplate(); Quote quote = template.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); } } <file_sep>/bootstrip/hints.md ## Found hints 1. mvn validate to find properties values ```xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.8</version> <executions> <execution> <phase>validate</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echoproperties /> </tasks> </configuration> </execution> </executions> </plugin> ```<file_sep>/springcontext/src/main/java/org/volhvporechja/springcontext/ContextConfig.java package org.volhvporechja.springcontext; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.volhvporechja.springcontext.beans.Person; @Configuration @PropertySource("classpath:application.yaml") @ComponentScan("org.volhvporechja.springcontext.beans") public class ContextConfig { @Bean("SomePerson") public Person GetSomePerson(){ return new Person(123, "Fucker"); } @Bean("OtherPerson") @Qualifier("OtherPerson") public Person GetOtherPerson(){ return new Person(123, "Looser"); } } <file_sep>/demo/src/main/java/org/volhvporechja/demo/services/PersonsService.java package org.volhvporechja.demo.services; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; import org.volhvporechja.demo.beans.Person; import org.volhvporechja.demo.components.ScheduledTasks; import org.volhvporechja.demo.conextevents.PersonRegisteredEvent; @Service public class PersonsService { private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); @EventListener public void PersonRegistered(PersonRegisteredEvent event) { Person source = (Person) event.getSource(); log.info(String.format("Registered %s person", source.toString())); } } <file_sep>/demo/src/main/java/org/volhvporechja/demo/RestApi.java package org.volhvporechja.demo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.volhvporechja.demo.contracts.Greetings; @RestController @RequestMapping("/fgreetings") public class RestApi { @RequestMapping(method = RequestMethod.GET) public Greetings greetings() { return new Greetings(123, "Fuck you stranger!!"); } } <file_sep>/demo/src/main/java/org/volhvporechja/demo/conextevents/PersonRegisteredEvent.java package org.volhvporechja.demo.conextevents; import org.springframework.context.ApplicationEvent; public class PersonRegisteredEvent extends ApplicationEvent { public PersonRegisteredEvent(Object source) { super(source); } } <file_sep>/demo-jsp/src/main/java/org/volhvporechja/demojsp/HomeController.java package org.volhvporechja.demojsp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.volhvporechja.demojsp.dao.Offer; import javax.servlet.http.HttpSession; import java.util.Map; import java.util.Optional; @Controller public class HomeController { @Autowired OffersRepository offersRepository; @RequestMapping("/") public String home(HttpSession model) { return "home"; } @RequestMapping("/some") public String some(HttpSession model) { model.setAttribute("message", "Fuck you some!!"); return "home"; } @RequestMapping("/other") public String other(HttpSession model) { model.setAttribute("message", "Fuck you other!!"); return "home"; } @RequestMapping("/mv") public ModelAndView mv() { ModelAndView home = new ModelAndView("home"); home.getModel().put("message", "Fucking model and view"); return home; } @RequestMapping("/offers") public String getOffers(Map<String, Object> model) { model.put("offers", offersRepository.getOffers().toArray()); return "offer"; } }<file_sep>/demo/src/main/java/org/volhvporechja/demo/aspects/SomeService.java package org.volhvporechja.demo.aspects; import org.springframework.stereotype.Service; @Service public class SomeService implements SomeServiceContract { @Override @Nuance public String SomeModification(String modifyingString) { return String.format("FUCK%sFUCK", modifyingString); } @Override @Nuance public String SomeGeneration() { return "FUCK YOU!!"; } } <file_sep>/demo/src/main/java/org/volhvporechja/demo/beans/Wallet.java package org.volhvporechja.demo.beans; import org.springframework.stereotype.Component; @Component public class Wallet { String id = "234"; public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return "Wallet{" + "id='" + id + '\'' + '}'; } } <file_sep>/demo/src/main/java/org/volhvporechja/demo/services/QuotesService.java package org.volhvporechja.demo.services; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.volhvporechja.demo.contracts.Quote; import org.volhvporechja.demo.contracts.QuoteServiceResponse; @Service public class QuotesService { @Autowired @Qualifier("FailedMessages") ResourceBundleMessageSource messagesSource; @Value("${services.quotes.connectionString}") String quotesServiceCS; private final RestTemplate template; public QuotesService(RestTemplate template) { this.template = template; } @HystrixCommand(fallbackMethod = "NextQuoteFallback") public QuoteServiceResponse GetNextQuote() { Quote quote = template.getForObject(quotesServiceCS, Quote.class); return QuoteServiceResponse.Success(quote); } public QuoteServiceResponse NextQuoteFallback() { return QuoteServiceResponse.Failed(messagesSource.getMessage("common.fail", null, "Default", null)); } }
46e41877fc622d33feac7ce80dc0c28f036f4052
[ "Markdown", "Java", "INI" ]
14
INI
VolhvPorechja/SpringLearning
f055b759b79ab54bed009280e187b76669b8ffb3
7000f4700e47f79fbb5cd115fbb967918c192cad
refs/heads/master
<file_sep>// import { PolymerElement, html } from "@polymer/polymer/polymer-element"; import { LitElement, html, css } from "lit-element"; export class PedruleAscensor extends LitElement{ static get properties() { return { showV: { type: Boolean, reflect: true, attribute: 'show-v', }, showH: { type: Boolean, reflect: true, attribute: 'show-h' }, sizeV: { type: Number, // observer: '__sizeVChanged' }, sizeH: { type: Number, // observer: '__sizeHChanged' }, deltaV: { type: Number, // observer: '__deltaVChanged' }, deltaH: { type: Number, // observer: '__deltaHChanged' }, isHorizontalScroll: { type: Boolean, } } } static get styles() { return css` :host{ pointer-events: none; /* @apply --layout-horizontal; */ display: flex; --weight-scroll-container: 6px; position: absolute; -webkit-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none; cursor: pointer; --background-ascensor: #eeeeee; --color-ascensor: #111111; } .container{ background: var(--background-ascensor); transition: width .1s ease-out; overflow: hidden; } .scrollBar{ background: var(--color-ascensor); } #containerH{ width: calc(100% - var(--weight-scroll-container)); } #ascensorH{ height: var(--weight-scroll-container); } #containerV{ height : 100%; width : var(--weight-scroll-container); } div.hide{ opacity: 0; pointer-events: none; } div.show{ opacity: 1; pointer-events: all; } :host(:hover){ --weight-scroll-container: 12px; } .self-end { align-self: flex-end; } ` } render() { return html` <div id="containerH" class="${this._hideH(this.showH)} self-end container" @mouseenter="${this._enableHorizontalScroll}" @mouseleave="${this._disableHorizontalScroll}"> <div id="ascensorH" class="scrollBar"></div> </div> <div id="containerV" class="${this._hideV(this.showV)} container"> <div id="ascensorV" class="scrollBar"></div> </div> ` } set sizeV(value) { const oldValue = this._sizeV; this._sizeV = value; this.requestUpdate('sizeV', oldValue); // this.__sizeVChanged(value); } get sizeV() { return this._sizeV; } set sizeH(value) { const oldValue = this._sizeH; this._sizeH = value; this.requestUpdate('sizeH', oldValue); // this.__sizeHChanged(value); } get sizeH() { return this._sizeH; } set deltaH(value) { const oldValue = this._deltaH; this._deltaH = value; this.requestUpdate('deltaH', oldValue); // this.__deltaHChanged(value); } get deltaH() { return this._deltaH; } set deltaV(value) { const oldValue = this._deltaV; this._deltaV = value; this.requestUpdate('deltaV', oldValue); // this.__deltaVChanged(value); } get deltaV() { return this._deltaV; } get ascensorV() { return this.shadowRoot.querySelector('#ascensorV'); } get ascensorH() { return this.shadowRoot.querySelector('#ascensorH'); } get containerH() { return this.shadowRoot.querySelector('#containerH'); } get containerV() { return this.shadowRoot.querySelector('#containerV'); } constructor() { super(); this.isHorizontalScroll = false; } updated(changedProperties) { if(changedProperties.has('deltaV')) this.__deltaVChanged(this.deltaV); if(changedProperties.has('deltaH')) this.__deltaHChanged(this.deltaH); if(changedProperties.has('sizeH')) this.__sizeHChanged(this.sizeH); if(changedProperties.has('sizeV')) this.__sizeVChanged(this.sizeV); } _hideH(showH){ return showH ? 'show' : 'hide'; } _hideV(showV){ return showV ? 'show' : 'hide'; } __sizeVChanged(arg) { this.ascensorV.style.height = `${arg}px` } __sizeHChanged(arg) { // we set width of horizontal scroll but we diminute it from width of vertical scroll this.ascensorH.style.width = `${arg - this.containerV.getBoundingClientRect().width}px`; } __deltaVChanged(arg) { this.ascensorV.style.transform = `translateY(${arg}px)`; } checkDeltaV(delta) { if (isNaN(delta) || delta === undefined || delta < 0) return 0; if (delta > (this.containerV.getBoundingClientRect().height - this.ascensorV.getBoundingClientRect().height)) return this.containerV.getBoundingClientRect().height - this.ascensorV.getBoundingClientRect().height; return delta; } __deltaHChanged(arg) { this.ascensorH.style.transform = `translateX(${arg}px)`; } checkDeltaH(delta) { if (isNaN(delta) || delta === undefined || delta < 0) return 0; if (delta > (this.containerH.getBoundingClientRect().width - this.ascensorH.getBoundingClientRect().width)) return this.containerH.getBoundingClientRect().width - this.ascensorH.getBoundingClientRect().width; return delta; } _enableHorizontalScroll(event) { this.isHorizontalScroll = true; } _disableHorizontalScroll() { this.isHorizontalScroll = false; } } if (!customElements.get('pedrule-scrollbar')) customElements.define('pedrule-scrollbar', PedruleAscensor);<file_sep> import { ScrollBehavior } from '../scrollBehavior/index'; export const ScrollVirtualBehavior = superClass => class extends ScrollBehavior(superClass) { static get properties() { return { lastIndex: { type: Number, // observer: '__lastIndexChanged' }, } } set lastIndex(value) { const oldValue = this._lastIndex; this._lastIndex = value; this.requestUpdate('lastIndex', oldValue); this.__lastIndexChanged(value, oldValue); } get lastIndex() { return this._lastIndex; } /** * each time delta property changes we set lastIndex property * @observer * @param {Number} arg * @param {Number} prev */ __deltaVChanged(arg, prev) { super.__deltaVChanged(arg); if(this.unitarySize && arg != undefined)this.lastIndex = this.numberInstance + Math.floor(arg*this.ratioV/this.unitarySize.height); } /** * each time lastIndex changes function update instances accordingly to * display gracefully virtualist * @observer * @param {Number} arg * @param {Number} prev */ __lastIndexChanged(arg, prev){ // we don't do anything if it is the first set on property if(arg && prev){ if(arg > prev){ for(let i = prev; i< arg; i++) { let indexOfItem = i%this.numberInstance; let loop = Math.floor(i/this.numberInstance); let item = this.instances[indexOfItem]; if(item) { item.item = this.items[i]; item.index = i; item.style.transform = `translate3d(0, ${(loop*(this.numberInstance*this.unitarySize.height))+(indexOfItem*this.unitarySize.height)}px, 0)` } } } if(arg < prev){ if(prev>arg+this.numberInstance)prev = arg + this.numberInstance //this is to be sure to not doing more that a loop in instances displayed to avoid to have bugs for(let i = arg; i< prev; i++) { let indexOfItem = (i-this.numberInstance)%this.numberInstance; let loop = Math.floor((i-this.numberInstance)/this.numberInstance); let item = this.instances[indexOfItem]; if(item) { item.item = this.items[(i-this.numberInstance)]; item.index = i-this.numberInstance; item.style.transform = `translate3d(0, ${(loop*(this.numberInstance*this.unitarySize.height))+(indexOfItem*this.unitarySize.height)}px, 0)` } } } } } }<file_sep>import { html, fixture, expect } from '@open-wc/testing'; import '../src/pedrule-virtual-scroll.js'; describe('<pedrule-virtual-scroll>', () => { it('has a default property heading', async () => { const el = await fixture('<pedrule-virtual-scroll></pedrule-virtual-scroll>'); expect(el.heading).to.equal('Hello world!'); }); it('allows property heading to be overwritten', async () => { const el = await fixture(html` <pedrule-virtual-scroll heading="different heading"></pedrule-virtual-scroll> `); expect(el.heading).to.equal('different heading'); }); }); <file_sep>// import { PolymerElement, html } from '@polymer/polymer/polymer-element'; // import { LitElement } from "lit-element"; import {ScrollVirtualBehavior} from './ScrollVirtualBehavior'; import {InstanceBehavior} from './InstanceBehavior'; // import '@polymer/iron-flex-layout/iron-flex-layout'; // import '@polymer/iron-flex-layout/iron-flex-layout-classes'; import { LitElement, html } from 'lit-element'; export default class PedruleVirtualScroll extends InstanceBehavior(ScrollVirtualBehavior(LitElement)) { static get properties() { return { _height: { type: Number, // computed: '__setHeight(items, unitarySize)', // observer: '__heightChanged' }, width: { type: Number, reflect: true, converter(value) { return Number(value); } // observer: '__widthChanged' }, items: { type: Array, // observer: '__itemsChanged', // value: [] }, } } static get styles() { return [ this.styleTemplate, this.containerStyle ] } set items(value) { let oldValue = this._items; this._items = value; this.requestUpdate('items', oldValue); this.__itemsChanged(value); this._height = this.__setHeight(value, this.unitarySize); } get items() { return this._items; } set _height(value) { let oldValue = this.__height; this.__height = value; if(value !== undefined && value !== false) { this.requestUpdate('_height', oldValue); this.__heightChanged(value, oldValue); } } get _height() { return this.__height; } set width(value) { let oldValue = this._width; this._width = value; this.requestUpdate('width', oldValue); // this.__widthChanged(value); } get width() { return this._width; } get templateItem() { return html` <div style="height: 65px; background: tan;position: absolute">Ceci est un test</div> ` } constructor() { super(); this.items = []; } render() { return html` ${this.containerTemplate} ${this.scrollTemplate}` } firstUpdated(changedProperties) { if(changedProperties.width) this.__widthChanged(changedProperties.width); this.computeSizeOfHost(); this.__observeSlot(); this.evaluateScroll(); this.deltaH = this.deltaV = 0; } /** * function that computed total size of element by factorizacion of unitarySize of an item and total count of items through * length of items array * @param {Array} items * @param {Number} unitarySize */ __setHeight(items, unitarySize) { return items && unitarySize ? unitarySize.height*items.length : false; } /** * retrieve new value of height property and assign it to css style of element * @observer * @param {Number} arg */ __heightChanged(arg, prev) { if(arg != undefined && arg !== prev){ this.container.style.height = `${arg}px`; // this.__resetInstances(); this.evaluateScroll(); } } /** * retrieve new value of width property and assign it to each instances of instances array property * @observer * @param {Number} arg */ __widthChanged(arg) { this.instances.forEach(item => item.style.width = `${arg}px`); this.container.style.width = `${arg}px`; } __itemsChanged(arg) { this.__resetInstances(); if (arg) this.instances.forEach((instance, index) => (instance.item = arg[index])); } } // const initElement = () => { // if(!customElements.get('pedrule-virtual-scroll')) customElements.define('pedrule-virtual-scroll', PedruleVirtualScroll); // } // export { initElement, PedruleVirtualScroll }<file_sep> // import { FlattenedNodesObserver } from '@polymer/polymer/lib/utils/flattened-nodes-observer'; // import { afterNextRender } from '@polymer/polymer/lib/utils/render-status'; import { html, css } from "lit-element"; export const SizeBehavior = SuperClass => class extends SuperClass{ static get properties() { return { unitarySize: { type: Object, // notify: true }, nameOfContainer: { type: String, reflect: true, attribute: "name-of-container" // observer: "onNameSetted" } } } set nameOfContainer(value) { const oldValue = this._nameOfContainer; this._nameOfContainer = value; this.requestUpdate('nameOfContainer', oldValue); this.onNameSetted(value); } get nameOfContainer() { return this._nameOfContainer; } set unitarySize(value) { const oldValue = this._unitarySize; this._unitarySize = value; this.requestUpdate('unitarySize', oldValue); this._height = this.__setHeight(this.items, value); this.numberInstance = this.__computeNumberOfInstance(value); } get unitarySize() { return this._unitarySize; } // render() { // return `${this.template}` // } static get template() { return html` <style include="iron-flex iron-flex-alignment"> :host { /* height: 50vh; position: absolute; width: 50vw; */ opacity: 0; flex: 1; } #container{ position: absolute; width: 100%; overflow: hidden; } </style> ${super.template} ` } static get containerStyle() { return css` #container{ position: absolute; width: 100%; overflow: hidden; } ` } connectedCallback(){ super.connectedCallback(); window.addEventListener('resize', () => { this.computeSizeOfHost(); this.evaluateScroll(); }) // if(this.nameOfContainer)this.__observeSlot(); // this.template = this.constructor.templateItem; } onNameSetted(arg) { // if(arg) this.__observeSlot(); } /** * @observer on slot * each time a child element is added in the */ __observeSlot(){ this.__getSizeTemplateVirtual().then((size) => { this.unitarySize = size; }); } /** * function that return size in the dom of a particular object * @return {DomRect} */ __getSizeTemplateVirtual() { return new Promise((resolve ,reject) => { let size; let slotelement = this.template = this.querySelector(this.nameOfContainer); if(!slotelement) return; let observer = new MutationObserver((mutationList) => { if(mutationList[0] && mutationList[0].addedNodes) { let slotelement = this.querySelector(this.nameOfContainer); size = slotelement.getBoundingClientRect(); this.template = slotelement; // this.computeSizeOfHost(); // size = mutationList[0].addedNodes[0].getBoundingClientRect(); // this.template = mutationList[0].addedNodes[0]; } if(slotelement) observer.disconnect(); resolve(size); }); observer.observe(this, {childList: true}) this.appendChild(this.content); }) } set template(value) { let template = document.createElement('template'); template.content.appendChild(value); this._template = template; // this._template = value; } get template() { return this._template; } set content(value) { this._content = value; } get content() { return this.template.content.cloneNode(true).firstElementChild; } computeSizeOfHost() { // setTimeout(() => { const position = this.getBoundingClientRect(); this.style.position = "absolute"; this.style.width = `${position.width}px`; this.style.height = `${position.height}px`; this.style.opacity = 1; // }, 1000) } }<file_sep>import { storiesOf, html, withKnobs, withClassPropertiesKnobs } from '@open-wc/demoing-storybook'; import PedruleVirtualScroll from '../src/PedruleVirtualScroll.js'; import '../src/pedrule-virtual-scroll.js'; import readme from '../README.md'; storiesOf('pedrule-virtual-scroll', module) .addDecorator(withKnobs) .add('Documentation', () => withClassPropertiesKnobs(PedruleVirtualScroll), { notes: { markdown: readme } }) .add( 'Alternative Header', () => html` <pedrule-virtual-scroll .header=${'Something else'}></pedrule-virtual-scroll> `, );
6ba35339c441d7d7bd6590af208e237fdacade3a
[ "JavaScript" ]
6
JavaScript
pedrule/virtual-scroll-v2
0680d1e534d83fd30a92c3bb92fc823954bf5446
5af17495b1f8a62b73280818603a1a58aeaafe10
refs/heads/master
<file_sep>import Vue from 'vue' import Vuex from 'vuex' import mutations from './mutations' import actions from './actions' Vue.use(Vuex) export default new Vuex.Store({ state: { pokemon: { sprite: 'https://fontmeme.com/images/Pokemon-Logo.jpg' }, showLoader: false }, actions, mutations })
27eb0ea4c6f728735569c5f50fdae05087736bbf
[ "JavaScript" ]
1
JavaScript
kingreyvie/Pokedex
25ec142e2034b492d02df97d145f55d5ac9b94c7
8da590f78628da912145d2d984ff2ff5341eb3d0
refs/heads/master
<repo_name>yurikaugusto/Projeto-JSP-com-consumo-de-API-Paises<file_sep>/src/main/java/com/brq/internet/projetojspbase/dto/PaisDTO.java package com.brq.internet.projetojspbase.dto; import java.io.Serializable; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class PaisDTO implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @JsonProperty("flag") private String bandeira; @JsonProperty("translations") private NomePaisDTO nomeNaoTraduzido; @JsonProperty("nativeName") private String nomeNativo; private String capital; @JsonProperty("population") private int populacao; @JsonProperty("currencies") private List<MoedaDTO> moeda; public String getBandeira() { return bandeira; } public void setBandeira(String bandeira) { this.bandeira = bandeira; } public NomePaisDTO getNomeNaoTraduzido() { return nomeNaoTraduzido; } public void setNomeNaoTraduzido(NomePaisDTO nomeNaoTraduzido) { this.nomeNaoTraduzido = nomeNaoTraduzido; } public String getNomeNativo() { return nomeNativo; } public void setNomeNativo(String nomeNativo) { this.nomeNativo = nomeNativo; } public String getCapital() { return capital; } public void setCapital(String capital) { this.capital = capital; } public int getPopulacao() { return populacao; } public void setPopulacao(int populacao) { this.populacao = populacao; } public List<MoedaDTO> getMoeda() { return moeda; } public void setMoeda(List<MoedaDTO> moeda) { this.moeda = moeda; } @Override public String toString() { return "PaisDTO [bandeira=" + bandeira + ", nomeNaoTraduzido=" + nomeNaoTraduzido + ", nomeNativo=" + nomeNativo + ", capital=" + capital + ", populacao=" + populacao + ", moeda=" + moeda + "]"; } } <file_sep>/src/main/java/com/brq/internet/projetojspbase/helper/PaisViewModelHelper.java package com.brq.internet.projetojspbase.helper; import java.text.Normalizer; import java.util.Comparator; import java.util.List; import com.brq.internet.projetojspbase.viewmodel.PaisViewModel; public class PaisViewModelHelper { public static PaisViewModel buscaPaisPorId(List<PaisViewModel> listaDePaises, String idPais) { PaisViewModel pais = new PaisViewModel(); for (PaisViewModel itemLista : listaDePaises) { //verifico cada item da lista com base no "nome" e "idPais" if (itemLista.getNomeTraduzido().equals(idPais)) { pais.setBandeira(itemLista.getBandeira()); pais.setNomeTraduzido(itemLista.getNomeTraduzido()); pais.setNomeNativo(itemLista.getNomeNativo()); pais.setCapital(itemLista.getCapital()); pais.setPopulacao(itemLista.getPopulacao()); pais.setCodigoMoeda(itemLista.getCodigoMoeda()); pais.setNomeMoeda(itemLista.getNomeMoeda()); pais.setSimboloMoeda(itemLista.getSimboloMoeda()); return pais; } } return pais; } public static List<PaisViewModel> ordenaLista(List<PaisViewModel> listaDePaises) { // para cada item (pais) o nome é recuperado, transformado em lowercase // e os acentos são removidos antes da ordenação ocorrer listaDePaises.sort(Comparator.comparing(pais -> removeAcento(pais.getNomeTraduzido().toLowerCase()))); // faz comparação lexicográfica return listaDePaises;//retorno a lista ordenada e com acentuação } private static String removeAcento(String src) { return Normalizer .normalize(src, Normalizer.Form.NFD) .replaceAll("[^\\p{ASCII}]", ""); } } <file_sep>/src/main/java/com/brq/internet/projetojspbase/service/impl/BuscaPaisesImpl.java package com.brq.internet.projetojspbase.service.impl; import java.util.List; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.brq.internet.projetojspbase.dto.PaisDTO; import com.brq.internet.projetojspbase.service.BuscaPaises; @Service public class BuscaPaisesImpl implements BuscaPaises{ @Autowired private WebTarget webTarget; @Override public List<PaisDTO> retornaResponse() { Response response = webTarget .queryParam("language", "pt-BR") .request() .get(); return response.readEntity(new GenericType<List<PaisDTO>>() {}); } } <file_sep>/src/main/java/com/brq/internet/projetojspbase/viewmodel/mapper/PaisViewModelMapper.java package com.brq.internet.projetojspbase.viewmodel.mapper; import java.util.ArrayList; import java.util.List; import com.brq.internet.projetojspbase.dto.PaisDTO; import com.brq.internet.projetojspbase.viewmodel.PaisViewModel; public class PaisViewModelMapper { public static List<PaisViewModel> from (List<PaisDTO> dto){ List<PaisViewModel> listaDePaises = new ArrayList<>(); for (PaisDTO paisDTO : dto) {//paisDTO item : dto lista PaisViewModel pais = new PaisViewModel(); pais.setBandeira(paisDTO.getBandeira()); pais.setNomeTraduzido(paisDTO.getNomeNaoTraduzido().getNomeTraduzido()); pais.setNomeNativo(paisDTO.getNomeNativo()); pais.setCapital(paisDTO.getCapital()); pais.setPopulacao(paisDTO.getPopulacao()); pais.setCodigoMoeda(paisDTO.getMoeda().get(0).getCodigoMoeda());//private List<MoedaDTO> moeda; é uma lista pais.setNomeMoeda(paisDTO.getMoeda().get(0).getNomeMoeda());//de um único objeto pais.setSimboloMoeda(paisDTO.getMoeda().get(0).getSimboloMoeda());//por isso o index 0 foi buscado listaDePaises.add(pais); } return listaDePaises; } } <file_sep>/README.md # Projeto MVC com JSP e consumo de API. ### Para executar o projeto é necessário adicionar o servidor Apache Tomcat version 9. ### Essa é a url padrão de acesso página inicial da aplicação http://localhost:8080/projeto-jsp-base/home. ### Obs: a Api consumida retorna todos os países e também as características que eles possuem.
c92d0230dbe857c56351c23144ccb78159d6d229
[ "Markdown", "Java" ]
5
Java
yurikaugusto/Projeto-JSP-com-consumo-de-API-Paises
c484686d96465ddfa88f4f75fd6d3778784d626f
c6a2c99d7e537010f57f856f8fc97bc5cf326c26
refs/heads/master
<file_sep>hw1 grading rubric hw1 Feedback ============ #### Successful use of Git, GitHub, and build automation tools (4/5) * Your commit history could be more made more useful. A useful commit history separates work into multiple commits, instead of one or two for the whole assignment. Each commit should have a concise, but descriptive name about what was changed. Committing your work incrementally protects you from data loss or network problems, which might otherwise cause you to lose work or fail to meet the homework deadlines (which are strictly enforced). For more information on writing useful commit messages, see [here](https://git-scm.com/book/ch5-2.html#Commit-Guidelines) or [here](http://chris.beams.io/posts/git-commit/) #### Basic proficiency in Java (14/20) * Instead of repeatedly creating new documents, create each Document once and store it in an array to access it later. Each time a Document is created, there is an expensive network call and computation, which can be avoided by storing a single instance of the document. * Instead of doing time consuming operations such as calculating constant values, you should perform these only once on Object initialization and store them for faster method calls later on. Your code calculates during each call to cosine similarity a new denominator, this value should have been created at the constructor and reused. * Improper use of object orientation. Make variables local unless they represent object properties or universally meaningful state. (Scanner in Document as field) * Avoid using boxed primitives (i.e. `Integer`, `Boolean`, etc.) in your code. Use primitive types when possible, as they avoid unnecessary memory allocations on the heap. See [Effective Java, Item 49: Prefer primitive types to boxed primitives](http://goo.gl/O8t5Tf). (HighestCosSim) * You should use the most general static type in variable declarations (e.g. `List` instead of `ArrayList`). (Document:17) #### Fulfilling the technical requirements of the program specification (15/15) #### Documentation and code style (10/10) --- #### Total (43/50) Late days used: 0 (5 left) --- #### Additional Notes Graded by: <NAME> (<EMAIL>) To view this file with formatting, visit the following page: https://github.com/CMU-15-214/said/blob/master/grades/hw1.md <file_sep>package edu.cmu.cs.cs214.hw2.expression; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import edu.cmu.cs.cs214.hw2.operator.Unary; public class UnaryExpressionTest { //CHECKSTYLE:OFF @Test public void test() { Expression operand1 = new NumberExpression(-3); Expression e = new UnaryExpression(Unary.ABSVALUE, operand1); assertEquals(e.eval(), 3.0, Math.pow(10, -5)); } @Test public void test1() { Expression operand1 = new NumberExpression(2); Expression e = new UnaryExpression(Unary.ABSVALUE, operand1); assertEquals(e.eval(), 2.0, Math.pow(10, -5)); } @Test public void test2() { Expression operand1 = new NumberExpression(-3); Expression e = new UnaryExpression(Unary.NEGATION, operand1); assertEquals(e.eval(), 3.0, Math.pow(10, -5)); } @Test public void test3() { Expression operand1 = new NumberExpression(2); Expression e = new UnaryExpression(Unary.NEGATION, operand1); assertEquals(e.eval(), -2.0, Math.pow(10, -5)); } // @Test(expected = NullPointerException.class) // public void test4() { // Expression e = new UnaryExpression(Unary.NEGATION, null); // // } @Test public void testToStringOperator() { Expression operand1 = new NumberExpression(2); Expression e = new UnaryExpression(Unary.ABSVALUE, operand1); assertTrue(e.toString().equals("(||(2.0))")); } @Test public void testToString() { Expression operand1 = new NumberExpression(2); Expression e = new UnaryExpression(Unary.NEGATION, operand1); assertTrue(e.toString().equals("(~(2.0))")); } } <file_sep>apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'findbugs' apply plugin: 'checkstyle' apply plugin: 'cobertura' test.testLogging { exceptionFormat "full"; events "failed", "passed", "skipped" } repositories { mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.11' } findbugs { toolVersion = "3.0.0" ignoreFailures = true excludeFilter = file("$projectDir/config/findbugs/excludeFilter.xml") } checkstyle { ignoreFailures = true toolVersion = "6.7" sourceSets = [sourceSets.main] checkstyleMain.exclude '**/edu/cmu/cs/cs214/hw6/util/*' } buildscript{ repositories { mavenCentral() } dependencies { classpath 'net.saliman:gradle-cobertura-plugin:2.2.5' } } cobertura.coverageFormats = ['html', 'xml'] apply plugin: 'application' mainClassName = "edu.cmu.cs.cs214.hw6.harness.MapReduceHarness" // These are the default arguments if no command line arguments are given to "gradle run". Feel free // to change them! List<String> defaultArgs = new ArrayList<String>(); defaultArgs.add('src/main/resources/server_config/one_worker_fail.csv'); defaultArgs.add('edu.cmu.cs.cs214.hw6.servers.DummyServer'); defaultArgs.add('edu.cmu.cs.cs214.hw6.servers.DummyServer'); run { args = defaultArgs if (project.hasProperty('myargs')) { args(myargs.split(',')) } } <file_sep>hw4b Feedback ============ #### Implementation of Scrabble game (60/60) * Your implementation seems to completely or almost completely implement the functionality related to the game’s board (squares, tiles, special tiles, drawing and exchanging tiles, purchasing special tiles, making moves, etc). Well done. * Your implementation seems to completely or almost completely implement the functionality related to the validating a move in the game (checking placement, etc.). Well done! * Your implementation seems to completely or almost completely implement the functionality related to challenging a move in the game (validating words, reverting board state, etc). Well done! * Your implementation seems to completely or almost completely implement the functionality related to scoring a move in the game (adding points for tiles and words, applying multipliers and scoring-related special tiles, etc). Well done. * Your implementation seems to completely or almost completely implement the special tiles in the game (reverse order, boom, negative points, and own tile). Well done. #### Program Design (21/25) * Overall, you did a pretty good job here. My only concerns are about your responsibility assignment. * Game is doing everything, it should be delegating all that work. Think about what has the most information for each thing-- wouldn't it make more sense for Board to validate a Move? * Think about how you could have made more classes that were smaller as opposed to making your Game into a "God Class" #### Testing and Build Automation (22/25) * Your testing practice meets our expectations. Well done! * Your testing coverage seems reasonable. * Travis is not building homework 4. Please change your settings.gradle file in the top level of your repository to fix this issue. #### Documentation and Style (5/10) * Please document your public classes/methods with comments. You are missing documentation in several classes. * You are missing several javadoc comments in the tiles package. Most importantly, in the SpecialTile interface. --- #### Total (108/120) Late days used: 0 (2 left) --- #### Additional Notes Graded by: <NAME> (<EMAIL>) To view this file with formatting, visit the following page: https://github.com/CMU-15-214/said/blob/master/grades/hw4b.md <file_sep>package edu.cmu.cs.cs214.hw2.expression; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import edu.cmu.cs.cs214.hw2.operator.Binary; /** * * @author dsai96 * creates derivative expressions and checks eval */ public class DerivativeExpressionTest { //CHECKSTYLE:OFF @Test public void test() { //f(x) = x^2 - 1 //derivative = 2x, which with x = 2, is 4.0 Expression operand1 = new NumberExpression(1); Variable var = new Variable("x"); var.store(2.0); Expression varSquared = new BinaryExpression(Binary.MULTIPLY, var, var); Expression subtracted = new BinaryExpression(Binary.SUBTRACT, varSquared, operand1); Expression derivativeFn = new DerivativeExpression(subtracted, var); assertEquals(derivativeFn.eval(), 4.00, Math.pow(10, -4)); } @Test public void testToString() { //f(x) = x^2 - 1 Expression operand1 = new NumberExpression(1); Variable var = new Variable("x"); Expression varSquared = new BinaryExpression(Binary.MULTIPLY, var, var); Expression subtracted = new BinaryExpression(Binary.SUBTRACT, varSquared, operand1); Expression derivativeFn = new DerivativeExpression(subtracted, var); assertTrue(derivativeFn.toString().equals("(((x = 0.0) * (x = 0.0)) - (1.0)) , x")); } } <file_sep>hw5a Feedback ============ #### Description of Framework (15/15) Your framework description is reasonably complete, good job! #### Framework Design (20/35) ##### Basic Structure * Your API does not describe behavior to cover exceptional cases. * Your framework should be able to manage multiple visualization plugins simultaneously. Your design model suggests that only one plugin can be supported at a time. * Your data plugin is not parameterized for different sources. A data plugin should be able to gather data from sources given at runtime, and create a separate object representing the data from each source. ##### Framework/Plugin Interaction and Control Flow * It is unclear how and when framework gets the information to display the visualization plugins in the GUI. ##### Style * The method call arguments are missing on the interaction diagram. #### Planning (8/10) * You did not describe how you plan to split up the work on the framework itself. * You did not have a timeline for completing each task. #### Other Feedback --- #### Total (43/60) Late days used: 0 (2 left for hw5) --- #### Additional Notes Graded by: <NAME> (<EMAIL>) To view this file with formatting, visit the following page: https://github.com/CMU-15-214/said/blob/master/grades/hw5a.md<file_sep>package edu.cmu.cs.cs214.hw3; import java.util.Arrays; import java.util.Iterator; public class PermutationGenerater implements Iterator<int[]>, Iterable<int[]> { private int[] numList; private int numOfPermutations; private int currIndex = 0; PermutationGenerater(int[] list) { Arrays.sort(list); this.numList = list; numOfPermutations = Factorial.getFactorial(numList.length); } @Override public boolean hasNext() { return (currIndex < numOfPermutations); } //code for this algorithm found online and made minor adjustments @Override public int[] next() { if (currIndex == 0) { currIndex++; return numList; } int i1 = numList.length - 1; while (i1 > 0 && numList[i1 - 1] >= numList[i1]) { i1--; } if (i1 <= 0) { return null; } int i2 = numList.length - 1; while (numList[i2] <= numList[i1 - 1]) { i2--; } int temp = numList[i1 - 1]; numList[i1 - 1] = numList[i2]; numList[i2] = temp; i2 = numList.length - 1; while (i1 < i2) { temp = numList[i1]; numList[i1] = numList[i2]; numList[i2] = temp; i1++; i2--; } currIndex++; return numList; } @Override public Iterator<int[]> iterator() { return this; } } <file_sep>package edu.cmu.cs.cs214.hw4.gui; import java.util.ArrayList; import java.util.List; import javax.swing.JToggleButton; import edu.cmu.cs.cs214.hw4.core.*; import edu.cmu.cs.cs214.hw4.tiles.LetterTile; public class ScrabbleGUI { private ScrabbleGame g; //The following are needed to keep track of Tiles being clicked private JToggleButton selectedButton; private LetterTile selectedTile; public boolean isSelected = false; private ScrabbleListener listener; private final List<ScrabbleListener> scrabbleListeners = new ArrayList<>(); public ScrabbleGUI(ScrabbleGame game) { this.g = game; } public ScrabbleGame getG() { return g; } public void createPlayerNuetralPanel() { } public void createPlayerlPanel() { } // public void addToPlaceTiles(LetterTile t, int row, int col) { // TilePlacement tp = new TilePlacement(row, col, t); // tilesToPlace.add(tp); // } // // public void addGameChangeListener(final ScrabbleListener listener) { scrabbleListeners.add(listener); } // // public void tempAddToBoard(int row, int col) { // // } // // private void notifyMoveMade(final int col, final int row) { // for (final ScrabbleListener listener : scrabbleListeners) { // listener.squareChanged(row, col); // } } <file_sep>package edu.cmu.cs.cs214.hw4.core; import java.util.Arrays; public class Board { final int size = 15; Square[][] boardArr = new Square[size][size]; /** * constructs initial board with squares(wordMult, letterMult, letterTile) */ public Board() { int[][] tripleWord = new int[][] { { 14, 14 }, { 0, 0 }, { 0, 7 }, { 7, 0 }, { 14, 0 }, { 0, 14 }, { 7, 14 }, { 14, 7 } }; int[][] doubleWord = new int[][] { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 }, { 10, 10 }, { 11, 11 }, { 12, 12 }, { 13, 13 }, { 1, 13 }, { 2, 12 }, { 3, 11 }, { 4, 10 }, { 10, 4 }, { 11, 3 }, { 12, 2 }, { 13, 1 } }; int[][] tripleLetter = new int[][] { { 1, 5 }, { 1, 9 }, { 5, 1 }, { 5, 5 }, { 5, 9 }, { 5, 13 }, { 9, 1 }, { 9, 5 }, { 9, 9 }, { 9, 13 }, { 13, 5 }, { 13, 9 } }; int[][] doubleLetter = new int[][] { { 0, 3 }, { 0, 11 }, { 2, 6 }, { 2, 8 }, { 3, 7 }, { 3, 0 }, { 3, 14 }, { 6, 2 }, { 6, 6 }, { 6, 8 }, { 6, 12 }, { 7, 3 }, { 7, 11 }, { 8, 2 }, { 8, 6 }, { 8, 8 }, { 8, 12 }, { 11, 0 }, { 11, 7 }, { 11, 14 }, { 12, 6 }, { 12, 8 }, { 14, 3 }, { 14, 11 } }; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { int[] curr = new int[] { i, j }; if (contains(curr, tripleLetter)) { boardArr[i][j] = new Square(1, 3, null); } if (contains(curr, doubleLetter)) { boardArr[i][j] = new Square(1, 2, null); } if (contains(curr, doubleWord)) { boardArr[i][j] = new Square(2, 1, null); } if (contains(curr, tripleWord)) { boardArr[i][j] = new Square(3, 1, null); } if (boardArr[i][j] == null) { boardArr[i][j] = new Square(1, 1, null); } } } } /** * * @param lint * array * @param list * 2d int array * @return if l is in list */ public boolean contains(int[] l, int[][] list) { for (int i = 0; i < list.length; i++) { if (Arrays.equals(list[i], l)) return true; } return false; } /** * * @return creates a new copy of the board to save */ public Board getDefensiveCopy() { Board copy = new Board(); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { copy.boardArr[i][j] = boardArr[i][j].getDefensiveCopy(); } } return copy; } /** * * @param row * of the board * @param col * of the board * @return if the col and row are in bounds of the board */ public boolean isInBounds(int row, int col) { return ((row < boardArr.length && row >= 0) && (col < boardArr.length && col >= 0)); } public boolean isEmpty(int row, int col) { return (boardArr[row][col].getLetter() == null); } public Square[][] getBoardArr() { return boardArr; } public void setBoardArr(Square[][] boardArr) { this.boardArr = boardArr; } @Override public String toString() { String result = "["; for (int i = 0; i < size; i++) { result += "[ "; for (int j = 0; j < size; j++) { result += boardArr[i][j].toString() + ","; } result += " ]" + "\n"; } result += " ]"; return result; } } <file_sep>My extra tile that I plan to implement is an extra turn for the player who activated that tile when placing a new word over it.<file_sep>hw5b Feedback ============ #### Core Framework Implementation (53/70) ##### Technical Requirements Your framework meets the technical requirements to a reasonable degree. Good job! ##### Correctly Working Framework and Testing * Your framework GUI throws exceptions when I press "Submit and Start" without first selecting a data plugin. * You did not write any unit tests for your framework. ##### General Design The general design of your framework is reasonable, but we identified the following issue: * The data plugins have direct access to parts of the framework internals that should only be accessible to the framework UI. For example, data plugins can register other plugins, and get a list of available plugins. Look at recitation 9 for one way to hide the the framework internals. #### Sample Plugins (15/30) * You only implemented one sample visualization plugin. You were required to implement at least two visualization plugins. * Your framework throws a `NullPointerException` that prevents it from doing anything default CSV file and pie chart plugin. #### Gradle run target (0/5) * Your build fails to compile with gradle because you neither included the `.jar` files for your dependencies nor did you include Maven dependencies in your `build.gradle`. #### High quality documentation and style (11/20) ##### Documentation * You did not provide a `README` file explaining how to use your framework (as specified in the homework handout). ##### Style * Some class fields do not use the most restrictive access modifier. ([link](https://github.com/CMU-15-214/Team22/blob/27f6c7ed4f35d14f7491c018ce77e6f111a50cb6/hw5b/edu/cmu/cs/cs214/hw5/framework/gui/GUIFrameworkImpl.java#L57-L58)) * Avoid using magic numbers in your code. Declare variables as `static final` constants at the top of the file. ([link](https://github.com/CMU-15-214/Team22/blob/27f6c7ed4f35d14f7491c018ce77e6f111a50cb6/hw5b/edu/cmu/cs/cs214/hw5/framework/gui/GUIFrameworkImpl.java#L189)) * `static` fields were used incorrectly. `core` should be a local variable in `main` and passed to the helper function. ([link](https://github.com/CMU-15-214/Team22/blob/27f6c7ed4f35d14f7491c018ce77e6f111a50cb6/hw5b/edu/cmu/cs/cs214/hw5/main/Main.java#L17)) #### Presentation/Demo (35/35) ##### Framework Description Your presentation of the framework description fully meets our expectations, good job! ##### Talk Quality The quality of your presentation fully met our expectations, good job! ##### Timing The length of your presentation met our expectations, good job! ##### Demo Your live demo met our expectations. --- #### Total (114/160) Late days used: 1 (1 left for hw5) --- #### Additional Notes Graded by: <NAME> (<EMAIL>) To view this file with formatting, visit the following page: https://github.com/CMU-15-214/said/blob/master/grades/hw5b.md<file_sep>hw4c Feedback ============ #### Design of GUI and Special Tile Implementation (30/30) * Your implementation effectively separates the GUI from the Core. * Your implementation seems to completely implement the additional special tile in an extensible way. Nice job! #### Implementation of GUI (18/40) * Your GUI does not display many of the key pieces of information we would expect to see while playing Scrabble. * Your GUI crashes when I run it. * Your GUI correctly handled the various board state change events. Well done! * Your GUI does not contain any of the key aspects of Scrabble gameplay. * I could not run it * Build automation using gradle and Travis CI seems to work fine, but we were unable to start your game using `gradle run`. * Your implementation meets our expectations regarding documentation and style. #### Reflection on the design process (5/10) * You did not submit a `discussion.pdf` --- #### Total (53/80) #### HW4A Points Back: 5 * 0.75 = 3.75 Late days used: 1 (1 left) --- #### Additional Notes Graded by: <NAME> (<EMAIL>) To view this file with formatting, visit the following page: https://github.com/CMU-15-214/said/blob/master/grades/hw4c.md <file_sep>package edu.cmu.cs.cs214.hw4.core; import static org.junit.Assert.*; import org.junit.Test; import edu.cmu.cs.cs214.hw4.tiles.LetterTile; public class SquareTest { @Test public void basicTest() { Character ch = new Character('Q'); LetterTile Q = new LetterTile(ch , 10); Square s = new Square(1, 1, Q); Square s2 = new Square(1, 2, Q); Square s3 = new Square(1, 1, Q); assertTrue(s.equals(s3)); assertTrue(!s.equals(s2)); assertTrue(s.toString().equals("[Q-10] - wm:1 - lm:1")); assertTrue(s.hashCode() != s2.hashCode()); } @Test public void defCopyTest() { Character ch = new Character('Q'); LetterTile Q = new LetterTile(ch , 10); Square s = new Square(1, 1, Q); Square s2 = s.getDefensiveCopy(); assertTrue(!s.equals(s2)); assertTrue(s.hashCode() == s2.hashCode()); } } <file_sep>package edu.cmu.cs.cs214.hw4.core; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import edu.cmu.cs.cs214.hw4.tiles.Bag; import edu.cmu.cs.cs214.hw4.tiles.LetterTile; import edu.cmu.cs.cs214.hw4.tiles.SpecialTile; public class Player { private int score = 0; private final static int numOfTiles = 7; /** * emptyRackIndeces are empty indeces of a rack when letters removed */ private List<Integer> emptyRackIndeces = new ArrayList<Integer>(); private List<SpecialTile> boughtST = new ArrayList<>(); private final String name; private int turnsLost = 0; private LetterTile[] rack = new LetterTile[numOfTiles]; private Bag bag; public Player(String name, Bag b) { this.name = name; this.bag = b; for (int i = 0; i < numOfTiles; i++) { rack[i] = getTile(); } } /** * swaps all 7 tiles for new (could be the same ones) tiles */ public void exchangeTiles() { for (int i = 0; i < numOfTiles; i++) { bag.getAllTiles().add(rack[i]); rack[i] = null; emptyRackIndeces.add(i); } Collections.shuffle(bag.getAllTiles()); replenishRack(); } /** * adds the required amount of tiles to make a rack full again */ public void replenishRack() { for (int i = 0; i < emptyRackIndeces.size(); i++) { rack[emptyRackIndeces.get(i)] = getTile(); } emptyRackIndeces.clear(); } LetterTile getTile() { return bag.getAllTiles().remove(bag.getAllTiles().size() - 1); } /** * * @param l * is the list of LetterTiles that need to be placed back on the rack * when a challenge is successful */ public void putLettersBackOnRack(List<LetterTile> l) { assert (l.size() == emptyRackIndeces.size()); for (int i = 0; i < emptyRackIndeces.size(); i++) { rack[emptyRackIndeces.get(i)] = l.get(i); } emptyRackIndeces.clear(); } public boolean equals(Object o) { if (!(o instanceof Player)) return false; Player other = (Player) o; return equals(other.getName() == (name)); } public String toString() { return getName(); } /** * * @param l * is the lettertile to remove from Rack */ public void removeTileFromRack(LetterTile l) { for (int i = 0; i < numOfTiles; i++) { if (rack[i] != null && rack[i].equals(l)) { rack[i] = null; emptyRackIndeces.add(i); break; } } } public String rackToString() { return String.format("[%s, %s, %s, %s, %s, %s, %s]", rack[0], rack[1], rack[2], rack[3], rack[4], rack[5], rack[6]); } public static int getNumoftiles() { return numOfTiles; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String getName() { return name; } public LetterTile[] getRack() { return rack; } public void setRack(LetterTile[] rack) { this.rack = rack; } public List<Integer> getEmptyRackIndeces() { return emptyRackIndeces; } public void setEmptyRackIndeces(List<Integer> emptyRackIndeces) { this.emptyRackIndeces = emptyRackIndeces; } public int getTurnsLost() { return turnsLost; } public void setTurnsLost(int turnsLost) { this.turnsLost = turnsLost; } public List<SpecialTile> getBoughtST() { return boughtST; } public void setBoughtST(List<SpecialTile> boughtST) { this.boughtST = boughtST; } } <file_sep>hw2 Feedback ============ #### Correctly applying the concepts of polymorphism and information hiding (/20) * Polymorphism (15/15) * Information Hiding (5/5) #### Java best practices and compatibility with our informal specification (29/30) * Part 1 (8/8) * Part 2 (9/9) * Part 3 (12/13) * Your `zero()` method does not restore your variable to its original value. This may result in unexpected results when evaluating other expressions using the same variable. #### Unit testing, including coverage and compliance with best practices (30/30) * Testing (12/12) * Coverage (12/12) * Best Practices (6/6) #### Documentation and style (19/20) * Constants should be in all uppercase, separated by underscores. Ex: `VARIABLE_NAME`. ([link](https://github.com/CMU-15-214/said/blob/master/homework/2/src/main/java/edu/cmu/cs/cs214/hw2/expression/DerivativeExpression.java#L14)) * _minor_ Constants should be declared `static final`. ([link](https://github.com/CMU-15-214/said/blob/master/homework/2/src/main/java/edu/cmu/cs/cs214/hw2/expression/DerivativeExpression.java#L14)) --- #### Total (98/100) Great work! Late days used: 0 (5 left) --- #### Additional Notes Graded by: <NAME> (<EMAIL>) To view this file with formatting, visit the following page: https://github.com/CMU-15-214/said/blob/master/grades/hw2.md <file_sep>package edu.cmu.cs.cs214.hw4.core; import static org.junit.Assert.assertTrue; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import edu.cmu.cs.cs214.hw4.tiles.Bag; import edu.cmu.cs.cs214.hw4.tiles.ExtraTurn; import edu.cmu.cs.cs214.hw4.tiles.LetterTile; import edu.cmu.cs.cs214.hw4.tiles.SpecialTile; public class ExtraturnTest { ScrabbleGame game; Board board; @Before public void setup() throws FileNotFoundException { Bag b = new Bag(); List<String> players = new ArrayList<>(); players.add("Kanye"); players.add("Kim"); players.add("North"); Set<String> dict = new HashSet<String>(); game = new ScrabbleGame(players, dict); board = game.getBoard(); } @Test public void ExtraTurnTileTest() throws FileNotFoundException { // initialization LetterTile Q = new LetterTile('Q', 10); LetterTile A = game.getCurrentPlayer().getRack()[0]; LetterTile B = game.getCurrentPlayer().getRack()[1]; LetterTile C = game.getCurrentPlayer().getRack()[2]; Player constantP = game.getCurrentPlayer(); System.out.println(constantP); board.boardArr[7][7].setLetter(Q); board.boardArr[0][7].setLetter(Q); game.getCurrentPlayer().setScore(100); SpecialTile extraTurn = new ExtraTurn(); game.placeSpecialTile(extraTurn, 0, 6); TilePlacement t1 = new TilePlacement(0, 6, A); TilePlacement t2 = new TilePlacement(0, 5, B); TilePlacement t3 = new TilePlacement(0, 4, C); List<TilePlacement> tiles = game.getTilesToPlace(); tiles.add(t1); tiles.add(t2); tiles.add(t3); game.placeTiles(tiles); game.activateSpecialTiles(); tiles.clear(); game.changeTurn(); assertTrue(game.getCurrentPlayer()==(constantP)); } } <file_sep>package edu.cmu.cs.cs214.hw2.expression; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import edu.cmu.cs.cs214.hw2.operator.Binary; /** * this tests for the variable expressions using the binary and unary operators * @author dsai96 * */ public class VariableExpressionTest { //CHECKSTYLE:OFF @Test public void test() { Variable x = new Variable("x"); x.store(3.0); Expression operand2 = new NumberExpression(10); Expression e = new BinaryExpression(Binary.ADD, x, operand2); assertEquals(e.eval(), 13.0, Math.pow(10, -4)); } @Test public void testToString() { Variable x = new Variable("x"); x.store(3.0); assertTrue(x.toString().equals("(x = 3.0)")); } @Test public void testGetter() { Variable x = new Variable("x"); x.store(3.0); assertTrue(x.name().equals("x")); } } <file_sep>package edu.cmu.cs.cs214.hw2.expression; import edu.cmu.cs.cs214.hw2.operator.BinaryOperator; /** * * @author dsai96 * Creates a BinaryExpression with 2 operands and operator * */ public class BinaryExpression implements Expression { private BinaryOperator operator; private Expression operand1; private Expression operand2; /** * * @param operator BinaryOperator that operands are being done on * @param operand1 expression that op is being done * @param operand2 expression that op is being done */ public BinaryExpression(BinaryOperator operator, Expression operand1, Expression operand2) { this.operator = operator; this.operand1 = operand1; this.operand2 = operand2; } @Override public double eval() { return operator.apply(operand1.eval(), operand2.eval()); } @Override public String toString() { return String.format("(%s %s %s)", operand1, operator, operand2); } } <file_sep>package edu.cmu.cs.cs214.hw4.tiles; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * * @author dsai96 The bag full of all LetterTiles initiated */ public class Bag { private List<LetterTile> allTiles = new ArrayList<LetterTile>(); public List<LetterTile> getAllTiles() { return allTiles; } public Bag() { populateBag(); Collections.shuffle(allTiles); } private void populateBag() { createTile(9, 'A', 1); createTile(2, 'B', 3); createTile(2, 'C', 3); createTile(4, 'D', 2); createTile(12, 'E', 1); createTile(2, 'F', 4); createTile(3, 'G', 2); createTile(2, 'H', 4); createTile(9, 'I', 1); createTile(1, 'J', 8); createTile(1, 'K', 5); createTile(4, 'L', 1); createTile(2, 'M', 3); createTile(6, 'N', 1); createTile(8, 'O', 1); createTile(2, 'P', 3); createTile(1, 'Q', 10); createTile(6, 'R', 1); createTile(4, 'S', 1); createTile(6, 'T', 1); createTile(4, 'U', 1); createTile(2, 'V', 4); createTile(2, 'W', 4); createTile(1, 'X', 8); createTile(2, 'Y', 4); createTile(1, 'Z', 10); } private void createTile(int count, char letter, int score) { LetterTile tile = new LetterTile(letter, score); for (int i = 0; i < count; i++) { allTiles.add(tile); } } } <file_sep>package edu.cmu.cs.cs214.hw4.core; import static org.junit.Assert.*; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import edu.cmu.cs.cs214.hw4.tiles.Bag; import edu.cmu.cs.cs214.hw4.tiles.LetterTile; import edu.cmu.cs.cs214.hw4.tiles.NegativePoints; import edu.cmu.cs.cs214.hw4.tiles.SpecialTile; public class NegativePointsTest { private ScrabbleGame game; private Board board; @Before public void setup() throws FileNotFoundException { Bag b = new Bag(); List<String> players = new ArrayList<>(); players.add("Kanye"); players.add("Kim"); players.add("North"); Set<String> dict = new HashSet<String>(); game = new ScrabbleGame(players, dict); board = game.getBoard(); } @Test public void NegativeTileTest() throws FileNotFoundException { //initialization LetterTile Q = new LetterTile('Q' , 10); LetterTile A = game.getCurrentPlayer().getRack()[0]; LetterTile B = game.getCurrentPlayer().getRack()[1]; LetterTile C = game.getCurrentPlayer().getRack()[2]; Board board = game.getBoard(); board.boardArr[7][7].setLetter(Q); board.boardArr[0][7].setLetter(Q); game.getCurrentPlayer().setScore(100); SpecialTile negpts = new NegativePoints(); game.buySpecialTile(negpts); assertTrue(game.getCurrentPlayer().getScore() == 75); game.placeSpecialTile(negpts, 0, 6); TilePlacement t1 = new TilePlacement(0, 6, A); TilePlacement t2 = new TilePlacement(0, 5, B); TilePlacement t3 = new TilePlacement(0, 4, C); List<TilePlacement> tiles = game.getTilesToPlace(); tiles.add(t1); tiles.add(t2); tiles.add(t3); game.placeTiles(tiles); game.findWordsandCalculateMoveScore(); game.activateSpecialTiles(); assertTrue(game.getCurrentPlayer().getScore() == 75); tiles.clear(); } }<file_sep>package edu.cmu.cs.cs214.hw4.core; import edu.cmu.cs.cs214.hw4.tiles.LetterTile; import edu.cmu.cs.cs214.hw4.tiles.SpecialTile; /** * * @author dsai96 * Square class is used in the board to represent the boxes */ public class Square { private final int wordMultiplier; private final int letterMultiplier; private LetterTile letter; private SpecialTile special; public Square(int wordMultiplier, int letterMultiplier, LetterTile letter) { this.wordMultiplier = wordMultiplier; this.letterMultiplier = letterMultiplier; this.letter = letter; } public SpecialTile getSpecial() { return special; } public void setSpecial(SpecialTile special) { this.special = special; } public int getWordMultiplier() { return wordMultiplier; } public int getLetterMultiplier() { return letterMultiplier; } public LetterTile getLetter() { return letter; } public Square getDefensiveCopy() { return new Square(wordMultiplier, letterMultiplier, letter == null ? null : letter.getDefensiveCopy()); } public void setLetter(LetterTile letter) { this.letter = letter; } @Override public boolean equals(Object o) { if (!(o instanceof Square)) { return false; } Square other = (Square) o; return (other.letter.getName() == this.letter.getName() && other.letter.getPointValue() == letter.getPointValue() && other.letterMultiplier == this.letterMultiplier && other.wordMultiplier == this.wordMultiplier); } @Override public int hashCode() { int result = 17; result = 31 * result + (int) (getLetter().getName()); result = 31 * result + letterMultiplier; result = 31 * result + wordMultiplier; return result; } @Override public String toString() { if (letter != null) { return String.format("[%s, %s, %s]", letter.toString(), wordMultiplier, letterMultiplier); } else { return String.format("[null, %s, %s]", wordMultiplier, letterMultiplier); } } } <file_sep>package edu.cmu.cs.cs214.hw6.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; /** * This class represents a class file that is ready to be serialized and sent * through the network, or "pickled", so to speak. A pickled class can then be * revived into a class object that can be used for reflections. */ public class PickledClass implements Serializable { /** The fully qualified class name (e.g. "java.lang.String") */ private final String name; /** The bytes from the class file for this class */ private final byte[] classFile; /** * Instantiates a new pickled class from a class object. * * @param classObj the class object of the class to be pickled. */ public PickledClass(Class<?> classObj) { name = classObj.getName(); String name = classObj.getName(); InputStream is = classObj.getResourceAsStream(name.substring(name.lastIndexOf('.') + 1) + ".class"); try { classFile = inputStreamToByteArray(is); } catch (IOException e) { throw new AssertionError(e); } } /** * Instantiates a new pickled class from a class file. * * @param fullClassName the fully qualified class name * @param path the relative or absolute path to the classfile * @throws IllegalArgumentException if the class file is invalid. Note * that you will *NOT* get this exception if the classfile and * the name don't match, but the revive method will fail when applied * to such a (broken) pickled class. */ public PickledClass(String fullClassName, Path path) { try { this.name = fullClassName; this.classFile = Files.readAllBytes(path); } catch (IOException e) { throw new IllegalArgumentException(e); } } /** * Load the class onto the current vm and return the class object for it. * * @return the loaded class object * @throws IllegalStateException if the class file bytes do not match the * class name. */ public Class<?> revive() { ByteArrayClassLoader loader = new ByteArrayClassLoader(); try { return loader.getClassFromBytes(name, classFile); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } /** Returns a byte array containing all of the data read from the given InputStream */ private static byte[] inputStreamToByteArray(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); byte[] buffer = new byte[4096]; int bytesRead; while((bytesRead = is.read(buffer)) > 0) { baos.write(buffer, 0, bytesRead); } return baos.toByteArray(); } // Appease the serialization gods private static final long serialVersionUID = 42L; } <file_sep>package edu.cmu.cs.cs214.hw4.core; import static org.junit.Assert.*; import org.junit.Test; import edu.cmu.cs.cs214.hw4.tiles.Bag; import edu.cmu.cs.cs214.hw4.tiles.LetterTile; public class PlayerTest { @Test public void test() { Bag b1 = new Bag(); Player p1 = new Player("Kanye", b1); LetterTile l = p1.getRack()[0]; p1.removeTileFromRack(l); assertTrue(p1.getRack()[0] == null); } @Test public void exchangeTest() { Bag b = new Bag(); Player p1 = new Player("Kanye", b); assertTrue(b.getAllTiles().size() == 91); p1.exchangeTiles(); System.out.println(b.getAllTiles().size() ); assertTrue(p1.getRack()[0] != null); assertTrue(b.getAllTiles().size() == 91); } @Test public void getTileTest() { Bag b = new Bag(); Player p1 = new Player("Kanye", b); assertTrue(b.getAllTiles().size() == 91); p1.getTile(); assertTrue(b.getAllTiles().size() == 90); p1.getTile(); p1.getTile(); p1.getTile(); p1.getTile(); assertTrue(b.getAllTiles().size() == 86); } @Test public void replenishTest() { Bag b = new Bag(); Player p1 = new Player("Kanye", b); assertTrue(b.getAllTiles().size() == 91); p1.replenishRack(); assertTrue(b.getAllTiles().size() == 91); p1.getEmptyRackIndeces().add(0); p1.replenishRack(); assertTrue(b.getAllTiles().size() == 90); p1.getEmptyRackIndeces().add(6); p1.getEmptyRackIndeces().add(0); p1.replenishRack(); assertTrue(b.getAllTiles().size() == 88); } } <file_sep>hw5c Feedback ============ #### Working Project (8/10) * You did not commit all the files required to run `gradle build`. #### Plugin Implementation (50/50) ##### Data Plugins Your data plugins look reasonable. Good job! ##### Visualization Plugins Your visualization plugins look reasonable. Good job! #### Documentation and style (4/5) * Several of your classes are missing Javadocs. #### Experience Report (10/10) Your experience report meets our expectations. Good job! --- #### Total (72/75) Late days used: 0 (1 left for hw5) --- #### Additional Notes Graded by: <NAME> (<EMAIL>) To view this file with formatting, visit the following page: https://github.com/CMU-15-214/said/blob/master/grades/hw5c.md<file_sep>package edu.cmu.cs.cs214.hw6.harness; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Creates a version of {@code Process} that can be restarted after it has been stopped. */ final class RestartableProcess extends Process { private final ProcessBuilder builder; private Process delegateProcess; private boolean paused = false; static RestartableProcess startWithBuilder(ProcessBuilder builder) throws IOException { return new RestartableProcess(builder); } private RestartableProcess(ProcessBuilder builder) throws IOException { this.builder = builder; delegateProcess = builder.start(); } @Override public OutputStream getOutputStream() { return delegateProcess.getOutputStream(); } @Override public InputStream getInputStream() { return delegateProcess.getInputStream(); } @Override public InputStream getErrorStream() { return delegateProcess.getErrorStream(); } @Override public int waitFor() throws InterruptedException { return delegateProcess.waitFor(); } @Override public int exitValue() { return delegateProcess.exitValue(); } @Override public void destroy() { // Setting pause to false prevents a destroyed process from being resumed paused = false; delegateProcess.destroy(); } @Override public Process destroyForcibly() { // Setting pause to false prevents a destroyed process from being resumed paused = false; return delegateProcess.destroyForcibly(); } /** * Allows a stopped process to be restarted. Requires that the process was previously suspended. * A process that was "destroyed" rather than "suspended" cannot be restarted. */ void restart() { assert paused && !delegateProcess.isAlive(); try { // Replace the old process with a new one delegateProcess = builder.start(); } catch (IOException e) { // An IOException should never be thrown here because we are restarting a process that we // know has already started successfully System.err.println("Unexpected IOException while restarting worker process."); System.exit(-1); } } /** * Terminate a process with the intent that it will later be restarted. Note that this method * kills the underlying process because it is unable to simply suspend operation. */ void stop() { assert !isAlive() && !paused; // Set the paused flag to indicate the process is allowed to be restarted paused = true; delegateProcess.destroyForcibly(); } boolean isResumable() { return !delegateProcess.isAlive() && paused; } } <file_sep>package edu.cmu.cs.cs214.hw2.expression; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import edu.cmu.cs.cs214.hw2.operator.Binary; //CHECKSTYLE:OFF public class BinaryExpressionTestTest { @Test public void testAdd() { Expression operand1 = new NumberExpression(3); Expression operand2 = new NumberExpression(10); Expression e = new BinaryExpression(Binary.ADD, operand1, operand2); assertEquals(e.eval(), 13.0, Math.pow(10, -4)); } @Test public void testSubtract() { Expression operand1 = new NumberExpression(3); Expression operand2 = new NumberExpression(10); Expression e = new BinaryExpression(Binary.SUBTRACT, operand1, operand2); assertEquals(e.eval(), -7.0, Math.pow(10, -4)); } @Test public void testMultiply() { Expression operand1 = new NumberExpression(3); Expression operand2 = new NumberExpression(10); Expression e = new BinaryExpression(Binary.MULTIPLY, operand1, operand2); assertEquals(e.eval(), 30.0, Math.pow(10, -4)); } @Test public void testDivide() { Expression operand1 = new NumberExpression(30); Expression operand2 = new NumberExpression(10); Expression e = new BinaryExpression(Binary.DIVIDE, operand1, operand2); assertEquals(e.eval(), 3.0, Math.pow(10, -4)); assertTrue(e.toString().equals("((30.0) / (10.0))")); } @Test public void testExponent() { Expression operand1 = new NumberExpression(3); Expression operand2 = new NumberExpression(4); Expression e = new BinaryExpression(Binary.EXP, operand1, operand2); assertEquals(e.eval(), 81.0, Math.pow(10, -4)); assertTrue(e.toString().equals("((3.0) ^ (4.0))")); } @Test public void testToString() { Expression operand1 = new NumberExpression(3); Expression operand2 = new NumberExpression(10); Expression e = new BinaryExpression(Binary.ADD, operand1, operand2); assertTrue(e.toString().equals("((3.0) + (10.0))")); } } <file_sep>package edu.cmu.cs.cs214.hw4.core; import static org.junit.Assert.*; import org.junit.Test; import edu.cmu.cs.cs214.hw4.tiles.LetterTile; public class BoardTest { @Test public void test() { Board b = new Board(); assertTrue(b.getDefensiveCopy() != b); Character ch = new Character('Q'); LetterTile Q = new LetterTile(ch , 10); Square s = new Square(1, 1, Q); b.boardArr[0][0] = s; // System.out.println(b.getDefensiveCopy()); // System.out.println(b); assertTrue(b.getDefensiveCopy().boardArr[0][0].equals(b.boardArr[0][0])); assertTrue(!b.getDefensiveCopy().equals(b)); int[] t = new int[]{ 0, 14 }; int[][] hi = new int[][]{{ 14, 14 }, { 0, 0 }, { 0, 7 }, { 7, 0 }, { 14, 0}, { 0, 14 }}; assertTrue(b.contains(t, hi)); } @Test public void isInBoundsTest() { Board b = new Board(); assertTrue(b.isInBounds(3, 3)); assertTrue(b.isInBounds(0, 0)); assertTrue(b.isInBounds(14, 14)); assertTrue(b.isInBounds(0, 14)); assertTrue(b.isInBounds(14, 0)); assertTrue(b.isInBounds(3, 14)); assertTrue(b.isInBounds(3, 0)); assertTrue(b.isInBounds(3, 13)); assertTrue(!b.isInBounds(-1, 3)); assertTrue(!b.isInBounds(15, 3)); assertTrue(!b.isInBounds(-1, 14)); assertTrue(!b.isInBounds(-1, 0)); assertTrue(!b.isInBounds(2, -1)); assertTrue(!b.isInBounds(3, 15)); assertTrue(!b.isInBounds(2, 34)); } @Test public void isEmptyTest() { Board b = new Board(); LetterTile Q = new LetterTile('Q', 10); Square s = new Square(1, 1, Q); b.boardArr[0][0] = s; b.boardArr[10][2] = s; assertTrue(!b.isEmpty(0,0)); assertTrue(!b.isEmpty(10,2)); assertTrue(b.isEmpty(14, 14)); assertTrue(b.isEmpty(0, 14)); assertTrue(b.isEmpty(14, 0)); } } <file_sep>package edu.cmu.cs.cs214.main; public class MyReduce implements Reduce { } <file_sep>package edu.cmu.cs.cs214.hw1; import java.io.IOException; /** * * @author dsai96 * This class HighestCosSim which records the cosSim value between two urls. */ public class HighestCosSim { private String url1; private String url2; private Double cosSim; /** * * @param url1 is the first url * @param url2 is the second url to compare with the first url * @param cosSim the cosSim value between those two urls. * @throws IOException needs to check if both urls inputted are valid */ public HighestCosSim(String url1, String url2, Double cosSim) throws IOException { this.url1 = url1; this.url2 = url2; this.cosSim = cosSim; } /** * * @return the cosSim value */ public Double getCosSim() { return cosSim; } /** * * @return url2 */ public String getUrl2() { return url2; } /** * @return url1 */ public String getUrl1() { return url1; } } <file_sep>package edu.cmu.cs.cs214.hw4.core; import static org.junit.Assert.assertTrue; import org.junit.Test; import edu.cmu.cs.cs214.hw4.tiles.Bag; public class BagTest { @Test public void test() { Bag b = new Bag(); assertTrue(b.getAllTiles().size() == 98); } @Test public void exchangeTest() { Bag b1 = new Bag(); assertTrue(b1.getAllTiles().size() == 98); Player p1 = new Player("Kanye", b1); assertTrue(b1.getAllTiles().size() == 91); assertTrue(p1.getRack().length == 7); // b1.exchangeTiles(p1); assertTrue(p1.getRack().length == 7); assertTrue(b1.getAllTiles().size() == 91); } } <file_sep>package edu.cmu.cs.cs214.hw2.termcalc; import edu.cmu.cs.cs214.hw2.expression.BinaryExpression; import edu.cmu.cs.cs214.hw2.expression.Expression; import edu.cmu.cs.cs214.hw2.expression.NumberExpression; import edu.cmu.cs.cs214.hw2.expression.UnaryExpression; import edu.cmu.cs.cs214.hw2.operator.Binary; import edu.cmu.cs.cs214.hw2.operator.Unary; /** * ExpressionMake implements expressionMaker * @author dsai96 * */ public class ExpressionMake implements ExpressionMaker { @Override public Expression sumExpression(Expression addend1, Expression addend2) { return new BinaryExpression(Binary.ADD, addend1, addend2); } @Override public Expression differenceExpression(Expression op1, Expression op2) { return new BinaryExpression(Binary.SUBTRACT, op1, op2); } @Override public Expression productExpression(Expression factor1, Expression factor2) { return new BinaryExpression(Binary.MULTIPLY, factor1, factor2); } @Override public Expression divisionExpression(Expression dividend, Expression divisor) { return new BinaryExpression(Binary.DIVIDE, dividend, divisor); } @Override public Expression exponentiationExpression(Expression base, Expression exponent) { return new BinaryExpression(Binary.EXP, base, exponent); } @Override public Expression negationExpression(Expression operand) { return new UnaryExpression(Unary.NEGATION, operand); } @Override public Expression absoluteValueExpression(Expression value) { return new UnaryExpression(Unary.ABSVALUE, value); } @Override public Expression numberExpression(double value) { return new NumberExpression(value); } } <file_sep>package edu.cmu.cs.cs214.hw4.core; import edu.cmu.cs.cs214.hw4.tiles.LetterTile; /** * * @author dsai96 This is the representation of tiles that need be row and col * and the letterTile */ public class TilePlacement { private final int row; private final int col; private final LetterTile letter; public TilePlacement(int row, int col, LetterTile letter) { this.row = row; this.col = col; this.letter = letter; } public int getRow() { return row; } public int getCol() { return col; } public LetterTile getLetter() { return letter; } public boolean equals(Object o) { if (!(o instanceof TilePlacement)) { return false; } TilePlacement other = (TilePlacement) o; return (other.row == row && other.col == col && other.letter == letter); } @Override public int hashCode() { int result = 17; result = 31 * result + (int) (letter.getName()); result = 31 * result + col; result = 31 * result + row; return result; } } <file_sep>package edu.cmu.cs.cs214.hw6.servers; import java.util.Arrays; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Placeholder to show how to user the chaos monkey build configuration. */ public final class DummyServer implements Runnable { private static final long NANO_PER_MILLI = 1000; private final String name; private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); private final long startTime; private DummyServer(String name) { this.name = name; this.startTime = System.nanoTime(); } /** * Prints out the number of milliseconds since the server started, roughly once per second. */ @Override public void run() { // The two integer arguments are the initial delay, and the period. Both // are 1 second. scheduledExecutor.scheduleAtFixedRate(() -> { long nanosElapsed = System.nanoTime() - startTime ; long msElapsed = nanosElapsed / NANO_PER_MILLI; System.out.println(name + " running after " + msElapsed + "ms."); }, 1, 1, TimeUnit.SECONDS); } public static void main(String[] args) { System.out.println("Spawning server with arguments: " + Arrays.toString(args)); new DummyServer(args[0]).run(); } } <file_sep>package edu.cmu.cs.cs214.hw3.expression; /** * * @author dsai96 this class returns zeros using Newtons method * */ public class NewtonMethod { /** * * @param fn function to take derative of * @param x with respect to * @param approxZero starting value, that has to be higher than the actual value * @param tolerance the zero * @return the zero */ public static double zero(Expression fn, Variable x, double approxZero, double tolerance) { x.store(approxZero); if (fn.eval() <= tolerance) return approxZero; DerivativeExpression d = new DerivativeExpression(fn, x); approxZero = x.eval() - fn.eval()/d.eval(); x.store(approxZero); return zero(fn, x, approxZero, tolerance); } } <file_sep>package edu.cmu.cs.cs214.hw2.expression; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * this creates tests for the number expression eval and toString * @author dsai96 * */ public class NumberExpressionTest { //CHECKSTYLE:OFF @Test public void testEval() { Expression operand1 = new NumberExpression(3); assertEquals(operand1.eval(), 3.0, Math.pow(10, -4)); } @Test public void testToString() { Expression operand1 = new NumberExpression(-3); assertTrue(operand1.toString().equals("(-3.0)")); } } <file_sep>hw4a Feedback ============ #### Notation (20/20) * Your diagrams conform well to our expectations on UML notation across all models. Well done. #### Domain Model (11/16) * Your domain model misses a few minor concepts and relationships. * Poor modeling of classes vs. attribute in your domain model * You have unlabeled relationships which makes your model hard to understand. * Your domain model matches our expectations regarding the level of abstraction #### System Sequence Diagram (8/8) * Your system sequence diagram matches our expectation regarding the level of abstraction * Your system sequence diagram sufficiently models the interactions in the given scenario #### Behavioral Contracts (4/4) * Your contracts reasonably describes the interface and are written at the right level of abstraction #### Interaction Diagram (`challenge`) (16/16) * Your interaction diagram matches our expectations regarding modeling accuracy of the challenging interaction. Well done. * We have no major concerns regarding the design (e.g., responsibility assignment) of your validation interaction * Your interaction diagram matches our expectation regarding the level of abstraction #### Interaction Diagram (`makeMove`) (8/16) * Your interaction diagram roughly describes the move mechanism, but misses several major aspects of counting points or evaluating special tiles, as annotated in the model. * Your diagram should start with a call on some object with parameters indicating a move * You do not check the physical validity of a move. Show how this interaction works * Your diagram should show how you get words from placed tiles * Your diagram should show the evaluation of special tiles * Special tiles should be able to modify the board, player order, and computed points * We have no major concerns regarding the design (e.g., responsibility assignment) of your move interaction * Your interaction diagram matches our expectation regarding the level of abstraction #### Object Model (16/16) * We have no major concerns regarding the completeness of your object model * In general, your object model seems reasonable from a design perspective (e.g., responsibility assignment). We have only minor suggestions for improvement, as annotated in the models. * We have no major concerns regarding abstraction level and use of object-oriented concepts in your object model * Your object model matches our expectation regarding the level of abstraction #### Justification (4/4) * Your justification meets our expectations regarding vocabulary and discussion of design goals and principles, thanks. #### Consistency (20/20) * We have no major concerns regarding consistency across your modeling artifacts. Well done! You can regain up to 75% of the points lost in this milestone in Milestone C by addressing our comments and updating your design documents. If you have lost a large number of points, we recommend some interaction with the course staff. Beyond that, we do *not* pose additional questions that you need to answer for Milestone C. --- #### Total (107/120) Late days used: 1 (2 left) --- #### Additional Notes Graded by: <NAME> (<EMAIL>) To view this file with formatting, visit the following page: https://github.com/CMU-15-214/said/blob/master/grades/hw4a.md <file_sep>package edu.cmu.cs.cs214.hw6.harness; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.Scanner; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; import static java.util.stream.Collectors.toList; /** * Runs a set of servers for a MapReduce system. Using a configuration file passed in via command * line argument, the testing harness will start a single master server, and multiple worker * servers. The configuration file will allow clients to configure the port numbers used, as well as * the probability that individual workers will fail. * <h2>Configuration File</h2> * <p>The configuration file should be a CSV file in which the first line corresponds to the master * server, and any remaining lines each correspond to a single worker server. The first two values * on each line are used to configure the fault injection features of the harness (these are * specified below). The remaining values on each line, if they exist, are passed to the * corresponding server's {@code main} method.</p> * <h2>Fault Injection</h2> * <p>As mentioned above, the first two values in each configuration line are used to configure * fault injection features. There are two methods of fault injection available via the harness: * <em>delayed kills</em> and <em>chaos</em>.</p> * <h3> Delayed Kills</h3> * <p>A delayed kill permanently deactivates the target server after a specified number of * milliseconds. The first argument of each configuration line will be interpreted as a {@code long} * number of milliseconds until a delayed kill should occur. A value of 0 in the first position will * be interpreted as "never kill this server".</p> * <h3>Chaos</h3> * <p>Adding chaos to a server makes it experience temporary outages. The second argument of each * configuration line will be interpreted as a {@code double} failure probability. This probability * represents the chance that the server will be inactive for a given chaos interval. Chaos * intervals are short periods (3s by default but you may change this). A server's given failure * probability is the chance that it is inaccessible for each chaos interval (i.e. the availability * is determined independently at each interval).</p> * <p>To ensure a server is always running, set its failure probability to 0.</p> * <p><strong>Note:</strong> The master server should have a failure probability of 0.</p> * <h2>Usage</h2> * <p>It is expected that the harness will be used mostly for build configuration at first. To run * the test harness without any fault injection behaviors, set both the kill delay and failure * probability to 0.</p> * <p>Once a MapReduce implementation runs reliably without any failures, faults can be added * slowly. Delayed kill faults are the simplest to deal with. Adding a single delayed kill will is a * good way to test simple fault tolerance abilities. Adding many delayed kills to workers may is a * good way to test how a framework responds when it cannot complete a computation. Adding chaos to * servers, especially simultaneously, is a way to challenge a MapReduce framework that includes * sophisticated mechanisms to handle faults.</p> * <h3>Example Configurations</h3> * <p> The following example configurations illustrate how to add custom arguments to configuration * files, as well as how to specify fault injection parameters. Clients can customize their * arguments to suit the needs of their specific server programs.</p> * <h4>Custom Arguments</h4> * <p>All arguments on a single line of a configuration file beyond the second argument will be * passed to the corresponding server's main method. These arguments can be different for each * server.</p> * <p>The example configuration files assume that the master server's {@code main} method will * expect its first argument to be its name, the second to be its port, and all remaining arguments * to be the port numbers of available worker servers. It is assumed that each worker server's * {@code main} method expects the first argument to be its port number, and the second to be its * name.</p> * <p><strong>Zero Failure Configuration</strong></p> * <p>The following configuration file will create a master server and 3 workers. None of them will * ever be killed by the harness.</p> * <pre> * 0, 0, Master, 8080, 8090, 8091, 8092 * 0, 0, Worker 0, 8090 * 0, 0, Worker 1, 8091 * 0, 0, Worker 2, 8092 * </pre> * <p>The resulting arguments for each server would be:</p> * <pre> * Master: [ "master", "8080", "8090", "8091", "8092"] * Worker0: [ "worker0", "8090" ] * Worker1: [ "worker1", "8091" ] * Worker2: [ "worker2", "8092" ] * </pre> * <p><strong>Compound Failure Configuration</strong></p> * <p>In the following configuration, the * master server, and workers 1 and 2 will not be killed by the harness, but Worker 0 will be. * Worker 0 is expected to be inactive for 25% of chaos intervals (expected). After ten seconds * (1000 milliseconds) it will be permanently killed. In other words, Worker 0 will be inactive for * 25% of the time between 0 and 5 seconds, and will be inactive for 100% of the time after 5 * seconds.</p> * <pre> * 0, 0, Master, 8080, 8090, 8091, 8092 * 10000, 0.5, Worker 0, 8090 * 0, 0, Worker 1, 8091 * 0, 0, Worker 2, 8092 * </pre> * <p>Notice that both the first and second configurations pass the same exact information to each * spawned server. Fault injection configuration is independent of server arguments.</p> */ public final class MapReduceHarness { // The chaos interval determines the amount of delay between the discrete chaos events, which // might terminate processes. private static final long CHAOS_INTERVAL = 3; private static final TimeUnit CHAOS_INTERVAL_UNITS = TimeUnit.SECONDS; private static final Random RANDOM = new Random(); private static final ScheduledExecutorService SCHEDULED_EXECUTOR = newSingleThreadScheduledExecutor(); // Used when executing other java programs as Processes private static final String JAVA_BIN = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; private static final String CLASSPATH_FLAG = "-cp"; private static final String JAVA_CLASSPATH = System.getProperty("java.class.path"); // Delimiter used to separate arguments in the configuration file private static final String CONFIG_DELIMITER = ","; // Type token to pass to toArray. private static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * Creates a new server process according to the given configuration, using the given class's main * method. * * @param serverClass {@code Class} object for the server to be started. Must have a psvm method. * @param config Configuration file to start the server with. The format of this * configuration file is specified in this class's top level javadoc. * @return The {@link Process} of the newly started server. * @throws IOException if the creation of a child process fails. */ private static Process startServerProcess(Class serverClass, ServerConfig config) throws IOException { // The process command will consist of the java executable, the master server class name, and // the user arguments. It will NOT include the failure probability. List<String> commandTokens = new ArrayList<>(); // The first command token is the full path to the "java" executable. commandTokens.add(JAVA_BIN); commandTokens.add(CLASSPATH_FLAG); commandTokens.add(JAVA_CLASSPATH); commandTokens.add(serverClass.getCanonicalName()); commandTokens.addAll(Arrays.asList(config.userArgs)); // Create a new server process, and begin scheduling chaos events ProcessBuilder processBuilder = new ProcessBuilder(commandTokens.toArray(EMPTY_STRING_ARRAY)).inheritIO(); RestartableProcess serverProcess = RestartableProcess.startWithBuilder(processBuilder); injectChaos(serverProcess, config.killDelay, config.failureProbability); return serverProcess; } /** * Creates a new MapReduce harness, using the given path for the configuration file, as well as * the given master and worker server classes. * * @param args Arguments should be in the following format: * <pre> * path/to/chaos_config.csv * fully.qualified.class.name.for.MasterServer * fully.qualified.class.name.for.WorkerServer * </pre> * @throws IOException if the creation of a child process fails. * @throws ClassNotFoundException if either the master or worker class cannot be found. */ public static void main(String[] args) throws IOException, ClassNotFoundException { if (args.length < 3) { System.out.println("Usage: java MapReduceHarness <config file> <MasterClass> <WorkerClass> [master/worker args]"); System.exit(0); } // Copy arguments into local variables to avoid confusion String configFilePath = args[0]; Class masterServerClass = Class.forName(args[1]); Class workerServerClass = Class.forName(args[2]); // Construct a list holding each workers configuration information List<ServerConfig> allServers = new ArrayList<>(); try (Scanner configScanner = new Scanner(new File(configFilePath))) { // Create a new server configuration object while (configScanner.hasNextLine()) { allServers.add(ServerConfig.configFromString(configScanner.nextLine())); } } if (allServers.size() < 2) { System.out.println("Invalid configuration: There must be one master server and at least one worker server."); System.exit(0); } // By convention, the first server configuration is the master, and the rest are workers ServerConfig masterConfig = allServers.get(0); List<ServerConfig> workers = allServers.subList(1, allServers.size()); // Create each worker server for (ServerConfig workerConfig : workers) { startServerProcess(workerServerClass, workerConfig); } // Once all workers have started, start the master server if (masterConfig.failureProbability != 0.0) { System.out.println("WARNING: Master server started with non-zero probability of failure."); } startServerProcess(masterServerClass, masterConfig); } /** * Schedules non-deterministic failure in the future based on the chaos interval and configurable * failure probability of the given process. * * @param workerProcess Process to (possibly) kill in the future. * @param failureProbability Probability that the process with fail at any given interval. */ private static void scheduleTemporaryFailure(RestartableProcess workerProcess, final double failureProbability) { SCHEDULED_EXECUTOR.schedule(() -> { if (!workerProcess.isAlive() && !workerProcess.isResumable()) { // Process was permanently killed, do not schedule more actions in the future return; } if (RANDOM.nextDouble() < failureProbability) { // Sends a kill -9 signal to the created process. This is guaranteed // to succeed with processes created by ProcessBuilder if (workerProcess.isAlive()) { workerProcess.stop(); } } else if (!workerProcess.isAlive()) { assert workerProcess.isResumable(); // Process is either currently running, or can be restarted workerProcess.restart(); } scheduleTemporaryFailure(workerProcess, failureProbability); }, CHAOS_INTERVAL, CHAOS_INTERVAL_UNITS); } private static void injectChaos(RestartableProcess workerProcess, final long killDelay, final double failureProbability) { assert 0.0 <= failureProbability && failureProbability <= 1.0; // If the failure probability is 0, don't bother scheduling a runnable. if (failureProbability > 0.0) { scheduleTemporaryFailure(workerProcess, failureProbability); } if (killDelay > 0.0) { SCHEDULED_EXECUTOR.schedule(workerProcess::destroyForcibly, killDelay, TimeUnit.MILLISECONDS); } } private MapReduceHarness() { } /** * Represents the configuration information for a single server. */ private static final class ServerConfig { private final long killDelay; private final double failureProbability; private final String[] userArgs; /** * Creates a configuration object with the given configuration options. * * @param killDelay Milliseconds after startup after which the server should be * permanently killed. * @param failureProbability Probability that the server will fail at each failure event. * @param userArgs Arguments to be passed to the server on startup. */ private ServerConfig(long killDelay, double failureProbability, String[] userArgs) { assert failureProbability >= 0.0 && failureProbability <= 1.0; assert userArgs != null; this.killDelay = killDelay; this.failureProbability = failureProbability; this.userArgs = userArgs; } /** * Parses a configuration string into a {@code ServerConfig} object. * * @param configString A non-empty list of arguments, separated by {@code CONFIG_DELIMITER}. The * first argument should be parseable into a {@code double} between 0 and 1, * as it represents a failure probability. * @return A {@code ServerConfig} object representing the parsed values of the configuration * string. */ private static ServerConfig configFromString(String configString) { // Split string on the delimiter, then trim each resulting string List<String> tokens = Arrays.asList(configString.split(CONFIG_DELIMITER)) .stream().map(String::trim).collect(toList()); // The first item MUST be a kill time. 0 is interpreted to mean that the process should not be // killed long killDelay = Long.parseLong(tokens.get(0)); if (killDelay < 0) { System.out.println("Invalid kill delay given:\n\t"); System.out.println(configString); System.out.println("The delay must be non-negative, with 0 indicating never to fail"); System.exit(0); } // The second item MUST be a failure rate, which is a probability between 0 and one double failureProbability = Double.parseDouble(tokens.get(1)); if (failureProbability < 0.0 || failureProbability > 1.0) { System.out.println("Invalid failure rate given:\n\t"); System.out.println(configString); System.out.println("Probability values must be between 0.0 and 1.0"); System.exit(0); } // The arguments after the first two items are user arguments String[] userArgs = tokens.subList(2, tokens.size()).toArray(EMPTY_STRING_ARRAY); return new ServerConfig(killDelay, failureProbability, userArgs); } } } <file_sep>hw3 Feedback ============ #### Demonstrate mastery of earlier learning goals, especially the concepts of information hiding and polymorphism, software design based on informal specifications, testing, and testing best practices. (26/50) * Information hiding (8/10) * You expose various information of your cryptarithm representation in its public API because you have a separate solver class. Apply the information expert heuristics here to decrease exposure. * Compliance with specification (10/20) * Your solution does not solve cryptarithms. * Testing practices (8/10) * __minor__ You did not test exceptions, this is important because you want to make sure that they are being thrown under the appropriate conditions. * __minor__ JUnit includes a @Before annotation that lets you run code that runs before your tests are run. This lets you initialize your test class and/or create test objects in one place, which is easier and more consistent than creating separate test objects in every different test methods. * Tests should be split up into the smallest testable parts of a program. Try to avoid testing multiple methods in one test case or just testing a method that calls the rest. * __minor__ You have methods that are never called. E.g. solve() * Java coding best practices and style (0/10) * Your commit messages are not very descriptive of the changes you make. The first line of a commit message should always contain a concise description of the specific changes you made, and you should commit sufficiently regularly that it's easy to describe your changes with such a concise, specific message. In practice commit messages are often very important to track changes in a project. Please attempt more descriptive changes in the future. * You committed all or most of your code in a single big commit. It is good practice (and also a good backup strategy) to commit regularly at milestones while you are still developing the solution. * __minor__, You should have comments/documentation for your fields, even if they are private ([link](https://github.com/CMU-15-214/said/blob/master/homework/3/src/main/java/edu/cmu/cs/cs214/hw3/SolveCryptarithm.java#L13)). This is important because it allows the reader to understand the invariants in your classes. * You have long, poorly documented methods. It is good practice to either comment large blocks of code from a high level, or better still, write small methods that are self-documenting. * Please remove commented out code or dead code, your submissions should be finalized. These include unused imports, private methods, variables, and initializations. ([link](https://github.com/CMU-15-214/said/blob/master/homework/3/src/test/java/edu/cmu/cs/cs214/hw3/SolveCryptarithmTest.java#L25)) * __minor__ It's better to import your homework 2 code by adding it to the build path and importing it, instead of copying and pasting it into your code for homework 3. #### Use inheritance and delegation, and design patterns effectively to achieve design flexibility and code reuse (20/30) * Your solution does not implement generic typing but instead focuses on one type. You should be using Java’s built in ([generic type system](https://en.wikipedia.org/wiki/Generics_in_Java)) to implement generic behavior. * Your cryptarithm solver's return value is not reusable for anything other than printing the solution. This makes your program not testable separately and is generally bad practice. #### Discuss the relative advantages and disadvantages of alternative design choices (7/20) * Your rationale for using the Iterator Pattern is incorrect because you misinterpreted the design of the other design patterns. The Template Method and Command Patterns do not require you to store all permutations in memory. * You used primitive arrays as the input type for your permutation generator but did not argue about the trade-offs. (or any other limitation to generality) * You did not provide client code for interacting with your APIs. * __minor__, It's better to describe an API with actual interface code or UML class diagrams rather than prose. * You did not describe an API for the Template Method design pattern, as required by the assignment. --- #### Total (53/100) Late days used: 2 (3 left) --- #### Additional Notes Graded by: <NAME> (<EMAIL>) To view this file with formatting, visit the following page: https://github.com/CMU-15-214/said/blob/master/grades/hw3.md
4dfef26b40bd27e3a3aa5a94fdf34e4053bbb136
[ "Markdown", "Java", "Text", "Gradle" ]
38
Markdown
dsai96/15-214
95dde7ff6dbce23d829dcfb0b10b6c34c23a02db
90e92c8475f4079d5c91a9227bf6b2ab579f5e5a
refs/heads/master
<file_sep>const webpack = require('webpack'); const paths = require('react-app-rewired/scripts/utils/paths'); const getClientEnvironment = require(paths.scriptVersion + '/config/env'); const appBuildPath = paths.scriptVersion + '/config/paths'; const path = require('path'); const reactAppPaths = require(appBuildPath); const createRewireHost = function(hostOptions) { return function(config, env) { if (!process.env.HOST_NAME) { return config; } const envs = getClientEnvironment(config.output.publicPath.slice(0, -1)); let host = hostOptions[process.env.HOST_NAME]; if (typeof host === 'object' && !(host instanceof RegExp)) { Object.keys(host).forEach(key => { host[key] = JSON.stringify(host[key]); }); } else { host = JSON.stringify(host || ''); } config.plugins.unshift( new webpack.DefinePlugin({ 'process.env': Object.assign({}, envs.stringified['process.env'], { REACT_APP_HOST: host }) }) ); if (env === 'production') { console.log(`Production build with hostname ${process.env.HOST_NAME}`); rewriteAppBuild(); config.output.path = path.join(config.output.path, process.env.HOST_NAME); config.output.filename = addHostNameTag(config.output.filename, 'js'); config.output.chunkFilename = addHostNameTag( config.output.chunkFilename, 'chunk' ); } return config; }; }; function addHostNameTag(filename, indexOfKey) { const splits = filename.split('.'); const index = splits.indexOf(indexOfKey); splits.splice(index, 0, process.env.HOST_NAME); return splits.join('.'); } function rewriteAppBuild() { reactAppPaths.appBuild = path.resolve( reactAppPaths.appBuild, process.env.HOST_NAME ); require.cache[require.resolve(appBuildPath)].exports = reactAppPaths; } module.exports = createRewireHost; <file_sep># react-app-rewire-host > Add a host to your create-react-app app process.env via react-app-rewired when build * [create-react-app](https://github.com/facebookincubator/create-react-app) * [react-app-rewired](https://github.com/timarney/react-app-rewired) ## Install ```bash # use npm $ npm install --save-dev react-app-rewire-host # use yarn $ yarn add --dev react-app-rewire-host ``` ## Usage In the `config-overrides.js` for [react-app-rewired](https://github.com/timarney/react-app-rewired) add code ```javascript /* config-overrides.js */ const createRewireHost = require('react-app-rewire-host'); module.exports = (config, env)=>{ // Also support object for config, like // const hostConfig = { // uat: { // api: 'http://xxxuat.api.com', // otherurl: 'http://xxxother.url.com', // }, // pro: ... // } const hostConfig = { uat: 'http://xxxuat.api.com', pro: 'https://xxx.api.com' } const rewireHost = createRewireHost(hostConfig); return rewireHost(config, env); } ``` Then add a env `HOST_NAME` when you build project in `package.json` ```diff "scripts": { - "build": "react-scripts build", + "build": "react-app-rewired HOST_NAME=pro build", + "build:uat": "react-app-rewired HOST_NAME=uat build", } ``` Finally you can use `process.env.REACT_APP_HOST` in your code and also the build dir will make a subdir that the name is `HOST_NAME`. ## License MIT
d82ee19f26881a23d27e93d522cd754efd32c4bc
[ "JavaScript", "Markdown" ]
2
JavaScript
likun7981/react-app-rewire-host
53a4b0066e46d4137f2731e9ea001b11b27d25d8
35f935f2abdae5e9bdbc04c3d68daf4f3412879b
refs/heads/master
<file_sep>// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from "vscode"; const terminal = vscode.window.terminals[0]; function sendTextFunc(setting: string, isGit: boolean = false) { let temp = vscode.workspace.getConfiguration("touchbar").get(setting) ?? setting; vscode.commands.executeCommand("workbench.action.terminal.focus"); terminal.show(); vscode.commands.executeCommand("workbench.action.terminal.clear"); isGit ? terminal.sendText("gitp commit -a -s") : terminal.sendText("tnpm run " + String(temp)); } // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log( 'Congratulations, your extension "touchbar-custom" is now active!' ); let NPM_RUN = vscode.commands.registerCommand("extension.NPM_run", () => { let temp = vscode.workspace.getConfiguration("touchbar").get("run"); vscode.commands.executeCommand("npm-script.run"); }); let GIT_PRO_COMMIT = vscode.commands.registerCommand( "extension.GIT_PRO_COMMIT", () => { sendTextFunc("start", true); } ); let NPM_DEV = vscode.commands.registerCommand("extension.NPM_dev", () => { sendTextFunc("dev"); }); let NPM_BUILD = vscode.commands.registerCommand("extension.NPM_build", () => { sendTextFunc("build"); }); let NPM_TEST = vscode.commands.registerCommand("extension.NPM_test", () => { sendTextFunc("test"); }); context.subscriptions.push( NPM_DEV, NPM_BUILD, NPM_TEST, NPM_RUN, GIT_PRO_COMMIT ); } // this method is called when your extension is deactivated export function deactivate() {}
e53dcfafc53eb88f881ff05c50d0856813d5c475
[ "TypeScript" ]
1
TypeScript
GodD6366/touchbar-custom
f625ab55ad2d36b73438dc184b58b426a95482c5
0c808274107ed2b38a24a079c9f557b9ac0956f6
refs/heads/master
<repo_name>pyramation/ra-postgraphile-examples<file_sep>/README.md # ra-postgraphile-examples The aim of this repo is to provide examples for the postgraphile community's implementation of react-admin, https://github.com/BowlingX/ra-postgraphile ## getting started if you have a postgres process running, skip this step. In a separate shell, spin up a postgres instance using docker-compose in the base directory of this repo: ```sh docker-compose up ``` ### roles First create the roles (we can remove these later): ```sh psql < ./server/sql/roles.sql ``` ** You may need to provide your username/password depending on your configuration: ```sh PGUSER=postgres PGPASSWORD=<PASSWORD> psql < ./server/sql/roles.sql ``` ### seed ```sh createdb exampledb make init ``` ### run server ```sh cd ./server yarn yarn run ra_app_user ``` the explorer will be here http://localhost:5678/graphiql ### run react admin ```sh cd ./client yarn yarn run start ``` the admin will be here http://localhost:3000 <file_sep>/client/src/App.js import React, { useEffect, useState } from "react"; import { ApolloProvider } from "@apollo/react-hooks"; import { Admin, Resource } from "react-admin"; import { useApolloClient } from "@apollo/react-hooks"; import pgDataProvider from "ra-postgraphile"; import { Loader } from "./Loader"; import TreeMenu from "@bb-tech/ra-treemenu"; import PeopleIcon from "@material-ui/icons/People"; import apolloClient from "./apollo/client"; import { LocationList, LocationEdit, LocationCreate } from "./tables/Locations"; import { EventList, EventEdit, EventCreate } from "./tables/Events"; const ReactAdminWrapper = () => { const [dataProvider, setDataProvider] = useState(null); const client = useApolloClient(); useEffect(() => { (async () => { try { const dataProvider = await pgDataProvider(client, { typeMap: { Interval: { expand: true, queryValueToInputValue: ({__typename, ...value} = {}) => { return value; } }, GeometryPoint: { expand: true, queryValueToInputValue: (value) => value.geojson, }, GeometryGeometry: { expand: true, queryValueToInputValue: (value) => value.geojson, }, GeographyPoint: { expand: true, queryValueToInputValue: (value) => value.geojson, }, }, }); setDataProvider(() => dataProvider); } catch (error) { console.log(error); } })(); }, [client]); if (!dataProvider) { return <Loader />; } return ( dataProvider && ( <Admin dataProvider={dataProvider} menu={TreeMenu} disableTelemetry> <Resource name="Events" options={{ label: "Events" }} list={EventList} icon={PeopleIcon} edit={EventEdit} create={EventCreate} /> <Resource name="Locations" options={{ label: "Locations" }} list={LocationList} icon={PeopleIcon} edit={LocationEdit} create={LocationCreate} /> </Admin> ) ); }; const App = () => { return ( <ApolloProvider client={apolloClient}> <ReactAdminWrapper /> </ApolloProvider> ); }; export default App; <file_sep>/client/src/tables/Locations.js import React from "react"; import { List, Datagrid, Edit, Create, SimpleForm, TextField, EditButton, TextInput, } from "react-admin"; import { Field } from "react-final-form"; import SmallMap from "./components/SmallMap"; export const LocationList = (props) => { return ( <List {...props} > <Datagrid> <TextField source="id" /> <TextField source="name" /> <TextField source="location" /> <EditButton basePath="/locations" /> </Datagrid> </List> ); }; const LocationTitle = ({ record }) => { return <span>Location {record ? `"${record.name}"` : ""}</span>; }; export const LocationEdit = (props) => { return ( <Edit title={<LocationTitle />} {...props}> <SimpleForm> <TextInput disabled source="id" /> <TextInput source="name" /> <Field id="location" name="location" source="location" label="Location" component={SmallMap} /> </SimpleForm> </Edit> ); }; export const LocationCreate = (props) => { return ( <Create title="Create a Location" {...props}> <SimpleForm> <TextInput source="name" /> <Field id="location" name="location" source="location" label="Location" component={SmallMap} /> </SimpleForm> </Create> ); }; <file_sep>/client/README.md # Frontend based on React-Admin ## Getting started ``` $ yarn install $ yarn run start ``` Open your browser on http://localhost:3000 ## Linter You can launch linter: ``` $ yarn run lint $ yarn run lint:css ```<file_sep>/Makefile init: PGUSER=ra_super_user PGPASSWORD=<PASSWORD> psql exampledb < ./server/sql/schema.sql roles: psql < ./server/sql/roles.sql drop-roles: psql < ./server/sql/drop-roles.sql clean: psql exampledb < ./server/sql/clean.sql up: docker-compose up down: docker-compose down -v <file_sep>/client/src/apollo/client.js import { ApolloClient, HttpLink, from } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; import { onError } from '@apollo/client/link/error'; import { InMemoryCache } from '@apollo/client/cache'; import { createUploadLink } from 'apollo-upload-client' const uri = process.env.REACT_APP_GRAPHQL_URL; const errorLink = onError(({ response, graphQLErrors, networkError }) => { console.log({ graphQLErrors }); console.log({ response }); if (graphQLErrors) graphQLErrors.map(({ message, locations, path, extensions }) => { if (extensions && extensions.code === 'UNAUTHENTICATED') { localStorage.removeItem('token'); // edit response so downstream can cat an error message response.errors = [new Error('UNAUTHENTICATED')]; } console.log( `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}` ); }); if (networkError) console.log(`[Network error]: ${networkError}`); }); const authLink = setContext((_, { headers }) => { const token = localStorage.getItem('token'); return { headers: { ...headers, authorization: token ? `Bearer ${token}` : '' } }; }); const link = from([ authLink, errorLink, createUploadLink({ uri }), new HttpLink({ uri, credentials: 'include' }), ]); const client = new ApolloClient({ link, cache: new InMemoryCache(), defaultOptions: { watchQuery: { fetchPolicy: 'no-cache', errorPolicy: 'ignore' }, query: { fetchPolicy: 'no-cache', errorPolicy: 'all' } } }); export default client;
efa1cafe129e8b5a1a35e4872e621ddedeb960ed
[ "Markdown", "JavaScript", "Makefile" ]
6
Markdown
pyramation/ra-postgraphile-examples
65039664959ba317082ef86725c499afc8e4bf6c
0ee107e246ab1b7fb60474ac3ab3d279d8d59cb9
refs/heads/master
<file_sep><?php if (!empty($_POST['data'])) { $data = $_POST['data']; $data = str_replace('contenteditable="true"', 'contenteditable="false"', $data); $data = str_replace('<script type="text/javascript" src="../ew-editor.js"></script>', '', $data); $data = str_replace('<link rel="stylesheet" href="../ew-editor.css">', '', $data); $templateUrl = explode('/', $_POST['templateUrl']); end($templateUrl); $template = prev($templateUrl); $filename = $_POST['filename']; $name = $template . '/web-' . $filename . '.html'; $file = fopen('' . $name, 'w'); fwrite($file, $data); fclose($file); } <file_sep># Web Page Editor Awesome website editor, fast and easy to use ;-) ## Features: ### Change template texts: ![Change Text](docs/1.gif) ### Change background color: ![Change Color](docs/capture-2.gif) ### Change an image: ![Change Image](docs/capture-3.gif) **Enjoy :-)** <file_sep><?php header("location:templates");
57789e4085d9339f085a92c20d89eaa8296511db
[ "Markdown", "PHP" ]
3
PHP
maurobonfietti/web-page-editor
6f0132e15de184252cb723ca6f095ba5fdab1aaf
051d6f4f32f263813a73ca1fc71d9dc97f500e2f
refs/heads/master
<file_sep><?php use Roots\Sage\Titles; ?> <div class="page-header"> <h1><?= Titles\title(); ?></h1> <?php if( is_post_type_archive('projects') ) { ?> <p>Works that I played a signicant role in. If you like what you see reach out to see if we can make your project happen.</p> <?php } ?> </div> <file_sep><?php namespace Roots\Sage\Setup; use Roots\Sage\Assets; if ( file_exists( dirname( __FILE__ ) . '/CMB2/init.php' ) ) { require_once dirname( __FILE__ ) . '/CMB2/init.php'; } /** * Theme setup */ function setup() { // Enable features from Soil when plugin is activated // https://roots.io/plugins/soil/ add_theme_support('soil-clean-up'); add_theme_support('soil-nav-walker'); add_theme_support('soil-nice-search'); add_theme_support('soil-jquery-cdn'); add_theme_support('soil-relative-urls'); // Make theme available for translation // Community translations can be found at https://github.com/roots/sage-translations load_theme_textdomain('sage', get_template_directory() . '/lang'); // Enable plugins to manage the document title // http://codex.wordpress.org/Function_Reference/add_theme_support#Title_Tag add_theme_support('title-tag'); // Register wp_nav_menu() menus // http://codex.wordpress.org/Function_Reference/register_nav_menus register_nav_menus([ 'primary_navigation' => __('Primary Navigation', 'sage'), 'footer_navigation' => __('Footer Navigation', 'sage') ]); // Enable post thumbnails // http://codex.wordpress.org/Post_Thumbnails // http://codex.wordpress.org/Function_Reference/set_post_thumbnail_size // http://codex.wordpress.org/Function_Reference/add_image_size add_theme_support('post-thumbnails'); // Enable post formats // http://codex.wordpress.org/Post_Formats add_theme_support('post-formats', ['aside', 'gallery', 'link', 'image', 'quote', 'video', 'audio']); // Enable HTML5 markup support // http://codex.wordpress.org/Function_Reference/add_theme_support#HTML5 add_theme_support('html5', ['caption', 'comment-form', 'comment-list', 'gallery', 'search-form']); // Use main stylesheet for visual editor // To add custom styles edit /assets/styles/layouts/_tinymce.scss //add_editor_style(Assets\asset_path('styles/editor.css')); } add_action('after_setup_theme', __NAMESPACE__ . '\\setup'); /** * Register sidebars */ function widgets_init() { register_sidebar([ 'name' => __('Footer Left', 'sage'), 'id' => 'sidebar-footer-1', 'before_widget' => '<section class="widget %1$s %2$s">', 'after_widget' => '</section>', 'before_title' => '<h3>', 'after_title' => '</h3>' ]); register_sidebar([ 'name' => __('Footer Right', 'sage'), 'id' => 'sidebar-footer-3', 'before_widget' => '<section class="widget %1$s %2$s">', 'after_widget' => '</section>', 'before_title' => '<h3>', 'after_title' => '</h3>' ]); } add_action('widgets_init', __NAMESPACE__ . '\\widgets_init'); /** * Determine which pages should NOT display the sidebar */ function display_sidebar() { static $display; isset($display) || $display = !in_array(true, [ // The sidebar will NOT be displayed if ANY of the following return true. // @link https://codex.wordpress.org/Conditional_Tags is_404(), is_front_page(), is_page(), is_home(), is_single(), ]); return apply_filters('sage/display_sidebar', $display); } /** * Theme assets */ function assets() { wp_enqueue_style('sage/css', Assets\asset_path('styles/main.css'), false, null); if (is_single() && comments_open() && get_option('thread_comments')) { wp_enqueue_script('comment-reply'); } wp_enqueue_script('sage/js', Assets\asset_path('scripts/main.js'), ['jquery'], null, true); } add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\assets', 100); function projects_custom_post_type() { register_post_type( 'projects', array( 'labels' => array( 'name' => 'Portfolio', 'singular_name' => 'Portfolio Post', 'all_items' => 'All Portfolio Posts', 'add_new' => 'Add New', 'add_new_item' => 'Add New Portfolio Post', 'edit' => 'Edit', 'edit_item' => 'Edit Portfolio Post', 'new_item' => 'New Portfolio Post', 'view_item' => 'View Portfolio Post', 'search_items' => 'Search Portfolio Post', 'not_found' => 'Nothing found in the Database.', 'not_found_in_trash' => 'Nothing found in Trash', 'parent_item_colon' => '' ), 'description' => 'Ron\'s portfolio of work.', 'public' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'show_ui' => true, 'query_var' => true, 'menu_position' => 8, 'menu_icon' => 'dashicons-portfolio', 'rewrite' => array( 'slug' => 'projects', 'with_front' => false ), 'has_archive' => 'projects', 'capability_type' => 'post', 'hierarchical' => false, 'supports' => array( 'title', 'editor', 'thumbnail', 'sticky', 'excerpt') ) ); // register_taxonomy_for_object_type( 'category', 'projects' ); // register_taxonomy_for_object_type( 'post_tag', 'projects' ); } add_action( 'init', __NAMESPACE__ . '\\projects_custom_post_type'); register_taxonomy( 'project_tax', array('projects'), array('hierarchical' => true, 'labels' => array( 'name' => 'Project Categories', 'singular_name' => 'Project Category', 'search_items' => 'Search Project Categories', 'all_items' => 'All Project Categories', 'parent_item' => 'Parent Project Category', 'parent_item_colon' => 'Parent Project Category:', 'edit_item' => 'Edit Project Category', 'update_item' => 'Update Project Category', 'add_new_item' => 'Add New Project Category', 'new_item_name' => 'New Project Category Name' ), 'show_admin_column' => true, 'show_ui' => true, 'query_var' => true, // 'rewrite' => array( 'slug' => 'custom-slug' ), ) ); register_taxonomy( 'client_tax', array('projects'), array('hierarchical' => true, 'labels' => array( 'name' => 'Clients', 'singular_name' => 'Client', 'search_items' => 'Search Clients', 'all_items' => 'All Clients', 'parent_item' => 'Parent Client', 'parent_item_colon' => 'Parent Client:', 'edit_item' => 'Edit Client', 'update_item' => 'Update Client', 'add_new_item' => 'Add New Client', 'new_item_name' => 'New Client Name' ), 'show_admin_column' => true, 'show_ui' => true, 'query_var' => true, // 'rewrite' => array( 'slug' => 'custom-slug' ), ) ); register_taxonomy( 'tools_tax', array('projects'), array('hierarchical' => true, 'labels' => array( 'name' => 'Tools', 'singular_name' => 'Tool', 'search_items' => 'Search Tools', 'all_items' => 'All Tools', 'parent_item' => 'Parent Tool', 'parent_item_colon' => 'Parent Tool:', 'edit_item' => 'Edit Tool', 'update_item' => 'Update Tool', 'add_new_item' => 'Add New Tool', 'new_item_name' => 'New Tool Name' ), 'show_admin_column' => true, 'show_ui' => true, 'query_var' => true, // 'rewrite' => array( 'slug' => 'custom-slug' ), ) ); register_taxonomy( 'project_type_tax', array('projects'), array('hierarchical' => true, 'labels' => array( 'name' => 'Project Types', 'singular_name' => 'Project Type', 'search_items' => 'Search Project Types', 'all_items' => 'All Project Types', 'parent_item' => 'Parent Project Type', 'parent_item_colon' => 'Parent Project Type:', 'edit_item' => 'Edit Project Type', 'update_item' => 'Update Project Type', 'add_new_item' => 'Add New Project Type', 'new_item_name' => 'New Project Type Name' ), 'show_admin_column' => true, 'show_ui' => true, 'query_var' => true, // 'rewrite' => array( 'slug' => 'custom-slug' ), ) ); /** * DIFFERENT BASE FILE FOR * HOME & PROJECTS CPT **/ add_filter('sage/wrap_base', __NAMESPACE__ . '\\sage_wrap_custom_base'); function sage_wrap_custom_base($templates) { $cpt = get_post_type(); // Get the current post type if ($cpt && is_singular($cpt) ) { array_unshift($templates, 'base-' . $cpt . '.php'); // Shift the template to the front of the array } if( is_front_page() ){ array_unshift($templates, 'base-home.php'); } return $templates; // Return our modified array with base-$cpt.php at the front of the queue } add_action( 'cmb2_admin_init', __NAMESPACE__ . '\\project_metaboxes' ); function project_metaboxes() { $prefix = 'rp_proj_'; $cmb_demo = new_cmb2_box( array( 'id' => $prefix . 'metabox', 'title' => 'Project Details', 'object_types' => array( 'projects' ), // Post type ) ); $cmb_demo->add_field( array( 'name' => 'Laptop Image', 'desc' => 'Upload an image or enter a URL.', 'id' => $prefix . 'laptop_image', 'type' => 'file', ) ); $cmb_demo->add_field( array( 'name' => 'Tablet Image', 'desc' => 'Upload an image or enter a URL.', 'id' => $prefix . 'tablet_image', 'type' => 'file', ) ); $cmb_demo->add_field( array( 'name' => 'Phone Image', 'desc' => 'Upload an image or enter a URL.', 'id' => $prefix . 'phone_image', 'type' => 'file', ) ); $cmb_demo->add_field( array( 'name' => 'Background Image', 'desc' => 'Upload an image or enter a URL.', 'id' => $prefix . 'bg_image', 'type' => 'file', ) ); $cmb_demo->add_field( array( 'name' => 'Project Link', 'desc' => 'Full URL to the project.', 'id' => $prefix . 'link', 'type' => 'text', ) ); $cmb_demo->add_field( array( 'name' => 'Project Snippet', 'desc' => 'The little snippet that goes next to the title, like, A WordPress Site.', 'id' => $prefix . 'snippet', 'type' => 'text', ) ); $cmb_demo->add_field( array( 'name' => 'Client', 'desc' => 'Typically the agency name the work was done through.', 'id' => $prefix . 'client', 'taxonomy' => 'client_tax', 'type' => 'taxonomy_select', 'remove_default' => 'true', ) ); $cmb_demo->add_field( array( 'name' => 'Agency Work', 'desc' => 'Was it an agency?', 'id' => $prefix . 'agency', 'type' => 'checkbox', ) ); $cmb_demo->add_field( array( 'name' => 'Role', 'desc' => 'The role I performed on this project.', 'id' => $prefix . 'role', 'type' => 'text', ) ); } add_action( 'cmb2_admin_init', __NAMESPACE__ . '\\theme_options' ); function theme_options() { $option_key = 'rp_options_'; $cmb_options = new_cmb2_box( array( 'id' => $option_key . 'page', 'title' => 'Theme Options', 'icon_url' => 'dashicons-palmtree', 'show_on' => array( 'options-page' => $option_key, ), ) ); $cmb_options->add_field( array( 'name' => 'Twitter Profile', 'desc' => 'Twitter URL', 'id' => $prefix . 'twitter', 'type' => 'text', ) ); $cmb_options->add_field( array( 'name' => 'LinkedIn Profile', 'desc' => 'LinkedIn URL', 'id' => $prefix . 'linedin', 'type' => 'text', ) ); $cmb_options->add_field( array( 'name' => 'GitHug Profile', 'desc' => 'GitHug URL', 'id' => $prefix . 'github', 'type' => 'text', ) ); } function modify_read_more_link( $more ){ global $post; return '&hellip;</p> <a href="' . get_permalink( $post->ID ) . '" class="read-more-link">Read</a>'; } add_action('excerpt_more', __NAMESPACE__ . '\\modify_read_more_link'); function excerpt_length( $length ){ return 20; } add_action('excerpt_length', __NAMESPACE__ . '\\excerpt_length'); //apply_filters('max_srcset_image_width', 3200, [3200,1000]); function do_ga_analytics(){ echo "<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-26659910-1', 'auto'); ga('send', 'pageview'); </script>"; } add_action('wp_head', __NAMESPACE__ . '\\do_ga_analytics');<file_sep><?php use Roots\Sage\Setup; use Roots\Sage\Wrapper; ?> <!doctype html> <html <?php language_attributes(); ?>> <?php get_template_part('templates/head'); ?> <body <?php body_class(); ?>> <!--[if IE]> <div class="alert alert-warning"> <?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'sage'); ?> </div> <![endif]--> <?php do_action('get_header'); get_template_part('templates/header'); ?> <div class="wrap container" role="document"> <div class="content row"> <main class="main"> <?php include Wrapper\template_path(); ?> <?php if( is_singular('post') ){ ?> <div class="social-wrapper"> <ul> <li><a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo rawurlencode( get_permalink() ); ?>" target="_blank" title="Share this article on the Facebook for everyone to ignore.">Fb</a></li> <li><a href="https://www.linkedin.com/shareArticle?mini=true&url=<?php echo rawurlencode( get_permalink() ); ?>&title=<?php echo rawurlencode( get_the_title() ); ?>" target="_blank" title="If you share this article on linkedIn it will help your career.">Li</a></li> <li><a href="https://twitter.com/intent/tweet?text=<?php echo rawurlencode( get_the_title() ); ?>&url=<?php echo rawurlencode( get_permalink() ); ?>" target="_blank" title="Share this article on the Twittersphere to blow up your retweets.">Tw</a></li> </ul> </div> <?php } ?> </main><!-- /.main --> </div><!-- /.content --> </div><!-- /.wrap --> <?php do_action('get_footer'); get_template_part('templates/footer'); wp_footer(); ?> </body> </html> <file_sep><div class="body-wrap"> <header class="banner"> <div class="container"> <div class="content"> <a class="brand" href="<?php echo esc_url(home_url('/')); ?>"> <span><NAME></span> <span><?php echo get_bloginfo('description'); ?></span> </a> <span class="nav-trigger trigger-open" role="button">Open Navigation</span> <div class="navs"> <span class="nav-trigger trigger-close" role="button">Close Navigation</span> <nav class="nav-primary"> <?php if (has_nav_menu('primary_navigation')) : wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav']); endif; ?> </nav> <div class="nav-secondary"> <ul> <li><a href="https://github.com/rpasillas" target="_blank"><svg version="1.1" id="github-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="35px" height="36.385px" viewBox="0 0 35 36.385" enable-background="new 0 0 35 36.385" xml:space="preserve"> <path fill-rule="evenodd" clip-rule="evenodd" fill="#191717" d="M17.499,1.128c-9.662,0-17.496,7.833-17.496,17.498 c0,7.729,5.014,14.287,11.967,16.601c0.875,0.161,1.195-0.379,1.195-0.843c0-0.416-0.016-1.516-0.025-2.976 c-4.865,1.058-5.893-2.347-5.893-2.347c-0.795-2.021-1.943-2.559-1.943-2.559c-1.588-1.086,0.119-1.063,0.119-1.063 c1.756,0.124,2.682,1.803,2.682,1.803c1.561,2.674,4.096,1.902,5.092,1.454c0.158-1.131,0.609-1.902,1.111-2.339 c-3.887-0.441-7.971-1.943-7.971-8.647c0-1.91,0.682-3.473,1.801-4.695c-0.18-0.442-0.779-2.222,0.172-4.631 c0,0,1.469-0.47,4.811,1.795c1.396-0.389,2.893-0.584,4.381-0.59c1.486,0.006,2.982,0.201,4.379,0.59 c3.342-2.265,4.809-1.795,4.809-1.795c0.955,2.409,0.354,4.188,0.174,4.631c1.121,1.223,1.799,2.785,1.799,4.695 c0,6.722-4.09,8.2-7.988,8.634c0.627,0.539,1.188,1.607,1.188,3.24c0,2.339-0.021,4.226-0.021,4.8c0,0.468,0.314,1.012,1.203,0.841 c6.945-2.317,11.955-8.872,11.955-16.599C34.997,8.961,27.163,1.128,17.499,1.128z"></path> </svg></a></li> <li><a href="http://www.linkedin.com/pub/ron-pasillas/22/8a6/660/" target="_blank"><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="35px" height="35px" viewBox="0 0 35 35" enable-background="new 0 0 35 35" xml:space="preserve"> <path fill="#1387C8" d="M17.5,1.25c-9.395,0-17.008,7.615-17.008,17.008c0,9.393,7.613,17.008,17.008,17.008 s17.008-7.615,17.008-17.008C34.508,8.865,26.895,1.25,17.5,1.25z M12.74,25.371H9.424V14.762h3.316V25.371z M10.997,13.435h-0.024 c-1.199,0-1.977-0.811-1.977-1.838c0-1.048,0.801-1.842,2.024-1.842c1.223,0,1.976,0.792,1.999,1.839 C13.02,12.621,12.243,13.435,10.997,13.435z M26.004,25.371h-3.76v-5.49c0-1.438-0.588-2.417-1.881-2.417 c-0.989,0-1.539,0.662-1.795,1.3c-0.096,0.229-0.081,0.547-0.081,0.867v5.74h-3.724c0,0,0.048-9.725,0-10.609h3.724v1.665 c0.22-0.728,1.409-1.767,3.31-1.767c2.355,0,4.207,1.526,4.207,4.812V25.371z"></path> </svg></a></li> <li><a href="https://twitter.com/rpasillas" target="_blank"><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="35px" height="35px" viewBox="0 0 35 35" enable-background="new 0 0 35 35" xml:space="preserve"> <path fill="#66CBEE" d="M17.354,1.25c-9.393,0-17.008,7.615-17.008,17.008c0,9.394,7.615,17.008,17.008,17.008 c9.394,0,17.008-7.614,17.008-17.008C34.362,8.865,26.748,1.25,17.354,1.25z M24.144,15.612c0.007,0.149,0.01,0.3,0.01,0.452 c0,4.62-3.515,9.945-9.945,9.945c-1.973,0-3.811-0.579-5.357-1.569c0.273,0.032,0.552,0.048,0.834,0.048 c1.637,0,3.145-0.559,4.341-1.497c-1.53-0.026-2.82-1.037-3.265-2.426c0.213,0.041,0.432,0.062,0.657,0.062 c0.319,0,0.628-0.041,0.921-0.123c-1.6-0.32-2.805-1.733-2.805-3.428v-0.043c0.473,0.26,1.012,0.419,1.584,0.437 c-0.938-0.627-1.555-1.698-1.555-2.909c0-0.641,0.172-1.241,0.473-1.759c1.726,2.116,4.301,3.506,7.205,3.652 c-0.061-0.255-0.09-0.521-0.09-0.796c0-1.93,1.564-3.495,3.494-3.495c1.006,0,1.915,0.424,2.551,1.104 c0.798-0.156,1.545-0.447,2.221-0.847c-0.26,0.816-0.814,1.5-1.537,1.933c0.707-0.084,1.381-0.272,2.008-0.55 C25.421,14.503,24.827,15.119,24.144,15.612z"></path> </svg></a></li> </ul> </div> </div> </div> </div> </header> <file_sep><?php if( !is_singular('projects') ){ ?> <section class="footer-form"> <div class="container"> <div class="content"> <h1>Let's Talk About Your Project</h1> <?php echo do_shortcode('[contact-form-7 id="82" title="Contact"]'); ?> </div> </div> </section> <?php } ?> <footer class="content-info"> <div class="container"> <div class="content"> <div class="col-1"><?php dynamic_sidebar('sidebar-footer-1'); ?></div> <div class="col-2"><?php dynamic_sidebar('sidebar-footer-3'); ?></div> </div> <div class="content"> <div class="col-full">Located in Temecula, CA | &copy; <?php echo date('Y'); ?> <NAME></div> </div> </div> </footer> </div> <file_sep><div class="wrap container" role="document"> <div class="content row"> <main class="main"> <article <?php post_class(); ?>> <h1><?php the_title(); ?></h1> <?php /** * CATEGORIES : TAXONOMY * **/ $categories = wp_get_object_terms(get_the_ID(), ['taxonomy' => 'post_tag' ]); $count = count( $categories ); $tag = ''; for( $i=0; $i<=$count; ++$i ){ if( $i == 0 ){ $tag .= $categories[$i]->name; }else if( $i == $count - 1 ){ $tag .= ' and ' . $categories[$i]->name; } } if( get_post_meta( get_the_ID(), 'rp_proj_agency', true ) ){ $credit_line = 'via '; }else{ $credit_line = 'for '; } /** * CLIENTS : TAXONOMY * **/ $clients = wp_get_object_terms(get_the_ID(), ['taxonomy' => 'client_tax' ]); $client = $clients[0]->name; /** * TOOLS : TAXONOMY * **/ $tools_array = wp_get_object_terms(get_the_ID(), ['taxonomy' => 'tools_tax' ]); $count = count( $tools_array ); $tools = ''; for( $i=0; $i<=$count; ++$i ){ $tools .= '<li>' . $tools_array[$i]->name . '</li>'; } /** * PROJECT TYPES : TAXONOMY * **/ $proj_type_array = wp_get_object_terms(get_the_ID(), ['taxonomy' => 'project_type_tax' ]); $count = count( $proj_type_array ); $proj_type = ''; for( $i=0; $i<=$count; ++$i ){ if( $i == 0 ){ $proj_type .= $proj_type_array[$i]->name; }else if( $i == $count - 1 ){ $proj_type .= ' and ' . $proj_type_array[$i]->name; } } ?> <p><?php echo get_post_meta( get_the_ID(), 'rp_proj_role', true ); ?> on a <?php echo $proj_type; ?> project <?php echo $credit_line . ' ' . $client; ?>.</p> <h3>At a Glance</h3> <ul class="check-list"> <?php echo $tools; ?> </ul> </article> </main><!-- /.main --> </div><!-- /.content --> </div><!-- /.wrap --> <div class="wrap container project-secondary" role="document" style="background-image: url('<?php echo get_post_meta( get_the_ID(), 'rp_proj_bg_image', true ); ?>');"> <div class="content row"> <div class="main"> <h2>Details of this Project</h2> <?php the_content(); ?> <?php if (get_post_meta( get_the_ID(), 'rp_proj_link', true )){ echo '<a href="' . get_post_meta( get_the_ID(), 'rp_proj_link', true ) .'" class="site-link" target="_blank">Visit the Site</a>'; } ?> <div class="project-images"> <?php $iid = get_post_meta( get_the_ID(), 'rp_proj_laptop_image_id', true ); $src = get_post_meta( get_the_ID(), 'rp_proj_laptop_image', true ); $srcset = wp_get_attachment_image_srcset( $iid, 'full'); $sizes = wp_get_attachment_image_sizes( $iid, 'full' ); $alt = (get_post_meta( $iid, '_wp_attachment_image_alt', true)) ? get_post_meta( $iid, '_wp_attachment_image_alt', true) : 'Project Image'; ?> <div class="project-image image-laptop"><img src="<?php echo esc_url($src); ?>" srcset="<?php echo esc_attr($srcset); ?>" sizes="<?php echo esc_attr($sizes); ?>" alt="<?php echo esc_attr($alt); ?>"></div> <?php $iid = get_post_meta( get_the_ID(), 'rp_proj_tablet_image_id', true ); $src = get_post_meta( get_the_ID(), 'rp_proj_tablet_image', true ); $srcset = wp_get_attachment_image_srcset( $iid, 'full'); $sizes = wp_get_attachment_image_sizes( $iid, 'full' ); $alt = (get_post_meta( $iid, '_wp_attachment_image_alt', true)) ? get_post_meta( $iid, '_wp_attachment_image_alt', true) : 'Project Image'; ?> <div class="project-image image-tablet"><img src="<?php echo esc_url($src); ?>" srcset="<?php echo esc_attr($srcset); ?>" sizes="<?php echo esc_attr($sizes); ?>" alt="<?php echo esc_attr($alt); ?>"></div> <?php $iid = get_post_meta( get_the_ID(), 'rp_proj_phone_image_id', true ); $src = get_post_meta( get_the_ID(), 'rp_proj_phone_image', true ); $srcset = wp_get_attachment_image_srcset( $iid, 'full'); $sizes = wp_get_attachment_image_sizes( $iid, 'full' ); $alt = (get_post_meta( $iid, '_wp_attachment_image_alt', true)) ? get_post_meta( $iid, '_wp_attachment_image_alt', true) : 'Project Image'; ?> <div class="project-image image-phone"><img src="<?php echo esc_url($src); ?>" srcset="<?php echo esc_attr($srcset); ?>" sizes="<?php echo esc_attr($sizes); ?>" alt="<?php echo esc_attr($alt); ?>"></div> </div> </div> </div> </div> <div class="wrap container project-footer" role="document"> <div class="content row"> <div class="main"> <div class="learn-more"> <span>Interested in learning more?</span> <a href="#">Contact Me</a> </div> </div> </div> </div> <file_sep><div class="post-metas"> <time class="updated" datetime="<?= get_post_time('c', true); ?>"><?= get_the_date(); ?></time> <span class="bullet-separator">&bull;</span> <?php $categories = get_categories(); $count = count( $categories ); if( $count ){ echo '<span class="categories">'; } for( $i=0; $i<=$count; ++$i ){ //wtf does it return an array of // [0], [2] if( $categories[$i]->term_id ){ echo '<a href="' . get_category_link( $categories[$i]->term_id ) . '" class="category">' . $categories[$i]->name . '</a> '; // if( $i < $count ){ // echo ' | '; // } } } if( $count ){ echo '</span>'; } ?> </div><file_sep><article <?php post_class(); ?>> <a class="image-wrap" href="<?php esc_url(the_permalink()); ?>" style="background-image: url('<?php echo get_post_meta( get_the_ID(), 'rp_proj_bg_image', true ); ?>');"> <?php the_post_thumbnail(); ?> </a> <h2 class="entry-title"><a href="<?php esc_url(the_permalink()); ?>"><?php the_title(); ?></a></h2> <?php /** * PROJECT TYPES : TAXONOMY * **/ $proj_type_array = wp_get_object_terms(get_the_ID(), ['taxonomy' => 'project_type_tax' ]); $count = count( $proj_type_array ); echo '<span class="project_type">'; echo 'A '; for( $i=0; $i<=$count; ++$i ){ if( $i == 0 ){ echo $proj_type_array[$i]->name; }else if( $i == $count - 1 ){ echo ' & ' . $proj_type_array[$i]->name; } } echo '</span> '; /** * PROJECT CATEGORIES : TAXONOMY * **/ $categories = wp_get_object_terms(get_the_ID(), array('taxonomy' => 'project_tax' )); $count = count( $categories ); echo '<span class="category">'; for( $i=0; $i<=$count; ++$i ){ if( $i == 0 ){ echo $categories[$i]->name; }else if( $i == $count - 1 ){ echo ' & ' . $categories[$i]->name; } } echo ' project.'; echo '</span> '; ?> </article> <file_sep><section class="wrap container" role="document"> <div class="content row"> <main class="main"> <?php while (have_posts()) : the_post(); ?> <h1><?php the_title(); ?></h1> <?php the_content(); ?> <?php endwhile; ?> </main><!-- /.main --> </div><!-- /.content --> </section><!-- /.wrap --> <section class="wrap container latest-projects" role="document"> <div class="content row"> <div class="main"> <?php $projects = new WP_Query( ['post_type'=>'projects', 'posts_per_page' => 3 ] ); if( $projects->have_posts() ): echo '<h1>Latest Projects</h1>'; echo '<div class="col-wrap">'; while( $projects->have_posts() ) : $projects->the_post(); get_template_part('templates/content', 'projects'); endwhile; echo '</div>'; wp_reset_postdata(); endif; ?> </div> </div> </section> <section class="wrap container latest-posts" role="document"> <div class="content row"> <div class="main"> <?php $posts = new WP_Query( ['posts_per_page' => 3 ] ); if( $posts->have_posts() ): echo '<h1>Latest Posts</h1>'; echo '<div class="col-wrap">'; while( $posts->have_posts() ) : $posts->the_post(); get_template_part('templates/content'); endwhile; echo '</div>'; wp_reset_postdata(); endif; ?> </div> </div> </section>
66aca88010e7fbcb29f694b0133c5cae8a0fd977
[ "PHP" ]
9
PHP
rpasillas/personal-site
81861af3f22c2e95def8155539238786f80c10e8
b07f5a47588185e6609425256dfb90489f942f0e
refs/heads/main
<file_sep>package kr.ac.gnu.news.calc; /** * Hello world! * */ public class Calc { public static int add(int x, int y) { return x+y; } public static void main( String[] args ) { int a; a=add(5,7); System.out.println("a"); } }
a5a97f7bc644ecf1f51608f641d5ef3350f5e639
[ "Java" ]
1
Java
LEESUBOK96/travis_calc_repro
4c9eec30196828848759614f670578abf6cc2592
7d2d97d7d5c22d209289d22947ee49104711ae4a
refs/heads/master
<repo_name>manojdobbala/efitbuy<file_sep>/src/data/tileData.js /** * Created by manojdobbala on 7/2/18. */ const tileData = [ { img: '../img/efitbay_1.jpg', title: 'Breakfast', author: 'Manoj', cols: 2, featured: true, }, { img: '../img/efitbay_2.jpg', title: 'Tasty burger', author: 'Sindhu', }, { img: '../img/efitbay_3.jpg', title: 'Camera', author: 'Sandeep', }, { img: '../img/efitbay_4.jpeg', title: 'Morning', author: 'Kartheek', featured: true, }, { img: '../img/efitbay_5.jpg', title: 'Hats', author: 'Hans', }, { img: '../img/efitbay_6.jpg', title: 'Honey', author: 'fancycravel', }, { img: '../img/efitbay_7.jpg', title: 'Vegetables', author: 'jill111', cols: 2, }, { img: '../img/efitbay_8.jpg', title: 'Water plant', author: 'BkrmadtyaKarki', }, { img: '../img/efitbay_cookies.jpg', title: 'Mushrooms', author: 'PublicDomainPictures', }, { img: '../img/efitbay_1.jpg', title: 'Olive oil', author: 'congerdesign', }, { img: '../img/efitbay_2.jpg', title: 'Sea star', cols: 2, author: '821292', }, { img: '../img/efitbay_3.jpg', title: 'Bike', author: 'danfador', }, ]; export default tileData;<file_sep>/src/header.js /** * Created by manojdobbala on 4/12/18. */ import React from 'react'; import AppBar from 'material-ui/AppBar'; /** * A simple example of `AppBar` with an icon on the right. * By default, the left icon is a navigation-menu. */ const AppBarExampleIcon = () => ( <div> <AppBar></AppBar> </div> ); export default AppBarExampleIcon;<file_sep>/src/components/homepage.js import * as React from 'react'; import Grid from '@material-ui/core/Grid'; import Hidden from '@material-ui/core/Hidden'; import Card from './card'; import '../Homepage.css'; import * as bannerImage from '../img/fitbay_cropped.png'; import Breakfast from './breakfast' class LandingPage extends React.Component { render() { const banner = <img src={bannerImage} className="bannerImage"/>; return ( <Grid container spacing={24}> <React.Fragment> <Grid item xs={12} sm={6} md={4} lg={3}> <Card></Card> </Grid> <Grid item xs={12} sm={6} md={4} lg={3}> <Breakfast/> </Grid> <Grid item xs={12} sm={6} md={4} lg={3}> <Breakfast/> </Grid> <Grid item xs={12} sm={6} md={4} lg={3}> <Breakfast/> </Grid> </React.Fragment> </Grid> ); } } export default LandingPage; <file_sep>/src/components/lunch.js /** * Created by manojdobbala on 7/4/18. */ import React from 'react'; import Card from '@material-ui/core/Card'; import CardHeader from '@material-ui/core/CardHeader'; import CardText from '@material-ui/core/CardText'; export default class ExpandableCard extends Component { render(){ // pass in your data through props const { cardDataJSONObject } = {"card": [{"title":"Oat Meal", "subtitle":"blue berries","text":"This is how you make it"}, {"title":"Oat Meal", "subtitle":"blue berries","text":"This is how you make it"}, {"title":"Oat Meal", "subtitle":"blue berries","text":"This is how you make it"}]}; // assuming you are getting your card data in a large json object let cardList = []; Object.keys(cardDataJSONObject).forEach((cardIndex) => { let card = cardDataJSONObject[cardIndex]; cardList.push ( <Card> <CardHeader title={card.title} subtitle={card.subtitle} actAsExpander={true} showExpandableButton={true} /> <CardText expandable={true}> { card.text } </CardText> </Card> ) }) return ( <MuiThemeProvider> <div> <div className='card-list'> {/* here we are rendering the list of cards we build up above */} { cardList } </div> </div> </MuiThemeProvider> ); } }<file_sep>/src/App.js import React, { Component } from 'react'; import './App.css'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Header from './header'; import Notifation from './components/notification'; import HomePage from './components/homepage'; import HeaderWithDrawer from './components/sideDrawer'; import SubHeader from './components/subheader'; class App extends Component { state = { username: "Manoj", selectedIndex: 0, dataSource: [] }; render() { return ( <div className="App"> <MuiThemeProvider> <HeaderWithDrawer /> <SubHeader/> <HomePage /> </MuiThemeProvider> </div> ); } } export default App;
50986de1ac9f670dd94348ba942cd831201a0273
[ "JavaScript" ]
5
JavaScript
manojdobbala/efitbuy
b55cb53763671ede3ab421f5914dfe073aafb173
74e9eee41e0aebb280f57f53e637079aa517db27
refs/heads/main
<repo_name>jtrupti07/CPP-code<file_sep>/constant.cpp #include<iostream> using namespace std; class Demo { public: int i; int j; //Constant variable should be initialized immidiately const int k=30; Demo() { i=10; j=20; //k=30; Error } void fun() { i++; j++; //k++; Not Allowed cause k is constant } void gun() const { //i++; //we cannot change the characteristics inside constant function //j++; //we cannot change the characteristics inside constant function //k++; Not Allowed cause k is constant } }; int main() { //Non constant object Demo obj1; cout<<obj1.k<<"\n"; //cout<<obj.k++<<"\n"; Not Allowed obj1.fun();//Non constant object can call non constant function obj1.gun();//non constant object can call constant function // constant object const Demo obj2; //obj2.fun(); //constant object can not call not constant function obj2.gun(); //constant object can call constant function //const int i; //It generates error cause it should be initialized immidiately //const int i=20; //Allowed return 0; }<file_sep>/friend1.cpp #include<iostream> using namespace std; class Demo { public: int i; private: int j; protected: int k; public: Demo() { i=10; j=20; k=30; } friend void fun(); }; void fun() // Nacked function : defined outside the class { Demo obj; cout<<obj.i<<"\n"; //Allowed cause public cout<<obj.j<<"\n"; // Not Allowed cause private cout<<obj.k<<"\n"; //Not Allowed cause protected } int main() { fun(); return 0; }<file_sep>/copycons.cpp #include<iostream> using namespace std; class Arithematic { public: // Access specifier int no1; // Charcteristics of class int no2; // Charcteristics of class Arithematic() // Default Constructor { cout<<"Inside Default Constructor\n"; no1 = 0; no2 = 0; } Arithematic(int i, int j) // Parametrised Constructor { cout<<"Inside parametrised Constructor\n"; no1 = i; no2 = j; } Arithematic(Arithematic &ref) // Copy Constructor { cout<<"Inside Copy constructor\n"; this->no1=ref.no1; this->no2=ref.no2; } ~Arithematic() // Destructor { cout<<"Inside Destructor\n"; // Used to deallocate the resources } int Add() // Behaviour of class { int result = 0; result = no1 + no2; return result; } int Sub() // Behaviour of class { int result = 0; result = no1 - no2; return result; } }; int main() { Arithematic obj1; //Default constructor Arithematic obj2(50,30); //Parametrised constructor Arithematic obj3(obj2); cout<<obj2.no1<<"\t"<<obj2.no2<<"\n"; cout<<obj3.no1<<"\t"<<obj3.no2<<"\n"; cout<<"Addition is :"<<obj2.Add()<<"\n"; cout<<"Subtraction is :"<<obj2.Sub()<<"\n"; cout<<"Addition is :"<<obj3.Add()<<"\n"; cout<<"Subtraction is :"<<obj3.Add()<<"\n"; return 0; }<file_sep>/access(1).cpp #include<iostream> using namespace std; class demo{ public: int i; void fun() // Any one can access { cout<<"Inside public fun"<<"\n"; } //Abstraction 100% private: // No one can access outside the class int j; void gun() { cout<<"Inside private gun"<<"\n"; } //Abstraction not 100% protected: // No one can access outside the class except the immidiate derived class int k; void sun() { cout<<"Inside protected sun"<<"\n"; } }; class hello { int i; void moon() { cout<<"Inside function moon"<<"\n"; } }; int main() { demo obj; cout<<sizeof(obj)<<"\n"; //12 byte obj.fun(); //Allowed cout<<obj.i<<"\n"; //Allowed // obj.gun(); declare privatly //cout<<obj.j<<"\n"; //Not Allowed // obj.sun(); declare in protected mode //cout<<obj.k<<"\n"; //Not Allowed /* by default declare as private hence not accesible cout<<hobj.i<<"\n"; hobj.moon(); return 0;*/ } /* public Any one can access private No one can access outside the class protected No one can access outside the class except the immidiate derived class */
b444d5c2af390e01249cfe5a54e5874d64589623
[ "C++" ]
4
C++
jtrupti07/CPP-code
a90abf47e9e65fd2df02c42c41fd594a0949bf8a
1e3ca66e2113de59f859a524e053af428a06d905
refs/heads/master
<file_sep># VL.Devices.DigiCamControl A set of [VL](https://vvvv.org/documentation/vl) nodes for remo controlling DSLR cameras based on [digiCamControl](https://github.com/dukus/digiCamControl). ## Contributing to the development If you want to contribute to this repository, clone it into a directory like: X:\vl-libs\VL.Devices.DigiCamControl ### Build the C# Project Open X:\vl-libs\VL.Devices.DigiCamControl\src\VL.Devices.DigiCamControl.sln in VisualStudio and build it. This is necessary for a few things that cannot yet be expressed in vl directly, like dynamic enums and static readonly instances of things. ### Start vvvv Then start vvvv with the commandline parameter: /package-repositories "X:\vl-libs\" which will make all packs found in that directory available as dependencies in vl documents. VL.Devices.DigiCamControl will now show up as Nuget among a .vl documents available dependencies as shown [here](https://vvvv.gitbooks.io/the-gray-book/content/en/reference/libraries/dependencies.html#_nugets). Simply select the nuget (via a rightclick) to get access to its nodes. There is also a demo-patch coming with this package that is a bit hidden in: "\VL.Devices.DigiCamControl\vvvv\girlpower\DigiCamDemo.v4p" <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Reactive.Linq; using VL.Core; using VL.Lib.Collections; namespace DigiCamControl { public class ShutterSpeedDefinition : ManualDynamicEnumDefinitionBase<ShutterSpeedDefinition> { public static ShutterSpeedDefinition Instance => ManualDynamicEnumDefinitionBase<ShutterSpeedDefinition>.Instance; override protected bool AutoSortAlphabetically => false; } [Serializable] public class ShutterSpeed : DynamicEnumBase<ShutterSpeed, ShutterSpeedDefinition> { public ShutterSpeed(string value) : base(value) { } //this method needs to be imported in VL to set the default public static ShutterSpeed CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } public class ApertureDefinition : ManualDynamicEnumDefinitionBase<ApertureDefinition> { public static ApertureDefinition Instance => ManualDynamicEnumDefinitionBase<ApertureDefinition>.Instance; override protected bool AutoSortAlphabetically => false; } [Serializable] public class Aperture : DynamicEnumBase<Aperture, ApertureDefinition> { public Aperture(string value) : base(value) { } //this method needs to be imported in VL to set the default public static Aperture CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } public class ISONumberDefinition : ManualDynamicEnumDefinitionBase<ISONumberDefinition> { public static ISONumberDefinition Instance => ManualDynamicEnumDefinitionBase<ISONumberDefinition>.Instance; override protected bool AutoSortAlphabetically => false; } [Serializable] public class ISONumber : DynamicEnumBase<ISONumber, ISONumberDefinition> { public ISONumber(string value) : base(value) { } //this method needs to be imported in VL to set the default public static ISONumber CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } public class ExposureMeteringModeDefinition : ManualDynamicEnumDefinitionBase<ExposureMeteringModeDefinition> { public static ExposureMeteringModeDefinition Instance => ManualDynamicEnumDefinitionBase<ExposureMeteringModeDefinition>.Instance; override protected bool AutoSortAlphabetically => false; } [Serializable] public class ExposureMeteringMode : DynamicEnumBase<ExposureMeteringMode, ExposureMeteringModeDefinition> { public ExposureMeteringMode(string value) : base(value) { } //this method needs to be imported in VL to set the default public static ExposureMeteringMode CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } public class ExposureCompensationDefinition : ManualDynamicEnumDefinitionBase<ExposureCompensationDefinition> { public static ExposureCompensationDefinition Instance => ManualDynamicEnumDefinitionBase<ExposureCompensationDefinition>.Instance; } [Serializable] public class ExposureCompensation : DynamicEnumBase<ExposureCompensation, ExposureCompensationDefinition> { public ExposureCompensation(string value) : base(value) { } //this method needs to be imported in VL to set the default public static ExposureCompensation CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } public class WhiteBalanceDefinition : ManualDynamicEnumDefinitionBase<WhiteBalanceDefinition> { public static WhiteBalanceDefinition Instance => ManualDynamicEnumDefinitionBase<WhiteBalanceDefinition>.Instance; override protected bool AutoSortAlphabetically => false; } [Serializable] public class WhiteBalance : DynamicEnumBase<WhiteBalance, WhiteBalanceDefinition> { public WhiteBalance(string value) : base(value) { } //this method needs to be imported in VL to set the default public static WhiteBalance CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } public class FocusModeDefinition : ManualDynamicEnumDefinitionBase<FocusModeDefinition> { public static FocusModeDefinition Instance => ManualDynamicEnumDefinitionBase<FocusModeDefinition>.Instance; override protected bool AutoSortAlphabetically => false; } [Serializable] public class FocusMode : DynamicEnumBase<FocusMode, FocusModeDefinition> { public FocusMode(string value) : base(value) { } //this method needs to be imported in VL to set the default public static FocusMode CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } public class CompressionSettingDefinition : ManualDynamicEnumDefinitionBase<CompressionSettingDefinition> { public static CompressionSettingDefinition Instance => ManualDynamicEnumDefinitionBase<CompressionSettingDefinition>.Instance; override protected bool AutoSortAlphabetically => false; } [Serializable] public class CompressionSetting : DynamicEnumBase<CompressionSetting, CompressionSettingDefinition> { public CompressionSetting(string value) : base(value) { } //this method needs to be imported in VL to set the default public static CompressionSetting CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } public class AdvancedPropertiesModeDefinition : ManualDynamicEnumDefinitionBase<AdvancedPropertiesModeDefinition> { public static AdvancedPropertiesModeDefinition Instance => ManualDynamicEnumDefinitionBase<AdvancedPropertiesModeDefinition>.Instance; override protected bool AutoSortAlphabetically => false; } [Serializable] public class AdvancedPropertiesMode : DynamicEnumBase<AdvancedPropertiesMode, AdvancedPropertiesModeDefinition> { public AdvancedPropertiesMode(string value) : base(value) { } //this method needs to be imported in VL to set the default public static AdvancedPropertiesMode CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } public class AdvancedPropertiesValueDefinition : ManualDynamicEnumDefinitionBase<AdvancedPropertiesValueDefinition> { public static AdvancedPropertiesValueDefinition Instance => ManualDynamicEnumDefinitionBase<AdvancedPropertiesValueDefinition>.Instance; override protected bool AutoSortAlphabetically => false; } [Serializable] public class AdvancedPropertiesValue : DynamicEnumBase<AdvancedPropertiesValue, AdvancedPropertiesValueDefinition> { public AdvancedPropertiesValue(string value) : base(value) { } //this method needs to be imported in VL to set the default public static AdvancedPropertiesValue CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } public class CameraDeviceDefinition : ManualDynamicEnumDefinitionBase<CameraDeviceDefinition> { public static CameraDeviceDefinition Instance => ManualDynamicEnumDefinitionBase<CameraDeviceDefinition>.Instance; override protected bool AutoSortAlphabetically => false; } [Serializable] public class CameraDevice : DynamicEnumBase<CameraDevice, CameraDeviceDefinition> { public CameraDevice(string value) : base(value) { } //this method needs to be imported in VL to set the default public static CameraDevice CreateDefault() { //use method of base class if nothing special required return CreateDefaultBase(); } } }<file_sep>using System.IO; using System.Drawing.Imaging; using System.Drawing; using System.Runtime.InteropServices; namespace DigiCamControl { public static class JpgDecompressor { public static byte[] DecompressJpeg(byte[] photoBytes) { byte[] result = photoBytes; if (photoBytes.Length > 4) { using (MemoryStream inStream = new MemoryStream(photoBytes)) { //using(var img = Image.FromStream(inStream)) using (Bitmap bmp = new Bitmap(inStream)) { var rect = new Rectangle(0, 0, bmp.Width, bmp.Height); var data = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); var arraySize = data.Stride * data.Height; result = new byte[arraySize]; var lineSize = data.Width * 4; //for (int i = 0; i < data.Height; i++) { Marshal.Copy(data.Scan0, result, 0, arraySize); } bmp.UnlockBits(data); } } } return result; } } }
c7ca7872681963737eda7c843677da506d979f6d
[ "Markdown", "C#" ]
3
Markdown
YanYas/VL.Devices.DigiCamControl
3b53d5b5dd153e04b727c87dda5b428e29e5413c
6ad470d720b8af6c05926d18773c43b4612d9bfb
refs/heads/main
<file_sep># PythonScripts Various python scripts for use <file_sep>#!/usr/bin/env python3 import os from PIL import Image #user input for source folder, make sure directory ends with / #ensure that source directory contains only images to be altered source = input("Input source directory here: ") #creates list of images in folder to run through with for loop images = os.listdir(source) #user input for destination folder, make sure directory ends with / destination = input("Input destination directory here: ") for image in images: if not image.startswith('.'): #open image img = Image.open(source + image) #convert image to RGB img = img.convert('RGB') #rotate image 90 degrees clockwise img = img.rotate(-90) #resize image to 128 X 128 img = img.resize((128, 128)) #save image to new file in .jpeg format in destination folder img = img.save(destination + image, 'jpeg') <file_sep>#! /usr/bin/env python3 import os import requests #list .txt files that contain feedback for file in os.listdir("/data/feedback"): #open.txt files with open('/data/feedback/' + file) as content: #split .txt files and place in feedback dictionary fbdict = content.read().split("\n") feedback = { "title":fbdict[0], "name":fbdict[1], "date":fbdict[2], "feedback":fbdict[3] } #use POST to post data to webserver request = requests.post("http://3172.16.31.10/feedback/", json=feedback) #print status code for verification print(request.status_code)
0f01df8c914c1553d31c3d4821525f86d92e1f29
[ "Markdown", "Python" ]
3
Markdown
jasellen/PythonScripts
ae20d57eb30299b318faba366267b9458ab815c0
29ee0a47f9cc6737e831ecfc79a738abafa904b9
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml; using System.Globalization; namespace BasicTest { public partial class Form1 : Form { readonly string filename = "notesList.xml"; readonly string NO_DATABASE_FOUND_ERROR_MESSAGE = "There is no database. Please ensure that an xml-based database is made available to the application."; readonly string DATA_SAVED_TO_FILE_SUCCESS_MESSAGE = "Data changes were successfully saved."; readonly string INVALID_FILTER_TYPE_NAME_ERROR_MESSAGE = "String does not contain a valid filter type name."; readonly string INVALID_DATE_STRING = "String does not contain a valid date."; readonly string INVALID_ROW_POSITION_ERROR_MESSAGE = "There is no row in the row position given."; readonly string XML_FILE_ROW_NAME = "row"; readonly string FILTER_BY_YEAR = "filterbyyear"; readonly string FILTER_BY_MONTH = "filterbymonth"; readonly string FILTER_BY_WEEK = "filterbyweek"; readonly string FILTER_BY_DAY = "filterbyday"; private Form2 noteEditorForm; public Form1() { InitializeComponent(); loadXMLData(); } private void toolStripButton3_Click(object sender, EventArgs e) { Application.Exit(); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { int rowNumber = e.RowIndex; displayRowNoteText(rowNumber); } private void toolStripNotesButton_Click(object sender, EventArgs e) { int rowNumber; if (dataGridView1.SelectedRows.Count == 0 && dataGridView1.SelectedCells.Count == 0) return; //a user can select a whole row or a cell inside a row if (dataGridView1.SelectedCells.Count > 0) rowNumber = dataGridView1.SelectedCells[0].RowIndex; else rowNumber = dataGridView1.SelectedRows[0].Index; editRowNote(rowNumber); } private void todayToolStripMenuItem_Click(object sender, EventArgs e) { filterByToday(); } private void thisWeekToolStripMenuItem_Click(object sender, EventArgs e) { filterByThisWeek(); } private void thisMonthToolStripMenuItem_Click(object sender, EventArgs e) { filterByThisMonth(); } private void thisYearToolStripMenuItem_Click(object sender, EventArgs e) { filterByThisYear(); } private void showAllToolStripMenuItem_Click(object sender, EventArgs e) { showAllRows(); } private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { int rowNumber = e.RowIndex; displayRowNoteText(rowNumber); } private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { } private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { int rowNumber = e.RowIndex; editRowNote(rowNumber); } private void Form1_MouseClick(object sender, MouseEventArgs e) { } private void editRowNote(int rowNumber) { string selectedRowNote = getRowNote(rowNumber); noteEditorForm = new Form2(selectedRowNote); var result = noteEditorForm.ShowDialog(); if (result == DialogResult.OK) { string editedRowNote = noteEditorForm.EditedNoteText; int notesColumnIndex = 3; dataGridView1.Rows[rowNumber].Cells[notesColumnIndex].Value = editedRowNote; int dateColumnIndex = 2; dataGridView1.Rows[rowNumber].Cells[dateColumnIndex].Value = DateTime.Now; saveDataInXMLFile(); displayRowNoteText(rowNumber); } } private void displayRowNoteText(int rowNumber) { string selectedRowNote = getRowNote(rowNumber); notesTextBox.Text = selectedRowNote; } private void loadXMLData() { notesDataSet = new DataSet(); if (File.Exists(filename)) { notesDataSet.ReadXml(filename); dataGridView1.DataSource = notesDataSet.Tables[0]; return; } String xmlString = Properties.Resources.testdemoxml; if (xmlString == null) { MessageBox.Show(NO_DATABASE_FOUND_ERROR_MESSAGE); return; } System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(xmlString, XmlNodeType.Document, null); notesDataSet.ReadXml(xmlReader); dataGridView1.DataSource = notesDataSet.Tables[0]; } private void saveDataInXMLFile() { DataSet dataset = new DataSet(); DataTable table = new DataTable(); table.TableName = XML_FILE_ROW_NAME; foreach (DataGridViewColumn column in dataGridView1.Columns) { table.Columns.Add(column.DataPropertyName, column.ValueType); } foreach (DataGridViewRow row in dataGridView1.Rows) { DataRow rowToBeAdded = table.NewRow(); for (int i = 0; i < dataGridView1.ColumnCount; i++) { if (row.Cells[i].Value == null) rowToBeAdded[i] = ""; else rowToBeAdded[i] = row.Cells[i].Value; } table.Rows.Add(rowToBeAdded.ItemArray); } dataset.Tables.Add(table); dataset.WriteXml(filename); MessageBox.Show(DATA_SAVED_TO_FILE_SUCCESS_MESSAGE); } private void hideRow(DataGridViewRow row) { CurrencyManager currencyManager = (CurrencyManager)BindingContext[dataGridView1.DataSource]; currencyManager.SuspendBinding(); row.Visible = false; currencyManager.ResumeBinding(); } private void showRow(DataGridViewRow row) { CurrencyManager currencyManager = (CurrencyManager)BindingContext[dataGridView1.DataSource]; currencyManager.SuspendBinding(); row.Visible = true; currencyManager.ResumeBinding(); } private Boolean rowMustBeHidden(string filterTypeName, string rowDateString) //uses a filter-related rule to determine if a row must be hidden { if (filterTypeName == null || filterTypeName.Length == 0) { Console.WriteLine(INVALID_FILTER_TYPE_NAME_ERROR_MESSAGE); return true; } if (rowDateString == null || rowDateString.Length == 0) { Console.WriteLine(INVALID_DATE_STRING); return true; } DateTime rowDate = Convert.ToDateTime(rowDateString); int currentYear = DateTime.Today.Year; if (filterTypeName.ToLower().Contains(FILTER_BY_DAY)) { int currentMonth = DateTime.Today.Month; int currentDay = DateTime.Today.Day; Boolean byDayFilterDecision = (rowDate.Year != currentYear || rowDate.Month != currentMonth || rowDate.Day != currentDay); return byDayFilterDecision; } else if (filterTypeName.ToLower().Contains(FILTER_BY_WEEK)) { Calendar calendar = DateTimeFormatInfo.CurrentInfo.Calendar; int currentWeek = getWeekOfYear(DateTime.Today); int rowDateWeek = getWeekOfYear(rowDate); Boolean byWeekFilterDecision = (rowDate.Year != currentYear || rowDateWeek != currentWeek); return byWeekFilterDecision; } else if (filterTypeName.ToLower().Contains(FILTER_BY_MONTH)) { int currentMonth = DateTime.Today.Month; Boolean byDayFilterDecision = (rowDate.Year != currentYear || rowDate.Month != currentMonth); return byDayFilterDecision; } else if (filterTypeName.ToLower().Contains(FILTER_BY_YEAR)) { Boolean byDayFilterDecision = (rowDate.Year != currentYear); return byDayFilterDecision; } Console.WriteLine(INVALID_FILTER_TYPE_NAME_ERROR_MESSAGE); return true; } private int getWeekOfYear(DateTime time) { Calendar calendar = DateTimeFormatInfo.CurrentInfo.Calendar; return calendar.GetWeekOfYear(time, DateTimeFormatInfo.CurrentInfo.CalendarWeekRule, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek); } private void showAllRows() { foreach (DataGridViewRow row in dataGridView1.Rows) { showRow(row); } } private void filterByThisYear() { foreach (DataGridViewRow row in dataGridView1.Rows) { String rowDateString = row.Cells[2].Value.ToString(); if (rowMustBeHidden(FILTER_BY_YEAR, rowDateString)) hideRow(row); } } private void filterByThisMonth() { foreach (DataGridViewRow row in dataGridView1.Rows) { String rowDateString = row.Cells[2].Value.ToString(); if (rowMustBeHidden(FILTER_BY_MONTH, rowDateString)) hideRow(row); } } private void filterByThisWeek() { foreach (DataGridViewRow row in dataGridView1.Rows) { String rowDateString = row.Cells[2].Value.ToString(); if (rowMustBeHidden(FILTER_BY_WEEK, rowDateString)) hideRow(row); } } private void filterByToday() { foreach (DataGridViewRow row in dataGridView1.Rows) { String rowDateString = row.Cells[2].Value.ToString(); if (rowMustBeHidden(FILTER_BY_DAY, rowDateString)) hideRow(row); } } private String getRowNote(int rowNumber) { int notesColumnNumber = 3; if (rowNumber >= dataGridView1.Rows.Count || dataGridView1.Rows.Count == 0) { Console.WriteLine(INVALID_ROW_POSITION_ERROR_MESSAGE); return ""; } string message = dataGridView1.Rows[rowNumber].Cells[notesColumnNumber].Value.ToString(); return message; } } } <file_sep># note-editor Note Editing app made with Windows Forms A desktop application that allows you to edit notes. Completed as part of a skills-based challenge. The application uses an xml database to retrieve/update data and C# for the business logic.
8dc6b0668f3138f253ac588f079d9b403c929bad
[ "Markdown", "C#" ]
2
C#
priestley/note-editor
13d500041e1cf299b7d10bd5aabbf76f09b1060e
21f49f6912535dc404f56cdba9a7a1f6f459797d
refs/heads/master
<repo_name>solutionsforeverything/online_voting_java<file_sep>/online voting system/source code/admin.java package jdbconnection; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import java.sql.*; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import javax.swing.SwingConstants; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.*; import java.util.Map.Entry; import java.util.stream.Stream; public class admin { private JFrame frame; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { admin window = new admin(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public admin() { initialize(); } private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JRadioButton rd1 = new JRadioButton("Start"); rd1.setBounds(89, 113, 109, 23); frame.getContentPane().add(rd1); JRadioButton rd2 = new JRadioButton("Stop"); rd2.setSelected(true); rd2.setBounds(89, 139, 109, 23); frame.getContentPane().add(rd2); ButtonGroup bg=new ButtonGroup(); bg.add(rd1); bg.add(rd2); JLabel lblNewLabel = new JLabel("Admin functions"); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblNewLabel.setBounds(51, 30, 303, 34); frame.getContentPane().add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("Start voting system?"); lblNewLabel_1.setBounds(39, 75, 117, 14); frame.getContentPane().add(lblNewLabel_1); JButton btnNewButton = new JButton("CONFIRM"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/voting","root", ""); Statement st = connection.createStatement(); int rs; if(rd1.isSelected()) { rs = st.executeUpdate("update admin set status='start'"); JOptionPane.showMessageDialog(frame, "Voting system has started....."); } else rs=st.executeUpdate("update admin set status='stop'"); } catch (SQLException sq) { System.out.println("SQL statement is not executed! Error is: " + sq.getMessage()); } frame.setVisible(false); } }); btnNewButton.setBounds(137, 191, 89, 23); frame.getContentPane().add(btnNewButton); JButton btnNewButton_1 = new JButton("Issue result"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Map<String ,Integer> map=new HashMap<String,Integer>(); String can;int temp; try { Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/voting","root", ""); Statement st = connection.createStatement(); ResultSet rs=st.executeQuery("select * from voteslist"); while(rs.next()) {temp=rs.getInt("votes"); can=rs.getString("candidate"); map.put(can,temp); } } catch (SQLException sq) { System.out.println("SQL statement is not executed! Error is: " + sq.getMessage()); } List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(map.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o2.getValue()).compareTo(o1.getValue()); } }); // put data from sorted list to hashmap HashMap<String, Integer> temp1 = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp1.put(aa.getKey(), aa.getValue()); } System.out.println("candidate\tvotes"); for (Map.Entry<String, Integer> en :temp1.entrySet()) { System.out.println(en.getKey()+"\t"+ en.getValue()); } String value = temp1.entrySet().stream().findFirst().get().getKey(); System.out.println("Winner: " + value); } }); btnNewButton_1.setBounds(290, 212, 134, 23); frame.getContentPane().add(btnNewButton_1); } } <file_sep>/online voting system/source code/voter.java package jdbconnection; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import javax.swing.JComboBox; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; public class voter { private JFrame frame; private JTextField tfr; /** * Launch the application. */ public void show(String a) { EventQueue.invokeLater(new Runnable() { public void run() { try { voter window = new voter(a); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public voter(String a) { initialize(a); } /** * Initialize the contents of the frame. */ private void initialize(String a) { frame = new JFrame(); frame.setBounds(100, 100, 834, 494); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel vdetails = new JLabel("VOTER DETAILS"); vdetails.setFont(new Font("Tahoma", Font.PLAIN, 17)); vdetails.setHorizontalAlignment(SwingConstants.CENTER); vdetails.setBounds(242, 24, 309, 26); frame.getContentPane().add(vdetails); JLabel label = new JLabel("DEPT"); label.setHorizontalAlignment(SwingConstants.CENTER); label.setBounds(212, 155, 86, 26); frame.getContentPane().add(label); JComboBox tfd = new JComboBox(); tfd.setBounds(456, 157, 117, 22); frame.getContentPane().add(tfd); tfd.addItem("IT"); tfd.addItem("CSE"); tfd.addItem("ECE"); tfd.addItem("EI"); tfd.addItem("AERO"); tfd.addItem("AUTO"); tfd.addItem("RPT"); tfd.addItem("PT"); JComboBox tfc = new JComboBox(); tfc.setBounds(456, 82, 117, 22); frame.getContentPane().add(tfc); tfc.addItem("student"); tfc.addItem("teacher"); JLabel lblRegnoifTeacherEnter = new JLabel("REGNO(if teacher enter ur ID number)"); lblRegnoifTeacherEnter.setHorizontalAlignment(SwingConstants.CENTER); lblRegnoifTeacherEnter.setBounds(79, 227, 219, 26); frame.getContentPane().add(lblRegnoifTeacherEnter); tfr = new JTextField(); tfr.setColumns(10); tfr.setBounds(456, 230, 117, 20); frame.getContentPane().add(tfr); JButton button = new JButton("Submit"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s1=(String)tfd.getSelectedItem(); String s2=(String)tfc.getSelectedItem(); String s=tfr.getText(); //String s=tfr.getText(); validate va=new validate(); if(va.nullcheck(s)) { if(!va.isdigitcheck(s)) JOptionPane.showMessageDialog(frame,"regno should be nos"); else {database db=new database(); db.show2(s, s1,s2,a); frame.setVisible(false); } } else JOptionPane.showMessageDialog(frame,"enter info"); } }); button.setBounds(297, 313, 89, 23); frame.getContentPane().add(button); JLabel lblNewLabel = new JLabel("CHOOSE"); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setBounds(223, 80, 67, 26); frame.getContentPane().add(lblNewLabel); } } <file_sep>/online voting system/source code/signup.java package jdbconnection; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JComboBox; import javax.swing.JPasswordField; import java.awt.Font; public class signup { private JFrame frame; private JTextField tfl; private JTextField tfp; private JTextField tfa; private JTextField tff; private JTextField tfu; private JPasswordField tfp1; /** * Launch the application. */ public void show() { EventQueue.invokeLater(new Runnable() { public void run() { try { signup window = new signup(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public signup() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 749, 498); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("SIGNUP FORM"); lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setBounds(303, 8, 172, 37); frame.getContentPane().add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("FIRSTNAME"); lblNewLabel_1.setBounds(338, 96, 87, 22); frame.getContentPane().add(lblNewLabel_1); JLabel lblPassword = new JLabel("LASTNAME"); lblPassword.setBounds(338, 147, 87, 22); frame.getContentPane().add(lblPassword); JLabel passs = new JLabel("PASSWORD"); passs.setBounds(21, 203, 87, 22); frame.getContentPane().add(passs); JLabel lblAge = new JLabel("AGE"); lblAge.setBounds(338, 191, 87, 22); frame.getContentPane().add(lblAge); tfl = new JTextField(); tfl.setBounds(523, 148, 139, 20); frame.getContentPane().add(tfl); tfl.setColumns(10); tfp = new JPasswordField(); tfp.setColumns(10); tfp.setBounds(118, 204, 139, 20); frame.getContentPane().add(tfp); tfa = new JTextField(); tfa.setColumns(10); tfa.setBounds(523, 192, 139, 20); frame.getContentPane().add(tfa); tff = new JTextField(); tff.setColumns(10); tff.setBounds(523, 97, 139, 20); frame.getContentPane().add(tff); JLabel users = new JLabel("USERNAME"); users.setBounds(21, 148, 87, 20); frame.getContentPane().add(users); tfp1 = new JPasswordField(); tfp1.setBounds(118, 245, 139, 20); frame.getContentPane().add(tfp1); tfu = new JTextField(); tfu.setText(""); tfu.setBounds(116, 148, 139, 20); frame.getContentPane().add(tfu); tfu.setColumns(10); JComboBox dn = new JComboBox(); dn.addItem("voter"); dn.addItem("candidate"); dn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); dn.setBounds(523, 237, 139, 22); frame.getContentPane().add(dn); JButton btnNewButton = new JButton("SIGNUP"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String n1=tff.getText(); String n2=tfu.getText(); String n3=tfp.getText();@SuppressWarnings("deprecation") String n4=tfp1.getText(); String n5=tfa.getText(); String n6=tfl.getText(); database db=new database(); validate va=new validate(); boolean bo=((va.nullcheck(n1))&&(va.nullcheck(n2))&&(va.nullcheck(n3))&&(va.nullcheck(n4))&&(va.nullcheck(n5))&&(va.nullcheck(n6))); if(bo) {int flag=0; if(va.isexistschecku(n2)) {JOptionPane.showMessageDialog(frame, "username taken"); //String a2=tfp.getText(); flag=1; } if((!n2.matches("[a-zA-Z0-9]+"))|| n2.length()<8) { JOptionPane.showMessageDialog(frame, "username should contain 1 uppercase one lowercase and a digit of length 8"); flag=1; } if((!n3.matches("((?=.*[a-z])(?=.*\\d)(?=.*[A-Z])(?=.*[@#$%!]).{8,40})"))) { JOptionPane.showMessageDialog(frame, "password should contain 1 uppercase one lowercase and any one special chararcter and a digit of length 8"); flag=1; } //String b1=tfp1.getText(); if(!n3.equals(n4)) {JOptionPane.showMessageDialog(frame, "password not matches"); flag=1; } /*else if(va.isexistscheckp(n3)) {JOptionPane.showMessageDialog(frame, "password taken");flag=1;}*/ String s=tfa.getText(); boolean k1=va.isdigitcheck(s); if(k1==false) JOptionPane.showMessageDialog(frame, "age should be numbers"); if (k1==true) {int a1=Integer.parseInt(s); //System.out.println(a1); if(a1<18 || a1>100) JOptionPane.showMessageDialog(frame, " age is less than 18"); else if(flag==0) {/*if(va.isexistscheck(n3)) JOptionPane.showMessageDialog(frame, "password taken"); String s=REGNO.getText(); int k=0;boolean k1=true; while(k<s.length()) k1=Character.isDigit(s.charAt(k++)); if(k1==false) JOptionPane.showMessageDialog(frame, "regno should be numbers");*/ //String s1=tfu.getText(); //String s2=tfp.getText(); String s3=(String)dn.getSelectedItem(); db.show(n2,n3,s3); //String s3=(String)cb.getSelectedItem(); if(s3=="candidate") {candidate c=new candidate(n2); c.show(n2); } else if(s3=="voter") {voter v=new voter(n2); v.show(n2); } db.show1(n2,n3,n1,n6,n5,s3); frame.setVisible(false); } } } else JOptionPane.showMessageDialog(frame,"enter info"); } }); btnNewButton.setBounds(338, 367, 89, 23); frame.getContentPane().add(btnNewButton); JLabel lblNewLabel_2 = new JLabel("designation"); lblNewLabel_2.setBounds(338, 245, 81, 14); frame.getContentPane().add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel("Confirm password"); lblNewLabel_3.setBounds(10, 236, 98, 46); frame.getContentPane().add(lblNewLabel_3); /*JComboBox cb = new JComboBox(); cb.addItem("voter"); cb.addItem("candidate"); cb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { /*cb.addItem("voter"); cb.addItem("candidate"); } }); cb.setBounds(333, 220, 81, 22); frame.getContentPane().add(cb);*/ } }
f0d0ab11a19bebb07a51f11569f3d235a913d6c0
[ "Java" ]
3
Java
solutionsforeverything/online_voting_java
c472da900577ffb776f3cc43bcbc66547cd84f0f
9b22eaf41a3b1671e283cb093d5c1c49fff24997
refs/heads/master
<file_sep>package day3; public class Practice { int wow; /** * * @param args */ public void stairs(int n){ String hash="#"; for(int i=1;i<=n;i++){ for(int k=1;k<=n-i;k++){ System.out.print(" "); } for(int j=1;j<=i;j++){ System.out.print(hash); } System.out.println(); } } public static void main(String args[]){ Practice p=new Practice(); //List<String> as=new ArrayList<String>(); String s1="Hello"; String s2=new String("Hello"); String s3="HELLO"; System.out.println(s1==s2); System.out.println(s1.equals(s2)); System.out.println(s2==s3); System.out.println(s2.equals(s3)); System.out.println(s1==s3); System.out.println(s1.equals(s3)); System.out.println(p.wow+" "); System.out.println(43%10); System.out.println("Staircase is starting now...!!!!"); p.stairs(10); ICalculation cal=new Parent(); } } <file_sep>package day3; public class Child extends Parent implements ICalculation{ public int c; public Child(){ c=10; super.c=89; System.out.println(c); } public void addition(String x, String y){ String z=x+y; System.out.println("The sum of the given numbers:" + z); } public void multiplication(int x, int y){ int z=x*y; System.out.println("The product of the given numbers:"+z); } public void sameMethod() { System.out.println("I am in method of class Child..."); } @Override public void method1() { System.out.println("I am in method of interface in child..."); } /** * * @param args */ public static void main(String args[]){ int a=20, b=10; Child demo = new Child(); //contains all methods demo.addition(a, b); demo.substraction(a, b); demo.multiplication(a, b); demo.sameMethod(); demo.method1(); System.out.println(); System.out.println(); Parent demo2 = new Parent(); //contains only parent's methods demo2.addition(a, b); demo2.substraction(a, b); demo2.sameMethod(); demo2.method1(); System.out.println(); //Child cs=new Parent(); Parent calc=new Child(); //contains only parent's methods but object of child calc.addition(a, b); calc.substraction(a, b); calc.sameMethod(); calc.method1(); System.out.println(); ICalculation c=new Child(); //Child ch= new Parent(); } }
847491ecf9f15bfe01f7e37ba047fa7096e679bf
[ "Java" ]
2
Java
SharmaBulbul/JAVA-Tutorial
81f5ca380d1441df70fcd756162769642ec58cf0
60173b5445ff7b0e9768f20b1c3bcb19effd6a34
refs/heads/master
<repo_name>suyangman/recast<file_sep>/RecastDemo/Source/InputGeom.cpp // // Copyright (c) 2009-2010 <NAME> <EMAIL> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <algorithm> #include "Recast.h" #include "InputGeom.h" #include "ChunkyTriMesh.h" #include "MeshLoaderObj.h" #include "DebugDraw.h" #include "RecastDebugDraw.h" #include "DetourNavMesh.h" #include "Sample.h" #include <fstream> #include <sstream> #define GUID_LEN (32) #define _MAKE_MAGIC_DWORD(a, b, c, d) ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24)) static const unsigned int SHAPE_FILE_MAGIC = _MAKE_MAGIC_DWORD('S', 'H', 'P', 'E'); static const unsigned int SHAPE_FILE_VERSION = 2; static bool intersectSegmentTriangle(const float* sp, const float* sq, const float* a, const float* b, const float* c, float &t) { float v, w; float ab[3], ac[3], qp[3], ap[3], norm[3], e[3]; rcVsub(ab, b, a); rcVsub(ac, c, a); rcVsub(qp, sp, sq); // Compute triangle normal. Can be precalculated or cached if // intersecting multiple segments against the same triangle rcVcross(norm, ab, ac); // Compute denominator d. If d <= 0, segment is parallel to or points // away from triangle, so exit early float d = rcVdot(qp, norm); if (d <= 0.0f) return false; // Compute intersection t value of pq with plane of triangle. A ray // intersects iff 0 <= t. Segment intersects iff 0 <= t <= 1. Delay // dividing by d until intersection has been found to pierce triangle rcVsub(ap, sp, a); t = rcVdot(ap, norm); if (t < 0.0f) return false; if (t > d) return false; // For segment; exclude this code line for a ray test // Compute barycentric coordinate components and test if within bounds rcVcross(e, qp, ap); v = rcVdot(ac, e); if (v < 0.0f || v > d) return false; w = -rcVdot(ab, e); if (w < 0.0f || v + w > d) return false; // Segment/ray intersects triangle. Perform delayed division t /= d; return true; } static char* parseRow(char* buf, char* bufEnd, char* row, int len) { bool start = true; bool done = false; int n = 0; while (!done && buf < bufEnd) { char c = *buf; buf++; // multirow switch (c) { case '\n': if (start) break; done = true; break; case '\r': break; case '\t': case ' ': if (start) break; // else falls through default: start = false; row[n++] = c; if (n >= len-1) done = true; break; } } row[n] = '\0'; return buf; } InputGeom::InputGeom() : m_chunkyMesh(0), m_mesh(0), m_hasBuildSettings(false), m_offMeshConCount(0), m_volumeCount(0) { } InputGeom::~InputGeom() { delete m_chunkyMesh; delete m_mesh; } bool InputGeom::loadMesh(rcContext* ctx, const std::string& filepath) { if (m_mesh) { delete m_chunkyMesh; m_chunkyMesh = 0; delete m_mesh; m_mesh = 0; } m_offMeshConCount = 0; m_volumeCount = 0; m_mesh = new rcMeshLoaderObj; if (!m_mesh) { ctx->log(RC_LOG_ERROR, "loadMesh: Out of memory 'm_mesh'."); return false; } if (!m_mesh->load(filepath)) { ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not load '%s'", filepath.c_str()); return false; } rcCalcBounds(m_mesh->getVerts(), m_mesh->getVertCount(), m_meshBMin, m_meshBMax); m_chunkyMesh = new rcChunkyTriMesh; if (!m_chunkyMesh) { ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Out of memory 'm_chunkyMesh'."); return false; } if (!rcCreateChunkyTriMesh(m_mesh->getVerts(), m_mesh->getTris(), m_mesh->getTriCount(), 256, m_chunkyMesh)) { ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Failed to build chunky mesh."); return false; } return true; } bool InputGeom::loadGeomSet(rcContext* ctx, const std::string& filepath) { char* buf = 0; FILE* fp = fopen(filepath.c_str(), "rb"); if (!fp) { return false; } if (fseek(fp, 0, SEEK_END) != 0) { fclose(fp); return false; } long bufSize = ftell(fp); if (bufSize < 0) { fclose(fp); return false; } if (fseek(fp, 0, SEEK_SET) != 0) { fclose(fp); return false; } buf = new char[bufSize]; if (!buf) { fclose(fp); return false; } size_t readLen = fread(buf, bufSize, 1, fp); fclose(fp); if (readLen != 1) { delete[] buf; return false; } m_offMeshConCount = 0; m_volumeCount = 0; delete m_mesh; m_mesh = 0; char* src = buf; char* srcEnd = buf + bufSize; char row[512]; while (src < srcEnd) { // Parse one row row[0] = '\0'; src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char)); if (row[0] == 'f') { // File name. const char* name = row+1; // Skip white spaces while (*name && isspace(*name)) name++; if (*name) { if (!loadMesh(ctx, name)) { delete [] buf; return false; } } } else if (row[0] == 'c') { // Off-mesh connection if (m_offMeshConCount < MAX_OFFMESH_CONNECTIONS) { float* v = &m_offMeshConVerts[m_offMeshConCount*3*2]; int bidir, area = 0, flags = 0; float rad; sscanf(row+1, "%f %f %f %f %f %f %f %d %d %d", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &rad, &bidir, &area, &flags); m_offMeshConRads[m_offMeshConCount] = rad; m_offMeshConDirs[m_offMeshConCount] = (unsigned char)bidir; m_offMeshConAreas[m_offMeshConCount] = (unsigned char)area; m_offMeshConFlags[m_offMeshConCount] = (unsigned short)flags; m_offMeshConCount++; } } else if (row[0] == 'v') { // Convex volumes if (m_volumeCount < MAX_VOLUMES) { ConvexVolume* vol = &m_volumes[m_volumeCount++]; sscanf(row+1, "%d %d %f %f", &vol->nverts, &vol->area, &vol->hmin, &vol->hmax); for (int i = 0; i < vol->nverts; ++i) { row[0] = '\0'; src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char)); sscanf(row, "%f %f %f", &vol->verts[i*3+0], &vol->verts[i*3+1], &vol->verts[i*3+2]); } } } else if (row[0] == 's') { // Settings m_hasBuildSettings = true; sscanf(row + 1, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d %f %f %f %f %f %f %f", &m_buildSettings.cellSize, &m_buildSettings.cellHeight, &m_buildSettings.agentHeight, &m_buildSettings.agentRadius, &m_buildSettings.agentMaxClimb, &m_buildSettings.agentMaxSlope, &m_buildSettings.regionMinSize, &m_buildSettings.regionMergeSize, &m_buildSettings.edgeMaxLen, &m_buildSettings.edgeMaxError, &m_buildSettings.vertsPerPoly, &m_buildSettings.detailSampleDist, &m_buildSettings.detailSampleMaxError, &m_buildSettings.partitionType, &m_buildSettings.navMeshBMin[0], &m_buildSettings.navMeshBMin[1], &m_buildSettings.navMeshBMin[2], &m_buildSettings.navMeshBMax[0], &m_buildSettings.navMeshBMax[1], &m_buildSettings.navMeshBMax[2], &m_buildSettings.tileSize); } } delete [] buf; return true; } void InputGeom::LoadMeshFormat(BufferStream& stream) { char szHeader[128] = { '\0', }; stream.Read(szHeader, sizeof(szHeader), 1); if (strcmp(szHeader, "Embedded Mesh File") != 0) { stream.AdjustOffset(-128); return; } uint32_t nNodeCount = 0; stream.Read(&nNodeCount, sizeof(nNodeCount), 1); m_vImportScene.nodes.resize(nNodeCount); for (uint32_t i = 0; i < nNodeCount; ++i) { ImportNode& rNode = m_vImportScene.nodes[i]; char szTmp[128] = { 0 }; stream.Read(szTmp, sizeof(szTmp), 1); szTmp[sizeof(szTmp) - 1] = '\0'; rNode.name = szTmp; stream.Read(&rNode.uClientUID, sizeof(rNode.uClientUID), 1); std::stringstream ss; ss << '_'; ss << rNode.uClientUID; rNode.name += ss.str(); stream.Read(&rNode.position, sizeof(rNode.position), 1); stream.Read(&rNode.rotation, sizeof(rNode.rotation), 1); stream.Read(&rNode.scale, sizeof(rNode.scale), 1); stream.Read(&rNode.iPenetrationCode, sizeof(rNode.iPenetrationCode), 1); stream.Read(&rNode.byMaterialType, sizeof(rNode.byMaterialType), 1); stream.Read(&rNode.layerIndex, sizeof(rNode.layerIndex), 1); rNode.layerIndex = 14; stream.Read(&rNode.meshIndex, sizeof(rNode.meshIndex), 1); } uint32_t nMeshCount = 0; stream.Read(&nMeshCount, sizeof(nMeshCount), 1); m_vImportScene.meshes.resize(nMeshCount); for (uint32_t i = 0; i < nMeshCount; ++i) { ImportMesh& rMesh = m_vImportScene.meshes[i]; char szTmp[128]; stream.Read(szTmp, sizeof(szTmp), 1); szTmp[sizeof(szTmp) - 1] = '\0'; rMesh.name = szTmp; int32_t nVertsCount = 0; stream.Read(&nVertsCount, sizeof(nVertsCount), 1); if (nVertsCount <= 0 || nVertsCount >= static_cast<int32_t>(rMesh.vertices.max_size())) { continue; } rMesh.vertices.resize(nVertsCount); stream.Read(&rMesh.vertices[0], sizeof(rMesh.vertices[0]), nVertsCount); int32_t nPolygonCount = 0; stream.Read(&nPolygonCount, sizeof(nPolygonCount), 1); rMesh.polygons.resize(nPolygonCount); stream.Read(&rMesh.polygons[0], sizeof(rMesh.polygons[0]), nPolygonCount); stream.Read(&rMesh.isConvex, sizeof(rMesh.isConvex), 1); } } void InputGeom::LoadTerrainFormat(BufferStream& stream) { char szHeader[128] = {}; stream.Read(szHeader, sizeof(szHeader), 1); if (strcmp(szHeader, "Embedded terrain File") != 0) { stream.AdjustOffset(-128); return; } int32_t nNodeCount = 0; stream.Read(&nNodeCount, sizeof(nNodeCount), 1); m_vImportScene.heightFields.resize(nNodeCount); for (int i = 0; i < nNodeCount; ++i) { ImportHeightField& heightField = m_vImportScene.heightFields[i]; memset(&heightField, 0, sizeof(heightField)); stream.Read(&heightField.iInstanceID, sizeof(heightField.iInstanceID), 1); // terrain data // terrainData.heightmapWidth, x, row stream.Read(&heightField.nbRows, sizeof(heightField.nbRows), 1); // terrainData.heightmapHeight, z, column stream.Read(&heightField.nbColumns, sizeof(heightField.nbColumns), 1); // terrainData.heightmapScale.y stream.Read(&heightField.heightScale, sizeof(heightField.heightScale), 1); // terrainData.heightmapScale.z stream.Read(&heightField.columnScale, sizeof(heightField.columnScale), 1); // terrainData.heightmapScale.x stream.Read(&heightField.rowScale, sizeof(heightField.rowScale), 1); // samples heightField.samples.resize(heightField.nbRows * heightField.nbColumns); for (int m = 0; m < (int)heightField.nbRows; ++m) { for (int n = 0; n < (int)heightField.nbColumns; ++n) { float height = 0; stream.Read(&height, sizeof(height), 1); // TODO: make sure int16 uint8_t isHole = 0; stream.Read(&isHole, sizeof(isHole), 1); heightField.samples[m * heightField.nbColumns + n].height = static_cast<short>(height); heightField.samples[m * heightField.nbColumns + n].isHole = isHole; } } // transform // TerrainPosOffset.x stream.Read(&heightField.position, sizeof(heightField.position), 1); } } bool InputGeom::loadBinInfo(class rcContext* ctx, const std::string& filepath) { char* buf = 0; FILE* fp = fopen(filepath.c_str(), "rb"); if (!fp) { return false; } if (fseek(fp, 0, SEEK_END) != 0) { fclose(fp); return false; } long bufSize = ftell(fp); if (bufSize < 0) { fclose(fp); return false; } if (fseek(fp, 0, SEEK_SET) != 0) { fclose(fp); return false; } buf = new char[bufSize]; if (!buf) { fclose(fp); return false; } size_t readLen = fread(buf, bufSize, 1, fp); fclose(fp); if (readLen != 1) { delete[] buf; return false; } if (m_mesh) { delete m_chunkyMesh; m_chunkyMesh = 0; delete m_mesh; m_mesh = 0; } m_offMeshConCount = 0; m_volumeCount = 0; bool bret = true; do { BufferStream stream(buf, bufSize); uint32_t uMagic = 0; stream.Read(&uMagic, sizeof(uMagic), 1); if (SHAPE_FILE_MAGIC != uMagic) { bret = false; break; } uint32_t uVersion = 0; stream.Read(&uVersion, sizeof(uVersion), 1); if (SHAPE_FILE_VERSION != uVersion) { bret = false; break; } char guid[GUID_LEN + 1]; stream.Read(guid, GUID_LEN, 1); guid[GUID_LEN] = '\0'; uint32_t nNodeCount = 0; stream.Read(&nNodeCount, sizeof(nNodeCount), 1); if (static_cast<unsigned int>(bufSize) < sizeof(uint32_t) * 2 + sizeof(ImportShape) * nNodeCount) { bret = false; break; } m_vImportScene.shapes.resize(nNodeCount); for (uint32_t i = 0; i < nNodeCount; ++i) { ImportShape& rNode = m_vImportScene.shapes[i]; stream.Read(rNode.szName, sizeof(rNode.szName), 1); rNode.szName[sizeof(rNode.szName) - 1] = '\0'; stream.Read(&rNode.byType, sizeof(rNode.byType), 1); stream.Read(&rNode.uClientUID, sizeof(rNode.uClientUID), 1); std::stringstream ss; ss << '_'; ss << rNode.uClientUID; int iTmpCnt = sizeof(rNode.szName) - strlen(rNode.szName); if (iTmpCnt > (int)ss.str().length()) iTmpCnt = ss.str().length(); strncpy(rNode.szName + strlen(rNode.szName), ss.str().c_str(), iTmpCnt); stream.Read(&rNode.vLocation, sizeof(rNode.vLocation), 1); stream.Read(&rNode.qRotate, sizeof(rNode.qRotate), 1); stream.Read(&rNode.vScale, sizeof(rNode.vScale), 1); stream.Read(&rNode.iPenetrationCode, sizeof(rNode.iPenetrationCode), 1); stream.Read(&rNode.byMaterialType, sizeof(rNode.byMaterialType), 1); stream.Read(&rNode.uLayer, sizeof(rNode.uLayer), 1); stream.Read(&rNode.vExtent, sizeof(rNode.vExtent), 1); // apply global scale to the geometry rNode.vExtent = Scale(rNode.vExtent, rNode.vScale); // it doesn't make sense for symmetrical primitives to have negative extents rNode.vExtent.x = fabs(rNode.vExtent.x); rNode.vExtent.y = fabs(rNode.vExtent.y); rNode.vExtent.z = fabs(rNode.vExtent.z); } if (stream.GetRemainSize() > 0) { LoadMeshFormat(stream); } if (stream.GetRemainSize() > 0) { LoadTerrainFormat(stream); } } while (0); m_mesh = new(std::nothrow) rcMeshLoaderObj; if (!m_mesh) { ctx->log(RC_LOG_ERROR, "loadMesh: Out of memory 'm_mesh'."); return false; } size_t i_shapes = m_vImportScene.shapes.size(); size_t i_nodes = m_vImportScene.nodes.size(); size_t i_meshes = m_vImportScene.meshes.size(); size_t i_heightFields = m_vImportScene.heightFields.size(); m_mesh->load(&m_vImportScene); rcCalcBounds(m_mesh->getVerts(), m_mesh->getVertCount(), m_meshBMin, m_meshBMax); m_chunkyMesh = new rcChunkyTriMesh; if (!m_chunkyMesh) { ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Out of memory 'm_chunkyMesh'."); return false; } if (!rcCreateChunkyTriMesh(m_mesh->getVerts(), m_mesh->getTris(), m_mesh->getTriCount(), 256, m_chunkyMesh)) { ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Failed to build chunky mesh."); return false; } return bret; } bool InputGeom::load(rcContext* ctx, const std::string& filepath) { size_t extensionPos = filepath.find_last_of('.'); if (extensionPos == std::string::npos) return false; std::string extension = filepath.substr(extensionPos); std::transform(extension.begin(), extension.end(), extension.begin(), tolower); if (extension == ".gset") return loadGeomSet(ctx, filepath); if (extension == ".obj") return loadMesh(ctx, filepath); if (extension == ".bin") return loadBinInfo(ctx, filepath); return false; } bool InputGeom::saveGeomSet(const BuildSettings* settings) { if (!m_mesh) return false; // Change extension std::string filepath = m_mesh->getFileName(); size_t extPos = filepath.find_last_of('.'); if (extPos != std::string::npos) filepath = filepath.substr(0, extPos); filepath += ".gset"; FILE* fp = fopen(filepath.c_str(), "w"); if (!fp) return false; // Store mesh filename. fprintf(fp, "f %s\n", m_mesh->getFileName().c_str()); // Store settings if any if (settings) { fprintf(fp, "s %f %f %f %f %f %f %f %f %f %f %f %f %f %d %f %f %f %f %f %f %f\n", settings->cellSize, settings->cellHeight, settings->agentHeight, settings->agentRadius, settings->agentMaxClimb, settings->agentMaxSlope, settings->regionMinSize, settings->regionMergeSize, settings->edgeMaxLen, settings->edgeMaxError, settings->vertsPerPoly, settings->detailSampleDist, settings->detailSampleMaxError, settings->partitionType, settings->navMeshBMin[0], settings->navMeshBMin[1], settings->navMeshBMin[2], settings->navMeshBMax[0], settings->navMeshBMax[1], settings->navMeshBMax[2], settings->tileSize); } // Store off-mesh links. for (int i = 0; i < m_offMeshConCount; ++i) { const float* v = &m_offMeshConVerts[i*3*2]; const float rad = m_offMeshConRads[i]; const int bidir = m_offMeshConDirs[i]; const int area = m_offMeshConAreas[i]; const int flags = m_offMeshConFlags[i]; fprintf(fp, "c %f %f %f %f %f %f %f %d %d %d\n", v[0], v[1], v[2], v[3], v[4], v[5], rad, bidir, area, flags); } // Convex volumes for (int i = 0; i < m_volumeCount; ++i) { ConvexVolume* vol = &m_volumes[i]; fprintf(fp, "v %d %d %f %f\n", vol->nverts, vol->area, vol->hmin, vol->hmax); for (int j = 0; j < vol->nverts; ++j) fprintf(fp, "%f %f %f\n", vol->verts[j*3+0], vol->verts[j*3+1], vol->verts[j*3+2]); } fclose(fp); return true; } static bool isectSegAABB(const float* sp, const float* sq, const float* amin, const float* amax, float& tmin, float& tmax) { static const float EPS = 1e-6f; float d[3]; d[0] = sq[0] - sp[0]; d[1] = sq[1] - sp[1]; d[2] = sq[2] - sp[2]; tmin = 0.0; tmax = 1.0f; for (int i = 0; i < 3; i++) { if (fabsf(d[i]) < EPS) { if (sp[i] < amin[i] || sp[i] > amax[i]) return false; } else { const float ood = 1.0f / d[i]; float t1 = (amin[i] - sp[i]) * ood; float t2 = (amax[i] - sp[i]) * ood; if (t1 > t2) { float tmp = t1; t1 = t2; t2 = tmp; } if (t1 > tmin) tmin = t1; if (t2 < tmax) tmax = t2; if (tmin > tmax) return false; } } return true; } bool InputGeom::raycastMesh(float* src, float* dst, float& tmin) { float dir[3]; rcVsub(dir, dst, src); // Prune hit ray. float btmin, btmax; if (!isectSegAABB(src, dst, m_meshBMin, m_meshBMax, btmin, btmax)) return false; float p[2], q[2]; p[0] = src[0] + (dst[0]-src[0])*btmin; p[1] = src[2] + (dst[2]-src[2])*btmin; q[0] = src[0] + (dst[0]-src[0])*btmax; q[1] = src[2] + (dst[2]-src[2])*btmax; int cid[512]; const int ncid = rcGetChunksOverlappingSegment(m_chunkyMesh, p, q, cid, 512); if (!ncid) return false; tmin = 1.0f; bool hit = false; const float* verts = m_mesh->getVerts(); for (int i = 0; i < ncid; ++i) { const rcChunkyTriMeshNode& node = m_chunkyMesh->nodes[cid[i]]; const int* tris = &m_chunkyMesh->tris[node.i*3]; const int ntris = node.n; for (int j = 0; j < ntris*3; j += 3) { float t = 1; if (intersectSegmentTriangle(src, dst, &verts[tris[j]*3], &verts[tris[j+1]*3], &verts[tris[j+2]*3], t)) { if (t < tmin) tmin = t; hit = true; } } } return hit; } void InputGeom::addOffMeshConnection(const float* spos, const float* epos, const float rad, unsigned char bidir, unsigned char area, unsigned short flags) { if (m_offMeshConCount >= MAX_OFFMESH_CONNECTIONS) return; float* v = &m_offMeshConVerts[m_offMeshConCount*3*2]; m_offMeshConRads[m_offMeshConCount] = rad; m_offMeshConDirs[m_offMeshConCount] = bidir; m_offMeshConAreas[m_offMeshConCount] = area; m_offMeshConFlags[m_offMeshConCount] = flags; m_offMeshConId[m_offMeshConCount] = 1000 + m_offMeshConCount; rcVcopy(&v[0], spos); rcVcopy(&v[3], epos); m_offMeshConCount++; } void InputGeom::deleteOffMeshConnection(int i) { m_offMeshConCount--; float* src = &m_offMeshConVerts[m_offMeshConCount*3*2]; float* dst = &m_offMeshConVerts[i*3*2]; rcVcopy(&dst[0], &src[0]); rcVcopy(&dst[3], &src[3]); m_offMeshConRads[i] = m_offMeshConRads[m_offMeshConCount]; m_offMeshConDirs[i] = m_offMeshConDirs[m_offMeshConCount]; m_offMeshConAreas[i] = m_offMeshConAreas[m_offMeshConCount]; m_offMeshConFlags[i] = m_offMeshConFlags[m_offMeshConCount]; } void InputGeom::drawOffMeshConnections(duDebugDraw* dd, bool hilight) { unsigned int conColor = duRGBA(192,0,128,192); unsigned int baseColor = duRGBA(0,0,0,64); dd->depthMask(false); dd->begin(DU_DRAW_LINES, 2.0f); for (int i = 0; i < m_offMeshConCount; ++i) { float* v = &m_offMeshConVerts[i*3*2]; dd->vertex(v[0],v[1],v[2], baseColor); dd->vertex(v[0],v[1]+0.2f,v[2], baseColor); dd->vertex(v[3],v[4],v[5], baseColor); dd->vertex(v[3],v[4]+0.2f,v[5], baseColor); duAppendCircle(dd, v[0],v[1]+0.1f,v[2], m_offMeshConRads[i], baseColor); duAppendCircle(dd, v[3],v[4]+0.1f,v[5], m_offMeshConRads[i], baseColor); if (hilight) { duAppendArc(dd, v[0],v[1],v[2], v[3],v[4],v[5], 0.25f, (m_offMeshConDirs[i]&1) ? 0.6f : 0.0f, 0.6f, conColor); } } dd->end(); dd->depthMask(true); } void InputGeom::addConvexVolume(const float* verts, const int nverts, const float minh, const float maxh, unsigned char area) { if (m_volumeCount >= MAX_VOLUMES) return; ConvexVolume* vol = &m_volumes[m_volumeCount++]; memset(vol, 0, sizeof(ConvexVolume)); memcpy(vol->verts, verts, sizeof(float)*3*nverts); vol->hmin = minh; vol->hmax = maxh; vol->nverts = nverts; vol->area = area; } void InputGeom::deleteConvexVolume(int i) { m_volumeCount--; m_volumes[i] = m_volumes[m_volumeCount]; } void InputGeom::drawConvexVolumes(struct duDebugDraw* dd, bool /*hilight*/) { dd->depthMask(false); dd->begin(DU_DRAW_TRIS); for (int i = 0; i < m_volumeCount; ++i) { const ConvexVolume* vol = &m_volumes[i]; unsigned int col = duTransCol(dd->areaToCol(vol->area), 32); for (int j = 0, k = vol->nverts-1; j < vol->nverts; k = j++) { const float* va = &vol->verts[k*3]; const float* vb = &vol->verts[j*3]; dd->vertex(vol->verts[0],vol->hmax,vol->verts[2], col); dd->vertex(vb[0],vol->hmax,vb[2], col); dd->vertex(va[0],vol->hmax,va[2], col); dd->vertex(va[0],vol->hmin,va[2], duDarkenCol(col)); dd->vertex(va[0],vol->hmax,va[2], col); dd->vertex(vb[0],vol->hmax,vb[2], col); dd->vertex(va[0],vol->hmin,va[2], duDarkenCol(col)); dd->vertex(vb[0],vol->hmax,vb[2], col); dd->vertex(vb[0],vol->hmin,vb[2], duDarkenCol(col)); } } dd->end(); dd->begin(DU_DRAW_LINES, 2.0f); for (int i = 0; i < m_volumeCount; ++i) { const ConvexVolume* vol = &m_volumes[i]; unsigned int col = duTransCol(dd->areaToCol(vol->area), 220); for (int j = 0, k = vol->nverts-1; j < vol->nverts; k = j++) { const float* va = &vol->verts[k*3]; const float* vb = &vol->verts[j*3]; dd->vertex(va[0],vol->hmin,va[2], duDarkenCol(col)); dd->vertex(vb[0],vol->hmin,vb[2], duDarkenCol(col)); dd->vertex(va[0],vol->hmax,va[2], col); dd->vertex(vb[0],vol->hmax,vb[2], col); dd->vertex(va[0],vol->hmin,va[2], duDarkenCol(col)); dd->vertex(va[0],vol->hmax,va[2], col); } } dd->end(); dd->begin(DU_DRAW_POINTS, 3.0f); for (int i = 0; i < m_volumeCount; ++i) { const ConvexVolume* vol = &m_volumes[i]; unsigned int col = duDarkenCol(duTransCol(dd->areaToCol(vol->area), 220)); for (int j = 0; j < vol->nverts; ++j) { dd->vertex(vol->verts[j*3+0],vol->verts[j*3+1]+0.1f,vol->verts[j*3+2], col); dd->vertex(vol->verts[j*3+0],vol->hmin,vol->verts[j*3+2], col); dd->vertex(vol->verts[j*3+0],vol->hmax,vol->verts[j*3+2], col); } } dd->end(); dd->depthMask(true); } <file_sep>/RecastDemo/Include/math/Quaternion.cpp #include "math/Quaternion.h" /* Quaternionf Slerp(const Quaternionf& a, const Quaternionf& b, float time) { #if DEBUGMODE float debugLengthA = Magnitude (a); float debugLengthB = Magnitude (b); #endif // ==================================================== // AART - Advanced Animation and Rendering Techniques // ==================================================== float cosom = a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w; if ( (1 + cosom) > std::numeric_limits<float>::epsilon() ) { float sp; float sq; if ( (1 - cosom) > std::numeric_limits<float>::epsilon() ) { double omega = acos(cosom); double sinom = 1.0 / sin(omega); sp = (sin((1 - time) * omega) * sinom); sq = (sin(time * omega) * sinom); } else { sp = 1 - time; sq = time; } Quaternionf res = Quaternionf ( a.x*sp + b.x*sq, a.y*sp + b.y*sq, a.z*sp + b.z*sq, a.w*sp + b.w*sq); AssertIf (!CompareApproximately (SqrMagnitude (res), 1.0F) && CompareApproximately (SqrMagnitude (b), 1.0) && CompareApproximately (SqrMagnitude (a), 1.0)); return res; } else { float halfpi = pi / 2; float sp = sin((1 - time) * halfpi); float sq = sin(time * halfpi); Quaternionf res = Quaternionf ( a.x*sp - a.y*sq, a.y*sp + a.x*sq, a.z*sp - a.w*sq, a.z); AssertIf (!CompareApproximately (SqrMagnitude (res), 1.0F) && CompareApproximately (SqrMagnitude (b), 1.0) && CompareApproximately (SqrMagnitude (a), 1.0)); return res; } } */ <file_sep>/RecastDemo/Include/math/Vector3f.h #pragma once #include <algorithm> //#include "cppcore/common/CommonDef.h" //#include "cppcore/math/FloatConversion.h" //#include "cppcore/containers/array.h" #ifndef M_PI #define M_PI 3.1415926 #endif class Vector3f { public: float x, y, z; Vector3f () : x(0.f), y(0.f), z(0.f) {} Vector3f (float inX, float inY, float inZ) { x = inX; y = inY; z = inZ; } explicit Vector3f (const float* array) { x = array[0]; y = array[1]; z = array[2]; } void Set (float inX, float inY, float inZ) { x = inX; y = inY; z = inZ; } void Set (const float* array) { x = array[0]; y = array[1]; z = array[2]; } float* GetPtr () { return &x; } const float* GetPtr ()const { return &x; } //float& operator[] (int i) { DebugAssertIf (i < 0 || i > 2); return (&x)[i]; } //const float& operator[] (int i)const { DebugAssertIf (i < 0 || i > 2); return (&x)[i]; } //bool operator == (const Vector3f& v)const { return FLOAT_IS_ZERO(x-v.x) && FLOAT_IS_ZERO(y-v.y) && FLOAT_IS_ZERO(z-v.z); } //bool operator != (const Vector3f& v)const { return !FLOAT_IS_ZERO(x-v.x) || !FLOAT_IS_ZERO(y-v.y) || !FLOAT_IS_ZERO(z-v.z); } Vector3f& operator += (const Vector3f& inV) { x += inV.x; y += inV.y; z += inV.z; return *this; } Vector3f& operator -= (const Vector3f& inV) { x -= inV.x; y -= inV.y; z -= inV.z; return *this; } Vector3f& operator *= (float s) { x *= s; y *= s; z *= s; return *this; } Vector3f& operator /= (float s); Vector3f operator - () const { return Vector3f (-x, -y, -z); } Vector3f& Scale (const Vector3f& inV) { x *= inV.x; y *= inV.y; z *= inV.z; return *this;} static const float epsilon; static const float infinity; static const Vector3f infinityVec; static const Vector3f zero; static const Vector3f one; static const Vector3f xAxis; static const Vector3f yAxis; static const Vector3f zAxis; static const Vector3f left; static const Vector3f right; }; inline Vector3f Scale(const Vector3f& lhs, const Vector3f& rhs) { return Vector3f(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z); }<file_sep>/RecastDemo/Include/math/Vector3f.cpp #include "math/Vector3f.h" #define FPFIXES 1 using namespace std; const float Vector3f::epsilon = 0.00001F; const float Vector3f::infinity = numeric_limits<float>::infinity (); const Vector3f Vector3f::infinityVec = Vector3f (numeric_limits<float>::infinity (), numeric_limits<float>::infinity (), numeric_limits<float>::infinity ()); const Vector3f Vector3f::zero = Vector3f (0, 0, 0); const Vector3f Vector3f::one = Vector3f (1.0F, 1.0F, 1.0F); const Vector3f Vector3f::xAxis = Vector3f (1, 0, 0); const Vector3f Vector3f::yAxis = Vector3f (0, 1, 0); const Vector3f Vector3f::zAxis = Vector3f (0, 0, 1); const Vector3f Vector3f::left = Vector3f (-1, 0, 0); const Vector3f Vector3f::right = Vector3f (1, 0, 0); #define k1OverSqrt2 float(0.7071067811865475244008443621048490) <file_sep>/RecastDemo/Source/BufferStream.cpp #include <stdlib.h> #include <stdio.h> #include <string.h> #include "BufferStream.h" BufferStream::BufferStream(char* buffer, int size) { _buffer = buffer; _size = size; _offset = 0; } int BufferStream::Read(void* output, int len) { if(_size - _offset < len) { return -1; } memcpy(output, _buffer + _offset, len); _offset += len; return len; } int BufferStream::Read(void* output, int size, int count) { if(_size - _offset < size * count) { return -1; } memcpy(output, _buffer + _offset, size * count); _offset += size * count; return count; } int BufferStream::GetSize() { return _size; } int BufferStream::GetRemainSize() { return _size - _offset; } int BufferStream::AdjustOffset(int delta) { _offset += delta; if (_offset < 0) { _offset = 0; } else if (_offset > _size) { _offset = _size; } return _offset; } <file_sep>/RecastDemo/Include/ImportScene.h #pragma once #include <string> #include "math/Public.h" #include "vector" #pragma pack(1) struct ImportShape { char szName[64]; //1箱子 2球体 3胶囊 4网格边界 unsigned char byType; uint32_t uClientUID; Vector3f vLocation; Quaternionf qRotate; Vector3f vScale; int iPenetrationCode; unsigned char byMaterialType; uint32_t uLayer; Vector3f vExtent; }; #pragma pack() struct ImportNode { std::string name; uint32_t uClientUID; Vector3f position; // zero (default) Quaternionf rotation; // identity (default) Vector3f scale; // identity (default) int iPenetrationCode; unsigned char byMaterialType; int meshIndex;// -1 default //Matrix4x4f meshTransform;// identity (default) int cameraIndex; int layerIndex; //array<ImportNode> children; // unused // instantiatedLodMeshes.size() is: // 0 - when ImportNode doesn't have meshes // 1 - when ImportNode has a mesh which doesn't have to be split (then instantiatedLodMeshes[0].gameObject is the same as instantiatedGameObject) // N - when ImportNode has a mesh which has to be split (then instantiatedLodMeshes[i].gameObject is a child of instantiatedGameObject) //mutable array<InstantiatedMesh> instantiatedLodMeshes; // unused ImportNode() : cameraIndex(-1), layerIndex(-1) { position = Vector3f::zero; rotation = Quaternionf::identity(); scale = Vector3f::one; meshIndex = -1; byMaterialType = 0; } }; struct ImportMesh { std::vector<Vector3f> vertices; // Before mesh is split across seams, these arrays are per polygon vertex! // That is their size == polygons.size std::vector<Vector3f> normals; std::vector<Vector4f> tangents; std::vector<int> smoothingGroups; // Index buffer, potentially arbitrary number of indices per polygon std::vector<uint32_t> polygons; // Per-polygon arrays. std::vector<uint32_t> polygonSizes; // Size of each polygon std::vector<int> materials; // Material index of each polygon std::string name; bool hasAnyQuads; bool isConvex; ImportMesh() : hasAnyQuads(false), isConvex(false) { } // src argument is optional void Reserve (int vertexCount, int faceCount, const ImportMesh* src); unsigned AdviseVertexFormat () const; }; // reference: PxHeightFieldSample struct ImportHeightFieldSample { int16_t height; uint8_t isHole; }; struct ImportHeightField { int iInstanceID; // reference: PxHeightFieldDesc uint32_t nbRows; uint32_t nbColumns; std::vector<ImportHeightFieldSample> samples; float thickness; float convexEdgeThreshold; uint16_t flags; // reference: PxHeightFieldGeom float heightScale; float rowScale; float columnScale; uint8_t heightFieldFlags; // transform Vector3f position; }; struct ImportScene { //形状 std::vector<ImportShape> shapes; //节点 std::vector<ImportNode> nodes; //网格 std::vector<ImportMesh> meshes; //高度域 std::vector<ImportHeightField> heightFields; }; <file_sep>/RecastDemo/Include/math/Quaternion.h #ifndef QUATERNION_H #define QUATERNION_H #include "math/Vector3f.h" //#include "cppcore/math/FloatConversion.h" #include <algorithm> #include <vector> class Quaternionf { public: float x, y, z, w; Quaternionf () { *this = identity(); } Quaternionf (float inX, float inY, float inZ, float inW); explicit Quaternionf (const float* array) { x = array[0]; y = array[1]; z = array[2]; w = array[3]; } // methods const float* GetPtr ()const { return &x; } float* GetPtr () { return &x; } const float& operator [] (int i)const { return GetPtr ()[i]; } float& operator [] (int i) { return GetPtr ()[i]; } void Set (const float* array) { x = array[0]; y = array[1]; z = array[2]; w = array[3]; } Quaternionf& operator += (const Quaternionf& aQuat); Quaternionf& operator -= (const Quaternionf& aQuat); Quaternionf& operator *= (const float aScalar); Quaternionf& operator *= (const Quaternionf& aQuat); friend Quaternionf operator + (const Quaternionf& lhs, const Quaternionf& rhs) { Quaternionf q (lhs); return q += rhs; } friend Quaternionf operator - (const Quaternionf& lhs, const Quaternionf& rhs) { Quaternionf t (lhs); return t -= rhs; } Quaternionf operator - () const { return Quaternionf(-x, -y, -z, -w); } Quaternionf operator * (const float s) const { return Quaternionf (x*s, y*s, z*s, w*s); } friend Quaternionf operator * (const float s, const Quaternionf& q) { Quaternionf t (q); return t *= s; } inline friend Quaternionf operator * (const Quaternionf& lhs, const Quaternionf& rhs) { return Quaternionf ( lhs.w*rhs.x + lhs.x*rhs.w + lhs.y*rhs.z - lhs.z*rhs.y, lhs.w*rhs.y + lhs.y*rhs.w + lhs.z*rhs.x - lhs.x*rhs.z, lhs.w*rhs.z + lhs.z*rhs.w + lhs.x*rhs.y - lhs.y*rhs.x, lhs.w*rhs.w - lhs.x*rhs.x - lhs.y*rhs.y - lhs.z*rhs.z); } static Quaternionf identity () { return Quaternionf (0.0F, 0.0F, 0.0F, 1.0F); } }; inline Quaternionf::Quaternionf(float inX, float inY, float inZ, float inW) { x = inX; y = inY; z = inZ; w = inW; } inline Quaternionf& Quaternionf::operator+= (const Quaternionf& aQuat) { x += aQuat.x; y += aQuat.y; z += aQuat.z; w += aQuat.w; return *this; } inline Quaternionf& Quaternionf::operator-= (const Quaternionf& aQuat) { x -= aQuat.x; y -= aQuat.y; z -= aQuat.z; w -= aQuat.w; return *this; } inline Quaternionf& Quaternionf::operator *= (float aScalar) { x *= aScalar; y *= aScalar; z *= aScalar; w *= aScalar; return *this; } inline Quaternionf& Quaternionf::operator *= (const Quaternionf& rhs) { float tempx = w * rhs.x + x * rhs.w + y * rhs.z - z * rhs.y; float tempy = w * rhs.y + y * rhs.w + z * rhs.x - x * rhs.z; float tempz = w * rhs.z + z * rhs.w + x * rhs.y - y * rhs.x; float tempw = w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z; x = tempx; y = tempy; z = tempz; w = tempw; return *this; } inline Vector3f RotateVectorByQuat(const Quaternionf& lhs, const Vector3f& rhs) { // Matrix3x3f m; // QuaternionToMatrix (lhs, &m); // Vector3f restest = m.MultiplyVector3 (rhs); float x = lhs.x * 2.0F; float y = lhs.y * 2.0F; float z = lhs.z * 2.0F; float xx = lhs.x * x; float yy = lhs.y * y; float zz = lhs.z * z; float xy = lhs.x * y; float xz = lhs.x * z; float yz = lhs.y * z; float wx = lhs.w * x; float wy = lhs.w * y; float wz = lhs.w * z; Vector3f res; res.x = (1.0f - (yy + zz)) * rhs.x + (xy - wz) * rhs.y + (xz + wy) * rhs.z; res.y = (xy + wz) * rhs.x + (1.0f - (xx + zz)) * rhs.y + (yz - wx) * rhs.z; res.z = (xz - wy) * rhs.x + (yz + wx) * rhs.y + (1.0f - (xx + yy)) * rhs.z; // AssertIf (!CompareApproximately (restest, res)); return res; } #endif <file_sep>/RecastDemo/Include/math/Public.h #pragma once #include "math/Quaternion.h" #include "math/Vector3f.h" #include "math/Vector4f.h" <file_sep>/RecastDemo/Include/BufferStream.h #pragma once class BufferStream { public: BufferStream(char* buffer, int size); int Read(void* output, int len); int Read(void* output, int size, int count); int GetSize(); int GetRemainSize(); int AdjustOffset(int delta); private: char* _buffer; int _size; int _offset; };
5abc5a5b4d6c72b33bd28543da802daf2123e7ba
[ "C", "C++" ]
9
C++
suyangman/recast
7028c09638b2086b40a90a6cc9620009a455f6b3
484687784b01f658498e28d899353b87af726bab
refs/heads/master
<repo_name>RyanFu/ccq<file_sep>/chachuqu/ccq/src/main/java/com/coldmn3/ccq/Intents.java /* CCQ Android Client Copyright (c) 2013 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.coldmn3.ccq; /** * Intent帮助类 * * @version 1.0 * @author: session * @date:2013-9-5 上午9:41 */ public class Intents { /** * 创建的所以Intent的前缀 */ public static final String INTENT_PREFIX = "com.coldmn3.ccq."; /** * Intent中所以extra data的前缀 */ public static final String INTENT_EXTRA_PREFIX = INTENT_PREFIX + "extra."; } <file_sep>/chachuqu/young/src/main/java/com/coldmn3/young/dagger/DaggerFragmentActivity.java package com.coldmn3.young.dagger; import android.os.Bundle; import android.support.v4.app.FragmentActivity; /** * Base class for injectable fragment activities. */ public abstract class DaggerFragmentActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getInjector().inject(this); } protected Injector getInjector() { return (Injector) getApplication(); } } <file_sep>/chachuqu/ccq/src/main/java/com/coldmn3/ccq/ui/topiclist/TopicListAdapter.java /* CCQ Android Client Copyright (c) 2013 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.coldmn3.ccq.ui.topiclist; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.coldmn3.young.android.YBaseAdapter; import java.util.List; /** * 一句话功能简述<br> * 功能详细描述 * * @version 1.0 * @author: session * @date:2013-9-16 下午5:27 */ public class TopicListAdapter extends YBaseAdapter { private List<TopicListEntity> mData; public final class ViewHolder { public TextView subject; } public TopicListAdapter(Context context, List<TopicListEntity> data) { super(context); this.mData = data; } @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { return convertView; } } <file_sep>/chachuqu/young/src/main/java/com/coldmn3/young/dagger/Injector.java package com.coldmn3.young.dagger; /** * Interface defining a dependency injector. */ public interface Injector { void inject(Object object); } <file_sep>/chachuqu/ccq/src/main/java/com/coldmn3/ccq/SplashActivity.java package com.coldmn3.ccq; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.Toast; import com.coldmn3.ccq.ui.login.LoginActivity; import com.coldmn3.young.utils.ULog; import com.umeng.update.UmengUpdateAgent; import com.umeng.update.UmengUpdateListener; import com.umeng.update.UpdateResponse; public class SplashActivity extends CCQBaseActivity { RefreshListView listView; private String[] adapterData; private ImageView refresh; AnimationDrawable anim; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); refresh = (ImageView) findViewById(R.id.imageView); refresh.setBackgroundResource(R.drawable.refresh_list_header_progress); anim = (AnimationDrawable) refresh.getBackground(); refresh.post(new Runnable() { @Override public void run() { anim.start(); } }); ULog.error("ULOG!@!@"); adapterData = new String[] { "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island" }; listView = (RefreshListView) findViewById(R.id.infomation_tab_list); listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, adapterData)); } public void checkNew(View view) { // 如果想程序启动时自动检查是否需要更新, 把下面两行代码加在Activity 的onCreate()函数里。 com.umeng.common.Log.LOG = true; UmengUpdateAgent.setUpdateOnlyWifi(false); // 目前我们默认在Wi-Fi接入情况下才进行自动提醒。如需要在其他网络环境下进行更新自动提醒,则请添加该行代码 UmengUpdateAgent.setUpdateAutoPopup(false); UmengUpdateAgent.setUpdateListener(updateListener); UmengUpdateAgent.update(this); startActivity(new Intent(this, LoginActivity.class)); } UmengUpdateListener updateListener = new UmengUpdateListener() { @Override public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) { switch (updateStatus) { case 0: // has update Log.i("--->", "callback result"); UmengUpdateAgent.showUpdateDialog(SplashActivity.this, updateInfo); break; case 1: // has no update Toast.makeText(SplashActivity.this, "没有更新", Toast.LENGTH_SHORT) .show(); break; case 2: // none wifi Toast.makeText(SplashActivity.this, "没有wifi连接, 只在wifi下更新", Toast.LENGTH_SHORT) .show(); break; case 3: // time out Toast.makeText(SplashActivity.this, "超时", Toast.LENGTH_SHORT) .show(); break; case 4: // is updating /*Toast.makeText(mContext, "正在下载更新...", Toast.LENGTH_SHORT) .show();*/ break; } } }; } <file_sep>/README.md ccq === Nga 艾泽拉斯国家地理大漩涡板块 Android客户端 <file_sep>/chachuqu/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.coldmn3.ccq</groupId> <artifactId>ccq-parent</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <name>CCQ Parent</name> <modules> <module>ccq</module> <module>young</module> <module>umeng</module> </modules> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>com.google.android</groupId> <artifactId>android</artifactId> <version>4.1.1.4</version> </dependency> <dependency> <groupId>com.squareup.dagger</groupId> <artifactId>dagger</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>com.squareup.dagger</groupId> <artifactId>dagger-compiler</artifactId> <version>1.1.0</version> <optional>true</optional> </dependency> <dependency> <groupId>com.google.android</groupId> <artifactId>support-v4</artifactId> <version>r18</version> </dependency> <dependency> <groupId>com.coldmn3.afinal</groupId> <artifactId>afinal</artifactId> <version>0.5</version> </dependency> </dependencies> </dependencyManagement> <build> <pluginManagement> <plugins> <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <version>3.6.1</version> <configuration> <sdk> <platform>16</platform> </sdk> <emulator> <avd>small</avd> <wait>10000</wait> <!--<options>-no-skin</options> --> </emulator> <zipalign> <verbose>true</verbose> </zipalign> <undeployBeforeDeploy>true</undeployBeforeDeploy> </configuration> <extensions>true</extensions> </plugin> </plugins> </pluginManagement> </build> </project> <file_sep>/chachuqu/young/src/main/java/com/coldmn3/young/android/YBaseActivity.java /* CCQ Android Client Copyright (c) 2013 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.coldmn3.young.android; import android.os.Bundle; import android.support.v4.app.FragmentActivity; /** * 一句话功能简述<br> * 功能详细描述 * * @version 1.0 * @author: session * @date:2013-9-4 下午4:34 */ public class YBaseActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 添加Activity到堆栈 AppManager.getAppManager().addActivity(this); } @Override protected void onDestroy() { super.onDestroy(); // 结束Activity&从堆栈中移除 AppManager.getAppManager().finishActivity(this); } } <file_sep>/chachuqu/ccq/src/main/java/com/coldmn3/ccq/CCQConstants.java package com.coldmn3.ccq; /** * 一句话功能简述<br> * 功能详细描述 * * @version 1.0 * @author: session * @date:2013-8-15 下午1:49 */ public class CCQConstants { public static final String LOGIN_URL = "http://account.178.com/q_account.php?_act=login"; public static final String SEGMENT_LOGIN_BODY = "type=username&email="; public static final String SEGMENT_LOGIN_BODY2 = "&password="; public static final String CHARSET_UTF8 = "UTF-8"; public static final String CHARSET_GBK = "GBK"; public static final String HOST_NGA = "bbs.ngacn.cc"; public static final String SEGMENT_THREAD = "/thread.php"; }
1dd45f61a647c562dbaf2fee73c55443be228e3b
[ "Markdown", "Java", "Maven POM" ]
9
Java
RyanFu/ccq
0f0e94aa64402fb76d2168284f1bd3dbfdc3dc59
ccc0cac51f8a4318e1abd05a5eeb3f899a47b9af
refs/heads/master
<file_sep># PHPCMSV9按年按月日期归档功能 PHPCMSV9在国内使用的人还是比较多的,也有一部分人当做博客使用,CMS做为blog使用也没问题,就是感觉少一个归档的功能,所以找时间写了一些。 功能:PHPCMSv9文章按年|按月归档 演示参考:www.linyufan.com > **效果图:** ![image](https://github.com/hamelong/PHPCMSV9_archives/blob/master/images/1.jpg) > **其他问题关注我的小程序即可:** ![image](https://github.com/hamelong/PHPCMSV9_archives/blob/master/images/MiniProgram.jpg) <file_sep> function archives_date(){ /** * 获取指定日期段内每个有 * @param $starttime 开始日期 * @param $starttime 结束日期 * @return Array */ function firstday_lastday($linyufan_date){ //本方法用于获取指定月份第1天和最后1天 //$linyufan_date 是时间戳格式 $today = date('Y-m-d',$linyufan_date); $firstday = date('Y-m-01', strtotime($today));//本月第一天 $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));//本月最后一天 $month_days_strtime = strtotime($firstday); $month_end_strtime = strtotime($lastday); //return $firstday_lastday = array($month_days_strtime,$month_end_strtime); return array($month_days_strtime,$month_end_strtime); } $linyufan_mysql_con = mysql_connect("localhost","",""); mysql_select_db(""); mysql_query("set names utf-8"); $starttime = strtotime('2012-01-01'); // 自动为00:00:00 时分秒 $endtime = strtotime(date('y-m-d',time())); $monarr = array(); while( ($starttime = strtotime('+1 month', $starttime)) <= $endtime){ $monarr[] = date('Y年m月',$starttime); // 取得递增月; $monarrs[] = strtotime(date('Y-m-d',$starttime)); // 判断年份用; rsort($monarr); rsort($monarrs); } //print_r($monarr); $month_count = count($monarr); //在列表页显示 for($month_counts=0;$month_counts<$month_count;$month_counts++){ //指定月份有没有数据 list($month_days_strtime,$month_end_strtime) = firstday_lastday($monarrs[$month_counts]); //函数使用方法 $linyufan_result = mysql_query("select * from v9_news where inputtime between '$month_days_strtime' and '$month_end_strtime' order by 'inputtime' DESC"); //输出所有月份 if(mysql_num_rows($linyufan_result)=='0'){ //没有数据的月份不用显示出来 }else{ $linyufan_date_list[] = $linyufan_years_style.'<li><a title="'.$monarr[$month_counts].'('.mysql_num_rows($linyufan_result).')" href="https://www.linyufan.com/archives-'.$monarrs[$month_counts].'.html">'.$monarr[$month_counts].'</a></li>'; $linyufan_months_substr = substr($monarr[$month_counts],7); if($linyufan_months_substr == '01月'){ $linyufan_years_style = intval(mb_substr($monarr[$month_counts],0,4,'utf-8'))-1; $linyufan_years_style = '<li style="width:92%;text-align: center;"><a style="width:100%;background:#338A9C;color:#fff;display:block;">'.$linyufan_years_style.'年</a></li>'; }else{$linyufan_years_style='';} } } return $linyufan_date_list; }
13f237c1d1bfc9e250f7aea53ad6755504030560
[ "Markdown", "PHP" ]
2
Markdown
hamelong/PHPCMSV9_archives
83b729b55da7884bb0a7c3795ed21bdec399c908
73c7ca963d6a1cdf55faa9fc299efd377fd0c9f6
refs/heads/master
<file_sep># CarND-Controls-PID Self-Driving Car Engineer Nanodegree Program --- # Overview This repository contains all the code needed to complete the PID control project in Udacity's Self-Driving Car Nanodegree. The original repository for this project is located at: [CarND-Controls-PID](https://github.com/udacity/CarND-Controls-PID) ### Attribution The infrastructure code in this project is supplied from project repository listed above. --- [//]: # (Image References) [image1]: ./writeup_images/Twiddle_overview.png "Twiddle Data" [image2]: ./writeup_images/twiddle_cycles.png "Tiddle changes" [image3]: ./writeup_images/oscillation.png "Oscillation" [image4]: ./writeup_images/pid_overview.png "PID Overview" [image5]: ./writeup_images/p_comp.png "P error view" [image6]: ./writeup_images/d_comp.png "D error view" [image7]: ./writeup_images/i_comp.png "I error view" ## Running the Code This project involves the Term 2 Simulator which can be downloaded [here](https://github.com/udacity/self-driving-car-sim/releases) This repository includes two files that can be used to set up and intall uWebSocketIO for either Linux or Mac systems. For windows you can use either Docker, VMware, or even Windows 10 Bash on Ubuntu to install uWebSocketIO. Once the install for uWebSocketIO is complete, the main program can be built and ran by doing the following from the project top directory. 1. mkdir build 2. cd build 3. cmake .. 4. make 5. ./pid ## Sucessful run With the settings chosen from a manual search of settings a starting default value of: ``` pid.Init(0.20, 0.001, 2.7); // order is P I D ``` The manual tuning was required to get a stable set of values such that using twiddle and it's adjustments were unlikely to run the car off the track. One big tool that is missing in this project is a way to reset the car to start so that the successive runs can encounter the same conditions. It's unclear that using twiddle on the live running car will converge or give useful data. I am running with short evaluation times of 200 data points. A longer time near the time of a full track loop may give good data without the need to reset the car to a common starting point. The car will complete any number of loops with a target speed of 25 mph. It will actually run successfully at 50mph, but I dropped the target speed to 25 to experiment with a twiddle search on parameters. The following is an overview of a longer twiddle search with about 17 laps and 120 twiddle 'cycles'. The way I'm defining a cycle in this case is a test of a parameter change. Since a twiddle loop includes an increment up and an increment down, it could have 2 cycles by this definition. The 17 laps can be seen by the i_err shape based on the shape of the track. ![alt text][image1] The p[3] and dp[3] parameters and their changes in the mentioned 120 twiddle cycles are presented below. There are 4 scales to get the data on the same graph. I won't be using the scales, only the trends and relative values. Note the parameter order here is PDI as used in the lessons. ``` p[0] = Kp; p[1] = Kd; p[2] = Ki; dp[0] = 0.02; dp[1] = 0.2; dp[2] = 0.0001; ``` Note that all 3 dp values have a downward trend. It is uncertain with this testing method that twiddle will converge, although the somewhat consistent downward trend of dp values suggests it will. ![alt text][image2] P2 still has an upward trend. P0 and P1 are somewhat stable near the initial manually searched. The downward trend of dp2 with the generally upward trend of p2 suggests a problem. This parameter is likely most succeptable to position on the track and the short testing cycle. It would probably benefit from a much longer evaluation time. (Or a consistent reset method.) The ossilation of steering value at time suggests that p1 could be significantly higher. My manual search did not do well much higher p1 values, although those tests were down with a target speed of 50 mph. The oscilations seen here some of the larger ones seen in my testing. There is a noticeable error problem shortly after the bridge and near the dirt entrance that seems to have a discontinous CTE value that almost always generates some degree of oscillation for my model. ![alt text][image3] ## Rubric ### Your code should compile. It does with the default procedure. ### The PID procedure follows what was taught in the lessons. It follows the PID procedure. ### Describe the effect each of the P, I, D components had in your implementation. Here is an overview of the components controlling the steering angle. Displayed are the p_error, d_error and i_error terms. Also displayed are the products of those terms and their p[0-2] values. For example p_error * p[0] is labeled as p_err_p0. ![alt text][image4] The graph is somewhat confusing, so I'll break it down starting with the p_error related components. In the image below, the p_err line is not visable as it is equal to cte, as can be seen in the boxed values. The p_err_p0 product can be seen as a scaled version of p_err as expected. ![alt text][image5] The d_err can be seen in the next plot as a derivitive(approximate) of the CTE. It is positive as the cte is increasing and negative as it is decreasing. This ends up reinforcing the P component when CTE is still increasing giving it a counter steer effect on the steering as D(CTE slope) goes negative. NOTE that the "spikiness" in the steering angle comes from the d_err component. The simple subtraction of the previous cte value does not produce a smooth function. Some additional prior values would not likely impede the intent of the D component and likely smooth it out. ![alt text][image6] As can be seen on any given steering adjustment the i_error and i_err_p2 product are not significantly affected. If you look at the overview data in one of the first graphs in this presentation, the values do reflect the shape of the track. The i_error component goes negative only in the section of the track where the car does a right turn. This does suggest the car simulation has a bias based on the direction it is turning. ![alt text][image7] ### Describe how the final hyperparameters were chosen. See above. The initial values were chosen by a manual search with input from the class lesson. The twiddle search values are still converging. ### The vehicle must successfully drive a lap around the track. It does. It also does even with the twiddle parameter search continueing. <file_sep>#include <cmath> #include <iostream> #include "PID.h" using namespace std; /* * TODO: Complete the PID class. */ PID::PID() {} PID::~PID() {} void PID::Init(double Kp, double Ki, double Kd) { p_error = 0.0; i_error = 0.0; d_error = 0.0; best_error = 1000000000000; total_error = 0.0; p[0] = Kp; p[1] = Kd; p[2] = Ki; dp[0] = 0.02; dp[1] = 0.2; dp[2] = 0.0001; // first twiddle twiddle_state = 0; p_index = 0; } void PID::NewRun() { total_error = 0.0; count = 0; d_error = 0.0; p_error = 0.0; i_error = 0.0; } void PID::EvalTwiddle() { // start twiddle switch (twiddle_state) { case 0: { p[p_index] += dp[p_index]; // do a run before next state twiddle_state = 1; NewRun(); return; } case 1: { if (total_error < best_error) { best_error = total_error; dp[p_index] *= 1.1; cout << "new p:\t" << p[0] << "\t" << p[1] << "\t" << p[2]; cout << "new dp:\t" << dp[0] << "\t" << dp[1] << "\t" << dp[2]; twiddle_state = 0; p_index++; p_index %= 3; NewRun(); return; } else { p[p_index] -= 2 * dp[p_index]; twiddle_state = 2; NewRun(); return; } } case 2: { if (total_error < best_error) { best_error = total_error; dp[p_index] *= 1.1; cout << "new p:\t" << p[0] << "\t" << p[1] << "\t" << p[2]; cout << "new dp:\t" << dp[0] << "\t" << dp[1] << "\t" << dp[2]; twiddle_state = 0; p_index++; p_index %= 3; NewRun(); return; } else { p[p_index] += dp[p_index]; dp[p_index] *= 0.9; twiddle_state = 0; p_index++; p_index %= 3; NewRun(); return; } } } cout << "unknown state\n"; exit(-1); } void PID::UpdateError(double cte) { d_error = cte - p_error; p_error = cte; i_error += cte; cout << "Count: " << count << endl; if (count == (settle_count + eval_count)) { EvalTwiddle(); } if (count > settle_count) { total_error += cte * cte; } count++; } double PID::TotalError() { return - p[0] * p_error - p[1] * d_error - p[2] * i_error; } double PID::SteerValue() { cout << "error:\t" << p_error << "\t" << d_error << "\t" << i_error << endl; cout << "dp values:\t" << dp[0] << "\t" << dp[1] << "\t" << dp[2] << endl; cout << "p values:\t" << p[0] << "\t" << p[1] << "\t" << p[2] << endl; cout << "error component:\t" << p[0] * p_error << "\t" << p[1] * d_error << "\t" << p[2] * i_error << endl; return - p[0] * p_error - p[1] * d_error - p[2] * i_error; } double PID::ThrottleValue() { return(0); }
afab8764c0a4c2a287fd70befc6d329b38276eec
[ "Markdown", "C++" ]
2
Markdown
chisolm/CarND-Controls-PID
bb866d2b5952ecf0ee2ed552cd8579d279c8b1f9
dd6b2436602bb27883f7812168b7aa03864cc545
refs/heads/main
<repo_name>KarboleW/ov65ufum<file_sep>/ov65ufum/function.py import numpy as np from ipywidgets import interact, fixed from PIL import Image import matplotlib.pyplot as plt def imshow(X, resize=None): """Plots an image of resized size if argument is given. Parameters ---------- X : numpy.array Image as numpy array.. resize : tuple, optional Resize size (width, height). Returns ------- PIL.Image Resized image as Pillow Image object. """ X = Image.fromarray(np.uint8(X)) if resize != None: X = X.resize(resize) plt.figure(), plt.imshow(X), plt.show() return X <file_sep>/README.md # ov65ufum containes DSSS files <file_sep>/setup.py from distutils.core import setup from setuptools import find_packages setup(name='ov65ufum', version='0.1', author='KarboleW', author_email='<EMAIL>', packages=find_packages(), install_requires=['numpy', 'Pillow', 'ipywidgets'])
5dc1c3d5e36ef1cc1716dc44c7c3d0f36674e1b0
[ "Markdown", "Python" ]
3
Python
KarboleW/ov65ufum
a9a231f1647f10d07740aa264b6505e51cf7a601
e9a9ace1e1bdcbff490ddadafdc2bd18dbc95ac2
refs/heads/master
<file_sep>var traverseDirectory = function traverseDirectory(dir, filelist) { var files = fs.readdirSync(dir); filelist = filelist || []; files.forEach(function(file) { if (fs.statSync(dir + file).isDirectory() && file.charAt(0) != '.') { filelist = traverseDirectory(dir + file + '/', filelist); } else if(file.charAt(0) != '.'){ filelist.push(dir + file); } }); return filelist; }; var configurationParser = function configurationParser(dataToParse){ dataToParse = dataToParse.replace(/\n/gm, ''); var commands = dataToParse.match(/\/\*:.+\*\//m); var moduleObject = (commands ? commands[0] : "").match(/@module-configuration:(.+)@end-module-configuration/m); var parsedData = JSON.parse(moduleObject ? moduleObject[1] : "{}"); if(parsedData){ return parsedData; } return false; } var harvestDirectory = function harvestDirectory(directory, harvester) { arrayOfFiles = traverseDirectory(directory); arrayOfTestFiles = []; arrayOfFiles.forEach(function (files) { if(harvester(files)){ arrayOfTestFiles.push(files); } }); return arrayOfTestFiles; } var fs = require("fs"); var arrayOfFiles, arrayOfTestFiles; ( module || {} ).exports.harvestDirectory = harvestDirectory; ( module || {} ).exports.configurationParser = configurationParser;
48fad0eacf82bf6e9885656a23b76383ac281099
[ "JavaScript" ]
1
JavaScript
webnified/harvest-directory
964063bb31af5e1849aa91e1d850ced341966c5d
ece7a435f6b4f6afb9a1353835b3b3265762a55e
refs/heads/master
<repo_name>stevenbeales/clinicaltrials-1<file_sep>/README.md clinicaltrials ============== Zephyr Health / Clinical Health To Do 2. change favicon<file_sep>/app/scripts/controllers/chart.js 'use strict'; var chartController = function($scope, $location, searchResults, ngTableParams){ // check if a search has been carried out, else redirect back to search if (searchResults.getTrials() === null){ $location.path('/search'); } else { var trials = searchResults.getTrials(); $scope.tableTrials = []; $scope.searchTerm = searchResults.getSearch(); $scope.showTable = false; // ************************************* set global options for the 2 charts here ************************************* // Highcharts.setOptions({ title: { text: 'source: clinicaltrial.gov' }, legend: { enabled: false } }); // ************************************* build StatusChart ************************************* // $scope.statusChartOptions = { chart: { type: 'bar', renderTo: 'statusChart' }, xAxis: { categories: [] }, yAxis: { title: { text: 'Trials' } }, series: [{ name: 'Clinical Trials', data: [] }] }; // populate categories for x-axis for (var status in trials){ $scope.statusChartOptions.xAxis.categories.push(status); $scope.statusChartOptions.series[0].data.push({ y: trials[status].trialcount, events:{ click: function(){ //invokes with an jquery event but we don't need it // things to clear the trial table if it's not empty $scope.showTable = false; $scope.tableTrials = []; $scope.selectedCategory = ''; $scope.selectedStatus = this.category; $scope.$apply(); $scope.buildCategoryChart(this.category); } } }); } $scope.statusChart = new Highcharts.Chart($scope.statusChartOptions); // ************************************* build category chart ************************************* // $scope.buildCategoryChart = function(status){ // status is a string $scope.categoryChartOptions = { chart: { type: 'bar', renderTo: 'categoryChart', }, xAxis: { categories: [] }, yAxis: { title: { text: 'Trials' } }, series: [{ name: 'Clinical Trials', data: [] }] }; // count how many categories there are and set height = 100 + #conditions*20 var conditions = 0; for (var category in trials[status].conditions){ conditions++; $scope.categoryChartOptions.xAxis.categories.push(category); $scope.categoryChartOptions.series[0].data.push({ y: trials[status].conditions[category].length, events: { click: function(){ $scope.selectedCategory = this.category; // ******************* trial table stuff ******************* // $scope.tableTrials = trials[status].conditions[this.category]; // go through each and parse the date into a usable number for (var i=0; i<$scope.tableTrials.length; i++){ $scope.tableTrials[i].last_changed[1] = Date.parse($scope.tableTrials[i].last_changed[0]); } $scope.sort = 'score'; $scope.showTable = true; $scope.$apply(); $('.trialTitle').tooltip({placement: 'top'}); // initialize bootstrap opt in for title hovering on each td } } }); } $scope.categoryChartOptions.chart.height = Math.max(100 + conditions*20, 200); $scope.categoryChart = new Highcharts.Chart($scope.categoryChartOptions); }; } // from else li9 }; angular.module('clinicaltrialsApp') .controller('chartCtrl', ['$scope', '$location','searchResults', chartController]); <file_sep>/app/views/search.html <div class="jumbotron"> <h3>Search for Clinical Studies</h3> <h4>results from clinicaltrials.gov</h4> <form role="form"> <div class="form-group"> <input id="searchBar" type="text" ng-model="searchTerm" placeholder="Search for..."/> </div> </form> <button id="searchButton" type="button" class="btn btn-default btn-lg" ng-click="search()">Search!</button> <p id='result' ng-show="searching">Searching for {{searchTerm}}</p> </div> <file_sep>/app/scripts/services/searchresults.js 'use strict'; var searchResults = function($rootScope){ /* trials structure is created when setTrials is called trials is an object, example: trials = { status1: { trialcount: number conditions: { condition1: [trialObj, trialObj, trialObj, ...], condition2: [], ... } }, status2: { trialcount: number conditions: { condition1: [trialObj, trialObj, trialObj, ...], condition2: [], ... } }, ... } trialObj have keys (all arrays) condition_summary: [string], last_changed: [string], nct_id: [string], order: [string], score: [string], title: [string], urlstring: [string], status: [{$:object, _:string}] */ var trials = {}; var search = ''; // public api return { getTrials: function(){ if ($.isEmptyObject(trials)){ return null; } else { return trials; } }, setTrials: function(inputArray){ // array of trialObj trials = {}; for (var i=0; i<inputArray.length; i++){ var status = inputArray[i].status[0]._; var conditions = inputArray[i].condition_summary[0].split('; '); // array of strings // check if the status is already in trials, if not, create it if (!trials[status]){ trials[status] = {trialcount: 0, conditions: {}}; } trials[status].trialcount++; for (var j=0; j<conditions.length; j++){ if(!trials[status].conditions[conditions[j]]){ trials[status].conditions[conditions[j]] = []; } trials[status].conditions[conditions[j]].push(inputArray[i]); } } console.log('Finished building trial structure'); $rootScope.$broadcast('dataReady'); }, getSearch: function(){ return search; }, setSearch: function(str){ search = str; } }; }; angular.module('clinicaltrialsApp') .factory('searchResults', ['$rootScope', searchResults]);
8d56c839685fb6fe9f4ca691d167f989e1777fb2
[ "Markdown", "JavaScript", "HTML" ]
4
Markdown
stevenbeales/clinicaltrials-1
ca29346a6d28d9f2e52e715619bb37b384324e2c
9a54d9e79aaf9cb6a85c371d20e911d95d4d3037
refs/heads/master
<file_sep>namespace RandomSquares.Modules { public class VirtualScreenRow { private VirtualScreenCell[] _cells; private int _screenWidth; public VirtualScreenRow(int screenWidth) { } public void AddBoxTopRow(int boxX, int boxWidth) { } public void AddBoxBottomRow(int boxX, int boxWidth) { } public void AddBoxMiddleRow(int boxX, int boxWidth) { } public void Show() { } } }<file_sep>class Supershape { constructor( steps=10000, n1 = (Math.random() * 20) + 5, n2 = (Math.random() * 20) + 5, n3 = (Math.random() * 20) + 10, m1 = (Math.random() * 20) + 20, m2 = (Math.random() * 20) + 20, a = (Math.random() * 10) , b = (Math.random() * 10) , factor = 3) { this.range = [...Array(steps).keys()].map(i => i*2*Math.PI*factor / (steps - 1)); this.parameters = { drawSteps: steps, n1: n1, n2: n2, n3: n3, m1: m1, m2: m2, a: a, b: b, factorPI: factor }; this.points = { x: [], y: [] }; } map(offsetX, offsetY, scale) { for (let i of this.range) { const r = this.calculate(i); this.points.x.push((r * Math.cos(i)) * scale + offsetX); this.points.y.push((r * Math.sin(i)) * scale + offsetY); } } showParams() { console.table(this.parameters); } newShape(offsetX = 0, offsetY = 0, scale = 1, canvas = false) { if (canvas) { canvas.wipe(); } this.points = { x: [], y: [] } this.parameters = { steps:10000, n1: (Math.random() * 20) + 5, n2: (Math.random() * 20) + 5, n3: (Math.random() * 20) + 10, m1: (Math.random() * 20) + 20, m2: (Math.random() * 20) + 20, a: (Math.random() * 10), b: (Math.random() * 10), factor: (Math.random() * 5) + 3 } this.map(offsetX, offsetY, scale); } calculate(theta) { //const part1 = Math.abs((Math.cos((this.parameters.m1 * theta) / 4)) / 4) ^ this.parameters.n2; //const part2 = Math.abs((Math.sin((this.parameters.m2 * theta) / 4)) / 4) ^ this.parameters.n3; //const r = (part1 + part2) ^ (-1 / this.parameters.n1); let part1 = (1 / this.parameters.a) * Math.cos(theta * this.parameters.m1 / 4); part1 = Math.abs(part1); part1 = Math.pow(part1, this.parameters.n2); let part2 = (1 / this.parameters.b) * Math.sin(theta * this.parameters.m2 / 4); part2 = Math.abs(part2); part2 = Math.pow(part2, this.parameters.n3); let part3 = Math.pow(part1 + part2, -1 / this.parameters.n1); const r = 1 / part3; return r; //{ //x: r * Math.cos(theta), //y: r * Math.sin(theta) //}; } } class Painter { constructor(canvasId) { this.canvas = document.getElementById(canvasId); this.ctx = this.canvas.getContext("2d"); this.width = this.canvas.width; this.height = this.canvas.height; this.color = "#FFFFFF"; } setColor(color = false) { if (color) { this.ctx.strokeStyle = color; } else { this.ctx.strokeStyle = this.color; } } line(from, to) { if (typeof (from) != "object" || typeof (to) != "object") { throw "From / To, needs to be in object form with {x: 'X-coordinate', y: 'Y-coordiante'}" } if (!from.x || !from.y || !to.x || !to.y) throw "Both objects must contain x and y values with x and y keys. {x: 'X-coordinate', y: 'Y-coordiante'}" this.ctx.moveTo(from.x, from.y); this.ctx.lineTo(to.x, to.y); } drawArc(from, to, rotation = false) { this.ctx.beginPath(); let radius = Math.abs(((to - from) / 2)); let center = (from < to) ? (from + radius) : (from - radius); this.ctx.arc(center, 300, radius, 0, Math.PI, rotation); this.ctx.stroke(); } drawShape(xy) { console.log('draw'); //console.log(xy); this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.ctx.beginPath(); for (let index = 0; index < xy.x.length; index++) { const x = xy.x[index]; const y = xy.y[index]; this.ctx.lineTo(x, y); } this.ctx.stroke(); } wipe() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.ctx.beginPath(); } pixelMap(dataset) { const imgData = new Uint8ClampedArray(this.width * this.height * 4); if (dataset.length === imgData.lenght) { // RGBA for (let i = 0; i < imgData.length; i += 4) { imgData[i + 0] = dataset[i + 0]; // R imgData[i + 1] = dataset[i + 1]; // G imgData[i + 2] = dataset[i + 2]; // B imgData[i + 3] = dataset[i + 3]; // A index++; } } else { // GREYSCALE let index = 0; for (let i = 0; i < imgData.length; i += 4) { imgData[i + 0] = dataset[index]; imgData[i + 1] = dataset[index]; imgData[i + 2] = dataset[index]; imgData[i + 3] = 255; index++; } } let image = new ImageData(imgData, this.width); this.ctx.putImageData(image, 0, 0); } }<file_sep>namespace RandomSquares.Modules { public class VirtualScreen { private VirtualScreenRow[] _rows; public VirtualScreen(int width, int height) { } public void Add(Box box) { } public void Show() { } } }<file_sep>using System; namespace RandomSquares.Modules { public class Box { public int X { get; private set; } public int Y { get; private set; } public int Width { get; private set; } public int Height { get; private set; } private int _minimumSize = 3; public Box(Random random, int maxX, int maxY) { } public Box(int x, int y, int width, int height) { } public int GetTopRowY() { } public int GetBottomRowY() { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using TrePaaRad.Modules; namespace TrePaaRad { class Program { private static readonly Random _rng = new Random(); private static BoardModel _brett; private static BoardView _visning; public static Dictionary<char, int> translate = new Dictionary<char, int>() { {'a', 0}, {'b', 1}, {'c', 2} }; static void Main(string[] args) { _brett = new BoardModel(); _visning = new BoardView(_brett); var finished = false; bool ai; Tuple<bool, char> result = new Tuple<bool, char>(false, ' '); Console.WriteLine("Play against the computer? (Y/N):"); while (true) { var userSelect = Console.ReadLine(); if (userSelect == "y" || userSelect == "Y") { ai = true; break; } if (userSelect == "n" || userSelect == "N") { ai = false; break; } } _visning.Show(); while (!finished) { var selectX = false; var selectY = false; while (!selectX) { if (!AddChar('x')) continue; result = IsGameOver(_brett); finished = result.Item1; _visning.Show(); selectX = true; } while (!selectY) { if (!ai) { if (!AddChar('o')) continue; result = IsGameOver(_brett); finished = result.Item1; _visning.Show(); selectY = true; } else { selectY = SetRandomO(); result = IsGameOver(_brett); finished = result.Item1; _visning.Show(); } } } Console.WriteLine($"Game over! Winner is: {result.Item2}"); } public static Tuple<bool, char> IsGameOver(BoardModel board) { var result = false; var player = ' '; Tuple<int, int>[][] indexes = { new Tuple<int, int>[] { new Tuple<int, int>(0, 0), new Tuple<int, int>(0, 1), new Tuple<int, int>(0, 2) }, new Tuple<int, int>[] { new Tuple<int, int>(1, 0), new Tuple<int, int>(1, 1), new Tuple<int, int>(1, 2) }, new Tuple<int, int>[] { new Tuple<int, int>(2, 0), new Tuple<int, int>(2, 1), new Tuple<int, int>(2, 2) }, new Tuple<int, int>[] { new Tuple<int, int>(0, 0), new Tuple<int, int>(1, 0), new Tuple<int, int>(2, 0) }, new Tuple<int, int>[] { new Tuple<int, int>(0, 1), new Tuple<int, int>(1, 1), new Tuple<int, int>(2, 1) }, new Tuple<int, int>[] { new Tuple<int, int>(0, 2), new Tuple<int, int>(1, 2), new Tuple<int, int>(2, 2) }, new Tuple<int, int>[] { new Tuple<int, int>(0, 0), new Tuple<int, int>(1, 1), new Tuple<int, int>(2, 2) }, new Tuple<int, int>[] { new Tuple<int, int>(0, 2), new Tuple<int, int>(1, 1), new Tuple<int, int>(2, 0) } }; foreach (var sequence in indexes) { var line = sequence.Aggregate("", (current, step) => current + _brett.board[step.Item1][step.Item2]); if (line != "xxx" && line != "ooo") continue; result = true; player = Convert.ToChar(line.Substring(0, 1)); break; } return new Tuple<bool, char>(result, player); } public static bool AddChar(char player) { Console.WriteLine($"Enter coordinates for '{player}' (row, column)"); var rawInput = Console.ReadLine()?.Split(' '); if (rawInput != null && rawInput.Length < 2) return false; if (!Int16.TryParse(rawInput[0], out var row)) return false; if (row > 2 || row < 0) return false; if (!Char.TryParse(rawInput[1], out var ch)) return false; if (!translate.TryGetValue(ch, out var col)) return false; if (player == 'x') { if (AddX(row, col)) return true; } else { if (AddO(row, col)) return true; } return false; } public static bool AddX(int r, int c) { if (IsOccupied(r, c)) return false; Console.WriteLine($"Setting {r} {c} to X"); _brett.board[r][c] = "x"; return true; } public static bool AddO(int r, int c) { if (IsOccupied(r, c)) return false; Console.WriteLine($"Setting {r} {c} to O"); _brett.board[r][c] = "o"; return true; } public static bool IsOccupied(int r, int c) { switch (_brett.board[r][c]) { case "x": case "o": return true; default: return false; } } public static bool SetRandomO() { var r = _rng.Next(3); var c = _rng.Next(3); while (true) { if (AddO(r, c)) return true; } } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace wordpuzzle { class Program { public static string filename = @"I:\GET\source\repos\AlmostGETit\C#\wordpuzzle\ordbank_bm\fullform_bm.txt"; private static readonly Random _Rnd = new Random(); public static string[] output; static void Main(string[] args) { string[] lines = ReadFile(filename); string[] words = parseWords(lines); List<string> validWords = new List<string>(); foreach (var V in words) { if (IsValid(V)) { validWords.Add(V); } } output = validWords.ToArray(); string randomWord = RandomWord(1, output)[0]; string pattern = randomWord.Substring(0, 3); int stop = 0; string returnWord = "null"; for (int i = 0; i < 3; i++) { if (SearchWord(pattern.Substring(0, (3 + i)), output)) { stop = i; returnWord = randomWord; Console.WriteLine("break"); break; } } Console.WriteLine("Found a match {0}, {1}, {2}", pattern, returnWord, randomWord); } static bool SearchWord(string pattern, string[] words) { foreach (var w in words) { if (MatchPattern(pattern, w)) return true; } return false; } static bool MatchPattern(string pattern, string word) { return (pattern == word.Substring(0, pattern.Length)); } static string[] RandomWord(int numbers, string[] words) { List<string> randomOutput = new List<string>(); for (int i = 0; i < numbers; i++) { int number = _Rnd.Next(words.Length); randomOutput.Add(words[number]); output = output.Where(val => val != words[number]).ToArray(); } return randomOutput.ToArray(); } static string[] ReadFile(string filename) { string[] rawText = System.IO.File.ReadAllLines(filename); return rawText; } static bool IsValid(string word) { if (word.Length > 10 || word.Length < 7) return false; if (word.Contains('-')) return false; return true; } static string[] parseWords(string[] lines) { List<string> uniqueWords = new List<string>(); bool firstWord = true; string lastWord = null; foreach (var line in lines) { string[] words = line.Split('\t'); if (words.Length != 6) continue; string word = words[1]; if (firstWord) { lastWord = word; uniqueWords.Add(word); firstWord = false; } else { if (word != lastWord) uniqueWords.Add(word); lastWord = word; } } return uniqueWords.ToArray(); } } } <file_sep>using System; namespace ConsoleApp2 { class Program { static readonly Random rand = new Random(); static void Main(string[] args) { if (!IsValid(args)) { Help(); return; } var letters = args[1]; var value = int.Parse(args[0]); var pass = ReturnPass(letters, value); Console.WriteLine(pass); } public static bool IsValid(string[] args) { switch (args.Length) { case 2 when int.TryParse(args[0], out int val): // Val is now int return true; default: return false; } } public static string GetRandomType(string input, char inType='0') { string outVar = ""; char type = (inType == '0') ? input[rand.Next(input.Length)] : inType; switch (type) { case 's': outVar += GetRandomSpecial(); break; case 'L': outVar += char.ToUpper(GetRandomChar()); break; case 'l': outVar += GetRandomChar(); break; case 'd': outVar += GetRandomInt(); break; default: Console.WriteLine("Parse Error"); Help(); outVar = null; break; //return outVar; } return outVar; } public static string ReturnPass(string input, int numberOfLetters) { var outVar = ""; foreach (char c in input) { outVar += GetRandomType(input, c); } for (var i = 0; i < numberOfLetters-input.Length; i++) { outVar += GetRandomType(input); } return outVar; } public static char GetRandomSpecial() { string sp = "!/\"#¤%&/(){}[]"; return sp[rand.Next(sp.Length)]; } public static char GetRandomChar() { var ch = (char) ('a' + rand.Next(0, 25)); return ch; } public static int GetRandomInt() { return rand.Next(0, 9); } public static bool IsValid(string arguments) { return true; } static void Help() { Console.WriteLine("Password Generator"); Console.WriteLine(" Options:"); Console.WriteLine(" - l = lower case letter"); Console.WriteLine(" - L = upper case letter"); Console.WriteLine(" - d = digit"); Console.WriteLine(" - s = special character (!/\"#¤%&/(){}[]"); Console.WriteLine("Example: PasswordGenerator 14 lLssdd"); Console.WriteLine(" Min. 1 lower case"); Console.WriteLine(" Min. 1 upper case"); Console.WriteLine(" Min. 2 special characters"); Console.WriteLine(" Min. 2 digits"); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { // Fields (Semi-Global Variables) static void Main(string[] args) { var range = 250; var counts = new int[range]; var percentages = new double[range]; var text = "something"; while (!string.IsNullOrWhiteSpace(text)) { text = Console.ReadLine(); foreach (var character in text.ToUpper() ?? string.Empty) { counts[(int)character]++; } var sum = counts.Sum(); var percentageFactor = Convert.ToDouble(sum); for (var i = 0; i < counts.Length; i++) { double percent = counts[i] / percentageFactor * 100; percentages[i] = percent; } for (var i = 0; i < range; i++) { if (counts[i] <= 0) continue; var character = (char)i; Console.WriteLine(character + " - " + String.Format("{0, 10}", Math.Round(percentages[i], 2)) + '%'); } } Console.WriteLine("Number of input parameters: " + args.Length); Console.WriteLine("All the numbers in the arguments sum to: " + SumArgs(args)); } static int SumArgs(IReadOnlyList<string> arguments) { var sum = 0; for (var i = 0; i < arguments.Count; i++) { var parameterNo = i + 1; Console.WriteLine("Parameter " + parameterNo + ": " + arguments[i]); if (int.TryParse(arguments[i], out var number)) { sum = sum + number; } } return sum; } } } <file_sep>using System; namespace TrePaaRad.Modules { public class BoardView { private BoardModel _board; public BoardView(BoardModel board) { _board = board; } public void Show() { Console.WriteLine(" a b c"); Console.WriteLine(" -------------"); Console.WriteLine("0 | " + _board.board[0][0] + " | " + _board.board[0][1] + " | " + _board.board[0][2] + " |"); Console.WriteLine("1 | " + _board.board[1][0] + " | " + _board.board[1][1] + " | " + _board.board[1][2] + " |"); Console.WriteLine("2 | " + _board.board[2][0] + " | " + _board.board[2][1] + " | " + _board.board[2][2] + " |"); Console.WriteLine(" -------------"); } } }<file_sep>using System.Dynamic; using System.Runtime.CompilerServices; namespace RandomSquares.Modules { public class VirtualScreenCell { public bool Up { get; private set; } public bool Down { get; private set; } public bool Left { get; private set; } public bool Right { get; private set; } public char GetCharacter() { } public void AddHorizontal() { } public void AddVertical() { } public void AddLowerLeftCorner() { } public void AddUpperLeftCorner() { } public void AddUpperRightCorner() { } public void AddLowerRightCorner() { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpClasses { class Program { static void Main(string[] args) { Car[] cars = { new Car(), new Car("Mazda", "6", 2005), new Car("Volkswagen", "Golf 5k", 2010), }; foreach (var car in cars) { car.WhatAmI(); } } } } internal class Car { private readonly int _age; private readonly string _model; private readonly string _make; public Car() { _age = 0; _model = "N/A"; _make = "N/A"; } public Car(string make, string model, int age) { this._make = make; this._model = model; this._age = age; } public void WhatAmI() { Console.WriteLine("Make: {0}\nModel: {1}\nModel Year: {2}",this._make, this._model, this._age); } }<file_sep>using System; using System.Linq; namespace PassordGenerator { class Program { public static string Pattern; public static int NumInt; public static char[] ValidChars = {'l', 'L', 's', 'd'}; private static readonly Random _rand = new Random(); static void Main(string[] args) { if (!IsValid(args)) { ShowHelpText(); return; } ParseArgs(args); } public static void ParseArgs(string[] args) { var pass = ""; foreach (char letter in Pattern) { Console.WriteLine(letter); switch (letter) { case 'l': pass += WriteRandomLowerCaseLetter(); break; case 'L': pass += WriteRandomUpperCaseLetter(); break; case 's': pass += WriteRandomSpecialCharacter(); break; case 'd': pass += WriteRandomDigit(); break; default: ShowHelpText(); break; } } for (var i = 0; i < (NumInt - Pattern.Length); i++) { pass += WriteRandomLowerCaseLetter(); } Console.WriteLine(pass); } public static bool IsValid(string[] args) { if (args.Length == 0 || args.Length == 1) return false; if (int.TryParse(args[0], out var val)) { NumInt = val; } else { return false; } foreach (var c in args[1]) { if (!ValidChars.Contains(c)) { return false; } } Pattern = args[1]; if (Pattern.Length > NumInt) return false; return true; } public static char WriteRandomLowerCaseLetter() { return (char)('a' + _rand.Next(26)); } public static char WriteRandomUpperCaseLetter() { return char.ToUpper(WriteRandomLowerCaseLetter()); } public static int WriteRandomDigit() { return _rand.Next(10); } public static char WriteRandomSpecialCharacter() { var s = "!\"#¤%&/(){}[]"; return (char)s[_rand.Next(s.Length)]; } public static void ShowHelpText() { var lineWidth = 80; var tab = new String(' ', 4); var edgeL = "|" + tab; var edgeR = "|"; var line = new String('=', lineWidth); string[] helpString = { line, edgeL + "PasswordGenerator", edgeL + "Options:", edgeL + tab + "-l = lower case letter", edgeL + tab + "- L = upper case letter", edgeL + tab + "- d = digit", edgeL + tab + "- s = special character(!\"#¤%&/(){}[]", edgeL + "Example: PasswordGenerator 14 lLssdd", edgeL + tab + "Min. 1 lower case", edgeL + tab + "Min. 1 upper case", edgeL + tab + "Min. 2 special characters", edgeL + tab + "Min. 2 digits", edgeL + "Pattern must be same length og less than first argument", line }; foreach (var t in helpString) { Console.WriteLine(t + new String(' ', lineWidth - t.Length) + edgeR); } } } } <file_sep>using System; public class Vector2D { public Vector2D(double x, double y) { this.x = x; this.y = y; } public void Add(Vector2D vector) { this.x += vector.x; this.y += vector.y; } public void Mult(Vector2D vector) { } public void Dec(Vector2D vector) { } public void Dot(Vector2D vector) { } public void Cross(Vector2D vector) { } public void Scale(double scalar) { this.x *= scalar; this.y *= scalar; } public void Invert() { this.y = -this.y; this.x = -this.x; } public double Mag() { return Math.Sqrt(this.x^2 + this.y^2); } }
44e454dd81ad6c2921944e926e152978bc9ecf84
[ "JavaScript", "C#" ]
13
C#
Wisetorsk/AlmostGETit
cc3b6675a9387a1e1458daab40324a6ab4d2fbf9
158dc498bc1b574e1d53396737918a6e33cc404a
refs/heads/master
<repo_name>EVAKuznetsov/StarWarsDB<file_sep>/src/component/pages/login-page.js import React from 'react' const LoginPage = ({isLoggedIn,onLoggin,outLoggin})=>{ if(isLoggedIn){ return( <div className="jumbotron"> <p>You are logged</p> <button className="btn btn-danger" onClick={outLoggin} >Log Out </button> </div> ) }else{ return( <div className="jumbotron"> <p>Login to see secret page</p> <button className="btn btn-primary" onClick={onLoggin} >Log In </button> </div> ) } } export default LoginPage<file_sep>/src/component/hoc-helpers/with-swapi-service.js //компонент высшего порядка, вытаскивает из контекста функцию, переданную вместе с оборачеваемым компонентом import React from 'react' import {SwapiServiceContext} from '../swapi-service-context' const withSwapiService =(mapMethodsToProps)=>(Wrapper) =>{//эквивалентно записи withSwapiService =(mapMethodsToProps, Wrapper)=>{} return (props)=>{ return( <SwapiServiceContext.Consumer> {(swapiService)=>{ const serviceProps = mapMethodsToProps(swapiService) return <Wrapper {...props} {...serviceProps}/> } } </SwapiServiceContext.Consumer> ) } } export default withSwapiService<file_sep>/src/component/error-indicator/index.js import React from 'react' import './error-indicator.css' export default function ErrorIndicator(){ return( <div className="error-block"> <h4>Sorry!!!</h4> <span>Something went wrong...</span> <span>This problem will be fixed soon.</span> </div> ) }; <file_sep>/src/component/spiner/index.js import React from 'react' import './spiner.css' export default function Spiner(){ return( <div className="lds-css ng-scope"> <div className="lds-double-ring"> <div></div> <div></div> </div> </div> ) }<file_sep>/src/component/app/index.js import React,{Component} from 'react' import './app.css' import Header from '../header' import RandomPlanet from '../random-planet' // import {RandomPlanetDetails} from '../sw-component'; import {SwapiService,TestSwapiService} from '../../services' import { SwapiServiceContext } from '../swapi-service-context' import {PeoplePage,PlanetPage, StarshipPage,LoginPage,SecretPage} from '../pages' import {BrowserRouter as Router, Route, Switch, Redirect} from 'react-router-dom' import { StarshipDetails } from '../sw-component'; import {Record} from '../item-details' export default class App extends Component{ swapiService = new SwapiService() state = { showPlanet:true, swapiService:new SwapiService(), isLoggedIn:false } handleClickPlanet = () =>{ this.setState(({showPlanet})=>{ return {showPlanet:!showPlanet} }) } onChangeService=()=>{ this.setState(({swapiService})=>{ return { swapiService:swapiService instanceof SwapiService?new TestSwapiService():new SwapiService() } }) } onLoggin=()=>{ this.setState({isLoggedIn:true}) } outLoggin=()=>{ this.setState({isLoggedIn:false}) } render(){ const {isLoggedIn} = this.state; const randomPlanet = this.state.showPlanet? <RandomPlanet swapiService = {this.state.swapiService}/>:null; return( <SwapiServiceContext.Provider value={this.state.swapiService}>{/* ОБЯЗАТЕЛЬНО В КОНТЕКСТЕ ПЕРЕДАВАТЬ ИМЕННО value!!!!!!!!!!!!!!!!*/} <Router> <div className="container"> <Header onChangeService={this.onChangeService}/> {randomPlanet} <button className="btn btn-success btn-menu" onClick={this.handleClickPlanet}>toggle random planet</button> <Switch>{/*нужен для того, чтобы срабатывал только однин внутренний route, как только один сработал, все остальные игнорируются*/} <Route exact path="/" render={()=><h2>Welcome to StarDB</h2>} /> <Route path ="/people/:id?" component = {PeoplePage} />{/*/people/:id? такой синтаксис позволяет нам добавить опциональный параметр, тоесть компонента будет отрендерена как с id, так и без него */} <Route exact path ="/planets" component = {PlanetPage} /> <Route exact path ="/starships/" component = {StarshipPage} /> <Route path = "/starships/:id" render={({match})=>{ const {id} = match.params; return(<StarshipDetails itemId={id}> <Record label = 'Model' field = 'model' /> <Record label = 'Manufacturer' field = 'manufacturer' /> <Record label = 'Cost' field = 'costInCredits' /> <Record label = 'Length' field = 'length' /> <Record label = 'Passengers' field = 'passengers' /> </StarshipDetails>) }} /> <Route path ="/login" render={()=><LoginPage isLoggedIn={isLoggedIn} onLoggin={this.onLoggin} outLoggin={this.outLoggin}/>} /> <Route path ="/secret" render={()=> <SecretPage isLoggedIn={isLoggedIn} />} /> <Redirect to="/" />{/*Если ни одна из существующих страниц не совпадает с адресной строкой, то происходит редирект на главную, строка ниже, как альтернаатива, выводит сообщение, что страницы не найдено*/} {/* <Route render ={()=><h2>Page not found</h2>} /> */} </Switch> </div> </Router> </SwapiServiceContext.Provider> ) } } <file_sep>/src/component/hoc-helpers/with-children-function.js import React from 'react' const withChildrenFunction =(fn) => (Wrapper)=>{//то же самое, что и withChildrenFunction=(fn, Wrapper)=>{} return(props)=>{ return( <Wrapper {...props}> {fn} </Wrapper> ) } } export default withChildrenFunction<file_sep>/src/component/hoc-helpers/with-data.js //Компонента высшего порядка с логикой для вывода блока со списком данных import React,{Component} from 'react' import Spiner from '../spiner' const widthData=(View)=>{ return class extends Component{ state={ data:null, loading:false } componentDidUpdate(prevProps){ if(prevProps.getData !== this.props.getData){ this.setState({loading:true}) this.UpdateData(); } } componentDidMount(){ this.UpdateData(); } UpdateData = ()=>{ this.props.getData() .then((data)=>{this.setState({data,loading:false})}) .catch(this.props.onError) } render(){ const {data,loading} = this.state; if(!data||loading){ return <Spiner /> } return <View {...this.props} data={data} /> } } } export default widthData<file_sep>/src/component/hoc-helpers/with-detail.js //Компонента высшего порядка с логикой для вывода блока детальной информации import React,{Component} from 'react' import Spiner from '../spiner' const withDetail=(View)=>{ return class extends Component{ state={ item:null, loading:false } componentDidUpdate(prevProps){ if(this.props.itemId!==prevProps.itemId){ this.setState({loading:true}) this.getItem(this.props.itemId) } //далее проверим на обновление входящих методов из SwapiService if(this.props.getItem!==prevProps.getItem||this.props.getItemImg!==prevProps.getItemImg){ this.setState({item:null}) } } componentDidMount(){ if(this.props.itemId){ this.setState({loading:true}) this.getItem(this.props.itemId) } } //Делаем функцию асинхронной через async/await чтобы записывать полученные из промисов ответы. getItem = async(id)=>{ //проверка на получение не пустого id if(id){ const item = await this.props.getItem(id) .then((item)=>{return item}) .catch(()=>{console.log(`Ошибка, не удалось получить элемент по id=${id}`)}) const img = await this.props.getItemImg(id) .then(img=>{return img}) await this.updateItem({img,...item}) }else{ await this.updateItem(null) } } updateItem = (item)=>{ this.setState({ item, loading:false }); } render(){ const {item,loading} = this.state; console.log(item); if (!item&&loading){ return <Spiner /> } if(!item){ return(<span>Select a person</span>) } if(loading){ return <Spiner /> } return(<View {...this.props} item = {item}/> ) } } } export default withDetail;<file_sep>/src/component/pages/secret-page.js import React from 'react' import {Redirect} from 'react-router-dom' const SecretPage=({isLoggedIn})=>{ if(isLoggedIn){ return( <div className="jumbotron"> <h2>This content is full secret</h2> </div> ) }else{ return( <Redirect to="/login" /> ) } } export default SecretPage<file_sep>/src/component/pages/people-page.js import React from 'react' import {Record} from '../item-details' import ErrorBoundry from '../error-boundry' import { PersonList, PersonDetails } from '../sw-component'; import Row from '../row' import {withRouter} from 'react-router-dom' const PeoplePage=(props)=>{ const peoplelist = <PersonList onItemSelected={(id)=>{ console.log('click '+Number(id)) props.history.push(id) }} /> const peopledetails = ( <PersonDetails itemId={props.match.params.id}> <Record label = 'Eye color' field = 'eyeColor' /> <Record label = 'Gender' field = 'gender' /> <Record label = 'Birth year' field = 'birthYear' /> </PersonDetails> ) return( <> <ErrorBoundry> <Row left = {peoplelist} right = {peopledetails} /> </ErrorBoundry> </> ) } export default withRouter(PeoplePage)<file_sep>/src/component/row/index.js import React from 'react' import PropTypes from 'prop-types' export default function Row ({left,right}){ return( <div className="row"> <div className="col-md-6"> {left} </div> <div className="col-md-6"> {right} </div> </div> )} //проверяем, чтобы переданные props были с JSX и могли быть отрендереными Row.propTypes = { left:PropTypes.node, right:PropTypes.node }<file_sep>/src/component/hoc-helpers/compose.js //функция compose принимает в себя массив функций funcs и оборачивает их одну в другую справа налево, возвращая композицию этих функций //так же используется частично применённая функция const compose = (...funcs)=>(comp)=>{ return funcs.reduceRight((prevResult,f)=>f(prevResult),comp) } export default compose <file_sep>/src/component/sw-component/details.js import {withDetail,withSwapiService} from '../hoc-helpers' import ItemDetails from '../item-details' import RandomPlanet from '../random-planet' //объявляем функции для выборки данных по API bp swapiService const mapPersonMethodToProps = (swapiService)=>{ return{ getItem:swapiService.getPerson, getItemImg:swapiService.getPersonImg } } const mapPlanetMethodToProps = (swapiService)=>{ return{ getItem:swapiService.getPlanet, getItemImg:swapiService.getPlanetImg } } const mapStarshipMethodToProps = (swapiService)=>{ return{ getItem:swapiService.getStarship, getItemImg:swapiService.getStarshipImg } } const PersonDetails = withSwapiService(mapPersonMethodToProps)(withDetail(ItemDetails)) const PlanetDetails = withSwapiService(mapPlanetMethodToProps)(withDetail(ItemDetails)) const StarshipDetails = withSwapiService(mapStarshipMethodToProps)(withDetail(ItemDetails)) const RandomPlanetDetails = withSwapiService(mapPlanetMethodToProps)(RandomPlanet) export { PersonDetails, PlanetDetails, StarshipDetails, RandomPlanetDetails };
07fd28f496aec4267853076f0d3719473fac1fd4
[ "JavaScript" ]
13
JavaScript
EVAKuznetsov/StarWarsDB
09dc6b4c97b1114d56caf11a757cb21234ae3114
67312988a8866010da0f8db44c9a8021b757dab1
refs/heads/master
<file_sep>from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import UnicodeUsernameValidator class ShopUser(AbstractUser): username_validator = UnicodeUsernameValidator() gender_types = [('m', 'male'), ('f', 'female')] gender = models.CharField(max_length=1, choices=gender_types, null=True, blank=True) email = models.EmailField(unique=True, null=False) phone_number = models.IntegerField(null=True, blank=True) def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email <file_sep>from rest_framework import serializers from .models import * from account.models import ShopUser class BookSerializer(serializers.ModelSerializer): author = serializers.SlugRelatedField( slug_field='name', read_only=True, ) genre = serializers.SlugRelatedField( slug_field='title', read_only=True, many=True ) class Meta: model = Book exclude = ['about', 'creation_date', 'is_deleted', 'is_active', 'modification_date'] class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author exclude = ['bio', 'creation_date', 'is_deleted', 'is_active', 'modification_date'] class PublisherSerializer(serializers.ModelSerializer): class Meta: model = Publisher fields = '__all__' """ In the following API, I used some extra features of DRF rather than above ones. Firstly, i don't want email field to be write_only and clients can't read this field. Secondly, username won't be admin while registering new users via API. """ class UserSerializer(serializers.ModelSerializer): class Meta: model = ShopUser exclude = ('password', 'is_superuser') extra_kwargs = { 'email': {'write_only': True} } def validate_username(self, value): if value == 'admin': raise serializers.ValidationError('username can not be admin') return value def validate_email(self, value): if value is None: raise serializers.ValidationError('Email field can not be empty') return value <file_sep>from django.views.generic import RedirectView from django.urls import path from . import views app_name = 'shop' urlpatterns = [ path('', views.index, name='home_page'), path('all-authors/', views.authors_list, name='all_authors'), path('author-details/<int:id>', views.show_author, name='author_details'), path('wikipedia/<str:name>/', RedirectView.as_view(url="https://fa.wikipedia.org/wiki/%(name)s"), name='wiki'), path('all-publishers/', views.publishers_list, name='all_publishers'), path('publisher-details/<int:id>', views.show_publisher, name='publisher_details'), path('book-details/<int:pk>', views.show_book, name='book_details'), path('book-by-genre/<int:id>', views.book_by_genre, name='book_by_genre'), path('search/', views.simple_search, name='simple_search'), path('advanced-search/', views.advanced_search, name='advanced_search'), path('advanced-search-result/', views.advanced_search, name='advanced_search_result'), path('aboutus/', views.about_us, name='aboutus'), path('contactus/', views.contact_us, name='contactus'), path('login', views.MyLoginView.as_view(), name="extended_login"), # path('uikit', views.uikit, name='uikit'), # api urls # path('api/books', api_views.api_book_list, name='api-book-list'), # path('api/book-details/<int:pk>/', api_views.api_book_details, name='api-book-details'), # path('api/authors', api_views.api_author_list, name='api-author-list'), # path('api/author-details/<int:pk>/', api_views.api_author_list, name='api-author-details'), # path('api/publisher-list', api_views.api_publisher_list, name='api-publisher-list'), # class based view urls # path('all-publishers/', views.PublisherListView.as_view(), name='all_publishers'), # path('publisher-detail/<int:pk>', views.PublisherDetailView.as_view(), name='publisher_details'), # path('genres/<int:pk>', views.BookDetailView.as_view(), name='book_by_genre'), ] <file_sep>from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.template.loader import render_to_string from django.core.mail import EmailMessage from django.contrib.auth import login from django.contrib import messages from django.shortcuts import render from .tokens import account_activation_token from shop import models, views from .forms import SignupFrom from .models import ShopUser # this method is just for fill the requirements def requirements_filler(request): genres = models.Genre.objects.filter(is_deleted=False) books = models.Book.objects.filter(is_deleted=False)[:3] author = views.get_random_object(1, models.Author) nominated_author = views.get_random_object(1, models.Author) form = views.simple_search(request) result = {'all_genres': genres, 'nominated_books': books, 'point_of_day': author, 'nominated_author': nominated_author, 'form': form} return result # this method is called when a new user wants to register # in site and send it an email for verification def signup(request): context = requirements_filler(request) if request.POST: signup_form = SignupFrom(request.POST) if signup_form.is_valid(): user = signup_form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) # creating an Email object from user's specifications mail_subject = 'Account Verification' email_context = render_to_string('account/active.html', { 'user': user, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'domain': current_site.domain, 'token': account_activation_token.make_token(user), # this method is built-in from django.contrib.auth.tokens }) email_addr = signup_form.cleaned_data.get('email') email = EmailMessage(mail_subject, email_context, to=[email_addr]) email.send() msg = 'باتشکر، لینک فعال سازی به ایمیل شما ارسال شد.' \ ' جهت فعال سازی حساب کاربری خود بروی آن کلیک نمایید' messages.add_message(request, messages.SUCCESS, msg) # creating a flash message return render(request, 'home_page.html', context) else: context['signup_form'] = signup_form return render(request, 'account/signup.html', context) else: signup_form = SignupFrom() context['signup_form'] = signup_form return render(request, 'account/signup.html', context) # this method is used for active the user by token that has been signed up before def activate(request, uidb64, token): context = requirements_filler(request) try: # trying to find the user first uid = force_text(urlsafe_base64_decode(uidb64)) user = ShopUser.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, ShopUser.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token) and not user.is_active: user.is_active = True # by this code, user will be active login(request, user) messages.add_message(request, messages.SUCCESS, 'فعال سازی با موفقیت انجام شد') return render(request, 'home_page.html', context) else: messages.add_message(request, messages.ERROR, 'فعال سازی با مشکل مواجه شد. لطفا دوباره تلاش کنید') return render(request, 'home_page.html', context) <file_sep># Bookstore A simple local library Developed with Django web framework of Python!! Yesss, Django time :) <file_sep># Generated by Django 2.2.3 on 2020-08-02 13:23 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Author', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('creation_date', models.DateTimeField(auto_now_add=True)), ('modification_date', models.DateTimeField(auto_now=True)), ('is_deleted', models.BooleanField(default=False)), ('is_active', models.BooleanField(default=True)), ('name', models.CharField(max_length=255)), ('birth', models.IntegerField(null=True)), ('death', models.IntegerField(blank=True, null=True)), ('bio', models.TextField(blank=True, null=True)), ('profile_pic', models.ImageField(blank=True, null=True, upload_to='author-profile-pic/')), ('quote', models.TextField(blank=True, null=True)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Genre', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('creation_date', models.DateTimeField(auto_now_add=True)), ('modification_date', models.DateTimeField(auto_now=True)), ('is_deleted', models.BooleanField(default=False)), ('is_active', models.BooleanField(default=True)), ('title', models.CharField(max_length=255)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Publisher', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('creation_date', models.DateTimeField(auto_now_add=True)), ('modification_date', models.DateTimeField(auto_now=True)), ('is_deleted', models.BooleanField(default=False)), ('is_active', models.BooleanField(default=True)), ('title', models.CharField(max_length=255)), ('tel', models.IntegerField(null=True)), ('address', models.TextField(null=True)), ('logo', models.ImageField(blank=True, null=True, upload_to='publisher-logo/')), ('site', models.CharField(blank=True, max_length=255, null=True)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Score', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('creation_date', models.DateTimeField(auto_now_add=True)), ('modification_date', models.DateTimeField(auto_now=True)), ('is_deleted', models.BooleanField(default=False)), ('is_active', models.BooleanField(default=True)), ('amount', models.IntegerField(blank=True, null=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('creation_date', models.DateTimeField(auto_now_add=True)), ('modification_date', models.DateTimeField(auto_now=True)), ('is_deleted', models.BooleanField(default=False)), ('is_active', models.BooleanField(default=True)), ('context', models.TextField()), ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('creation_date', models.DateTimeField(auto_now_add=True)), ('modification_date', models.DateTimeField(auto_now=True)), ('is_deleted', models.BooleanField(default=False)), ('is_active', models.BooleanField(default=True)), ('title', models.CharField(max_length=255)), ('year', models.IntegerField(null=True)), ('cover', models.ImageField(blank=True, null=True, upload_to='book-covers/')), ('available_count', models.IntegerField(default=1)), ('price', models.IntegerField()), ('page_count', models.IntegerField()), ('about', models.TextField()), ('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='shop.Author')), ('comment', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='shop.Comment')), ('genre', models.ManyToManyField(to='shop.Genre')), ('publisher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='shop.Publisher')), ('score', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='shop.Score')), ], options={ 'abstract': False, }, ), ] <file_sep>""" Here we have all our API views, In order to show you two of the best ways of implementing API in DRF i'm using: 1) Function based API for Authors 2) Class based API which are: a. ViewSets API for Publishers b. ModelViewSets for Books But regardless of them, I write an example of function based API views for Book object, too. """ from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.decorators import api_view from rest_framework import status from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework import viewsets from account.models import ShopUser from .serializers import * from .models import * """ This is a function based API as mentioned above, but it's not a useful way so I only write it as comment. @api_view(['GET', 'POST']) # This decorator is used to block any other requests except GET and POST @permission_classes([IsAuthenticated]) # This decorator allows for authenticated users only to pass def api_book_list(request): if request.method == 'GET': book_list = Book.objects.filter(is_deleted=False) serializer = BookSerializer(book_list, many=True) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) """ ########################### """ In real projects, we use ViewSets and ModelViewSets to create standard API with DRF """ class BookViewSet(viewsets.ViewSet): """ A simple ViewSet for handling GET, POST, PUT and DELETE client requests for book model. GET => list, retrieve POST => create PUT => update DELETE => destroy """ def list(self, request): queryset = Book.objects.filter(is_deleted=False) serializer = BookSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Book.objects.filter(is_deleted=False) book = get_object_or_404(queryset, pk=pk) serializer = BookSerializer(book) return Response(serializer.data) def create(self, request): serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors) def update(self, request, pk=None): queryset = Book.objects.filter(is_deleted=False) book = get_object_or_404(queryset, pk=pk) serializer = BookSerializer(book) def destroy(self, request, pk=None): queryset = Book.objects.filter(is_deleted=False) book = get_object_or_404(queryset, pk=pk) book.is_deleted = True book.save() return Response(status=status.HTTP_204_NO_CONTENT) class AuthorViewSet(viewsets.ModelViewSet): """ A simple ModelViewSet for authors. THIS ONE IS AWESOME! """ queryset = Author.objects.filter(is_deleted=False) serializer_class = AuthorSerializer class PublisherViewSet(viewsets.ModelViewSet): """ A simple ModelViewSet for publishers. THIS ONE IS AWESOME! """ queryset = Publisher.objects.filter(is_deleted=False) serializer_class = PublisherSerializer class UserViewSet(viewsets.ModelViewSet): queryset = ShopUser.objects.filter(is_active=True) serializer_class = UserSerializer <file_sep>""" Django settings for Bookstore project. Generated by 'django-admin startproject' using Django 2.2.3. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from django.contrib.messages import constants as message_constants # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = <KEY>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['bookstore.ir', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'bootstrap_datepicker_plus', 'rest_framework', 'rest_framework.authtoken', 'shop', 'account', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Bookstore.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Bookstore.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3306', 'NAME': 'bookstore', 'USER': 'django', 'PASSWORD': '<PASSWORD>', } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # these are used by web server STATIC_ROOT = "/var/www/django" STATIC_URL = '/staticfiles/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #### LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' # these are settings which will be used to send email to users EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_PORT = 587 #### # these settings are mean to activate django flash message system MESSAGE_LEVEL = message_constants.SUCCESS MESSAGE_TAGS = { message_constants.DEBUG: 'alert-info', message_constants.INFO: 'alert-info', message_constants.SUCCESS: 'alert-success', message_constants.WARNING: 'alert-warning', message_constants.ERROR: 'alert-danger', } #### BOOTSTRAP4 = { 'include_jquery': True, } # setting for custom user model AUTH_USER_MODEL = 'account.ShopUser' #### # setting custom authentication system AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'account.authenticate.EmailBackend', ] """ Here are Django Rest Framework - DFR - global settings including: 1) Authentication method: I use TokenAuth and SessionAuth as the authentication's methods 2) Permissions : I want to allow only authenticated users to access all APIs 3) Throttling Policy: This feature allows us to limit amount of incoming requests form anonymous and authenticated users; There is also a scoped throttle which help us on control the requests for a specific part of our API. 4) Pagination: Just a decoration for showing results on browsable api, here every 5 objects will show on each page """ REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], # 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAuthenticated', # ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'anon': '500/day', 'user': '100/hour' }, 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 5 } #### <file_sep>from rest_framework import routers from shop.api_views import BookViewSet, AuthorViewSet, PublisherViewSet, UserViewSet router = routers.SimpleRouter() router.register('book', BookViewSet, base_name='book') router.register('author', AuthorViewSet, base_name='author') router.register('publisher', PublisherViewSet, base_name='publisher') router.register('user', UserViewSet, base_name='user') <file_sep>from django.contrib.auth import backends, get_user_model from django.db.models import Q UserModel = get_user_model() class EmailBackend(backends.ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: # user = UserModel._default_manager.get_by_natural_key(username) # You can customise what the given username is checked against, here I compare to both # username and email fields of the User model user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username)) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user return super().authenticate(request, username, password, **kwargs) <file_sep>{% extends 'home_page.html' %} {% load staticfiles %} {% load bootstrap4 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}Login Page{% endblock %}</title> </head> <body> {% block search %}{% endblock %} {% block main_content %} <div class="col-md-8 p-2"> <div class="row"> <div class="mx-auto"> <form method="post" class="pt-3" action="{% url 'shop:extended_login' %}"> {% csrf_token %} <table> <tr> {% bootstrap_form form %} </tr> <tr> <td> <input type="submit" value="ورود" class="mt-3 mr-5 btn btn-primary"> </td> </tr> </table> </form> </div> </div> </div> {% endblock %} {% block lower_content %}{% endblock %} </body> </html><file_sep>from rest_framework.authtoken.views import obtain_auth_token from django.urls import path from . import views app_name = 'account' urlpatterns = [ path('signup/', views.signup, name='signup'), path('activate/<str:uidb64>/<str:token>/', views.activate, name='activate'), # this url path is for generate authentication token. # client can now request to address below to take his/her auth token in API view. # requests must be POST and Multipart Form, parameters to send: username & password path('api/token-auth/', obtain_auth_token, name='api_token_auth'), ] <file_sep>from django.shortcuts import render, render_to_response, get_object_or_404 from django.db.models import Max, Count, Q from django.contrib.auth import views as auth_views from django.urls import reverse from .models import * from .forms import * import random from django.http import HttpResponse # This method is to find a random record from a given model of models.py def get_random_object(minimum, model): max_id = model.objects.filter(is_deleted=False).aggregate(max_id=Max("id"))['max_id'] random_id = random.randint(minimum, max_id) random_object = model.objects.filter(pk=random_id, is_deleted=False).first() return random_object # This method is to find best 3 books of a given genre to # Fill home page's best books of a genre box def find_best_books(): result = Genre.objects.annotate(Count('book')) for _ in result: if _.book__count >= 3: return _ # Simple book search method def simple_search(request): if request.method == "POST": form = SimpleSearch(request.POST) if form.is_valid(): title = form.cleaned_data['title'] result = Book.objects.filter(title__contains=title).filter(is_deleted=False) all_genre = Genre.objects.filter(is_deleted=False) if result.count() != 0: return render(request, 'shop/simple_search.html', {'result': result, 'all_genres': all_genre, 'form': form}) else: return render(request, 'shop/simple_search.html', {'all_genres': all_genre, 'form': form}) else: form = SimpleSearch() return form # This view fills home page's requirements def index(request): genres = Genre.objects.filter(is_deleted=False) books = Book.objects.filter(is_deleted=False)[:3] author = get_random_object(1, Author) nominated_author = get_random_object(1, Author) form = simple_search(request) return render(request, 'home_page.html', {'all_genres': genres, 'nominated_books': books, 'point_of_day': author, 'nominated_author': nominated_author, 'form': form, }) # We could use class based views too def authors_list(request): authors = Author.objects.filter(is_deleted=False) genres = Genre.objects.filter(is_deleted=False) author = get_random_object(1, Author) nominated_author = get_random_object(1, Author) form = simple_search(request) return render(request, 'shop/authors.html', {'all_authors': authors, 'all_genres': genres, 'point_of_day': author, 'nominated_author': nominated_author, 'form': form, }) """ In the method below, I have used my custom model manager 'bs_object' instead of django default manager, objects. """ def show_author(request, id): # author = Author.objects.filter(is_deleted=False).get(pk=id) author = Author.bs_object.get(pk=id) genres = Genre.objects.filter(is_deleted=False) form = simple_search(request) return render(request, 'shop/author-details.html', {'author': author, 'all_genres': genres, 'form': form}) def publishers_list(request): all_genres = Genre.objects.filter(is_deleted=False) point_of_day = get_random_object(1, Author) nominated_author = get_random_object(1, Author) all_publishers = Publisher.objects.filter(is_deleted=False) form = simple_search(request) return render(request, 'shop/publishers.html', {'all_genres': all_genres, 'point_of_day': point_of_day, 'nominated_author': nominated_author, 'all_publishers': all_publishers, 'form': form, }) def show_publisher(request, id): publisher = Publisher.objects.filter(is_deleted=False).get(pk=id) all_genres = Genre.objects.filter(is_deleted=False) form = simple_search(request) return render(request, 'shop/publisher-details.html', {'publisher': publisher, 'all_genres': all_genres, 'form': form, }) def book_by_genre(request, id): genre = Genre.objects.filter(is_deleted=False).get(pk=id) all_genres = Genre.objects.filter(is_deleted=False) point_of_day = get_random_object(1, Author) nominated_author = get_random_object(1, Author) form = simple_search(request) return render(request, 'shop/book_by_genre.html', {'genre': genre, 'all_genres': all_genres, 'point_of_day': point_of_day, 'nominated_author': nominated_author, 'form': form }) def show_book(request, pk): book = Book.objects.filter(is_deleted=False).get(pk=pk) genres = Genre.objects.filter(is_deleted=False) form = simple_search(request) return render(request, 'shop/book-details.html', {'book': book, 'all_genres': genres, 'form': form}) ############################# # Class based list and detail view sample for publisher model # class PublisherListView(ListView): # model = Publisher # template_name = 'shop/publishers.html' # # def get(self, request, **kwargs): # return simple_search(request) # # def get_context_data(self, **kwargs): # context = super().get_context_data(**kwargs) # context['all_genres'] = Genre.objects.all() # context['point_of_day'] = get_random_object(1, Author) # context['nominated_author'] = get_random_object(1, Author) # return context # # # class PublisherDetailView(DetailView): # model = Publisher # template_name = 'shop/publisher-details.html' # # def get_context_data(self, **kwargs): # context = super().get_context_data(**kwargs) # context['all_genres'] = Genre.objects.all() # return context # # # class BookDetailView(DetailView): # model = Genre # template_name = 'shop/book_by_genre.html' # # def get_context_data(self, **kwargs): # context = super().get_context_data(**kwargs) # context['all_genres'] = Genre.objects.all() # context['point_of_day'] = get_random_object(1, Author) # context['nominated_author'] = get_random_object(1, Author) # return context ############################ def advanced_search(request): if request.method == 'POST': form = AdvancedSearch(request.POST) if form.is_valid(): query_1 = Q(author__name__contains=form.cleaned_data['author_name']) &\ Q(title__contains=form.cleaned_data['book_title']) &\ Q(publisher__title__contains=form.cleaned_data['publisher_title']) &\ Q(genre__title__contains=form.cleaned_data['genre_title']) # query_2 = Q(title__contains=form.cleaned_data['book_title']) \ # | Q(author__name__contains=form.cleaned_data['author_name']) \ # | Q(publisher__title__contains=form.cleaned_data['publisher_title']) \ # | Q(genre__title__contains=form.cleaned_data['genre_title']) result = Book.objects.filter(query_1, is_deleted=False) genres = Genre.objects.filter(is_deleted=False) form = simple_search(request) return render(request, 'shop/advanced_search.html', {'result': result, 'form': form, 'all_genres': genres}) else: adv_form = AdvancedSearch() genres = Genre.objects.filter(is_deleted=False) form = simple_search(request) return render(request, 'shop/advanced_search_form.html', {'adv_form': adv_form, 'all_genres': genres, 'form': form}) def about_us(request): genres = Genre.objects.filter(is_deleted=False) form = simple_search(request) return render(request, 'aboutus.html', {'all_genres': genres, 'form': form}) def contact_us(request): genres = Genre.objects.filter(is_deleted=False) form = simple_search(request) return render(request, 'contactus.html', {'all_genres': genres, 'form': form}) # login view needs to be change because it extends home.html class MyLoginView(auth_views.LoginView): template_name = 'registration/login.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) genres = Genre.objects.filter(is_deleted=False) context.update({ 'all_genres': genres, }) return context # def uikit(request): # return render(request, 'UIkit.html') # Custom Error Handler def handler_404(request, exception=None): return render(request, '404.html', status=404) def handler_400(request, exception=None): return render(request, '400.html', status=404) def handler_403(request, exception=None): return render(request, '403.html', status=404) def handler_500(request, exception=None): return render(request, '500.html', status=500) <file_sep>from django.contrib import admin from .models import * @admin.register(Book) class BookAdmin(admin.ModelAdmin): """ Here I'm using some customization options for django admin panel: list_display => what should be shown in Book admin page filter_horizontal => changes add/change for genre interface list_filter => right filter panel keys search_fields => search box basis keys raw_id_fields => changes 1=>N, N=>M fields display form in add/change actions """ list_display = ['title', 'year', 'author', 'price', 'creation_date', 'publisher'] filter_horizontal = ('genre',) list_filter = ('title', 'genre', 'author') search_fields = ('title', 'author__name') raw_id_fields = ('genre', 'author') @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(Publisher) admin.site.register(Score) admin.site.register(Comment) admin.site.register(Genre) <file_sep>from django import forms class SimpleSearch(forms.Form): title = forms.CharField(label="", max_length=255) class AdvancedSearch(forms.Form): book_title = forms.CharField(label='عنوان کتاب', max_length=255) author_name = forms.CharField(label='نام نویسنده', max_length=255) publisher_title = forms.CharField(label='نام انتشارات', max_length=255) genre_title = forms.CharField(label='ژانر کتاب', max_length=255) <file_sep>from django.contrib.auth import get_user_model from django.db import models shop_user = get_user_model() class BookShopManager(models.Manager): # custom model manager def get_queryset(self): return super().get_queryset().filter(is_deleted=False) class AbstractModel(models.Model): creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) is_deleted = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = models.Manager() # activate default django manager bs_object = BookShopManager() # custom model manager class Meta: abstract = True class Genre(AbstractModel): title = models.CharField(max_length=255) def __str__(self): return self.title class Author(AbstractModel): name = models.CharField(max_length=255) birth = models.IntegerField(null=True) death = models.IntegerField(null=True, blank=True) bio = models.TextField(null=True, blank=True) profile_pic = models.ImageField(upload_to='author-profile-pic/', blank=True, null=True) quote = models.TextField(null=True, blank=True) def __str__(self): return '{}- from {} to {}'.format(self.name, self.birth, self.death or 'now') class Publisher(AbstractModel): title = models.CharField(max_length=255) tel = models.IntegerField(null=True) address = models.TextField(null=True) logo = models.ImageField(upload_to='publisher-logo/', null=True, blank=True) site = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return '{} - tel: {} - address: {}'.format(self.title, self.tel, self.address) class Score(AbstractModel): amount = models.IntegerField(null=True, blank=True) user = models.ForeignKey(shop_user, on_delete=models.PROTECT) def __str__(self): return '{} to {}'.format(self.user, self.amount) class Comment(AbstractModel): context = models.TextField() user = models.ForeignKey(shop_user, on_delete=models.PROTECT) def __str__(self): return '{} has said: {}'.format(self.user, self.context) class Book(AbstractModel): title = models.CharField(max_length=255) year = models.IntegerField(null=True) cover = models.ImageField(upload_to='book-covers/', blank=True, null=True) available_count = models.IntegerField(default=1) price = models.IntegerField(null=False, blank=False) page_count = models.IntegerField(null=False, blank=False) about = models.TextField() genre = models.ManyToManyField(Genre) author = models.ForeignKey(Author, on_delete=models.PROTECT) comment = models.ForeignKey(Comment, on_delete=models.PROTECT, null=True, blank=True) score = models.ForeignKey(Score, on_delete=models.PROTECT, null=True, blank=True) publisher = models.ForeignKey(Publisher, on_delete=models.PROTECT, null=True, blank=True) def __str__(self): return '{} ({})'.format(self.title, self.author.name) <file_sep>from django.contrib.auth.forms import UserCreationForm from account.models import ShopUser from django import forms class SignupFrom(UserCreationForm): email = forms.EmailField(max_length=200, label='Email', widget=forms.EmailInput(attrs= {'placeholder': 'required'})) class Meta: model = ShopUser fields = ('username', 'email', 'gender', '<PASSWORD>', '<PASSWORD>') <file_sep>from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import ShopUser admin.site.register(ShopUser, UserAdmin)
206ba3f71bdab49ed43b12077d47674386ee42d9
[ "Markdown", "Python", "HTML" ]
18
Python
raminBadri/Bookstore
fda615c8219fa3a4f5f1e6798681b5e7fdcd7c37
ff16ccffa5fa6a48849740584ca420b56abebb67
refs/heads/master
<repo_name>niewenlong/shadowsocks<file_sep>/src/lib/ss_core.cc #include "shadowsocks/ss_core.h" #define DEBUG_LOGGER_NAME ("debug") // SsCore static members std::vector<std::function<void()>> SsCore::_exitCallbacks; // shadowsocks environment initializing void SsCore::initEnvironments() { std::atexit(&SsCore::shutdownHandler); socketStartup(); } // on internal error occurs, cleanup resources void SsCore::shutdownHandler() { for (auto it = _exitCallbacks.rbegin(); it != _exitCallbacks.rend(); ++it) { (*it)(); } } // register an cleanup handler to queue void SsCore::atExit(std::function<void()> callback) { _exitCallbacks.emplace_back(callback); } // socket environment initializing on windows platform void SsCore::socketStartup() { #if defined(__platform_windows__) WSAData winSocketData{}; if (WSAStartup(MAKEWORD(2, 2), &winSocketData) != OPERATOR_SUCCESS) { SsLogger::emergency("Socket environment startup failure on windows"); } auto socketCleanup = [] () { if (WSACleanup() != OPERATOR_SUCCESS) { SsLogger::emergency("Socket environment cleanup failure"); } }; SsCore::atExit(socketCleanup); SsLogger::debug("Socket environment startup on windows"); #endif } // enable debug logger with stdout void SsCore::enableDebugLogger(SsLogger::LoggerLevel level) { auto logger = std::make_shared<SsLogger>(std::cout); #if defined(__type_debug__) logger->setLevel(level); #endif SsLogger::addLogger(DEBUG_LOGGER_NAME, std::move(logger)); } // disable debug logger void SsCore::disableDebugLogger() { SsLogger::removeLogger(DEBUG_LOGGER_NAME); } <file_sep>/include/shadowsocks/ss_core.h #ifndef __SHADOWSOCKS_CORE_INCLUDED__ #define __SHADOWSOCKS_CORE_INCLUDED__ #include "shadowsocks/ss_types.h" #include "shadowsocks/ss_logger.h" class SsCore { public: static void initEnvironments(); static void atExit(std::function<void()> callback); static void shutdownHandler(); static void enableDebugLogger(SsLogger::LoggerLevel level); static void disableDebugLogger(); private: static void socketStartup(); private: static std::vector<std::function<void()>> _exitCallbacks; }; #endif // __SHADOWSOCKS_CORE_INCLUDED__ <file_sep>/include/shadowsocks/ss_logger.h #ifndef __SHADOWSOCKS_LOGGER_INCLUDED__ #define __SHADOWSOCKS_LOGGER_INCLUDED__ #include "shadowsocks/ss_types.h" /* runtime get index of tuple */ template <size_t I> struct VisitImpl { template <typename Type, typename Func> static void visit(Type &tuple, size_t idx, Func func) { if (idx == I - 1) { func(std::get<I - 1>(tuple)); } else { VisitImpl<I - 1>::visit(tuple, idx, func); } } }; template <> struct VisitImpl<0> { template <typename Type, typename F> static void visit(Type &tuple, size_t idx, F fun) { assert(false); } }; template <typename Func, typename ...Types> void visit(const std::tuple<Types...> &tuple, size_t idx, Func func) { VisitImpl<sizeof...(Types)>::visit(tuple, idx, func); } class TupleElementPrinter { public: explicit TupleElementPrinter(std::ostream &out); void setFlag(std::ios::fmtflags flags); template<typename tuple> void operator()(tuple value) { _output << value; if (_defaultFlags) { _output.setf(_defaultFlags); _defaultFlags = static_cast<std::ios_base::fmtflags>(0); } } private: std::ostream &_output; std::ios::fmtflags _defaultFlags; }; class SsLogger { public: enum class LoggerLevel : uint8_t { LL_VERBOSE = 0x00, LL_DEBUG = 0x10, LL_INFO = 0x20, LL_WARNING = 0x40, LL_ERROR = 0x80, LL_EMERGENCY = 0xff }; using Format = const char *; using LoggerName = const char *; using SsLoggerPtr = std::shared_ptr<SsLogger>; public: explicit SsLogger(std::ostream &out); virtual ~SsLogger(); void setLevel(LoggerLevel level); void setName(LoggerName name); static void addLogger(LoggerName name, SsLoggerPtr logger); static bool removeLogger(LoggerName name); template <typename ...Args> static void verbose(Format fmt, Args ...args); template <typename ...Args> static void debug(Format fmt, Args ...args); template <typename ...Args> static void info(Format fmt, Args ...args); template <typename ...Args> static void warning(Format fmt, Args ...args); template <typename ...Args> static void error(Format fmt, Args ...args); template <typename ...Args> static void emergency(Format fmt, Args ...args); template <typename ...Args> static std::string log(SsLogger::LoggerLevel level, Format fmt, Args ...args); template <typename ...Args> static std::string format(Format fmt, Args ...args); private: static std::string currentDate(Format fmt); static void log(LoggerLevel level, std::string message); private: LoggerName _name = nullptr; std::ostream &_output; std::string _dateFormat = "%A %b %d %H:%M:%S %Y \t->\t "; LoggerLevel _level = LoggerLevel::LL_INFO; static std::map<SsLogger::LoggerName, SsLogger::SsLoggerPtr> _loggers; friend std::ostream &operator<<(std::ostream &out, SsLogger *logger); }; /* utility methods declare */ std::ostream &operator<<(std::ostream &out, const SsLogger::LoggerLevel &level); // all the things that happened template<typename ...Args> void SsLogger::verbose(SsLogger::Format fmt, Args... args) { log(LoggerLevel::LL_VERBOSE, format(fmt, args...)); } // detailed debug information template<typename ...Args> void SsLogger::debug(SsLogger::Format fmt, Args... args) { log(LoggerLevel::LL_DEBUG, format(fmt, args...)); } // interesting events. template<typename ...Args> void SsLogger::info(SsLogger::Format fmt, Args... args) { log(LoggerLevel::LL_INFO, format(fmt, args...)); } // exceptional occurrences that are not errors. template<typename ...Args> void SsLogger::warning(SsLogger::Format fmt, Args... args) { log(LoggerLevel::LL_WARNING, format(fmt, args...)); } // runtime errors that do not require immediate action but should typically // be logged and monitored. template<typename ...Args> void SsLogger::error(SsLogger::Format fmt, Args... args) { log(LoggerLevel::LL_ERROR, format(fmt, args...)); } // system is unusable, will be exit template<typename ...Args> void SsLogger::emergency(SsLogger::Format fmt, Args... args) { log(LoggerLevel::LL_EMERGENCY, format(fmt, args...)); std::exit(OPERATOR_FAILURE); } // custom log message and return message template<typename ...Args> std::string SsLogger::log(SsLogger::LoggerLevel level, SsLogger::Format fmt, Args... args) { std::string message = format(fmt, args...); log(level, message); if (level == SsLogger::LoggerLevel::LL_EMERGENCY) { std::exit(OPERATOR_FAILURE); } return message; } // format parameters and output it template<typename ...Args> std::string SsLogger::format(Format fmt, Args... args) { std::stringstream ss; TupleElementPrinter printer(ss); auto tuple = std::make_tuple(args...); size_t tupleSize = std::tuple_size<std::tuple<Args...>>::value; size_t index = 0; auto output = [&] (size_t &i) { if (index < tupleSize) { visit(tuple, index++, printer); while (isalnum(fmt[++i])) { ; } --i; } else { printer('%'); } }; for (size_t i = 0; i < strlen(fmt); ++i) { if (fmt[i] != '%') { ss << fmt[i]; } else { /** * @todo hex oct and dec */ switch (fmt[i + 1]) { case '%': ss << fmt[i++]; break; // escape % case 'x': { ss << "0x"; printer.setFlag(std::ios::hex); } default: output(++i); } } } return ss.str(); } #define VVV(FMT, ARGS...) SsLogger::verbose(FMT, ##ARGS) #define DBG(FMT, ARGS...) SsLogger::debug(FMT, ##ARGS) #define INF(FMT, ARGS...) SsLogger::info(FMT, ##ARGS) #define WARN(FMT, ARGS...) SsLogger::warning(FMT, ##ARGS) #define ERR(FMT, ARGS...) SsLogger::error(FMT, ##ARGS) #define EXT(FMT, ARGS...) SsLogger::emergency(FMT, ##ARGS) #endif // __SHADOWSOCKS_LOGGER_INCLUDED__ <file_sep>/include/shadowsocks/network/ss_udp_network.h #ifndef __SHADOWSOCKS_UDP_NETWORK_INCLUDED__ #define __SHADOWSOCKS_UDP_NETWORK_INCLUDED__ #include "shadowsocks/network/ss_network.h" class SsUdpNetwork : public SsNetwork { public: explicit SsUdpNetwork(NetworkFamily family); SsUdpNetwork(Descriptor descriptor, Address address); ConnectingTuple accept() final; protected: void doConnect(HostName host, HostPort port) final; void doListen(HostName host, HostPort port) final; }; #endif // __SHADOWSOCKS_TCP_NETWORK_INCLUDED__ <file_sep>/include/shadowsocks/network/ss_network.h #ifndef __SHADOWSOCKS_NETWORK_INCLUDED__ #define __SHADOWSOCKS_NETWORK_INCLUDED__ #include "shadowsocks/ss_types.h" #include "shadowsocks/ss_selector.h" class SsNetwork { public: enum class NetworkFamily : uint8_t { NF_INET_4 = AF_INET, NF_INET_6 = AF_INET6 }; enum class NetworkType : uint8_t { NT_RAW = SOCK_RAW, NT_TCP = SOCK_STREAM, NT_UDP = SOCK_DGRAM }; using HostName = const char *; using HostPort = int; using Address = sockaddr_storage; using Descriptor = SsSelector::Descriptor; using ConnectingTuple = std::pair<Descriptor, std::shared_ptr<Address>>; protected: enum class NetworkState : uint8_t { NS_NONE = 0x0, NS_LISTEN = 0x1, NS_ESTABLISHED = 0x2 }; public: SsNetwork(NetworkFamily family, NetworkType type); SsNetwork(Descriptor descriptor, Address address, NetworkType type); ~SsNetwork(); Descriptor getDescriptor() const; void connect(HostName host, HostPort port); void listen(HostName host, HostPort port); virtual ConnectingTuple accept(); protected: virtual void doConnect(HostName host, HostPort port); virtual void doListen(HostName host, HostPort port); private: NetworkFamily _family; NetworkType _type; NetworkState _state = NetworkState::NS_NONE; Descriptor _descriptor; friend std::ostream &operator<<(std::ostream &o, SsNetwork *network); friend std::ostream &operator<<(std::ostream &o, NetworkFamily &family); friend std::ostream &operator<<(std::ostream &o, NetworkType &type); friend std::ostream &operator<<(std::ostream &o, NetworkState &state); }; #endif // __SHADOWSOCKS_NETWORK_INCLUDED__ <file_sep>/src/client/client.cc #include "shadowsocks/ss_core.h" #include "shadowsocks/network/relay/ss_tcp_relay.h" int main(int argc, char *argv[]) { SsCore::enableDebugLogger(SsLogger::LoggerLevel::LL_DEBUG); SsCore::initEnvironments(); auto selector = std::make_shared<SsSelector>(); auto tcpRelay = std::make_shared<SsTcpRelay>(); return 0; } <file_sep>/include/shadowsocks/network/relay/ss_tcp_relay.h #ifndef __SHADOWSOCKS_TCP_RELAY_INCLUDED__ #define __SHADOWSOCKS_TCP_RELAY_INCLUDED__ #include "shadowsocks/ss_types.h" #include "shadowsocks/network/ss_tcp_network.h" class SsTcpRelay { public: using Stream = std::vector<DATA_STREAM_UNIT>; using StreamCallback = std::function<void(Stream&, Stream&)>; public: void before(StreamCallback callback); void after(StreamCallback callback); private: std::shared_ptr<SsTcpNetwork> _source; std::map< SsNetwork::Descriptor, std::pair<SsTcpNetwork, SsTcpNetwork> > _streams; }; #endif // __SHADOWSOCKS_TCP_RELAY_INCLUDED__ <file_sep>/src/lib/ss_logger.cc #include "shadowsocks/ss_logger.h" #define LOGGER_TIME_INFO_SIZE (128) // static members definition std::map<SsLogger::LoggerName, SsLogger::SsLoggerPtr> SsLogger::_loggers{}; // SsLogger constructor SsLogger::SsLogger(std::ostream &out) : _output(out) { // empty constructor } // SsLogger destructor SsLogger::~SsLogger() { SsLogger::debug("%s closed", this); } // add logger to global void SsLogger::addLogger(SsLogger::LoggerName name, SsLoggerPtr logger) { logger->setName(name); _loggers[name] = std::move(logger); } // remove logger by name bool SsLogger::removeLogger(SsLogger::LoggerName name) { if (_loggers.find(name) == _loggers.end()) { return false; } _loggers.erase(name); return true; } // set level of logger void SsLogger::setLevel(LoggerLevel level) { _level = level; } // named logger void SsLogger::setName(SsLogger::LoggerName name) { _name = name; } // do output message when level correct void SsLogger::log(LoggerLevel level, std::string message) { if (_loggers.empty()) { return; } for (auto &pair : _loggers) { auto &logger = pair.second; if (level >= logger->_level) { logger->_output << level << ": " << currentDate(logger->_dateFormat.c_str()) << message << std::endl; } } } // format current time std::string SsLogger::currentDate(SsLogger::Format fmt) { time_t rawTime; std::time(&rawTime); static auto buffer = new char[LOGGER_TIME_INFO_SIZE]; std::strftime(buffer, LOGGER_TIME_INFO_SIZE, fmt, std::localtime(&rawTime)); return buffer; } // output logger std::ostream &operator<<(std::ostream &out, SsLogger *logger) { out << "SsLogger[" << "name=" << logger->_name << "]"; return out; } // output level text std::ostream &operator<<(std::ostream &out, const SsLogger::LoggerLevel &level) { switch (level) { case SsLogger::LoggerLevel::LL_VERBOSE: out << "VERBOSE"; break; case SsLogger::LoggerLevel::LL_DEBUG: out << "DEBUG"; break; case SsLogger::LoggerLevel::LL_INFO: out << "INFO"; break; case SsLogger::LoggerLevel::LL_WARNING: out << "WARNING"; break; case SsLogger::LoggerLevel::LL_ERROR: out << "ERROR"; break; case SsLogger::LoggerLevel::LL_EMERGENCY: out << "EMERGENCY"; break; } return out; } // TupleElementPrinter constructor TupleElementPrinter::TupleElementPrinter(std::ostream &out) : _output(out), _defaultFlags(_output.flags()) { } // temporarily set a flags to stream void TupleElementPrinter::setFlag(std::ios::fmtflags flags) { _defaultFlags = _output.setf(flags, std::ios::basefield); } <file_sep>/src/lib/network/ss_tcp_relay.cc #include "shadowsocks/network/relay/ss_tcp_relay.h" // when stream before calling void SsTcpRelay::before(SsTcpRelay::StreamCallback callback) { } // when stream after calling void SsTcpRelay::after(SsTcpRelay::StreamCallback callback) { } <file_sep>/include/shadowsocks/ss_exception.h #ifndef __SHADOWSOCKS_EXCEPTION_INCLUDED__ #define __SHADOWSOCKS_EXCEPTION_INCLUDED__ #include "shadowsocks/ss_types.h" #include "shadowsocks/ss_logger.h" class SsException : public std::runtime_error { public: SsException(SsLogger::LoggerLevel level, std::string message); SsException(SsLogger::LoggerLevel level, std::string &&message); }; #endif // __SHADOWSOCKS_EXCEPTION_INCLUDED__ <file_sep>/include/shadowsocks/ss_types.h #ifndef __SHADOWSOCKS_TYPES_INCLUDED__ #define __SHADOWSOCKS_TYPES_INCLUDED__ // config by auto generated #include "ss_config.h" // standard headers #include <map> #include <list> #include <ctime> #include <tuple> #include <cstdio> #include <memory> #include <cassert> #include <csignal> #include <cstdint> #include <cstdlib> #include <cstring> #include <fstream> #include <sstream> #include <iostream> #include <algorithm> #include <functional> #include <forward_list> #include <initializer_list> // platform headers #if defined(__platform_linux__) #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/epoll.h> #include <poll.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h> #elif defined(__platform_windows__) #include <Windows.h> #include <WinSock2.h> #include <ws2tcpip.h> #endif #define OPERATOR_SUCCESS (0) #define OPERATOR_FAILURE (-1) #if defined(__platform_linux__) #define INVALID_DESCRIPTOR (~0) #elif defined(__platform_windows__) #define INVALID_DESCRIPTOR (INVALID_SOCKET) #endif #define DATA_STREAM_UNIT u_char #endif // __SHADOWSOCKS_TYPES_INCLUDED__ <file_sep>/include/shadowsocks/network/ss_tcp_network.h #ifndef __SHADOWSOCKS_TCP_NETWORK_INCLUDED__ #define __SHADOWSOCKS_TCP_NETWORK_INCLUDED__ #include "shadowsocks/network/ss_network.h" class SsTcpNetwork : public SsNetwork { public: explicit SsTcpNetwork(NetworkFamily family); SsTcpNetwork(Descriptor descriptor, Address address); ConnectingTuple accept() final; protected: void doConnect(HostName host, HostPort port) final; void doListen(HostName host, HostPort port) final; }; #endif // __SHADOWSOCKS_TCP_NETWORK_INCLUDED__ <file_sep>/src/lib/network/ss_udp_network.cc #include "shadowsocks/network/ss_udp_network.h" #include "shadowsocks/ss_logger.h" // SsUdpNetwork constructor SsUdpNetwork::SsUdpNetwork(SsNetwork::NetworkFamily family) : SsNetwork(family, NetworkType::NT_UDP) { } // SsUdpNetwork constructor SsUdpNetwork::SsUdpNetwork(SsNetwork::Descriptor descriptor, SsNetwork::Address address) : SsNetwork(descriptor, address, NetworkType::NT_UDP) { } // udp server unsupported accept connection SsNetwork::ConnectingTuple SsUdpNetwork::accept() { return {INVALID_DESCRIPTOR, nullptr}; } // UDP network unsupported connect action void SsUdpNetwork::doConnect(SsNetwork::HostName host, SsNetwork::HostPort port) { SsLogger::warning("UDP network unsupported connect operator"); } // listening on host:port via UDP void SsUdpNetwork::doListen(SsNetwork::HostName host, SsNetwork::HostPort port) { SsNetwork::doListen(host, port); } <file_sep>/src/lib/ss_selector.cc #include "shadowsocks/ss_selector.h" #include "shadowsocks/ss_logger.h" // SsSelector constructor SsSelector::SsSelector() : _objects({}) { DBG("SsSelector created"); } // SsSelector destructor SsSelector::~SsSelector() { _objects.clear(); DBG("SsSelector closed"); } // add an object to selector void SsSelector::add(SsSelector::Descriptor descriptor, SsSelector::SelectorEvents events) { if (descriptorExists(descriptor)) { WARN("Duplicate register descriptor = %d to selector", descriptor); } else { DBG("Register descriptor = %d to selector with events = %s", descriptor, "EVENTS"); #if defined(__platform_linux__) pollfd fd = { .fd = descriptor, .events = 0 }; for (auto &event : events) { fd.events |= static_cast<uint8_t>(event); } _objects.push_back(fd); #elif defined(__platform_windows__) for (auto &event : events) { _objects[descriptor] |= static_cast<uint8_t>(event); } #endif } } // remove object from selector void SsSelector::remove(SsSelector::Descriptor descriptor) { if (descriptorExists(descriptor)) { WARN("Not found descriptor = %d in selector", descriptor); } else { DBG("Remove descriptor = %d in selector", descriptor); #if defined(__platform_linux__) _objects.erase(std::remove_if(_objects.begin(), _objects.end(), [&] (pollfd &fd) { return fd.fd == descriptor; } ), _objects.end()); #elif defined(__platform_windows__) _objects.erase(descriptor); #endif } } // modify object events attribute void SsSelector::movify(SsSelector::Descriptor descriptor, SsSelector::SelectorEvents events) { if (descriptorExists(descriptor)) { WARN("Not found descriptor = %d in selector", descriptor); } else { DBG("Modify descriptor = %d events to %s", descriptor, "EVENTS"); #if defined(__platform_linux__) auto it = std::find_if(_objects.begin(), _objects.end(), [&] (pollfd &fd){ return fd.fd == descriptor; } ); it->events = 0; for (auto &event : events) { it->events |= static_cast<uint8_t>(event); } #elif defined(__platform_windows__) _objects[descriptor] = 0; for (auto &event : events) { _objects[descriptor] |= static_cast<uint8_t>(event); } #endif } } // start select all objects #if defined(__platform_linux__) SsSelector::SelectResult SsSelector::select(int timeout) { SelectResult result; int pollResult = ::poll(&_objects[0], _objects.size(), timeout * 1000); if (pollResult == OPERATOR_FAILURE) { result.first = SelectorState::SS_FAILURE; } else if (pollResult == 0) { result.first = SelectorState::SS_TIMEOUT; } else { result.first = SelectorState::SS_SUCCESS; for (auto &fd : _objects) { auto descriptorReadable = false; auto descriptorWritable = false; if (fd.revents != 0) { if (fd.revents & SELECTOR_EVENT_IN) { descriptorReadable = true; } if (fd.revents & SELECTOR_EVENT_OUT) { descriptorWritable = true; } result.second.push_back({fd.fd, { descriptorReadable, descriptorWritable }}); if (--pollResult == 0) { break; } } } } return result; } #elif defined(__platform_windows__) SsSelector::SelectResult SsSelector::select(int timeout) { static FD_SET readable; static FD_SET writable; static timeval tv = { .tv_sec = timeout }; FD_ZERO(&readable); FD_ZERO(&writable); for (auto &pair : _objects) { if (pair.second & SELECTOR_EVENT_IN) { FD_SET(pair.first, &readable); } if (pair.second & SELECTOR_EVENT_OUT) { FD_SET(pair.first, &writable); } } SelectResult result; int selectResult = ::select(FD_SETSIZE, &readable, &writable, nullptr, &tv); if (selectResult == OPERATOR_FAILURE) { result.first = SelectorState::SS_FAILURE; } else if (selectResult == 0) { result.first = SelectorState::SS_TIMEOUT; } else { result.first = SelectorState::SS_SUCCESS; for (auto &pair : _objects) { auto descriptorReadable = false; auto descriptorWritable = false; if (FD_ISSET(pair.first, &readable)) { descriptorReadable = true; } if (FD_ISSET(pair.first, &writable)) { descriptorWritable = true; } if (descriptorReadable || descriptorWritable) { result.second.push_back({pair.first, { descriptorReadable, descriptorWritable }}); if (--selectResult == 0) { break; } } } } return result; } #endif // check descriptor exists bool SsSelector::descriptorExists(SsSelector::Descriptor &descriptor) { #if defined(__platform_linux__) return std::find_if(_objects.begin(), _objects.end(), [&] (pollfd &fd) { return fd.fd == descriptor; }) != _objects.end(); #elif defined(__platform_windows__) return _objects.find(descriptor) == _objects.end(); #endif } <file_sep>/src/lib/network/ss_network.cc #include "shadowsocks/network/ss_network.h" #include "shadowsocks/ss_logger.h" // SsNetwork constructor SsNetwork::SsNetwork(SsNetwork::NetworkFamily family, SsNetwork::NetworkType type) : _family(family), _type(type), _descriptor(0) { SsLogger::debug("%s created", this); } // SsNetwork constructor SsNetwork::SsNetwork(SsNetwork::Descriptor descriptor, SsNetwork::Address address, SsNetwork::NetworkType type): _family(NetworkFamily::NF_INET_4), _type(type), _descriptor(descriptor) { } // SsNetwork destructor SsNetwork::~SsNetwork() { SsLogger::debug("%s closed", this); } // get network descriptor SsNetwork::Descriptor SsNetwork::getDescriptor() const { return _descriptor; } // connecting to host:port void SsNetwork::connect(SsNetwork::HostName host, SsNetwork::HostPort port) { if (_state != NetworkState::NS_NONE) { SsLogger::warning("cannot convert state form %s to %s", _state, NetworkState::NS_ESTABLISHED); } _state = NetworkState::NS_ESTABLISHED; doConnect(host, port); } // listening on host:port void SsNetwork::listen(SsNetwork::HostName host, SsNetwork::HostPort port) { if (_state != NetworkState::NS_NONE) { SsLogger::warning("cannot convert state form %s to %s", _state, NetworkState::NS_LISTEN); } _state = NetworkState::NS_LISTEN; doListen(host, port); } // connecting to host:port void SsNetwork::doConnect(SsNetwork::HostName host, SsNetwork::HostPort port) { SsLogger::info("%s connecting to %s:%d", this, host, port); } // listening on host:port void SsNetwork::doListen(SsNetwork::HostName host, SsNetwork::HostPort port) { SsLogger::info("%s listening on %s:%d", this, host, port); } // from server accept a new client SsNetwork::ConnectingTuple SsNetwork::accept() { Descriptor client; auto address = std::make_shared<SsNetwork::Address>(); #if defined(__platform_linux__) socklen_t length = sizeof(SsNetwork::Address); #elif defined(__platform_windows__) int length = sizeof(SsNetwork::Address); #endif if (_state != NetworkState::NS_LISTEN) { SsLogger::error("accept client from non-listening network"); return {INVALID_DESCRIPTOR, address}; } client = ::accept(getDescriptor(), (sockaddr*) address.get(), &length); if (client == INVALID_DESCRIPTOR || client < 0) { SsLogger::error("accept connection error from %s", this); } return {client, address}; } // network toString and output std::ostream &operator<<(std::ostream &o, SsNetwork *network) { o << "SsNetwork[" << "descriptor=" << network->_descriptor << "," << "family=" << network->_family << "," << "type=" << network->_type << "," << "state=" << network->_state << "]"; return o; } // network family output std::ostream &operator<<(std::ostream &o, SsNetwork::NetworkFamily &family) { switch (family) { case SsNetwork::NetworkFamily::NF_INET_4: o << "INET4"; break; case SsNetwork::NetworkFamily::NF_INET_6: o << "INET6"; break; } return o; } // network type output std::ostream &operator<<(std::ostream &o, SsNetwork::NetworkType &type) { switch (type) { case SsNetwork::NetworkType::NT_TCP: o << "TCP"; break; case SsNetwork::NetworkType::NT_UDP: o << "UDP"; break; case SsNetwork::NetworkType::NT_RAW: o << "RAW"; break; } return o; } // network state output std::ostream &operator<<(std::ostream &o, SsNetwork::NetworkState &state) { switch (state) { case SsNetwork::NetworkState::NS_NONE: o << "NONE"; break; case SsNetwork::NetworkState::NS_LISTEN: o << "LISTEN"; break; case SsNetwork::NetworkState::NS_ESTABLISHED: o << "ESTABLISHED"; break; } return o; } <file_sep>/src/server/server.cc #include <iostream> #include <cstdlib> #include "ss_config.h" void atExitHandler() { std::cout << "atExitHandler" << std::endl << std::flush; } int main(int argc, char *argv[]) { std::cout << APPLICATION_NAME << std::endl; std::cout << std::atexit(atExitHandler); return 0; } <file_sep>/src/lib/ss_exception.cc #include "shadowsocks/ss_exception.h" // SsException constructor SsException::SsException(SsLogger::LoggerLevel level, std::string message): std::runtime_error(message) { SsLogger::log(level, message.c_str()); } // SsException constructor SsException::SsException(SsLogger::LoggerLevel level, std::string &&message): std::runtime_error(message) { SsLogger::log(level, what()); } <file_sep>/src/lib/network/ss_tcp_network.cc #include "shadowsocks/network/ss_tcp_network.h" // SsTcpNetwork constructor SsTcpNetwork::SsTcpNetwork(SsNetwork::NetworkFamily family) : SsNetwork(family, NetworkType::NT_TCP) { } // SsTcpNetwork constructor SsTcpNetwork::SsTcpNetwork(SsNetwork::Descriptor descriptor, SsNetwork::Address address) : SsNetwork(descriptor, address, NetworkType::NT_TCP) { } // accept new connecting SsNetwork::ConnectingTuple SsTcpNetwork::accept() { return SsNetwork::accept(); } // connecting to host:port via TCP void SsTcpNetwork::doConnect(SsNetwork::HostName host, SsNetwork::HostPort port) { SsNetwork::doConnect(host, port); } // listening to host:port via TCP void SsTcpNetwork::doListen(SsNetwork::HostName host, SsNetwork::HostPort port) { SsNetwork::doListen(host, port); } <file_sep>/include/shadowsocks/ss_selector.h #ifndef __SHADOWSOCKS_SELECTOR_INCLUDED__ #define __SHADOWSOCKS_SELECTOR_INCLUDED__ #include "shadowsocks/ss_types.h" #if defined(__platform_linux__) #define SELECTOR_EVENT_IN POLLIN #define SELECTOR_EVENT_OUT POLLOUT #elif defined(__platform_windows__) #define SELECTOR_EVENT_IN 1 #define SELECTOR_EVENT_OUT 2 #endif class SsSelector { public: enum class SelectorEvent : uint8_t { SE_READABLE = SELECTOR_EVENT_IN, SE_WRITABLE = SELECTOR_EVENT_OUT }; enum class SelectorState : uint8_t { SS_TIMEOUT = 0xff, SS_SUCCESS = 0x00, SS_FAILURE = 0x01 }; using SelectorEvents = std::initializer_list<SelectorEvent>; #if defined(__platform_linux__) using Descriptor = int; #elif defined(__platform_windows__) using Descriptor = SOCKET; #endif using SelectResult = std::pair< SelectorState, std::vector<std::pair<Descriptor, std::pair<bool, bool>>> >; public: SsSelector(); ~SsSelector(); void add(Descriptor descriptor, SelectorEvents events); void remove(Descriptor descriptor); void movify(Descriptor descriptor, SelectorEvents events); SelectResult select(int timeout); private: bool descriptorExists(Descriptor &descriptor); private: #if defined(__platform_linux__) std::vector<pollfd> _objects; #elif defined(__platform_windows__) std::map<Descriptor, uint8_t> _objects; #endif }; #endif // __SHADOWSOCKS_SELECTOR_INCLUDED__
077de2a2a2d8a619c070556343276e2eca079bb2
[ "C++" ]
19
C++
niewenlong/shadowsocks
57e9be85349e30134058657f07b1441bcd55b441
0ddcb3f7895b225fc672af613df1d21daf1d650c
refs/heads/master
<repo_name>AmjedHizran/angular-mission<file_sep>/src/app/app-routing.module.ts import { Routes, RouterModule } from "@angular/router"; import { HomeComponent } from "./home/home.component"; import { CountryListComponent } from "./country-list/country-list.component"; import { NgModule } from "@angular/core"; const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'countries', component: CountryListComponent } ]; const appRouter = RouterModule.forRoot(routes); @NgModule({ imports: [appRouter] }) export class AppRoutingModule { }<file_sep>/src/app/shared/pipe/filter.pipe.ts import { Pipe, PipeTransform, Injectable } from '@angular/core'; import { Country } from '../models/country.model'; @Pipe({ name: 'filtered' }) @Injectable() export class FilterPipe implements PipeTransform { transform(countries: any[], field: string, value: string): any[] { if (!countries) {return [];} if (!field || !value) {return countries;} return countries.filter(country => country[field].toLowerCase().includes(value.toLowerCase())); } }<file_sep>/src/app/shared/models/country.model.ts export class Country { constructor(public name: string, public nativeName: string, public capital: string, public population: number, public flag: string) { } } <file_sep>/src/app/shared/services/country.service.ts import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Country } from "../models/country.model"; @Injectable() export class CountryService { constructor(private http: HttpClient) { } public getCountry(callback: (countries: Country[]) => void): void { this.http.get("https://restcountries.eu/rest/v2/all") .subscribe(callback); } public getCountries(id:number, callback: (country: Country) => void): void{ this.getCountry(country => { for(let i = 0; i < country.length; i++){callback(country[id]);}}); } }
32e278e2b7a4805c13c2142a4760ee3a010d7c7f
[ "TypeScript" ]
4
TypeScript
AmjedHizran/angular-mission
02d47c09a477cb55b918b5b98ec087126d26d588
a2852d7f9017a387afacc58b7243e68bdbf0f510
refs/heads/main
<repo_name>karasalihovicAmela/sfg-pet-clinic<file_sep>/sfg-pet-clinic/pet-clinic-data/src/main/java/com/amela/sfgpetclinic/services/PetService.java package com.amela.sfgpetclinic.services; import com.amela.sfgpetclinic.model.Pet; public interface PetService extends CrudService<Pet, Long>{ } <file_sep>/sfg-pet-clinic/pet-clinic-web/src/test/java/com/amela/sfgpetclinic/SfgPetClinicApplicationTest.java package com.amela.sfgpetclinic; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; @RunWith(JUnitPlatform.class) @SpringBootTest class SfgPetClinicApplicationTest { @Test void main() { } }<file_sep>/sfg-pet-clinic/pet-clinic-web/src/main/resources/application.properties spring.banner.image.location=original.jpg spring.messages.basename=messages/messages spring.profiles.active=springdatajpa<file_sep>/sfg-pet-clinic/pet-clinic-data/src/main/java/com/amela/sfgpetclinic/repositories/VetRepostory.java package com.amela.sfgpetclinic.repositories; import com.amela.sfgpetclinic.model.Vet; import org.springframework.data.repository.CrudRepository; public interface VetRepostory extends CrudRepository<Vet, Long> { } <file_sep>/sfg-pet-clinic/pet-clinic-data/src/main/java/com/amela/sfgpetclinic/services/SpecialtyService.java package com.amela.sfgpetclinic.services; import com.amela.sfgpetclinic.model.Specialty; public interface SpecialtyService extends CrudService<Specialty, Long> { }
9c09728bec6822fea4e7c2a66339aced7f088dcf
[ "Java", "INI" ]
5
Java
karasalihovicAmela/sfg-pet-clinic
30607769a7f1e451e920430836621c4fbf526244
d256de3f7a4fa9725bef652f2247032e094c4265
refs/heads/master
<repo_name>wolf10D/Prueba-seleccion-akelab<file_sep>/src/components/badge.js // import React from 'react'; // import './styles/Badge.css' // import confLogo from '../images/badge-header.svg'; // class Badge extends React.Component{ // render(){ // const{ // fristName, // lastName, // jobTitle, // twitter, // avatar // }=this.props // return <div className="Badge"> // <div className="Badge__header"> // <img src={confLogo} alt="Logo de la imagen"></img> // </div> // <div className="Badge__section-name"> // <img // className="Badge__avatar" // src={avatar} // alt="Avatar"></img> // <h1>{fristName}<br/>{lastName}</h1> // </div> // <div className="Badge__section-info"> // <h3>{jobTitle}</h3> // <div>{!twitter ? '' : `@${twitter}`}</div> // </div> // <div className="Badge__footer"> // #platziconf // </div> // </div>; // } // } // export default Badge;<file_sep>/src/action/usuariosAction.js import axios from "axios" export const traerTodos = () => async (dispatch) =>{ const respuesta = await axios.get('http://localhost:6969/results') dispatch({ type: 'traer_usuarios', payload: respuesta.data }) }<file_sep>/src/pages/Badges.js import React from 'react'; import './styles/Badges.css'; import Navbar from '../components/Navbar'; import BadgesList from '../components/BadgesList'; class Badges extends React.Component{ state = { data: [ { id: '2de30c42-9deb-40fc-a41f-05e62b5939a7', firstName: 'Ren', lastName: 'goku', email: '<EMAIL>', jobTitle: 'Pilar Llama', twitter: 'RenGokuDemon', avatarUrl: 'https://64.media.tumblr.com/0fb2d85890c158b0f25cd43ede54c54d/7203d54e1b0c611b-63/s540x810/542177e234e434672cc49c34cad34d00e3ee8c67.jpg', }, { id: 'd00d3614-101a-44ca-b6c2-0be075aeed3d', firstName: 'Zet', lastName: 'nitsu', email: '<EMAIL>', jobTitle: 'Cazador', twitter: 'Zetnitsu666', avatarUrl: 'https://i.pinimg.com/736x/47/e4/c2/47e4c2cb5c2faf164902c4ba52bd5f75.jpg', }, { id: '63c03386-33a2-4512-9ac1-354ad7bec5e9', firstName: 'Kim', lastName: 'etsu', email: '<EMAIL>', jobTitle: 'Pilar Sonido', twitter: 'KimetsuSonido', avatarUrl: 'https://i.pinimg.com/originals/d0/e8/b4/d0e8b4a7183818cc80feed04e7662162.png', }, ] } render(){ return( <div> <Navbar /> {/* <div className="Badges"> <div className="Badges__hero"> <div className="Badges__container"> </div> </div> </div> */} <BadgesList /> {/* <div className="Badge__container"> <div className="Badges__buttons"> </div> <div className="Badge__list"> <div className="Badge__conatiner"> <BadgesList badges={this.state.data}/> </div> </div> </div> */} </div> ) } } export default Badges <file_sep>/README.md # Introducción a la aplicación Prueba de akelab Este proyecto se inició con la aplicación [Create React App](https://github.com/facebook/create-react-app). ## Tabla de contenido 1. [Fork](#Fork). 2. [Comandos](#iniciar-proyecto). 3. [Pagina web](#sobre-la-pagina). 4. [Fibonacci](#Fibonacci). 5. [Akelab](#Akelab). ### 🔄 Fork Comienza haciendo Fork a este Repositorio y corriendolo con los siguientes comandos 👇 ### 👨‍💻iniciar-proyecto #### `npm run start` Para ejecutar la aplicación usamos en la terminal `npm run star` este correra en el [http://localhost:3000](http://localhost:3000) y nos mostrara el proyecto #### `npm run servers` la aplicación hace llamdos a un servidor local hecho en JSONserver por lo cual es necesario iniciar en una segunda terminal el comando `npm run servers` este correra en el [http://localhost:6969](http://localhost:6969) ### 🧐sobre-la-pagina Esta pagina es una SPA hecha en **React.JS** sobre datos de peliculas clasicas en la que puedes ver - titulos pelicuas - poster de la pelicula - una breve descripción de la pelicula - calificación en estrellas - genero - fecha de estreno Toda los datos son traidos de un archivo JSON desde un servidro local por esto para interactuar con el proyecto debes estar en [http://localhost:3000/](http://localhost:3000) ### 🔢Fibonacci Una vez estes en el [http://localhost:3000/](http://localhost:3000) podras ver dos botones `Akelab` y `fibonacci` que se hicieron con react router para una mejor velocidad, si le das click en fibonacci podras interactuar con un input donde puedes digitar cualquier numero y este te dara el resultado de la suma Fibonacci ### ⚙Akelab Una vez este en el [http://localhost:3000/](http://localhost:3000) podras ver dos botones `Akelab` y `fibonacci` que se hicieron con react router para una mejor velocidad, si le das click en Akelab podras interactuar con un boton `NEXT` donde dependiendo si el numero es multiplo de 3 mostrara AKE si es multiplo de 5 mostrara LAB y si el numero es multiplo de 3 y 5 mostrara AKELAB <file_sep>/src/components/BadgesList.js import React, {Component} from 'react'; import { connect } from 'react-redux'; import './styles/BadgesList.css'; import Calification from '../images/icons/Star 3.png' import Calification2 from '../images/icons/Star 5.png' import * as usuariosAction from '../action/usuariosAction'; import axios from 'axios'; class BadgesList extends Component{ componentDidMount(){ this.props.traerTodos() } ponerFilas = () => this.props.usuarios.map((usuario) =>( <tr key={usuario.id}> {usuario ? (<div className="card__container"> <h6>{usuario.title}({usuario.release_date})</h6> <div className="card_content"> <div className="card__image"> <img src={usuario.poster_path} alt="Card image cap"/> </div> <div className="card-body card__text"> <p className="card-text description">{usuario.overview}</p> <div className="list_card-text"> <p><strong>Titulo: </strong> {usuario.original_title}</p> <div className="calification"> <p><strong>Calificación:</strong> {usuario.vote_average}</p> <img src={Calification}/> <img src={Calification}/> <img src={Calification}/> <img src={Calification2}/> <img src={Calification2}/> </div> <p><strong>Genero:</strong> {usuario.genre_ids}</p> <p><strong>Fecha de realización:</strong> {usuario.release_date}</p> </div> </div> </div> </div>) : null} </tr> )); render(){ console.log(this.props) return( <div className="json__container"> {this.ponerFilas()} </div> ) } } const mapStateToProps = (reducers) => { return reducers.usuarioReducer; } export default connect(mapStateToProps, usuariosAction)(BadgesList)
50b8340e4c9b11608372c1c8bded29f3d9e698ee
[ "JavaScript", "Markdown" ]
5
JavaScript
wolf10D/Prueba-seleccion-akelab
59e701626cd6dd6b4f7f2bc906cc31b3451091d5
7001e6a0b3767bb33c3a8abe7c97c14c435939af
refs/heads/master
<repo_name>SarahLN/hybridapp-CYBR8480<file_sep>/app/components/netwk-status.js import Component from '@ember/component'; import { later } from '@ember/runloop'; export default Component.extend({ status: 'init', on: true, init: function() { //determine network status upon component launch this._super(...arguments); this.getNtwkStatus(this); }, getNtwkStatus(component) { later(function() { try { var states = {}; states[Connection.UNKNOWN] = 'Unknown connection'; states[Connection.ETHERNET] = 'Ethernet connection'; states[Connection.WIFI] = 'WiFi connection'; states[Connection.CELL_2G] = 'Cell 2G connection'; states[Connection.CELL_3G] = 'Cell 3G connection'; states[Connection.CELL_4G] = 'Cell 4G connection'; states[Connection.CELL] = 'Cell generic connection'; states[Connection.NONE] = 'No network connection'; var conn = navigator.connection.type; component.set('status', states[conn]); } catch(err) { console.log('error: ' + err); } if(component.get('on')){ //keep running component.getNtwkStatus(component); //recurse } }, 100); } });
b0bef2b6c65fcaed5786a061cb17c61365381a58
[ "JavaScript" ]
1
JavaScript
SarahLN/hybridapp-CYBR8480
6473cf623b3ebc7a3118539d7ba2225819a6d6e2
f376d01a4b8a87135a3c7a4898a5e3d5db1021f9
refs/heads/master
<repo_name>Harrysibbenga/DjangoAuth<file_sep>/accounts/views.py from django.shortcuts import render, redirect, reverse from django.contrib import auth, messages # Create your views here. def index(request): # Return the index.html template return render(request, 'index.html') def logout(request): # Logout the user auth.logout(request) messages.success(request, 'You have been logged out') return redirect(reverse('index'))
0f58e2972b25056fd8ec8c8a559521a49936a3f3
[ "Python" ]
1
Python
Harrysibbenga/DjangoAuth
175994b54f969fec3a6601133d31081a55689999
cf75f1774de0aecd3f4bf33c29139e87f34f91e9
refs/heads/main
<file_sep>import React, { Component } from "react" import ReactDOM from "react-dom"; import * as THREE from "three" class App extends Component { componentDidMount(){ // === THREE.JS CODE START === let scene = new THREE.Scene(); let camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 ); let renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); // document.body.appendChild( renderer.domElement ); this.mount.appendChild( renderer.domElement ); let geometry = new THREE.BoxGeometry( 1, 1, 1 ); let material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); let cube = new THREE.Mesh( geometry, material ); scene.add( cube ); camera.position.z = 5; let animate = function () { requestAnimationFrame( animate ); cube.rotation.x += 0.01; cube.rotation.y += 0.01; renderer.render( scene, camera ); }; animate(); // === THREE.JS EXAMPLE CODE END === } render(){ return ( <div ref={ref=> (this.mount = ref)} /> ) } } const container = document.getElementById("container"); ReactDOM.render(<App />, container); <file_sep>### Description: The template include - React - Three bundled with webpack ### Run ``` npm install npm build npm run ```
b8a475bccded778c0b0b3ac0c850ea1c2197b1c8
[ "JavaScript", "Markdown" ]
2
JavaScript
draibolit/react_three-template
00509f1e15c6b3950bf023d2cf4013b6a64e86e2
14d106b1d7581f09615a34bc21c8d9b8a9233c21
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlayerMover : MonoBehaviour { [SerializeField] private float _speed; private float _currentSpeed; private void Start() { _currentSpeed = _speed; } private void Update() { float horizontalDirection = Input.GetAxis("Horizontal"); float verticalDirection = Input.GetAxis("Vertical"); if (horizontalDirection != 0 || verticalDirection != 0) Move(horizontalDirection, verticalDirection); } private void Move(float horizontalDirection, float verticalDirection) { Vector3 direction = new Vector3(horizontalDirection, verticalDirection); transform.Translate(direction * Time.deltaTime * _currentSpeed); } public void SpeedUp() { _currentSpeed += _speed; } public void SpeedDown() { _currentSpeed -= _speed; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyMover : MonoBehaviour { [SerializeField] private float _radius; [SerializeField] private float _speed; private Vector3 _targetPosition; void Start() { GenerateTarget(); } private void Update() { Move(_targetPosition); if (Vector3.Distance(transform.position, _targetPosition) == 0) GenerateTarget(); } public void Move(Vector3 target) { transform.position = Vector3.MoveTowards(transform.position, target, _speed * Time.deltaTime); } private void GenerateTarget() { _targetPosition = Random.insideUnitCircle * _radius; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Timer : MonoBehaviour { private float _interval; private UnityAction _timeEnded; public bool IsFinished => _interval <= 0; public Timer(float interval, UnityAction timeEndedHandler) { _interval = interval; _timeEnded += timeEndedHandler; } public void Tick(float deltaTime) { _interval -= deltaTime; if (IsFinished) { _timeEnded?.Invoke(); _timeEnded = null; } } private void OnDisable() { _timeEnded = null; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Timers : MonoBehaviour { private List<Timer> _timers; private void Start() { _timers = new List<Timer>(); } private void Update() { foreach (Timer timer in _timers) timer.Tick(Time.deltaTime); _timers.RemoveAll(t => t.IsFinished); } public void Add(float interval, UnityAction timeEndedHandler) { Timer timer = new Timer(interval, timeEndedHandler); _timers.Add(timer); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class EnemyDeathTrigger : PlayerDistanceChecker { public event UnityAction<EnemyDeathTrigger> Died; protected override void CollisionHandle() { Died?.Invoke(this); } } <file_sep>using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class GameOverChecker : MonoBehaviour { [SerializeField] private GameObject _endPanel; [SerializeField] private PlayerMover _player; private List<EnemyDeathTrigger> _enemyList; private void OnEnable() { _enemyList = FindObjectsOfType<EnemyDeathTrigger>().ToList(); foreach (var enemy in _enemyList) enemy.Died += OnEnemyDied; } private void OnDisable() { foreach (var enemy in _enemyList) enemy.Died -= OnEnemyDied; } private void OnEnemyDied(EnemyDeathTrigger enemy) { _enemyList.Remove(enemy); if (_enemyList.Count == 0) { _player.enabled = false; ShowEndScreen(); } } public void ShowEndScreen() { _endPanel.SetActive(true); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public abstract class PlayerDistanceChecker : MonoBehaviour { [SerializeField] protected PlayerMover _player; private void Update() { if (Vector3.Distance(_player.transform.position, transform.position) < 0.2f) { CollisionHandle(); Destroy(gameObject); } } protected abstract void CollisionHandle(); } <file_sep>using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpeedUpActivator : PlayerDistanceChecker { [SerializeField] private Timers _timer; [SerializeField] private float _interval; protected override void CollisionHandle() { _timer.Add(_interval, _player.SpeedDown); _player.SpeedUp(); } }
47767c3fedfb53fd4fbf2946080c996f3fa06614
[ "C#" ]
8
C#
BatDen52/SHK-Unity-fork
b000bb0f489f49840c3280f0d028c8a369ec1df3
9c90ea3c63b4935e83da84cb80f374c1607b5693
refs/heads/master
<file_sep>const express = require("express"); const bookRouter = express.Router(); const bookController = require("../controllers/bookController"); const { getIndex, getById } = bookController; bookRouter.get("/:id", function (req, res) { const { id } = req.params; getById; }); bookRouter.get("/", function (req, res) { res.send(getIndex); }); module.exports = bookRouter; <file_sep>const debug = require("debug")("app:bookController"); const { MongoClient, ObjectID } = require("mongodb"); module.exports = function bookController() { function getIndex(req, res) { const url = "mongodb://localhost:27017"; const dbName = "libraryApp"; (async function mongo() { let client; try { client = await MongoClient.connect(url); debug("connected to db"); const db = client.db(dbName); const col = await db.collection("books"); const books = await col.find().toArray(); return books; } catch (error) { debug(error.stack); } })(); } function getById(req, res, id) { const url = "mongodb://localhost:27017"; const dbName = "libraryApp"; (async function mongo() { let client; try { client = await MongoClient.connect(url); debug("connected to db"); const db = client.db(dbName); const col = await db.collection("books"); const book = await col.findOne({ _id: new ObjectID(id) }); debug(book); return book; } catch (error) { debug(error.stack); } })(); } return getIndex, getById; }; <file_sep>const express = require("express"); const { MongoClient } = require("mongodb"); const adminRouter = express.Router(); const debug = require("debug")("app:adminRoutes"); adminRouter.get("/", function (req, res) { const url = "mongodb://localhost:27017"; const dbName = "libraryApp"; (async function mongo() { let client; try { client = await MongoClient.connect(url); debug("connected to db"); const db = client.db(dbName); const books = [ { author: "<NAME>", country: "Nigeria", imageLink: "images/things-fall-apart.jpg", language: "English", link: "https://en.wikipedia.org/wiki/Things_Fall_Apart\n", pages: 209, title: "Things Fall Apart", year: 1958, }, { author: "<NAME>", country: "Denmark", imageLink: "images/fairy-tales.jpg", language: "Danish", link: "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.\n", pages: 784, title: "Fairy tales", year: 1836, }, { author: "<NAME>", country: "Italy", imageLink: "images/the-divine-comedy.jpg", language: "Italian", link: "https://en.wikipedia.org/wiki/Divine_Comedy\n", pages: 928, title: "The Divine Comedy", year: 1315, }, ]; const response = await db.collection("books").insertMany(books); return response; } catch (error) { debug(error); } })(); }); module.exports = adminRouter;
81368504caf73c56291da26c39fa8e13233b0005
[ "JavaScript" ]
3
JavaScript
andresmanzanaressouthworks/express-course
611eeadeb7023171198ffbfd6273972be12e4c12
968851cfb533713180dc6c0b73f6b7babce49188
refs/heads/master
<file_sep>USE BDICDM; INSERT INTO status (sta_ds) VALUES ('Aguardando pagamento'), ('Em análise'), ('Paga'), ('Disponível'), ('Em disputa'), ('Devolvida'), ('Cancelada')
b51dd59d241f441b2d741aae53a5d9991da72139
[ "SQL" ]
1
SQL
laissiles/bdic-dm
a33edd7e00f6fec9d059c37939dde136bff11988
79ebb764901f0abe0448fad6e639e1217bafa1a1
refs/heads/master
<repo_name>enconta/widget-front<file_sep>/README.md # Enconta Proyecto de front-end para el cliente de **Enconta**. [![Build Status](https://enconta.semaphoreci.com/badges/enconta-frontend.svg?key=4e3d89bf-9e43-4f7d-bbe3-5873f49f576d)](https://enconta.semaphoreci.com/projects/enconta-frontend) ## Metas - Administrar únicamente el front-end, servido como SPA. - Comunicarse con la API REST ofrecida por **[Enconta](https://github.com/enconta/enconta-app)**. - Proveer un entorno claro de desarollo. - Tener código claro y bien documentado. - Crear componentes independientes y modulares. ## Motivación **Enconta** es una app muy grande que busca: - **Disminución de costos**: los costos de servicios son muy altos, pueden ser disminuidos significativamente si se optimiza adecuadamente la app. - **Más rapidez**: es muy lenta, hay cosas que por naturaleza son lentas pero podemos quitarle el peso de la vista y hacerla mucho más rápida. - **Menor frustración**: muchas de las cosas no necesitan comunicación al servidor, se ahorraría el _90%_ de tiempo con validaciones locales para estas. - **Mejores resultados**: se aprovecharía mejor el tiempo de los contadores, pasarían menos tiempo esperando a la app y más tiempo produciendo. ## Características - [Node.js](https://nodejs.org/en/) - [Babel / ES2015](https://babeljs.io/docs/learn-es2015) - [React](https://github.com/facebook/react) / [React Router](https://github.com/reactjs/react-router) - [Standard](http://standardjs.com/) - [ESLint](https://eslint.org/docs/user-guide/integrations) - [Husky](https://github.com/typicode/husky) - [hotjar](https://www.hotjar.com) ## Guía de Instalación Realiza los pasos indicados en el archivo [INSTALLATION](INSTALLATION.md) y, de ser necesario, resolver los posibles problemas presentados antes de continuar. ## Ejecución ```shell make start ``` Ahora se puede visitar el proyecto en <http://localhost:3000> o bien <http://0.0.0.0:3000> **NOTA**: El puerto puede cambiar dependiendo de la variable de entorno `PORT` establecido en el archivo `.dev`. ## Guía de estilo Se siguen las guías de estilo de [JavaScript Standard Style](http://standardjs.com). Para _autoformatear_ el código se debe integrar [ESLint](https://eslint.org/docs/user-guide/integrations) en el editor, habilitando la opción de arreglar errores al guardar. ## Flujo y razonamiento **React** es una tecnología creada por _Facebook_ para poder hacer el trabajo de front-end de aplicaciones grandes más sano. **React** es una interfaz de JavaScript que tiene como meta hacer que los cambios visuales de una página sean administrados desde una _vista mayor_, esto hace que toda la información salga de un solo lugar y el flujo de datos pueda ser predecible, lo que nos permite saber cual será el resultado de una operación, acción o evento. Esto se logra gracias a que cada componente de **React** tiene un estado (_state_), dicho estado guarda la información que cada componente necesita para operar. **React** puede funcionar de forma independiente pero en éste proyecto está mezclado con: - **Babel**: para poder usar las últimas características del lenguaje (actualmente **[ES6](https://github.com/lukehoban/es6features>)** en navegadores que aúno no lo soportan) - **Webpack**: para poder crear un _servidor web_ de desarollo y construir la versión de producción (para producción todos los componentes de JavaScript se guardan en un solo archivo: `scripts/app.js). El archivo que el servidor cargará es `public/index.html` que contiene una referencia al archivo al que será compilada la aplicación. Los componentes externos se instalan mediante **NPM** según sean para producción o sólo desarollo y **SIEMPRE** deben guardarse en el `package.json`. ### Router El archivo de entrada de **Webpack** y de toda la aplicación es `src/index.js`, éste funciona como un _router_ que decide que componente cargar según la ruta desde la que se está viendo. Para desarollo el router no necesita nada extra, en producción va a necesitar agregar una configuración especial para _Nginx_, _Apache_ o cualquier otro _servidor web_ que indique que las rutas mostradas en ese archivo no corresponden a archivos reales en el servidor si no que necesitan ser cargadas desde el archivo `public/index.html`. <file_sep>/src/components/app/views/editClient/synchronization/index.js import React, { Component, Fragment } from 'react' import { withRouter } from 'react-router' import BanksSynchronizationActions from 'actions/smartsync' import BanksSynchronizationStores from 'stores/smartsync' function getCurrentState () { return { widgetToken: BanksSynchronizationStores.getWidgetToken() } } export class NewBank extends Component { defaultState = {} state = { ...this.defaultState, ...getCurrentState() } componentDidMount () { BanksSynchronizationActions.getWidgetToken() BanksSynchronizationStores.addChangeListener(this._onChange) } componentWillUnmount () { BanksSynchronizationStores.removeChangeListener(this._onChange) BanksSynchronizationActions.clearBank() } _onChange = () => { this.setState(getCurrentState()) } onEventCallbackFunction = data => { // Do something with the event data } onExitCallbackFunction = data => { // Do something with the exit data } successCallbackFunction = (link, institution) => { // Do something with the link_id or institution name } openBelvoWidget = () => { const { widgetToken } = this.state console.log(widgetToken) belvoSDK // eslint-disable-line .createWidget(widgetToken, { locale: 'es', company_name: 'Enconta', // institution: 'bancomer_mx_retail', // to start the widget directly on a specific institution credentials page // institution_types: ['fiscal', 'retail', 'business', 'gig'], // to select the type of institution to show in the widget access_mode: 'recurrent', // to specify the type of link to be created from the widget country_codes: ['MX'], callback: (link, institution) => this.successCallbackFunction(link, institution), onExit: data => this.onExitCallbackFunction(data), onEvent: data => this.onEventCallbackFunction(data) }) .build() } render () { return <Fragment>hola mundo</Fragment> } } export default withRouter(NewBank) <file_sep>/src/components/app/views/notifications/index.js // Libraries import React, { Component } from 'react' import PropTypes from 'prop-types' class Notifications extends Component { constructor (props) { super(props) this.data = { notifications: [] } this.state = Object.assign({}, this.data) } // Get notifications on component mount componentDidMount () { this.getNotifications() } // Get a list of notifications, not from the server yet getNotifications () { let notifications = [ { id: 10, date: '2017-06-17', description: 'Se descargaron 17 facturas nuevas', icon: 'mdi mdi-file-check' }, { id: 9, date: '2017-06-16', description: 'Tus certificados expiran en 7 días', icon: 'mdi mdi-alert' }, { id: 8, date: '2017-06-16', description: 'Se descargaron 4 facturas nuevas', icon: 'mdi mdi-file-check' }, { id: 7, date: '2017-06-16', description: 'Se descargó 1 factura nueva', icon: 'mdi mdi-file-check' }, { id: 6, date: '2017-06-16', description: 'Se descargaron 3 facturas nuevas', icon: 'mdi mdi-file-check' } ] this.setState({ notifications: notifications }) } // Render a list of notifications with icons renderNotifications () { let notifications = ( <p className='notification'>No tienes notificaciones.</p> ) if (this.state.notifications.length > 0) { let renderNotifications = this.state.notifications.map(function ( notification, index ) { return ( <div key={notification.id} className='notificationsList--notification' > <span className='notificationsList--date'>{notification.date}</span> <i className={'notificationsList--icon ' + notification.icon} /> <span className='notificationsList--description'> {notification.description} </span> </div> ) }) notifications = ( <div className='notificationsList'>{renderNotifications}</div> ) } return notifications } // Main render render () { return ( <div> <h1 className='headline'>{this.props.route.title}</h1> <hr /> <h2 className='title is-5'> Tus notificaciones de los últimos 30 días </h2> {this.renderNotifications()} </div> ) } } Notifications.propTypes = { route: PropTypes.shape({ title: PropTypes.string }) } export default Notifications <file_sep>/src/stores/diagnosis.js import BaseStore from './baseStore' class DiagnosisStore extends BaseStore { constructor () { super() this.diagnosis = '' this.url = '' this.userId = '' this.actions = { STATUS_ASKED: action => { this.setDiagnosis(action.data) this.setUrl(action.data.diagnosis) }, ACCOUNT_CREATED: action => { this.setUserId(action.data) }, CLEAR_CURRENT_DIAGNOSIS: () => { this.clearCurrentDiagnosis() } } } getDiagnosis () { return this.diagnosis } setDiagnosis (data) { this.diagnosis = data.diagnosis } setUrl (data) { this.url = data.quote_signed && data.quote_signed.url } getUserId () { return this.userId } setUserId (data) { this.userId = data.user.id } getUrl () { return this.url } clearCurrentDiagnosis () { this.diagnosis = '' } } export default DiagnosisStore.getInstance() <file_sep>/src/api/appStorage/index.js /* * The AppStorage is used to store data in the LocalStorage for its use * even when the page is reloaded/refreshed. * The only way to delete this data is logging out from the app * or manually delete it with the browser tools. * It is encouraged to NOT use this Storage except when it is strictly necessary, * use the app stores instead to manage the application state. */ // Libraries import store from 'store' // Constants // Key names const SESSION_DATA = 'SessionData' const NOTIFICATION_DATA = 'NotificationData' const AppStorage = { // Checks if is there a SessionData key in the local storage, if not, adds it alongside other required keys init () { ;(this.getAllSessionData() && this.getAllNotifications()) || this.clearAll() }, // Inserts empty objects in the keys in the local storage. If there was data in this mentioned keys, it will be lost clearAll () { // Keys that will be cleared let keys = [SESSION_DATA, NOTIFICATION_DATA] keys.map(key => { let emptyObject = {} store.set(key, emptyObject) }) }, // Inserts passed attributes with its data in the passed keyNames without losing previous data insertIntoKey (keyName, attr) { let key = this.getKey(keyName) Object.assign(key, attr) store.set(keyName, key) }, setAuthToken (token) { this.insertIntoKey(SESSION_DATA, { ENCONTA_AUTH_TOKEN: token }) }, setUserData (user) { this.insertIntoKey(SESSION_DATA, { user }) }, setTaxableEntities (taxableEntities) { this.insertIntoKey(SESSION_DATA, { taxableEntities }) }, setCurrentEntity (id) { this.insertIntoKey(SESSION_DATA, { currentEntity: id }) }, // Returns all data from a key getKey (keyName) { return store.get(keyName) }, // Returns passed attribute data from a passed key name getValue (keyName, valueName) { return store.get(keyName)[valueName] }, getAllSessionData () { return this.getKey(SESSION_DATA) }, getAuthToken () { return this.getValue(SESSION_DATA, 'ENCONTA_AUTH_TOKEN') }, getUserData () { return this.getValue(SESSION_DATA, 'user') }, getTaxableEntities () { return this.getValue(SESSION_DATA, 'taxableEntities') }, getCurrentEntity () { return this.getValue(SESSION_DATA, 'currentEntity') }, // Checks if session has an auth token and a user stored, if so returns true hasSession () { this.init() return !!(this.getAuthToken() && this.getUserData()) }, // Notifications // Store notifications setNotifications (notifications) { this.insertIntoKey(NOTIFICATION_DATA, { notifications }) }, // Get all notification info getAllNotifications () { return this.getKey(NOTIFICATION_DATA) }, // Get notifications getNotifications () { return this.getValue(NOTIFICATION_DATA, 'notifications') }, // Initialize notifications as empty object initNotifications () { store.set(NOTIFICATION_DATA, {}) }, // Return false if notifications empty, null or undefined hasNotifications () { return !!this.getNotifications() }, setFeatures (features) { this.insertIntoKey(SESSION_DATA, { features }) }, getFeatures () { return this.getValue(SESSION_DATA, 'features') } } export default AppStorage <file_sep>/src/setupTests.js import 'react-testing-library/cleanup-after-each' import 'jest-dom/extend-expect' import 'jest-canvas-mock' <file_sep>/src/api/plan.js import { Get } from 'api' class Plan { static GetPlanRemainingDays (id) { return Get(`/user_plans/${id}`) } } export default Plan <file_sep>/src/stores/smartsync.js import BaseStore from './baseStore' class BankSynchronization extends BaseStore { constructor () { super() this.current = { institution: '', username: '', password: '' } this.accounts = [] this.synchronizedAccounts = [] this.unsynchronizedAccounts = [] this.hasToIntroduceToken = false this.widgetToken = {} this.actions = { CLEAR_CURRENT_BANK: () => { this.clearCurrentBank() }, BANKS_RECEIVED: action => { this.setBankAccounts(action.data) this.filterSynchronizedAccounts(action.data) }, CLEAR_CURRENT_BANK_ACCOUNTS: () => { this.clearCurrentBankAccounts() }, TOKEN_DEFEATED: action => { this.setTokenInfo() }, WIDGET_TOKEN_RECEIVED: action => { this.setWidgetToken(action.data.token) } } } getCurrent () { return this.current } setBankAccounts (data) { this.accounts = data.accounts } filterSynchronizedAccounts ({ accounts }) { accounts.forEach(account => { if (account.synchronized) { this.synchronizedAccounts.push(account) } else { this.unsynchronizedAccounts.push(account) } }) } getSynchronizedAccounts () { return this.synchronizedAccounts } getUnsynchronizedAccounts () { return this.unsynchronizedAccounts } getAccounts () { return this.accounts } getInfoToken () { return this.hasToIntroduceToken } getWidgetToken () { return this.widgetToken } setTokenInfo () { this.hasToIntroduceToken = true } setWidgetToken ({ access }) { this.widgetToken = access } setCurrent () { this.current = this.current } clearCurrentBank () { this.current = { institution: '', username: '', password: '' } } clearCurrentBankAccounts () { this.accounts = [] this.synchronizedAccounts = [] this.unsynchronizedAccounts = [] } } export default BankSynchronization.getInstance() <file_sep>/src/index.js import React from 'react' import { render } from 'react-dom' import { Router, Route, browserHistory } from 'react-router' import ReactGa from 'react-ga' import EditClient from './components/app/views/editClient' // API import { unregister } from './registerServiceWorker' const $app = document.getElementById('app') const routes = ( <Route> <Route path='/entidades/:id' component={EditClient} tab='entidades' title='Editar Cliente' content='edit' /> <Route path='/entidades' component={EditClient} tab='entidades' title='Editar Cliente' content='list' /> <Route path='/sucursal/nueva' component={EditClient} tab='sucursales' title='Nueva Sucursal' content='edit' /> <Route path='/sucursal/:id' component={EditClient} tab='sucursales' title='Editar Sucursal' content='edit' /> <Route path='/sucursales' component={EditClient} tab='sucursales' title='Editar Cliente' content='list' /> <Route path='/cuentas-de-pago' component={EditClient} tab='cuentas-de-pago' title='Cuentas de Pago' content='list' /> <Route path='/cuenta-de-pago/nueva' component={EditClient} tab='cuentas-de-pago' title='Crear Cuenta Bancaria' content='edit' /> <Route path='/cuenta-de-pago/:id' component={EditClient} tab='cuentas-de-pago' title='Editar Cuenta Bancaria' content='edit' /> <Route path='/cliente/nuevo' component={EditClient} tab='clientes' title='Nuevo Cliente' content='edit' /> <Route path='/cliente/:id' component={EditClient} tab='clientes' title='Editar Cliente' content='edit' /> <Route path='/clientes' component={EditClient} tab='clientes' title='Editar Cliente' content='list' /> <Route path='/' component={EditClient} tab='cuentas-de-pago' title='Sincronización de cuentas automáticas' content='editSecond' /> <Route path='/sincronizacion-finalizada' component={EditClient} tab='cuentas-de-pago' title='Sincronización de cuentas automáticas' content='finished' /> <Route path='/smart-sync' component={EditClient} tab='cuentas-de-pago' title='Sincronización de cuentas automáticas' content='smartSync' /> <Route path='/seleccionar/banco/:bank' component={EditClient} tab='cuentas-de-pago' title='Seleccionar banco' content='continue' /> <Route path='/:bank/editar-cuentas/' component={EditClient} tab='cuentas-de-pago' title='Editar cuentas' content='edit-sync-accounts' /> <Route path='/proveedores' component={EditClient} tab='proveedores' title='Editar Proveedor' content='list' /> <Route path='/proveedor/nuevo' component={EditClient} tab='proveedores' title='Nuevo proveedor' content='edit' exact /> <Route path='/proveedor/:id' component={EditClient} tab='proveedores' title='Editar Proveedor' content='edit' /> <Route path='/empleado/nuevo' component={EditClient} tab='empleados' title='Nuevo Empleado' content='edit' /> <Route path='/empleado/:id' component={EditClient} tab='empleados' title='Editar Empleado' content='edit' /> <Route path='/empleados' component={EditClient} tab='empleados' title='Editar Cliente' content='list' /> {/* * When requesting root route, redirects to Login component * which looks if a session is active in the browser and if so * will replace its own route for /dashboard */} </Route> ) // Initializes Storages for the Ap const onDev = (window.location.hostname === 'localhost' || window.location.hostname === '0.0.0.0') && process.env.API_SERVER !== 'https://api.enconta.com/' // Configure Google Analytics ReactGa.initialize(process.env.GA_TOKEN, { debug: false }) // If we are on dev, do not send the events if (onDev) ReactGa.ga('set', 'sendHitTask', null) // Updates the visited page in Google Analytics function firePageView () { // Get the router object const { router } = this if (!router) return // Get current location with the current params const { location, params } = router let { pathname: currentLocation } = location // Convert param value into param name for (const param in params) { currentLocation = currentLocation.replace(params[param], param) } // Call GA library ReactGa.pageview(currentLocation) } render( <Router onUpdate={firePageView} routes={routes} history={browserHistory} />, $app ) unregister() <file_sep>/src/actions/smartsync.js import AppDispatcher from '../dispatcher' import API from '../api' export default { // Resets the current bank form to its defaults in the store clearBank () { AppDispatcher.handleAction({ actionType: 'CLEAR_CURRENT_BANK' }) }, clearBankAccounts () { AppDispatcher.handleAction({ actionType: 'CLEAR_CURRENT_BANK_ACCOUNTS' }) }, getBelvoBanks (bank) { return API.BanksSynchronization.BankAccounts(bank) .then(response => { AppDispatcher.handleAction({ actionType: 'BANKS_RECEIVED', data: response }) }) .catch(error => { AppSignal.sendError(new Error(error)) throw error }) }, addBank (data) { return API.BanksSynchronization.AddBank(data) }, async askStatus (institution) { let statusRegistration = 'failed' try { const { status } = await API.BanksSynchronization.AskStatus(institution) statusRegistration = status } catch (error) { statusRegistration = 'failed' } return statusRegistration }, getReponseRegister (bank) { return API.BanksSynchronization.GetResponse(bank) .then(response => { AppDispatcher.handleAction({ actionType: 'GET_RESPONSE', data: response }) return response }) .catch(error => { throw error }) }, saveSelectedAccount (data) { return API.BanksSynchronization.SaveSelectedAccount(data) .then(response => { AppDispatcher.handleAction({ actionType: 'ACCOUNT_SELECTED', data: response }) return response }) .catch(error => { throw error }) }, getBankList () { return API.BanksSynchronization.GetBankList() .then(response => { AppDispatcher.handleAction({ actionType: 'SMART_BANK_LIST_RECEIVED', data: response }) return response }) .catch(error => { throw error }) }, tokenDefeated () { AppDispatcher.handleAction({ actionType: 'TOKEN_DEFEATED' }) }, getWidgetToken () { return API.BanksSynchronization.WidgetToken() .then(response => { AppDispatcher.handleAction({ actionType: 'WIDGET_TOKEN_RECEIVED', data: response }) return response }) .catch(error => { throw error }) } } <file_sep>/src/stores/editClient.js import BaseStore from './baseStore' class EditClientStore extends BaseStore { constructor () { super() this.editingEntity = { platform_status: 'demo', address: '', cerFile: '', createdAt: '', active: false, email: '', fielCerFile: null, fielKeyFile: null, id: '', keyFile: '', lastSignInAt: '', legalName: '', logo: '', rfc: '' } this.actions = { ENTITY_DATA_RECEIVED: action => { this.setEditingEntity(action.data) }, CLEAR_EDITING_ENTITY: () => { this.clearEditingEntity() } } } getEditingEntity () { return this.editingEntity } setEditingEntity (data) { this.editingEntity = this.camelCase(data.taxable_entity) } clearEditingEntity () { this.editingEntity = { platform_status: 'demo', address: '', cerFile: '', createdAt: '', active: false, email: '', fielCerFile: null, fielKeyFile: null, id: '', keyFile: '', lastSignInAt: '', legalName: '', logo: '', rfc: '' } } } export default EditClientStore.getInstance() <file_sep>/src/stores/baseStore.js import { EventEmitter } from 'events' import { camelCase } from 'utils' import AppDispatcher from '../dispatcher' class BaseStore extends EventEmitter { constructor () { super() this.registeredActions = {} this.camelCase = object => camelCase(object) } // Emits the string 'change' using the method emit(), it is part of the EventEmitter library emitChange () { this.emit('change') } // Method used when components mount to attach a callback function when the emmiter emmits the string 'change' addChangeListener (callback) { this.on('change', callback) } // Method used when components unmount to unattach the callback function and avoid memory leaks removeChangeListener (callback) { this.removeListener('change', callback) } // Static method used to create new Stores, it instatiates this BaseStore, // iterates over the child class actions and registers its own actions to the Dispatcher, // and then returns the new Instance (the new Store) static getInstance () { let ClassName = this this.instance = new ClassName() this.instance.registerAll() return this.instance } // Register all actions to Dispatcher registerAll () { let actions = Object.keys(this.actions) actions.forEach(key => { let action = this.actions[key] // Keep the reference action each action handler this.registeredActions[key] = AppDispatcher.register(payload => { let data = payload.action let actionType = data.actionType if (actionType !== key) { return true } // Invoke callback and emit change in the store only when the keys match let triggerChange = action.call(this, data) // Allow the callback to return false to avoid triggering change event if (triggerChange !== false) { this.emitChange() } return true }) }) } } export default BaseStore <file_sep>/src/stores/invoices.js import BaseStore from './baseStore' import moment from 'moment' class InvoicesStore extends BaseStore { constructor () { super() this.incomes = { invoices: [], totalPages: 1, currentPage: 1, totalItems: 0 } this.expenses = { invoices: [], totalPages: 1, currentPage: 1, totalItems: 0 } this.payroll_expenses = { invoices: [], totalPages: 1, currentPage: 1, totalItems: 0 } this.products = [] this.units = [] this.cancelationStatus = false this.dateTime = moment() this.remainingInvoices = 0 this.time = { hour: '', minute: '' } this.originalDateTime = moment().utc() this.invoice = {} this.actions = { INVOICES_RECEIVED: action => { this.setInvoices(action) }, USED_DATA_RECEIVED: action => { this.setProducts(action.data) this.setUnits(action.data) }, INVOICE_DATA_RECEIVED: action => { this.setInvoiceInformation(action.data) } } } // Returns stored total pages, this is used when explicitly you want to know it getTotalPages (invoiceType) { return this[invoiceType].totalPages } // Returns stored total pages, this is used when explicitly you want to know it getTotalItems (invoiceType) { return this[invoiceType].totalItems } // Returns stored current page, this is used when explicitly you want to know it getCurrentPage (invoiceType) { return this[invoiceType].currentPage } // Returns stored invoice list, this is used when explicitly you want to know it getInvoices (invoiceType) { return this[invoiceType].invoices } // Sets the invoice list from the data received from the api setInvoices (action) { let { invoiceType, data } = action this[invoiceType] = { invoices: data.invoices, totalPages: data.pagination.total_pages, currentPage: data.pagination.current_page, totalItems: data.pagination.total_items } } setProducts ({ products }) { this.products = products } getProducts () { return this.products } setUnits ({ units }) { this.units = units } getUnits () { return this.units } setInvoiceInformation ({ new_invoice: newInvoice }) { const { current_datetime: currentDateTime, next_folio: nextFolio, next_serie: nextSerie, remaining_invoices: remainingInvoices } = newInvoice this.dateTime = moment.utc(currentDateTime) this.remainingInvoices = remainingInvoices this.time['hour'] = this.dateTime.format('HH') this.time['minute'] = this.dateTime.format('mm') this.invoice = { folio: nextFolio !== '' ? nextFolio : '0001', series: nextSerie !== '' ? nextSerie : 'A', issue_date: moment.utc(currentDateTime), comments: '', exchange_rate: '1.0', currency: 'MXN', voucher_type: '' } this.originalDateTime = moment.utc(currentDateTime) } getDateTime () { return this.dateTime } getRemainingInvoices () { return this.remainingInvoices } getTime () { return this.time } getInvoice () { return this.invoice } getOriginalDateTime () { return this.originalDateTime } } export default InvoicesStore.getInstance() <file_sep>/src/components/app/index.js /* eslint-disable */ import React from 'react' import PropTypes from 'prop-types' import DocumentTitle from 'react-document-title' import {browserHistory} from 'react-router' import AppSignal from 'appsignal' import {ErrorBoundary} from '@appsignal/react' import {getCurrentServer, isWarningActivated, getClientsPlan} from 'utils' import AppStorage from 'api/appStorage' import classNames from 'classnames' import moment from 'moment-timezone' import ReactGA from 'react-ga' import Topbar from 'shared/topbar' import NotificationsContainer from 'shared/notifications' import AppWideNotification from 'shared/appWideNotification' import Footer from 'shared/footer' import ChatButton from 'shared/appWideNotification/button' import SessionStore from 'stores/session' // prettier-ignore const loadZenDesk = () => { window.zEmbed || (function (e, t) { var n var o var d var i var s var a = [] var r = document.createElement('iframe') ;(window.zEmbed = function () { a.push(arguments) }), (window.zE = window.zE || window.zEmbed), (r.src = 'javascript:false'), (r.title = ''), (r.role = 'presentation'), ((r.frameElement || r).style.cssText = 'display: none'), (d = document.getElementsByTagName('script')), (d = d[d.length - 1]), d.parentNode.insertBefore(r, d), (i = r.contentWindow), (s = i.document) try { o = s } catch (e) { ;(n = document.domain), (r.src = 'javascript:var d=document.open();d.domain="' + n + '";void(0);'), (o = s) } ;(o.open()._l = function () { var e = this.createElement('script') n && (this.domain = n), (e.id = 'js-iframe-async'), (e.src = 'https://assets.zendesk.com/embeddable_framework/main.js'), (this.t = +new Date()), (this.zendeskHost = 'enconta.zendesk.com'), (this.zEQueue = a), this.body.appendChild(e) }), o.write('<body onload="document._l();">'), o.close() })() // eslint-disable-line } const App = props => { let title = props.children.props.route.title ? `${props.children.props.route.title} - Enconta` : 'Enconta' const plan = getClientsPlan() const isVisibleZenDesk = plan !== 'free' && plan !== 'free_premium' && getCurrentServer() === 'production' if (isVisibleZenDesk) { loadZenDesk() } const currentEntity = SessionStore.getCurrentEntity() const {legal_type: legalType, rfc, email} = currentEntity const warning = isWarningActivated() const displayChatbutton = legalType === 'individual' && plan === 'integral_service' moment.tz.setDefault('America/Mexico_City') if (!email.includes('@enconta.com') && !email.includes('@resuelve.mx')) { ReactGA.set({dimension4: rfc}) ReactGA.set({dimension5: plan}) ReactGA.set({dimension6: email}) } return ( <ErrorBoundary instance={AppSignal} fallback={() => { browserHistory.push('/500') }} > <DocumentTitle title={title}> <div className='app-content'> <Topbar pathname={props.location.pathname} /> <div className={classNames('main-container', { 'main-container--warning-active': warning })} > <div className='main-container__children'> <AppWideNotification /> {props.children} </div> <Footer /> </div> {displayChatbutton && <ChatButton />} <NotificationsContainer /> </div> </DocumentTitle> </ErrorBoundary> ) } App.propTypes = { children: PropTypes.element, location: PropTypes.shape({ pathname: PropTypes.string }) } export default App <file_sep>/src/components/app/views/editClient/index.js import React, { Component } from 'react' import PropTypes from 'prop-types' import NewBank from './synchronization' import SessionStore from 'stores/session' function getCurrentState () { return { checkFeature: SessionStore.getFeatures() } } class EditClient extends Component { state = { ...getCurrentState() } componentDidMount () { SessionStore.addChangeListener(this._onChange) } componentWillUnmount () { SessionStore.removeChangeListener(this._onChange) } _onChange = () => { this.setState(getCurrentState()) } render () { let content = null let button = null switch (this.props.route.tab) { case 'cuentas-de-pago': switch (this.props.route.content) { case 'editSecond': content = <NewBank {...this.props} /> break } break } return ( <div> <div className='flex-between'> <div>{button}</div> </div> <p title={[ { id: 'entidades', label: 'Entidades' }, { id: 'sucursales', label: 'Sucursales' }, { id: 'cuentas-de-pago', label: 'Cuentas Bancarias' }, { id: 'clientes', label: 'Clientes' }, { id: 'empleados', label: 'Empleados' }, { id: 'proveedores', label: 'proveedores' } ]} activeTab={this.props.route.tab} > {content} </p> </div> ) } } EditClient.propTypes = { route: PropTypes.shape({ tab: PropTypes.number, content: PropTypes.element }) } export default EditClient <file_sep>/src/stores/accountingPeriods.js import BaseStore from './baseStore' class AccountingPeriodsStore extends BaseStore { constructor () { super() this.accountingPeriods = [] this.totalPages = 1 this.totalItems = 0 this.currentPage = 1 this.actions = { ACCOUNTING_PERIODS_RECEIVED: action => { this.setAccountingPeriods(action.data) } } } // Returns stored total pages, this is used when explicitly you want to know it getTotalPages () { return this.totalPages } // Returns stored total pages, this is used when explicitly you want to know it getTotalItems () { return this.totalItems } // Returns stored current page, this is used when explicitly you want to know it getCurrentPage () { return this.currentPage } // Returns stored accounting preriod list, this is used when explicitly you want to know it getAccountingPeriods () { return this.accountingPeriods } // Sets the accounting periods list from the data received from the api setAccountingPeriods (data) { this.accountingPeriods = data.accounting_periods this.totalItems = data.pagination.total_items this.totalPages = data.pagination.total_pages this.currentPage = data.pagination.current_page } } export default AccountingPeriodsStore.getInstance() <file_sep>/src/stores/session.js import BaseStore from './baseStore' class SessionStore extends BaseStore { constructor () { super() this.preloginPage = '/dashboard' this.user = { name: '', email: '', role: 'account_holder', keys: false } this.currentEntity = { id: '', rfc: '', legal_name: '', plaform_status: 'demo', active: false } this.taxableEntities = [] this.features = [] this.actions = { PRELOGIN_PAGE_SET: action => { this.setPreloginPage(action.data) }, USER_SET: action => { this.setUser(action.data) }, USER_ENTITIES_RECEIVED: action => { this.setTaxableEntities(action.data) }, CURRENT_ENTITY_SET: action => { this.setCurrentEntity(action.data) }, CLEAR_SESSION: () => { this.clearAll() }, FEATURES_RECEIVED: action => { this.setFeatures(action.data) } } } // Returns stored pre-logon page requested by the user getPreloginPage () { return this.preloginPage } // Returns stored User, this is used when explicitly you want to know it getUser () { return this.user } // Returns stored Current Entity, this is used when explicitly you want to know it getCurrentEntity () { return this.currentEntity } // Returns stored Taxable Entities, this is used when explicitly you want to know it getTaxableEntities () { return this.taxableEntities } // Returns the type of legal entity, it can be individual or business getLegalEntityKind () { return this.getCurrentEntity().legal_type } // Sets the pre-login page requested by the user setPreloginPage (page) { this.preloginPage = page === '/' ? '/dashboard' : page } // Sets the user for the session when succesfully login setUser (user) { this.user = { id: user.id, name: `${user.first_name} ${user.last_name}`, email: user.email, role: user.role, keys: user.keys } } // Sets the available taxable entities for the session setTaxableEntities (taxableEntities) { this.taxableEntities = taxableEntities } // Sets the current taxable entity for the session setCurrentEntity (currentEntity) { this.currentEntity = currentEntity } clearUser () { this.user = { name: '', email: '', role: 'account_holder', keys: false } } // Clears the current entity to the default clearCurrentEntity () { this.currentEntity = { id: '', rfc: '', legal_name: '', plaform_status: 'demo', active: false } } // Clears the available entities to the default clearTaxableEntites () { this.taxableEntities = [] } // Clears all to the default values clearAll () { this.clearUser() this.clearCurrentEntity() this.clearTaxableEntites() } setFeatures ({ features }) { this.features = features } getFeatures () { return this.features } } export default SessionStore.getInstance() <file_sep>/Makefile .DEFAULT_GOAL := help .PHONY: setup build help help: @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' setup: clean ## Setup project npm install install: clean npm ci start: ## Run project npm run start clean: ## Remove node_modules rm -rf node_modules test: ## Remove node_modules npm run test test.coverage: npm run test --coverage build: ## Build project with local settings npm run build build.production: ## Build project with production settings API_SERVER=$$API_SERVER && PAYMENT_GATEWAY=$$PAYMENT_GATEWAY && PAYMENT_GATEWAY_ROUTE=$$PAYMENT_GATEWAY_ROUTE && APPSIGNAL_KEY=$$APPSIGNAL_KEY && ENCRYPTION_KEY=$$ENCRYPTION_KEY && INITIALIZATION_VECTOR=$$INITIALIZATION_VECTOR && npm run build build.staging: ## Build project with staging settings API_SERVER=$$API_SERVER && PAYMENT_GATEWAY=$$PAYMENT_GATEWAY && PAYMENT_GATEWAY_ROUTE=$$PAYMENT_GATEWAY_ROUTE && APPSIGNAL_KEY=$$APPSIGNAL_KEY && ENCRYPTION_KEY=$$ENCRYPTION_KEY && INITIALIZATION_VECTOR=$$INITIALIZATION_VECTOR && npm run build deploy.production: ## Deploy project with production settings sh bin/production deploy.staging: ## Deploy project with staging settings sh bin/staging standard: ## Run linter with auto fix npm run lint <file_sep>/src/actions/session.js import { browserHistory } from 'react-router' import AppDispatcher from '../dispatcher' import API from '../api' import AppStorage from '../api/appStorage' // This action creator sends the type of action and the params (if any) to the dispatcher export default { // Sends email and password to the API to login, if success, stores the session data in the local // storage and sets it in the application state, else throw error login (user) { return API.User.Login(user) .then(response => { this.setSession(response) return 'success' }) .catch(error => { AppSignal.sendError(error) throw error }) }, // Sends token to the API to logout, if success, clears local storage and redirects to Login page logout () { API.User.Logout(AppStorage.getAuthToken()) .then(() => { AppDispatcher.handleAction({ actionType: 'CLEAR_SESSION' }) AppStorage.clearAll() browserHistory.push('/') }) .catch(error => { AppSignal.sendError(error) AppDispatcher.handleAction({ actionType: 'CLEAR_SESSION' }) AppStorage.clearAll() browserHistory.push('/') }) }, // Receives data to store the session data in the local storage and sets it in the application state setSession (data, setSessionFromStorage = false, isEntityChange = false) { if (setSessionFromStorage) { AppStorage.setAuthToken(data['ENCONTA_AUTH_TOKEN']) this.setUser(data.user) this.setTaxableEntities(data.taxableEntities) this.setCurrentEntity(data.currentEntity) } else { if (!isEntityChange) AppStorage.setAuthToken(data.auth_token) this.setUser(data.user) this.setTaxableEntities(data.user.taxable_entities) this.setCurrentEntity(data.user.current_taxable_entity) } }, // Sets the user data in the local storage and sets it in the application state setUser (user) { AppStorage.setUserData(user) AppDispatcher.handleAction({ actionType: 'USER_SET', data: user }) }, // Sets the available taxable entities list in the local storage and sets it in the application state setTaxableEntities (taxableEntities) { AppStorage.setTaxableEntities(taxableEntities) AppDispatcher.handleAction({ actionType: 'USER_ENTITIES_RECEIVED', data: taxableEntities }) }, // Sets the current entity in the local storage and sets it in the application state setCurrentEntity (currentEntity) { AppStorage.setCurrentEntity(currentEntity) AppDispatcher.handleAction({ actionType: 'CURRENT_ENTITY_SET', data: currentEntity }) }, // Stores the page the user wanted to enter to before he realizes there is no active session setPreloginPage (page) { AppDispatcher.handleAction({ actionType: 'PRELOGIN_PAGE_SET', data: page }) }, // Get the available taxable entities list for the user, if success, stores it in the local storage // and sets it in the application state getTaxableEntities () { API.TaxableEntities.GetTaxableEntities().then(response => { this.setTaxableEntities(response) }) }, changeCurrentEntity (id) { // Send the entity change to the API, if success, stores it in the local storage // and sets it in the application state return API.User.ChangeCurrentEntity(id) .then(response => { this.setSession(response, false, true) // data, setSessionFromStorage, isEntityChange }) .catch(error => { AppSignal.sendError(error) throw error }) }, resetPassword (data) { // Request the password reset for the specified client (or demo) return API.User.ResetPassword(data).catch(error => { AppSignal.sendError(error) throw error }) }, // Returns true if there is a session active, else false hasSession () { return AppStorage.hasSession() }, // Get notifications getNotifications () { return API.User.GetNotifications() .then(r => { AppStorage.setNotifications(r.notifications) }) .catch(error => { AppSignal.sendError(error) throw error }) }, /** * This gets all the Enconta's features available for an specific client */ setFeatures () { return API.User.GetFeatures() .then(response => { AppStorage.setFeatures(response.features) AppDispatcher.handleAction({ actionType: 'FEATURES_RECEIVED', data: response }) }) .catch(err => console.error(err)) }, clearEntity () { AppDispatcher.handleAction({ actionType: 'CLEAR_SESSION' }) } } <file_sep>/alias.js const path = require('path') module.exports = { utils: path.resolve(__dirname, 'src/utils/'), api: path.resolve(__dirname, 'src/api/'), actions: path.resolve(__dirname, 'src/actions/'), stores: path.resolve(__dirname, 'src/stores/'), shared: path.resolve(__dirname, 'src/components/app/shared'), appsignal: path.resolve(__dirname, 'src/appSignal/'), test: path.resolve(__dirname, 'src/test/') }
d57508d6f028fd76160662c9960eaa6df41f70ce
[ "Markdown", "JavaScript", "Makefile" ]
20
Markdown
enconta/widget-front
25905ed01934aa630907a1cb4f9ad8eeceee58be
d8d8f56b6b1dba5a5313b63d46ab599fa8cf984d
refs/heads/main
<file_sep>/* * --------------------------------------------------------------------------------------------- * * Copyright (c) IJSE Corporation. All rights reserved. * * Licensed under the MIT License. See License.txt in the project root for license information. * *-------------------------------------------------------------------------------------------- */ package lk.ijse.pos.service; import lk.ijse.pos.dto.OrderDTO; import lk.ijse.pos.dto.OrderDetailDTO; import java.util.List; /** * @author : <NAME> <<EMAIL>> * @since : 3/18/2021 **/ public interface OrderService { boolean saveOrder(OrderDTO dto); boolean updateOrder(OrderDTO dto); OrderDTO searchOrder(String id); boolean deleteOrder(String id); List<OrderDTO> getAllOrder(); } <file_sep>/* * --------------------------------------------------------------------------------------------- * * Copyright (c) IJSE Corporation. All rights reserved. * * Licensed under the MIT License. See License.txt in the project root for license information. * *-------------------------------------------------------------------------------------------- */ package lk.ijse.pos.controller; import lk.ijse.pos.dto.CustomerDTO; import lk.ijse.pos.dto.ItemDTO; import lk.ijse.pos.service.ItemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author : <NAME> <<EMAIL>> * @since : 3/19/2021 **/ @RestController @RequestMapping("/api/v1/item") @CrossOrigin public class ItemController { @Autowired ItemService itemService; @PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<Boolean> addItem(@RequestBody ItemDTO dto){ System.out.println("Item controller called"); System.out.println("item controller id "+dto.getItemCode()); try { System.out.println("item controller id "+dto.getItemCode()); boolean b = itemService.saveItem(dto); return new ResponseEntity<>(b, HttpStatus.OK); }catch (Exception e){ System.out.println("item controller id "+dto.getItemCode()); return new ResponseEntity<>(false, HttpStatus.NOT_FOUND); } } @DeleteMapping(params = {"id"}) public ResponseEntity<Boolean> deleteItem(@RequestParam String id) { try{ boolean b = itemService.deleteItem(id); return new ResponseEntity<>(b,HttpStatus.OK); }catch (Exception e){ return new ResponseEntity<>(false, HttpStatus.NOT_FOUND); } } @PutMapping public ResponseEntity<Boolean> updateItem(@RequestBody ItemDTO dto) { try{ boolean b = itemService.updateItem(dto); return new ResponseEntity<>(b,HttpStatus.OK); }catch (Exception e){ return new ResponseEntity<>(false, HttpStatus.NOT_FOUND); } } @GetMapping(path = "/{id}") public ResponseEntity searchItem(@PathVariable String id) { try{ ItemDTO itemDTO = itemService.searchItem(id); return new ResponseEntity( HttpStatus.OK); }catch (Exception e){ return new ResponseEntity(HttpStatus.NOT_FOUND); } } @GetMapping public ResponseEntity getAllCustomers() { try{ List<ItemDTO> allCustomers = itemService.getAllItem(); return new ResponseEntity(HttpStatus.OK); }catch (Exception e){ return new ResponseEntity(HttpStatus.NOT_FOUND); } } } <file_sep>/* * --------------------------------------------------------------------------------------------- * * Copyright (c) IJSE Corporation. All rights reserved. * * Licensed under the MIT License. See License.txt in the project root for license information. * *-------------------------------------------------------------------------------------------- */ package lk.ijse.pos.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author : <NAME> <<EMAIL>> * @since : 3/18/2021 **/ @Data @AllArgsConstructor @NoArgsConstructor public class OrderDetailDTO { private String orderDetailsId; private String orderId; private String itemCode; private int qty; private double unitePrice; } <file_sep>/* * --------------------------------------------------------------------------------------------- * * Copyright (c) IJSE Corporation. All rights reserved. * * Licensed under the MIT License. See License.txt in the project root for license information. * *-------------------------------------------------------------------------------------------- */ package lk.ijse.pos.dto; import lk.ijse.pos.entity.OrderDetails; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.sql.Date; /** * @author : <NAME> <<EMAIL>> * @since : 3/18/2021 **/ @Data @AllArgsConstructor @NoArgsConstructor public class OrderDTO { private String orderId; private String customerId; private String orderDate; private OrderDetails details; } <file_sep>/* * --------------------------------------------------------------------------------------------- * * Copyright (c) IJSE Corporation. All rights reserved. * * Licensed under the MIT License. See License.txt in the project root for license information. * *-------------------------------------------------------------------------------------------- */ package lk.ijse.pos.service; import lk.ijse.pos.dto.OrderDTO; import lk.ijse.pos.dto.OrderDetailDTO; import java.util.List; /** * @author : <NAME> <<EMAIL>> * @since : 3/18/2021 **/ public interface OrderDetailsService { boolean saveOrderDetails(OrderDetailDTO dto); boolean updateOrderDetails(OrderDetailDTO dto); OrderDetailDTO searchOrderDetails(String id); boolean deleteOrderDetails(String id); List<OrderDetailDTO> getAllOrderDetails(); } <file_sep>/* * --------------------------------------------------------------------------------------------- * * Copyright (c) IJSE Corporation. All rights reserved. * * Licensed under the MIT License. See License.txt in the project root for license information. * *-------------------------------------------------------------------------------------------- */ package lk.ijse.pos.service; import lk.ijse.pos.dto.CustomerDTO; import java.util.List; /** * @author : <NAME> <<EMAIL>> * @since : 3/18/2021 **/ public interface CustomerService { boolean saveCustomer(CustomerDTO dto); boolean updateCustomer(CustomerDTO dto); CustomerDTO searchCustomer(String id); boolean deleteCustomer(String id); List<CustomerDTO> getAllCustomers(); }
5a19a240b7ca84f6096e30a6d4086be56b47ba7e
[ "Java" ]
6
Java
nipunChathura/thogakade-pos-back-end
2c7d18a63efd4a3b34242518fb8dca8c4629fbd7
8bc1b91841a5ef856fd982639b9ec2d077e1152b
refs/heads/master
<file_sep>Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return [Meteor.subscribe('notifications')]; } }); // Router.route('/', {name: 'postsList'}); Router.route('/posts/:_id', { name: 'postPage', waitOn: function() { return [ Meteor.subscribe('singlePost', this.params._id), Meteor.subscribe('comments', this.params._id) ]; }, data: function() { return Posts.findOne(this.params._id); } }); Router.route('/posts/:_id/edit', { name: 'postEdit', waitOn: function() { return Meteor.subscribe('singlePost', this.params._id); }, data: function() { return Posts.findOne(this.params._id); } }); Router.route('/submit', { name: 'postSubmit' }); var requireLogin = function() { if (! Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('accessDenied'); } } else { this.next(); } } Router.route('/search', { name: 'search', waitOn: function() { return Meteor.subscribe('users') }, data: { users: Meteor.users.find() } }); Router.route('/allUsers', { name: 'allUsers', waitOn: function() { return Meteor.subscribe('users') }, data: { users: Meteor.users.find() }, }); Router.route('/:username', { name: 'profile', waitOn: function() { console.log('user profile subscription') check(this.params.username, String) var params = { username: this.params.username, following: [] } return [ Meteor.subscribe('userProfile', this.params.username), // Meteor.subscribe('userStream', params) ] }, data: function() { return { user: Meteor.users.findOne({ username: this.params.username }), // posts: Posts.find({ username: this.params.username }, { sort: { date: -1 }}) } } }); Router.route('/:username/:type', { name: 'followlist', waitOn: function() { return Meteor.subscribe('relatedUsers', _.pick(this.params, 'username', 'type')); }, data: function() { var that = this; var options = { username: { $ne: that.params.username }}; return { users: function() { return Meteor.users.find(options) }, usersCount: function() { return Meteor.users.find(options).count() }, type: function() { return that.params.type.capitalize() } } } }); Router.route('/profileEdit', { name: 'profileEdit', data: function() { return Meteor.users.findOne(this.params._id); } }); Router.onBeforeAction('dataNotFound', {only: 'postPage'}); Router.onBeforeAction(requireLogin, {only: 'postSubmit'});
6259446b8db491e7e954174f03839fe0c659d7f3
[ "JavaScript" ]
1
JavaScript
JMiller686/kg-app
e23a1faba7fc4ecf95ac4fc996b96d873242a133
5a1dff027e0f3303ce119f82a6f601194ac9bc8f
refs/heads/main
<repo_name>aaronpowell/vscode-course-sample<file_sep>/01-sort/sort.py words = ['magnificent', 'world', 'hello', 'python'] words.sort() print(words) <file_sep>/03-fibonacci/fib.py #recursive approach numTerms = int(input("How many terms of Fibonacci sequence to print? ")) # main method def fibonacci(n): if n < 1: return n else: return(fibonacci(n-1) + fibonacci(n-2)) # check if the number of terms is valid if numTerms <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(numTerms): print(fibonacci(i)) <file_sep>/02-reverse/reverse.py words = ['magnificent', 'world', 'hello', 'python'] words.sort(reverse=True) words = [ w[::-1] for w in words ] print(words)
4b0487f42c9e35eba537e51f5f7c7b1190d77ad8
[ "Python" ]
3
Python
aaronpowell/vscode-course-sample
3b614d14f80328c16d0f58b849d675ffaf9377f8
5b7d12c04163b1726cc5d8f924a43ba6647f6ca9
refs/heads/master
<repo_name>albertojuan/WekoJump<file_sep>/game/graphics.js import consts from "./consts.js"; class Graphics { constructor(logic, graphicContext) { this.camera = 0; this.logic = logic; this.graphicContext = graphicContext; } clear() { this.graphicContext.clearRect(0, 0, consts.CANVAS_WIDTH, consts.CANVAS_HEIGHT); } draw() { this.clear(); this.updateCamera(); for (var platform of this.logic.platforms) { this.drawPlatform(platform); } this.drawPlayer(this.logic.player); this.drawScore(); } updateCamera() { if (this.logic.player.y < consts.SKYLINE + this.camera) { this.camera = this.logic.player.y - consts.SKYLINE; } if (this.logic.player.y + consts.PLAYER_HEIGHT > consts.CANVAS_HEIGHT + this.camera) { this.camera = this.logic.player.y + consts.PLAYER_HEIGHT - consts.CANVAS_HEIGHT; } } drawScore() { this.graphicContext.font = "30px Verdana"; // Create gradient var gradient= this.graphicContext.createLinearGradient(0, 0, 300, 0); gradient.addColorStop("0", "magenta"); gradient.addColorStop("0.5", "blue"); gradient.addColorStop("1.0", "red"); // Fill with gradient this.graphicContext.fillStyle=gradient; this.graphicContext.fillText(`Max Height! ${-this.logic.maxScore.toFixed(0)}` , 10, 40); } drawPlatform(plataforma) { this.graphicContext.drawImage(consts.BRICK_IMG, plataforma.x, plataforma.y - this.camera); } drawPlayer(player) { let img = player.lastDirection === consts.MOVE_EVTS.LEFT ? consts.PLEFT_IMG : consts.PRIGHT_IMG; this.graphicContext.drawImage(img, player.x - consts.PLAYER_COLLISION_PADDING, player.y - this.camera); } drawRectangle(x, y, width, height, color) { this.graphicContext.beginPath(); this.graphicContext.fillStyle = color; this.graphicContext.rect(x, y, width, height); this.graphicContext.fillRect(x, y, width, height); this.graphicContext.stroke(); } } export default Graphics;<file_sep>/game/init.js "use strict"; import consts from "./consts.js"; import Player from "./player.js"; import Platform from "./platform.js"; import Logic from "./logic.js"; import Graphics from "./graphics.js"; // requestAnimFramew polifill window.requestAnimFrame = (function(callback) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; })(); // Anonymous function autocall (function () { // Game initialization let keypressed, moveLeft, moveRight, canvas = document.getElementById("game"), logic = new Logic(), context = canvas.getContext("2d"), graphics = new Graphics(logic, context); canvas.width = consts.CANVAS_WIDTH; canvas.height = consts.CANVAS_HEIGHT; // User actions document.onkeydown = (ev) => { keypressed = ev.keyCode; }; document.onkeyup = (ev) => { if (ev.keyCode == keypressed) keypressed = 0; }; function onTouch(evt) { evt.preventDefault(); var touch = evt.changedTouches[0]; if (touch) { switch (evt.type) { case "touchstart": moveLeft = touch.pageX <= consts.CANVAS_WIDTH/2; moveRight = touch.pageY > consts.CANVAS_WIDTH/2; break; case "touchend": moveLeft = moveRight = false; break; } } } canvas.addEventListener("touchstart", onTouch, false); canvas.addEventListener("touchend", onTouch, false); // Game loop using requestAnimFrame function mainStep() { let events = { direction: (keypressed === 65 || moveLeft) ? consts.MOVE_EVTS.LEFT : (keypressed === 68 || moveRight) ? consts.MOVE_EVTS.RIGHT : null }; logic.step(events); graphics.draw(); window.requestAnimFrame(mainStep); } mainStep(); })();<file_sep>/game/logic.js import consts from "./consts.js"; import Player from "./player.js"; import Platform from "./platform.js"; class Logic { constructor() { this.maxScore = 0; this.player = new Player(consts.CANVAS_WIDTH/2 - consts.PLAYER_WITH/2, consts.CANVAS_HEIGHT - consts.PLAYER_HEIGHT); this.platforms = []; this.platformGenerator = Platform.generatePlatform(); } createPlatforms() { if(this.platforms.length === 0 || this.platforms.slice(-1)[0].y > (this.player.y - consts.CANVAS_HEIGHT)) { var platform = this.platformGenerator.next().value; console.debug(platform); this.platforms.push(platform); } } checkJumpCollision() { if (this.player.vy > 0) { // Colisiona suelo salta if (this.player.y + consts.PLAYER_HEIGHT >= consts.PLAYER_BOTTOM) { return true; } // Colisiona plataforma salta for (let platform of this.platforms) { if (this.checkCollisionPlayerWithPlatform(this.player, platform)) { return true; } } } return false; } checkCollisionPlayerWithPlatform(player, platform) { return (((player.x >= platform.x && player.x <= platform.x + consts.PLATFORM_WIDTH) || (player.x + consts.PLAYER_WITH >= platform.x && player.x + consts.PLAYER_WITH <= platform.x + consts.PLATFORM_WIDTH)) && player.y + consts.PLAYER_HEIGHT >= platform.y && player.y + consts.PLAYER_HEIGHT <= platform.y + consts.PLATFORM_HEIGHT); } updateScore() { this.maxScore = Math.min(this.maxScore, this.player.y - consts.CANVAS_HEIGHT); } step(events) { this.createPlatforms(); if (this.checkJumpCollision(this.player)) { this.player.vy = consts.V_JUMP; } this.player.step(events); this.updateScore(); } } export default Logic<file_sep>/game/consts.js const s = ((Math.random()*4 + 1).toFixed(0)); const PLEFT_IMG = new Image(); PLEFT_IMG.src = `resources/sprites${s}/pleft.png`; const PRIGHT_IMG = new Image(); PRIGHT_IMG.src = `resources/sprites${s}/pright.png`; const BRICK_IMG = new Image(); BRICK_IMG.src = `resources/sprites${s}/brick.png`; const consts = { CANVAS_WIDTH: 640, CANVAS_HEIGHT: 1024, GRAVITY: 1.10, V_JUMP: -24, VX: 6, PLAYER_WITH: 55, PLAYER_HEIGHT: 124, PLATFORM_HEIGHT: 34, PLATFORM_WIDTH: 116, PLAYER_BOTTOM: 1024, PLAYER_COLLISION_PADDING: 34, VY_MAX: 26, SKYLINE: 450, MOVE_EVTS: { LEFT: Symbol("move left"), RIGHT: Symbol("move right") }, FIRST_PLATFORM_Y: 1000, PLATFORM_MARGIN_Y: 200, PLATFORM_RANGE_X: 500, // ES6 Feature: Autoresolves creates a property with the same name and value than the consts declared at the top PLEFT_IMG, PRIGHT_IMG, BRICK_IMG }; export default consts; <file_sep>/game/platform.js import consts from "./consts.js" class Platform { constructor(posX, posY, width, heigth) { this.x = posX; this.y = posY; this.width = width; this.heigth = heigth; } } function * generatePlatform() { var fy = consts.FIRST_PLATFORM_Y; while(true) { var x = Math.random() * consts.PLATFORM_RANGE_X; fy -= Math.random() * consts.PLATFORM_MARGIN_Y; yield new Platform(x, fy, consts.PLATFORM_WIDTH, consts.PLATFORM_HEIGHT); } } Platform.generatePlatform = generatePlatform; export default Platform<file_sep>/README.md # WekoJump Doodle jump clone using html and JS ES6 for educational purposes <file_sep>/game/player.js import consts from "./consts.js" class Player { constructor(posX, posY) { this.x = posX; this.y = posY; this.vy = 0; } step(events) { // Actualizo posición X según teclado if (events.direction === consts.MOVE_EVTS.LEFT) { this.lastDirection = consts.MOVE_EVTS.LEFT; this.x -= consts.VX; } else if (events.direction === consts.MOVE_EVTS.RIGHT) { this.lastDirection = consts.MOVE_EVTS.RIGHT; this.x += consts.VX; } // Actualizo velocidad según gravedad if (this.vy < consts.VY_MAX) this.vy += consts.GRAVITY; // Actualizo posición Y según velocidad this.y += this.vy; } } export default Player;
605d03792446194f3b426e79220dcc956d25bcef
[ "JavaScript", "Markdown" ]
7
JavaScript
albertojuan/WekoJump
1b64bdcbd1a02c32d616be35b1ff94b161fd34bf
7aeb3a95232c4659c8156ef82aa77d90f0ac5035
refs/heads/master
<repo_name>fgq999/chatroom<file_sep>/datapush/modules/entity/Room.js /** * Created by lkt on 15-4-17. */ function Room(name,ho){ this.users = new Array(); this.addUser(ho); this.ho=ho; this.name=name; return this; } module.exports = Room; Room.prototype.addUser=function addUser(user){ this.users.push(user); } Room.prototype.removeUser=function removeUser(user){ var index = this.users.indexOf(user); //删除数组中的元素,长度也跟着改变 this.users.splice(index,1); } Room.prototype.setName=function setName(name){ this.name=name; } Room.prototype.getName=function getName(){ return this.name; } Room.prototype.getUsers=function getUsers(){ return this.users; } Room.prototype.setHO=function setHO(ho){ this.ho=ho; } Room.prototype.getHO=function getHO(){ return this.ho; } Room.prototype.userContains=function userContains(user){ for(var i=0;i<this.users.length;i++){ if(this.users[i]==user){ return true; } } return false; } <file_sep>/datapush/modules/chatSocket.js /** * Created by lkt on 15-4-17. */ var room = require("../modules/entity/Room.js") function chatSocket(){ return this; } module.exports = chatSocket; chatSocket.Start = function Start(io){ var rooms = new Array(); var userList = new Array(); var userSocketMap = {}; io.sockets.on('connection',function(socket){ //socket.emit('conn',{'value':'hello,welcome!','user':'System'}); //接收用户修改姓名 socket.on('setName',function(data){ var index = userList.indexOf(data.name); if(index==-1){ userList.push(data.name); userSocketMap[data.name] = socket; socket.emit('setName',{'value':'欢迎您! '+data.name,'user':'System','type':'new'}); }else{ socket.emit('setName',{'value':'昵称 '+data.name+' 已经存在!','user':'System','type':'rep'}); } }); //私聊 socket.on('pchat',function(data){ var v = data.value; var tname = v.substring(v.indexOf('@')+1,v.indexOf(']')); console.log(tname); var s = userSocketMap[tname]; s.emit('pchat',{value:data.value,fname:data.fname}); }); //给用户发送房间信息 socket.emit('rooms',{rooms:rooms}); //接收用户创建房间的指令 socket.on('cRoom',function(data){ var repCreate=false; //判断房间是否存在 rooms.forEach(function(r){ if(r.name==data.name){ repCreate = true; } }); if(!repCreate){ leaveMyInRoom(data,socket,rooms); var r = new room(data.name,data.ho); rooms.push(r); socket.join(data.name); socket.emit('rooms',{rooms:rooms,room:data.name,value:'房间 ['+data.name+'] 创建成功!','user':'System'}); //给除了自己以外的客户端广播消息 socket.broadcast.emit('refRooms',{rooms:rooms}); }else{ socket.emit('rooms',{rooms:rooms,room:data.name,value:'房间 ['+data.name+'] 已经存在!','user':'System'}); } // }); socket.on('say',function(data){ var rname = data.room; var ruser = data.user; var rsay = data.value; io.in(rname).emit('say',{value:rsay,'user':ruser}); //socket.emit('say',{value:rsay,'user':ruser}); }); socket.on('leaveRoom',function(data){ console.log(data); leaveMyInRoom(data,socket,rooms); var index = userList.indexOf(data.user); if(index!=-1){ userList.splice(index,1); } socket.broadcast.emit('say',{value:' ['+data.user+']离开了房间!','user':'System'}); io.emit('refRooms',{rooms:rooms}); }); socket.on('joinRoom',function(data){ //是否重复加入 var repJoin = false; leaveMyInRoom(data,socket,rooms); rooms.forEach(function(r){ if(r.name==data.room){ //repJoin = r.getUsers().contains(data.name); repJoin= r.userContains(data.user); if(!repJoin) r.addUser(data.user); } }); if(!repJoin){ socket.join(data.room); socket.emit('say',{value:'欢迎加入 ['+data.room+'] 房间!','user':'System'}); socket.broadcast.emit('say',{value:'欢迎 ['+data.user+']加入房间!','user':'System'}); io.emit('refRooms',{rooms:rooms}); }else{ socket.emit('say',{value:'您已经在 ['+data.room+'] 房间!','user':'System'}); } }); socket.on('disconnect',function(socket){ //console.log(socket.); }); }); } function leaveMyInRoom(data,socket,rooms){ //记录房间用户为0的序号 var delRoom = -1; var index = 0; if(data.currRoom!='无'){ socket.leave(data.currRoom); rooms.forEach(function(r){ if(r.name==data.currRoom){ r.removeUser(data.user); if(r.getUsers().length==0){ delRoom = index; } } index++; }); } if(delRoom!=-1){ rooms.splice(delRoom,1); } }
4ae75f68d049904c2832e4141191380ee2af7a48
[ "JavaScript" ]
2
JavaScript
fgq999/chatroom
517fcf1a4793c1c90225115a55d5a5352144f4d6
ec139c2bcc51a55d700429d0e50b7a518468231d
refs/heads/master
<repo_name>novemberkilo/ink-blot-middleman-source<file_sep>/source/2013/09/12/contributing-to-oss.markdown --- title: Contributing to Discourse subtitle: Therapeutic Refactoring tags: oss, software --- _Junior/Intermediate Ruby developers looking for an Open Source project to contribute to should consider practising clean coding techniques by refactoring the Discourse project._ Until around July this year, I had not contributed any code to an open source project. I have just ticked over three years as a professional developer and I have had the mandatory _contribute to OSS_ on a to-do list for a while now. Until July this year I had submitted pull requests to a couple of projects that added to their documentation - I wanted to contribute code but despite the many posts out there on how-to-get-started-contributing-to-oss, I didn't have much success! Then a couple of things happened: - I realised that I too find refactoring to be therapeutic - I met Discourse To elaborate, <NAME>'s ([@kytrinyx](http://twitter.com/kytrinyx)) [talk on Therapeutic Refactoring](http://www.youtube.com/watch?v=J4dlF0kcThQ) had a profound impact on me. A couple of days after watching it, I found in a state of almost post-meditative calm, staring at a pull request that cleaned up some complicated and unhappy code that I had written at work a few years ago. Code Climate showed me some nice shades of green, and I realised that I also find refactoring to be therapeutic! [Discourse](https://github.com/discourse/discourse) is an Ember and Rails project and so uses the technologies that I had spent a lot of time with at work. Its core team includes <NAME> ([@codinghorror](http://twitter.com/codinghorror)), <NAME> ([@eviltrout](http://twitter.com/eviltrout)) and <NAME>([@samsaffron](http://twitter.com/samsaffron)) of Stack Overflow fame, and its [pitch](http://www.codinghorror.com/blog/2013/02/civilized-discourse-construction-kit.html) is pretty far reaching! I had met <NAME> at a Ruby meetup in Sydney and was inspired by his talk on his [MiniProfiler](http://miniprofiler.com/) project so when I first heard about (his involvement with) Discourse, I poked around a bit and ended up on [meta.discourse.org](http://meta.discourse.org) - before long I found their post on [how to contribute to Discourse.](http://meta.discourse.org/t/so-you-want-to-help-out-with-discourse/3823) I figured maybe I'd use Discourse as an opportunity to practise refactoring and reinforce the coding principles I had been reading about in [Sandi Metz's book](http://www.amazon.com/Sandi-Metz/e/B0097WWH62), and on the [Code Climate blog](http://blog.codeclimate.com/), and submitted [my first pull request.](https://github.com/discourse/discourse/pull/881) Wondering how I knew where to start? By looking at the [Code Climate report of Discourse](https://codeclimate.com/github/discourse/discourse) and picking a smell. Setting up the project for development wasn't so hard thanks to [excellent documentation.](https://github.com/discourse/discourse/blob/master/docs/DEVELOPER-ADVANCED.md) I used [flog and flay](http://sadi.st/Ruby_Sadist.html) locally to monitor the progress of my efforts until I discovered later that you can register your fork of Discourse with Code Climate. Once you have forked the project, try hitting _http://codeclimate.com/github/your-github-handle/discourse_ and Code Climate will help you through the rest. I found Sam and Robin's feedback to be excellent and encouraging and was reminded how important it is to find a project that is maintained by folks who communicate well! By the end of the summer (I'm in the northern hemisphere at the moment), I had made several contributions to Discourse, learning a ton along the way. I even implemented a feature and helped a bit on their Rails4 upgrade. One of my [better refactoring pull requests](https://github.com/discourse/discourse/pull/1185#issuecomment-20971446) was used in an interview to demonstrate my journey towards writing better code (I got the job!). If you are in a similar stage in your journey as a developer, I encourage you to spend some time (therapeutically) refactoring your open source project of choice. As you can see, Discourse is a good candidate! Also, a word of advice - stay with the principle of having fun and playing to your strengths. I found contributing to the Rails side of Discourse to have a much better yield than the Ember side. Good luck! <file_sep>/source/2013/09/29/scopes-for-finding-empty-relationships.markdown --- title: Handy scopes for associations tags: rails, arel --- If your Rails project has a has-many association and you want a way of finding records that have no associated records, or, records that have at least one associated record, you might find this post useful. Suppose you have classes `Person` and `Friend` that are associated via a `has_many` relationship: class Person < ActiveRecord::Base has_many :friends end class Friend < ActiveRecord::Base belongs_to :person end How do you find `persons` that have no `friends`? Person.includes(:friends).where("friends.person_id IS NULL") Or that have at least one `friend` Person.includes(:friends).where("friends.person_id IS NOT NULL") #### Using Arel To accomplish this with Arel set up the following scopes on `Friend` (thanks to [@macfanatic](http://twitter.com/macfanatic) for the tip), class Friend belongs_to :person scope :to_somebody, ->{ where arel_table[:person_id].not_eq(nil) } scope :to_nobody, ->{ where arel_table[:person_id].eq(nil) } end And then, Persons who have at least one friend: Person.includes(:friends).merge(Friend.to_somebody) The friendless: Person.includes(:friends).merge(Friend.to_nobody) *Note:* If you are on Rails 4 don't forget to append `references(:friends)` to these. <file_sep>/source/2011/10/07/tdop-math.html.markdown --- title: A Top Down Operator Precedence parser for algebraic expressions date: 2011-10-07 00:00 +00:00 tags: --- In my [previous post](/2011/10/02/polar-curve-grapher.html) I wrote about a polar curve grapher and its use of <NAME>'s `tdop_math.js` to parse a user input algebraic expression into a javascript eval(uable) string. I ended up spending some time with `tdop_math.js` - you can find the source [here](https://github.com/kevinmehall/EquationExplorer/blob/master/tdop_math.js) - and I fell into the magical rabbit hole of Top Down Operator Precedence (TDOP) parsers. This post describes how I ended up writing a TDOP parser for algebraic expressions in Ruby. Some facts: - <NAME> first wrote about Top Down Operator Precedence parsers in 1973 - <NAME> wrote about them in Beautiful Code, and in [an article](http://javascript.crockford.com/tdop/tdop.html) that includes an implementation of a parser for a Simplified Javascript - he went on to use this in [JSlint](http://jslint.com) #### Overview of TDOP parsers In a nutshell, Top Down Operator Precedence parsers are similar to [Recursive Descent parsers,](http://en.wikipedia.org/wiki/Recursive_descent_parser) but, as claimed by <NAME>, simpler to understand, implement, and providing of better performance. Borrowing from [this](http://eli.thegreenplace.net/2010/01/02/top-down-operator-precedence-parsing/) excellent article by <NAME>, the main features of a TDOP parser are: - A _binding power_ mechanism to handle precedence levels - e.g. the binding power of multiplication `'*'` is higher than that of addition `'+'` in arithmetic - A means of implementing different functionality of tokens depending on their position relative to their neighbors: _prefix_ or _infix._ For example, the minus `'-'` operator is behaving as a prefix operator in `-2` but in its infix form, it is subtraction `4 - 2.` - As opposed to classic Recursive Descent, where semantic actions are associated with grammar rules (BNF), TDOP associates them with tokens. Tokens have a binding power, and know how to handle themselves in infix and/or in prefix situations. Expressions are then evaluated recursively by evaluating them at each 'precedence' level and returning the result to its caller. Compilers are difficult to understand at the best of times and most articles I have come across on TDOP parsers are by very bright people finishing (or pausing) on their journey to get to know Pratt's work. At my current stage of comfort with TDOP parsers, I cannot come close to explaining the parser any better than Eli Bendersky. Eli's [article,](http://eli.thegreenplace.net/2010/01/02/top-down-operator-precedence-parsing/) elaborates on the features described above and explains the parser by setting one up to handle simple arithmetic. He then works through a simple example that illustrates it in action as it parses the expression `3 + 1 * 2 * 4 + 5.` For further detail on TDOP parsers, I refer the interested reader to this and Douglas Crockford's article referenced above. ### TDOP and Ruby As I was working on the [polar curve grapher](2011/10/Polar-curve-grapher/) I got curious about implementing `tdop_math.js` in Ruby. I studied the source of `tdop_math.js,` and its tokeniser `tokens.js,` and felt that I had a decent understanding of its structure and operation (improving my Javascript skills along the way!). However, a like-for-like implementation in Ruby seemed out of the question. Well, it seemed like a hard proposition that would involve first developing new metaprogramming skills in Ruby! And then I ran into Glen Vandenburg's project `radish,` which is now called [`smithereen`.](http://github.com/glv/smithereen) #### Smithereen Smithereen is a result of <NAME>'s meditation on TDOP parsers, during which he decided to write an implementation in Ruby. He has implemented a _library for building Top Down Operator Precedence parsers,_ using Ruby idioms that were completely unfamiliar to me, but that provided an excellent opportunity to learn. As Glen says, he has _tried to provide a well-factored set of tools to help with the core TDOP algorithm and several related problems,_ and so I decided to fork Smithereen with the intention of helping with its development, and, using it to implement `tdop_math` in Ruby. Smithereen comes with two samples, an arithmetic parser, and the Simplified Javascript parser. I found it quite difficult to get started with Smithereen and asked Glen a question or two. To my delight, he helped me get started and I found this to be so inspiring that I made rapid progress towards implementing a simple scientific calculator. This is available on [my fork of Smithereen](http://github.com/novemberkilo/smithereen/tree/develop) as [`equation_parser.rb`](https://github.com/novemberkilo/smithereen/blob/develop/samples/equation_parser.rb) `equation_parser.rb` will, for instance, take strings such as `sin(cos(2pi))` and return `0.84147` By way of explanation, it has hardcoded hashes that declare functions and constants, and these are tokenised as `names` and given a high binding power. fns = { 'sin' => Proc.new { |x| Math.sin(x) }, 'cos' => Proc.new { |x| Math.cos(x) }, 'tan' => Proc.new { |x| Math.tan(x) }, 'sqrt' => Proc.new { |x| Math.sqrt(x) }, 'exp' => Proc.new { |x| Math.exp(x) } } CONSTANTS = { 'pi' => Math::PI, 'e' => Math::E } The `infix` method on the token `(` checks for the presence of a function or a constant (essentially a key in the above hashes), and looks up the corresponding value for the definition of the function. Smithereen takes care of the rest. Well, that is, after tokens for the usual arithmetic operators are defined, with infix and prefix methods as described above. #### tdop_math.rb Completing my goal to create a Ruby equivalent to `tdop_math.js,` I've taken the work in the example `equation_parser.rb` and used it to create a Ruby gem called `tdop_math.` This takes an algebraic expression, parses it, and returns a string of Ruby that represents the expression. Because the `tdop_math` gem depends on `smithereen` (which has yet to be released), it is not available as a built gem. As far as I know, if you want to install this, you are going to need to pull down my [repo](http://github.com/novemberkilo/tdop_math) and `include '<path-to-tdop_math.rb>'` manually. Once you have, you use it as follows: u = "sin(cos(2x))" ## or some user input algebraic expression t = TDOPMath::Parser.new(u) f = t.parse ## f == "Math.sin(Math.cos(2 * x))" `tdop_math` reserves symbols `x`,`y` and `t` as variables. It also provides a basic list of functions, namely, `sin`, `cos`, `tan`, `sqrt` and `exp`. If you need to provide an alternate list of variables and functions, you can do so as follows: u = "baz(foo(2a))" ## or some user input algrebraic expression t = TDOPMath::Parser.new(u, :vars => ['a'], :functions => { 'foo' => 'Foo::foo', 'baz' => 'Baz::baz' }) f = t.parse ## f == "Baz::baz(Foo::foo(2 * a))" You can use `tdop_math` wherever you need a user to input an algebraic expression, comprising of a known set of functions and variables. This could find use in apps in maths education or science/data analytics. I hope the community finds it useful, although my motivation was mainly to build it as an exercise, along my path to becoming a better programmer. I've made a gem! <file_sep>/source/2011/12/04/principle-of-simple-design.markdown --- title: Simple Design tags: design, software --- Yesterday I attended the [_Global Day of Code Retreat, 2011_](http://coderetreat.org/events/global-day-of-coderetreat-2011) in Sydney. We were incredibly privileged to have the creator of Code Retreat, [<NAME>](http://twitter.com/coreyhaines) facilitating. I found the experience to be really very profound and recommend it without reserve to developers of all levels. Here are some of the things I took from the day: - My C++/RUP based thinking of OO really needs a makeover - I thought I was practising Test Driven Development (TDD) but I now see how narrow my understanding of TDD was. The _evil coder_ or _Mute with Find the Loophole_ session of the retreat was simultaneously hilarious, frustrating and enlightening on how well tests actually serve as a specification for code - The principles of _Simple Design_ (attributed to the best of my knowledge to <NAME> and <NAME> in the Extreme Programming book) I've come across each of the 4 principles of simple design but when I heard Corey talk through them in sequence, it really made a difference to the way I understand them. I know that this understanding will change as I practice with them and I will not remember them as well when I am in the thick of the work day, so I'm writing them down here as a note to self: 1. Runs all the tests 1. Expresses every idea that we need to express 1. Says everything once and only once 1. Has no superfluous parts I look forward to practicing the principles I learned at code retreat. I have no doubt that I have had a step change in my perspective as a programmer - more power to Corey's efforts at [coderetreat.org](http://coderetreat.org) I say! <file_sep>/source/2014/05/25/json-finders.html.markdown --- title: Postgres JSON Functions From Rails date: 2014-05-25 02:03 UTC tags: rails, postgres --- Say you are storing JSON in Postgres and need scopes to get records based on their JSON attributes. This post covers the use of JSON functions available in Postgres v9.3 to achieve this. Suppose you have an Order class, containing a JSON blob that describes the product that the order relates to: # == Schema Information # # Table name: orders # # id :integer not null, primary key # customer_id :integer # product :json # created_at :datetime # updated_at :datetime class Order < ActiveRecord::Base end Suppose `product` has the following structure: { "name": "Widget 01", "code": "W001", "plan": { "name": "Silver", "terms": "12 months" }, "created_at": "2013-12-22 09:27:45 UTC", "updated_at": "2014-10-21 10:30:40 UTC" } And you want a scope on `Order` to find all orders with a particular code - something like `Order.with_code("W001")` If you are using version 9.3 of Postgres, you can get it to do the heavy lifting for you using its [JSON functions](http://www.postgresql.org/docs/9.3/static/functions-json.html) like so: scope :with_code, ->(code) { where("product ->> 'code' = ?", code) } Getting to nested JSON attributes is a bit trickier. Say you want a scope for all orders with a particular plan name - something like `Order.with_plan_name("Silver")` scope :with_plan_name, ->(plan_name) { where("product::json #>> '{ plan,name }' = ?", plan_name) } I got to these by looking through Stack Overflow posts, grokking the Postgres docs on JSON functions and [this post](http://devblog.avdi.org/2014/01/31/playing-with-json-in-postgres/) of Avdi Grimm's. As usual, you can't comment here but if you see an error or want to offer a suggestion for improvement, please get in touch via email. <file_sep>/Gemfile source 'https://rubygems.org' gem "haml" gem "sass" gem "builder" gem "redcarpet", "~> 2.0.0" gem "middleman" gem "middleman-blog" gem 'bootstrap-sass', '~> 2.2.2.0' gem 'nokogiri' # Compass plugins gem 'susy', "~>1.0.1" # Susy # gem 'compass-960-plugin' # 960.gs <file_sep>/README.md The source of my blog. Uses my middleman-twitter-bootstrap as a starting point. <file_sep>/source/2011/09/24/jquery-scroller.html.markdown --- title: A simple jquery scroller date: 2011-09-24 00:00 +00:00 tags: jquery --- Recently we implemented a variation on a scroller. We needed to flash up a set of snippets, one by one, in the same text area of a page. Here's a [demo](/examples/jquery_scroller.html) of it in action. You can view the source of the demo but here's a quick, plain-English explanation of how it works. #### The markup In the page, the snippets are list elements `li` in a `section`. You can make them definition elements or whatever you like. The section has an `id` so we can find it from javascript - I've called it `snippets` in the example. #### The CSS Pretty much the only style elements that are important to the correct operation of the scroller is `display: none` on the list elements. This ensures that all list elements start out being invisible. Having `overflow: hidden` on the `section` makes it easier to deal with any stuttering in the javascript loop shown below. #### The javascript We're using jQuery so make sure you've got that loaded. And here's the javascript: $().ready(function(){ var loopSnippets = function() { var snippets = $("li", $("#snippets")); snippets.each( function(index, element) { $(element).delay( index*5000 ).fadeIn(100).delay(4500).fadeOut(200); if (index == snippets.length-1) { setTimeout( loopSnippets, index*5000 + 5000 ) } }); }; loopSnippets(); }); So this is where all the action is of course. The variable `snippets` collects all the list items and then we iterate over this collection, showing each list item and then hiding them again (using `fadeIn` and `fadeOut`). What you have to wrap your head around is that all of the code gets executed in one shot, so to get items to display in sequence and to loop around again, you have to show-and-hide each item at different times. The trick is to use `delay` and the index of the item in the array to calculate the amount of time we need to wait before kicking off the show-and-hide routine for the item. Finally, to loop back and start over at the top, we use `setTimeout` to kick off the `loopSnippets` function again. Again, use the length of `snippets` and the amount of time used up in showing and hiding each element to figure out how long you have to wait before setting off `loopSnippets` again. Keep in mind that the above code works irrespective of the length of the list of snippets - which is of course what you want if the snippets are dynamically loaded. #### In summary Use `delay` and the index of elements in an array if you want to operate on each element in sequence. Use `setTimeout` to repeat a function call at specific time intervals. Thanks go to _<NAME>_ and _<NAME>_ for collaborating on this and showing me how to use `delay` and `setTimeout` creatively! <file_sep>/source/2014/06/14/asset-pipeline-note.html.markdown --- title: Different fingerprints for same asset date: 2014-06-14 02:43 UTC tags: --- Documenting an issue that we ran into with the Rails asset pipeline on a recent upgrade to Rails 4.1.0. Specifically [this issue](https://github.com/rails/sprockets-rails/issues/138) with sprockets-rails 2.1.3. ### Symptoms - Different nodes have different fingerprints for the same assets. Thus assets don't load consistently and you end up with 404s. - Repeatedly running `rake assets:precompile` locally results in different fingerprints for the same assets on each run. ### The fix If you are seeing these symptoms don't use sprockets-rails 2.1.3. The [issue](https://github.com/rails/sprockets-rails/issues/138) references a pull-request that fixes the problem - this is now on master and should be in the 2.1.4 release. We rolled back to sprockets-rails 2.0.1 (simply because that's what was on our Rails 4.0 master branch) but later versions of sprockets-rails might work as well.
ed38f4b98e77a99448c4f251541ddc852fb346bc
[ "Markdown", "Ruby" ]
9
Markdown
novemberkilo/ink-blot-middleman-source
a77125fae952e9173623e237eee2c899b873beb7
33117c4014cefb553ca416d8cc4780da9c9140d6
refs/heads/master
<file_sep>using PrintService.Common; using PrintService.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PrintService.Server { public class LogContainer { public PrintServerLogging OnLogging = null; private List<string> logs = new List<string>(); private int maxLogCount = 1000; public LogContainer() { var maxCount = AppSettingHelper.GetOne("MaxLog", this.maxLogCount.ToString()); int.TryParse(maxCount, out this.maxLogCount); } /// <summary> /// Get the logs /// </summary> /// <returns></returns> public List<string> GetLogs() { return this.logs; } /// <summary> /// Add one log /// </summary> /// <param name="log"></param> public void AddLog(string log) { lock (this.logs) { if (this.logs.Count > this.maxLogCount) { this.logs.RemoveAt(0); } this.logs.Add(log); try { this.OnLogging?.Invoke(log); } catch { } } } } } <file_sep>using System; using System.IO; using Telerik.Reporting; using Telerik.Reporting.Processing; namespace PrintService.Template { /// <summary> /// Generate pdf file /// </summary> public class ReportGenerator { public static string FileSavePath = Environment.CurrentDirectory + "\\PrintFiles"; public static bool SaveReport(IReportDocument report, string filename, out Exception exception, string format) { try { ReportProcessor reportProcessor = new ReportProcessor(); InstanceReportSource instanceReportSource = new InstanceReportSource(); instanceReportSource.ReportDocument = report; RenderingResult renderingResult = reportProcessor.RenderReport(format.ToUpper(), instanceReportSource, null); filename = filename.Replace('\n', ' '); using (FileStream fs = new FileStream(filename, FileMode.Create)) { fs.Write(renderingResult.DocumentBytes, 0, renderingResult.DocumentBytes.Length); } exception = null; return true; } catch (Exception ex) { exception = ex; return false; } } } } <file_sep>using PrintService.UI; using System; namespace PrintService.Template { /// <summary> /// Build model using json string and engin name /// </summary> public class PrintObjectFactory { public static IEngin GetEngin(string enginName) { switch (enginName) { case "PDF": return new PdfEngin(); default: throw new Exception(Language.I.Text("ex_unkown_engin", "Print error unknown engin name!")); } } } } <file_sep>using System; namespace PrintService.Update { public class UpdateItem { public string FileName; public UpdateType UpdateType; public string Version = ""; public string FullPath() { return Environment.CurrentDirectory + "\\" + this.FileName; } } } <file_sep>using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { [TestFixture] public class TestUpdateServices { [SetUp] public void Start() { } [TestCase] public void GetFileList() { } [TearDown] public void TearDown() { } } } <file_sep>using System.Collections.Generic; namespace PrintService.Template { /// <summary> /// Define a queue to achive print serial /// </summary> public class PrintQueue { private static Queue<IPrintObject> _printJobs = new Queue<IPrintObject>(); private static object jobLock = new object(); /// <summary> /// Add a job /// </summary> /// <param name="m"></param> public static void AddJob(IPrintObject m) { lock (jobLock) { _printJobs.Enqueue(m); } } /// <summary> /// Pop a print job /// </summary> /// <returns></returns> public static IPrintObject PopAJob() { lock (jobLock) { if (_printJobs.Count > 0) return _printJobs.Dequeue(); return null; } } } } <file_sep>using PrintServer2.Properties; using PrintService.Server; using PrintService.UI; using PrintService.Utility; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; namespace PrintServer2.UI { public class PrintTray { private NotifyIcon notifyIcon = null; private Language language = null; private PrintServer printServer = null; private TrayEventHander clickHander = null; private MenuItem exitItem = null; private MenuItem selectPrinter = null; private MenuItem printNow = null; private MenuItem showLog = null; private MenuItem changeLanguage = null; private MenuItem changePort = null; private MenuItem supportedTemplate = null; public PrintTray() { this.InitServer(); this.InitEventHalder(); this.InitTray(); this.printServer.StartProcess(); } /// <summary> /// Init the event handler /// </summary> private void InitEventHalder() { this.clickHander = new TrayEventHander(this.printServer); } /// <summary> /// Init the tray object /// </summary> private void InitTray() { this.language = Language.I; this.notifyIcon = new NotifyIcon(); this.notifyIcon.BalloonTipText = AppSettingHelper.GetOne("IconHint", "Print server was runing in backgroud"); this.notifyIcon.Text = AppSettingHelper.GetOne("HideHint", "Click icon to open main window"); this.notifyIcon.Icon = this.GetTaskBarIcon(); this.notifyIcon.Visible = true; this.notifyIcon.ShowBalloonTip(2000); this.changeLanguage = new MenuItem(this.language.Text("language", "Lanaguage")); var portString = this.language.Text("language", "Lanaguage") + "(" + this.printServer.GetWorkingPort().ToString() + ")"; this.changePort = new MenuItem(); this.supportedTemplate = new MenuItem(this.language.Text("show_templates", "Show Temlpates")); this.supportedTemplate.Click += this.clickHander.SupportedTemplates_Click; this.selectPrinter = new MenuItem(this.language.Text("select_printer", "Select Printer")); this.printNow = new MenuItem(this.language.Text("print_now", "Print Now")); this.printNow.Checked = this.printServer.GetPrintMode(); this.printNow.Click += this.clickHander.PrintMode_Click; this.showLog = new MenuItem(this.language.Text("show_log", "Show Logs")); this.showLog.Click += this.clickHander.ShowLog_Click; this.exitItem = new MenuItem(this.language.Text("exit", "Exit")); this.exitItem.Click += this.clickHander.Exit_Click; MenuItem[] childen = new MenuItem[] { this.changeLanguage, this.selectPrinter, this.supportedTemplate, this.showLog, this.printNow, this.exitItem }; notifyIcon.ContextMenu = new ContextMenu(childen); } /// <summary> /// Try to get icon for task bar /// first: try to find a icon file named logo.icon in folder Resources. if not found then use the build-in icon /// </summary> /// <returns></returns> private Icon GetTaskBarIcon() { var filePath = Environment.CurrentDirectory + "\\logo.ico"; var logo = File.Exists(filePath); if (logo) { return new Icon(filePath); } return Resources._default; } /// <summary> /// Init the print server /// </summary> private void InitServer() { this.printServer = new PrintServer(); this.printServer.OnPrinterLoaded = this.OnPrinterLoaded; this.printServer.OnPrinterChanged = this.OnPrinterSelected; this.printServer.OnPrintModeChanged = this.OnPrintModeChanded; } private void OnPrintModeChanded(bool printNow) { this.printNow.Checked = printNow; } /// <summary> /// When the print server has loaded all printer names then call this method to add meun items /// </summary> /// <param name="printerNames"></param> private void OnPrinterLoaded(List<string> printerNames) { this.selectPrinter.MenuItems.Clear(); var refreshPrinter = new MenuItem(this.language.Text("refresh_printer", "Refresh Printer")); refreshPrinter.Click += this.clickHander.RefreshPrinter_Click; this.selectPrinter.MenuItems.Add(refreshPrinter); foreach (var pName in printerNames) { var printerMenu = new MenuItem(pName); printerMenu.Tag = pName; printerMenu.Click += this.clickHander.SelectPrinter_Click; this.selectPrinter.MenuItems.Add(printerMenu); } } /// <summary> /// Triggered when print selected /// </summary> /// <param name="printName"></param> private void OnPrinterSelected(string printName) { foreach (var mi in this.selectPrinter.MenuItems) { if (mi is MenuItem) { var it = mi as MenuItem; if (it.Tag != null && it.Tag.ToString() == this.printServer.GetSelectedPrinterName()) { it.Checked = true; } else { it.Checked = false; } } } } /// <summary> /// Change language name /// </summary> /// <param name="languageName"></param> private void ChangeLanguage(string languageName) { this.language.ChangLanguage(languageName); } } } <file_sep>using PrintService.Update; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PrintService.Common { public class ThrowHelper { /// <summary> /// Throw the exception when needed /// </summary> /// <param name="condition"></param> /// <param name="step"></param> /// <param name="message"></param> public static void TryThrow(bool condition, StepEnum step, string message) { if (!condition) { throw new UpdateException(step, message); } } } } <file_sep>using PrintService.Server; using PrintService.UI; using System; using System.Collections.Generic; using System.Windows.Forms; namespace PrintServer2.UI { public partial class Templates : Form { private PrintServer printServer = null; public Templates() { InitializeComponent(); this.Text = Language.I.Text("title_templates", "Supported Templates"); } public void SetList(PrintServer printServer) { this.printServer = printServer; foreach (var t in this.printServer.GetEngin().GetTemplates()) { this.listTemplates.Items.Add(t); } } private void listTemplates_MouseDoubleClick(object sender, MouseEventArgs e) { var box = (ListBox)sender; if (box.SelectedItem != null) { var tempName = box.SelectedItem.ToString(); var descObjects = this.printServer.GetEngin().GetTemplateDesc(tempName); var form = new ShowTemplateDesc(); form.SetList(descObjects); form.Show(); } } protected override void OnClosed(EventArgs e) { this.printServer = null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PrintService.Template { public class TemplateDesc { public string ParaName; public string ParaType; public string Demo; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HTTPServerLib { public interface IServer { /// <summary> /// 响应GET方法 /// </summary> /// <param name="request">Http请求</param> void OnGet(HttpRequest request, HttpResponse response); /// <summary> /// 响应Post方法 /// </summary> /// <param name="request">Http请求</param> void OnPost(HttpRequest request, HttpResponse response); /// <summary> /// 响应默认请求 /// </summary> /// <param name="request">Http请求</param> void OnDefault(HttpRequest request, HttpResponse response); } } <file_sep>using System; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Runtime.InteropServices; namespace HTTPServerLib { public class HttpServer : IServer { /// <summary> /// 服务器IP /// </summary> public string ServerIP { get; private set; } /// <summary> /// 服务器端口 /// </summary> public int ServerPort { get; private set; } /// <summary> /// 服务器目录 /// </summary> public string ServerRoot { get; private set; } /// <summary> /// 是否运行 /// </summary> public bool IsRunning { get; private set; } /// <summary> /// 服务器协议 /// </summary> public Protocols Protocol { get; private set; } /// <summary> /// 服务端Socet /// </summary> private TcpListener serverListener; /// <summary> /// 日志接口 /// </summary> public ILogger Logger { get; set; } /// <summary> /// SSL证书 /// </summary> private X509Certificate serverCertificate = null; /// <summary> /// 构造函数 /// </summary> /// <param name="ipAddress">IP地址</param> /// <param name="port">端口号</param> /// <param name="root">根目录</param> private HttpServer(IPAddress ipAddress, int port, string root) { this.ServerIP = ipAddress.ToString(); this.ServerPort = port; //如果指定目录不存在则采用默认目录 if (!Directory.Exists(root)) this.ServerRoot = AppDomain.CurrentDomain.BaseDirectory; this.ServerRoot = root; } /// <summary> /// 构造函数 /// </summary> /// <param name="ipAddress">IP地址</param> /// <param name="port">端口号</param> /// <param name="root">根目录</param> public HttpServer(string ipAddress, int port, string root) : this(IPAddress.Parse(ipAddress), port, root) { } /// <summary> /// 构造函数 /// </summary> /// <param name="ipAddress">IP地址</param> /// <param name="port">端口号</param> public HttpServer(string ipAddress, int port) : this(IPAddress.Parse(ipAddress), port, AppDomain.CurrentDomain.BaseDirectory) { } /// <summary> /// 构造函数 /// </summary> /// <param name="port">端口号</param> /// <param name="root">根目录</param> public HttpServer(int port, string root) : this(IPAddress.Loopback, port, root) { } /// <summary> /// 构造函数 /// </summary> /// <param name="port">端口号</param> public HttpServer(int port) : this(IPAddress.Loopback, port, AppDomain.CurrentDomain.BaseDirectory) { } /// <summary> /// 构造函数 /// </summary> /// <param name="ip"></param> public HttpServer(string ip) : this(IPAddress.Parse(ip), 80, AppDomain.CurrentDomain.BaseDirectory) { } #region 公开方法 /// <summary> /// 开启服务器 /// </summary> public void Start() { if (IsRunning) return; //创建服务端Socket this.serverListener = new TcpListener(IPAddress.Parse(ServerIP), ServerPort); this.Protocol = serverCertificate == null ? Protocols.Http : Protocols.Https; this.IsRunning = true; this.serverListener.Start(); this.Log(string.Format("Sever is running at {0}://{1}:{2}", Protocol.ToString().ToLower(), ServerIP, ServerPort)); try { while (IsRunning) { TcpClient client = serverListener.AcceptTcpClient(); Thread requestThread = new Thread(() => { ProcessRequest(client); }); requestThread.Start(); } } catch (Exception e) { Log(e.Message); } } public HttpServer SetSSL(string certificate) { return SetSSL(X509Certificate.CreateFromCertFile(certificate)); } public HttpServer SetSSL(X509Certificate certifiate) { this.serverCertificate = certifiate; return this; } public void Stop() { if (!IsRunning) return; IsRunning = false; serverListener.Stop(); } /// <summary> /// 设置服务器目录 /// </summary> /// <param name="root"></param> public HttpServer SetRoot(string root) { if (!Directory.Exists(root)) this.ServerRoot = AppDomain.CurrentDomain.BaseDirectory; this.ServerRoot = root; return this; } /// <summary> /// 获取服务器目录 /// </summary> public string GetRoot() { return this.ServerRoot; } /// <summary> /// 设置端口 /// </summary> /// <param name="port">端口号</param> /// <returns></returns> public HttpServer SetPort(int port) { this.ServerPort = port; return this; } #endregion #region 内部方法 /// <summary> /// 处理客户端请求 /// </summary> /// <param name="handler">客户端Socket</param> private void ProcessRequest(TcpClient handler) { //处理请求 Stream clientStream = handler.GetStream(); //处理SSL if (serverCertificate != null) clientStream = ProcessSSL(clientStream); if (clientStream == null) return; //构造HTTP请求 HttpRequest request = new HttpRequest(clientStream); request.Logger = Logger; //构造HTTP响应 HttpResponse response = new HttpResponse(clientStream); response.Logger = Logger; //处理请求类型 switch (request.Method) { case "GET": OnGet(request, response); break; case "POST": OnPost(request, response); break; default: OnDefault(request, response); break; } } /// <summary> /// 处理ssl加密请求 /// </summary> /// <param name="clientStream"></param> /// <returns></returns> private Stream ProcessSSL(Stream clientStream) { try { SslStream sslStream = new SslStream(clientStream); sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, true); sslStream.ReadTimeout = 10000; sslStream.WriteTimeout = 10000; return sslStream; } catch (Exception e) { Log(e.Message); clientStream.Close(); } return null; } /// <summary> /// 记录日志 /// </summary> /// <param name="message">日志消息</param> protected void Log(object message) { if (Logger != null) Logger.Log(message); } #endregion #region 虚方法 /// <summary> /// 响应Get请求 /// </summary> /// <param name="request">请求报文</param> public virtual void OnGet(HttpRequest request, HttpResponse response) { } /// <summary> /// 响应Post请求 /// </summary> /// <param name="request"></param> public virtual void OnPost(HttpRequest request, HttpResponse response) { } /// <summary> /// 响应默认请求 /// </summary> public virtual void OnDefault(HttpRequest request, HttpResponse response) { } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using HTTPServerLib; using System.IO; namespace PrintService.Server { public delegate string PostRequestReceived(HttpRequest request, string requestBody); public class HTTPServer : HttpServer { public PostRequestReceived OnPostRequestReceived = null; public HTTPServer(string ipAddress, int port) : base(ipAddress, port) { } public override void OnPost(HttpRequest request, HttpResponse response) { var returnMessage = ""; try { if (this.OnPostRequestReceived == null) { returnMessage = "Print server was not right configurated please concat your administrator!"; } else { returnMessage = this.OnPostRequestReceived(request, request.Body); } } catch (Exception ex) { returnMessage = "Unhanlded exception :" + ex.Message; } string jsonResult = "{\"code\":200, \"msg\":\"" + returnMessage + "\"}"; //build the response header response.SetContent(jsonResult); response.Content_Encoding = "utf-8"; response.StatusCode = "200"; response.Content_Type = "text/json; charset=UTF-8"; response.Headers = new Dictionary<string, string>(); response.SetHeader("Access-Control-Allow-Origin", "*"); response.SetHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Cookie, Accept"); response.SetHeader("Access-Control-Allow-Methods", "GET, POST"); response.SetHeader("Access-Control-Allow-Credentials", "true"); response.SetHeader("Server", "PrintServer"); //send the response response.Send(); } /// <summary> /// Report server status when GET request received /// </summary> /// <param name="request"></param> /// <param name="response"></param> public override void OnGet(HttpRequest request, HttpResponse response) { response = response.SetContent("Print server is running...", Encoding.UTF8); response.Content_Type = "text/html; charset=UTF-8"; response.StatusCode = "200"; response.Send(); } private string ConvertPath(string[] urls) { string html = string.Empty; int length = ServerRoot.Length; foreach (var url in urls) { var s = url.StartsWith("..") ? url : url.Substring(length).TrimEnd('\\'); html += String.Format("<li><a href=\"{0}\">{0}</a></li>", s); } return html; } private string ListDirectory(string requestDirectory, string requestURL) { //List directory var folders = requestURL.Length > 1 ? new string[] { "../" } : new string[] { }; folders = folders.Concat(Directory.GetDirectories(requestDirectory)).ToArray(); var foldersList = ConvertPath(folders); //List files var files = Directory.GetFiles(requestDirectory); var filesList = ConvertPath(files); //build html StringBuilder builder = new StringBuilder(); builder.Append(string.Format("<html><head><title>{0}</title></head>", requestDirectory)); builder.Append(string.Format("<body><h1>{0}</h1><br/><ul>{1}{2}</ul></body></html>", requestURL, filesList, foldersList)); return builder.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HTTPServerLib { public class ServiceRoute { public RouteMethod Method { get; private set; } public string RoutePath { get; private set; } public static ServiceRoute Parse(HttpRequest request) { var route = new ServiceRoute(); route.Method = (RouteMethod)Enum.Parse(typeof(RouteMethod), request.Method); route.RoutePath = request.URL; return route; } } } <file_sep>using System.IO; using System.Linq; namespace PrintService.Utility { public class FileHelper { #region invalid char in file name private static readonly char[] InvalidFileNameChars = new[] { '"', '<', '>', '|', '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ':', '*', '?', '\\', '/' }; #endregion /// <summary> /// Remove invalid char when try get a file name /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static string CleanInvalidFileName(string fileName) { fileName = fileName + ""; fileName = InvalidFileNameChars.Aggregate(fileName, (current, c) => current.Replace(c + "", "")); if (fileName.Length > 1) if (fileName[0] == '.') fileName = "dot" + fileName.TrimStart('.'); return fileName; } /// <summary> /// Create folder with giving path if it doesn't existed /// </summary> /// <param name="dir"></param> /// <returns></returns> public static string CreateDir(string directory) { try { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } } catch (DirectoryNotFoundException) { throw; } return directory; } /// <summary> /// Delete all files in sepcified folder /// </summary> /// <param name="dir"></param> public static void DeleteFilesInDir(string dir) { if (Directory.Exists(dir)) { foreach (string fileName in Directory.GetFiles(dir)) { File.Delete(fileName); } } } } } <file_sep>using PrintService.Server; using PrintService.Update; using System.Collections.Generic; namespace PrintService.Common { public delegate void VoidStringDelegate(string message); public delegate void PrinterChanged(string newPrintName); public delegate void PrinterLoaded(List<string> printerNames); public delegate void PrintServerLogging(string logMaeesage); public delegate void OnUpdateProcessed(StepEnum step, string message); public delegate void TemplateLoaded(string templateDesc); public delegate void OnPrintModeChanged(bool printNow); public delegate void OnPrintStatistics(PrintStatistics statistics); } <file_sep>using System.Configuration; using System.Linq; namespace PrintService.Utility { /// <summary> /// Helper for appSetting /// </summary> public class AppSettingHelper { /// <summary> /// Ttry to get value from appSetting with a seting name /// </summary> /// <param name="settingName"></param> /// <returns></returns> public static string GetOne(string settingName) { var config = GetConfiguration(); if (config.AppSettings.Settings.AllKeys.Any(key => key == settingName)) { return config.AppSettings.Settings[settingName].Value; } return ""; } /// <summary> /// Ttry to get value from appSetting with a seting name /// </summary> /// <param name="settingName"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string GetOne(string settingName, string defaultValue) { var setting = GetOne(settingName); if ("" == setting) { return defaultValue; } return setting; } /// <summary> /// Get the configuration object /// </summary> /// <returns></returns> private static Configuration GetConfiguration() { string file = System.Windows.Forms.Application.ExecutablePath; var config = ConfigurationManager.OpenExeConfiguration(file); return config; } /// <summary> /// Try to update setting /// </summary> /// <param name="settingName"></param> /// <param name="newValue"></param> public static void SetOne(string settingName, string newValue) { var config = GetConfiguration(); if (config.AppSettings.Settings.AllKeys.Any(key => key == settingName)) { config.AppSettings.Settings.Remove(settingName); } config.AppSettings.Settings.Add(settingName, newValue); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HTTPServerLib { public class BaseHeader { public string Body { get; set; } public Encoding Encoding { get; set; } public string Content_Type { get; set; } public string Content_Length { get; set; } public string Content_Encoding { get; set; } public string ContentLanguage { get; set; } public Dictionary<string, string> Headers { get; set; } /// <summary> /// 不支持枚举类型约束,所以采取下列方案:) /// </summary> protected string GetHeaderByKey(Enum header) { var fieldName = header.GetDescription(); if (fieldName == null) return null; var hasKey = Headers.ContainsKey(fieldName); if (!hasKey) return null; return Headers[fieldName]; } protected string GetHeaderByKey(string fieldName) { if (string.IsNullOrEmpty(fieldName)) return null; var hasKey = Headers.ContainsKey(fieldName); if (!hasKey) return null; return Headers[fieldName]; } /// <summary> /// 不支持枚举类型约束,所以采取下列方案:) /// </summary> protected void SetHeaderByKey(Enum header, string value) { var fieldName = header.GetDescription(); if (fieldName == null) return; var hasKey = Headers.ContainsKey(fieldName); if (!hasKey) Headers.Add(fieldName, value); Headers[fieldName] = value; } protected void SetHeaderByKey(string fieldName, string value) { if (string.IsNullOrEmpty(fieldName)) return; var hasKey = Headers.ContainsKey(fieldName); if (!hasKey) Headers.Add(fieldName, value); Headers[fieldName] = value; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.IO; using System.Text.RegularExpressions; namespace HTTPServerLib { /// <summary> /// HTTP请求定义 /// </summary> public class HttpRequest : BaseHeader { /// <summary> /// URL参数 /// </summary> public Dictionary<string, string> Params { get; private set; } /// <summary> /// HTTP请求方式 /// </summary> public string Method { get; private set; } /// <summary> /// HTTP(S)地址 /// </summary> public string URL { get; set; } /// <summary> /// HTTP协议版本 /// </summary> public string ProtocolVersion { get; set; } /// <summary> /// 定义缓冲区 /// </summary> private const int MAX_SIZE = 1024 * 1024 * 2; private byte[] bytes = new byte[MAX_SIZE]; public ILogger Logger { get; set; } private Stream handler; public HttpRequest(Stream stream) { this.handler = stream; var data = GetRequestData(handler); var rows = Regex.Split(data, Environment.NewLine); //Request URL & Method & Version var first = Regex.Split(rows[0], @"(\s+)") .Where(e => e.Trim() != string.Empty) .ToArray(); if (first.Length > 0) this.Method = first[0]; if (first.Length > 1) this.URL = Uri.UnescapeDataString(first[1]).Split('?')[0]; if (first.Length > 2) this.ProtocolVersion = first[2]; //Request Headers this.Headers = GetRequestHeaders(rows); //Request "GET" if (this.Method == "GET") { this.Body = GetRequestBody(rows); var isUrlencoded = this.URL.Contains('?'); if (isUrlencoded) this.Params = GetRequestParameters(URL.Split('?')[1]); } //Request "POST" if (this.Method == "POST") { this.Body = GetRequestBody(rows); var contentType = GetHeader(RequestHeaders.ContentType); var isUrlencoded = contentType == @"application/x-www-form-urlencoded"; if (isUrlencoded) this.Params = GetRequestParameters(this.Body); } } public Stream GetRequestStream() { return this.handler; } public string GetHeader(RequestHeaders header) { return GetHeaderByKey(header); } public string GetHeader(string fieldName) { return GetHeaderByKey(fieldName); } public void SetHeader(RequestHeaders header, string value) { SetHeaderByKey(header, value); } public void SetHeader(string fieldName,string value) { SetHeaderByKey(fieldName, value); } private string GetRequestData(Stream stream) { var length = 0; var data = string.Empty; do { length = stream.Read(bytes, 0, MAX_SIZE - 1); data += Encoding.UTF8.GetString(bytes, 0, length); } while (length > 0 && !data.Contains("\r\n\r\n")); return data; } private string GetRequestBody(IEnumerable<string> rows) { var target = rows.Select((v, i) => new { Value = v, Index = i }).FirstOrDefault(e => e.Value.Trim() == string.Empty); if (target == null) return null; var range = Enumerable.Range(target.Index + 1, rows.Count() - target.Index - 1); return string.Join(Environment.NewLine, range.Select(e => rows.ElementAt(e)).ToArray()); } private Dictionary<string, string> GetRequestHeaders(IEnumerable<string> rows) { if (rows == null || rows.Count() <= 0) return null; var target = rows.Select((v, i) => new { Value = v, Index = i }).FirstOrDefault(e => e.Value.Trim() == string.Empty); var length = target == null ? rows.Count() - 1 : target.Index; if (length <= 1) return null; var range = Enumerable.Range(1, length - 1); return range.Select(e => rows.ElementAt(e)).ToDictionary(e => e.Split(':')[0], e => e.Split(':')[1].Trim()); } private Dictionary<string, string> GetRequestParameters(string row) { if (string.IsNullOrEmpty(row)) return null; var kvs = Regex.Split(row, "&"); if (kvs == null || kvs.Count() <= 0) return null; return kvs.ToDictionary(e => Regex.Split(e, "=")[0], e => Regex.Split(e, "=")[1]); } } } <file_sep>using System; using HTTPServerLib; namespace PrintService.Server { public class ConsoleLogger : ILogger { public void Log(object message) { Console.WriteLine(message); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HTTPServerLib { public class HttpResponse : BaseHeader { public string StatusCode { get; set; } public string Protocols { get; set; } public string ProtocolsVersion { get; set; } public byte[] Content { get; private set; } private Stream handler; public ILogger Logger { get; set; } public HttpResponse(Stream stream) { this.handler = stream; } public HttpResponse SetContent(byte[] content, Encoding encoding = null) { this.Content = content; this.Encoding = encoding != null ? encoding : Encoding.UTF8; this.Content_Length = content.Length.ToString(); return this; } public HttpResponse SetContent(string content, Encoding encoding = null) { //初始化内容 encoding = encoding != null ? encoding : Encoding.UTF8; return SetContent(encoding.GetBytes(content), encoding); } public Stream GetResponseStream() { return this.handler; } public string GetHeader(ResponseHeaders header) { return GetHeaderByKey(header); } public string GetHeader(string fieldName) { return GetHeaderByKey(fieldName); } public void SetHeader(ResponseHeaders header, string value) { SetHeaderByKey(header, value); } public void SetHeader(string fieldName, string value) { SetHeaderByKey(fieldName, value); } /// <summary> /// 构建响应头部 /// </summary> /// <returns></returns> protected string BuildHeader() { StringBuilder builder = new StringBuilder(); if (!string.IsNullOrEmpty(StatusCode)) builder.Append("HTTP/1.1 " + StatusCode + "\r\n"); if (!string.IsNullOrEmpty(this.Content_Type)) builder.AppendLine("Content-Type:" + this.Content_Type); if (this.Headers != null && this.Headers.Count > 0) { foreach (KeyValuePair<string, string> header in this.Headers) { builder.AppendLine(header.Key + ":" + header.Value + "\r\n"); } builder.Remove(builder.Length - 2, 2); } return builder.ToString(); } /// <summary> /// 发送数据 /// </summary> public void Send() { if (!handler.CanWrite) return; try { //发送响应头 var header = BuildHeader(); byte[] headerBytes = this.Encoding.GetBytes(header); handler.Write(headerBytes, 0, headerBytes.Length); //发送空行 byte[] lineBytes = this.Encoding.GetBytes(System.Environment.NewLine); handler.Write(lineBytes, 0, lineBytes.Length); //发送内容 handler.Write(Content, 0, Content.Length); } catch (Exception e) { Log(e.Message); } finally { handler.Close(); } } /// <summary> /// 记录日志 /// </summary> /// <param name="message">日志消息</param> private void Log(object message) { if (Logger != null) Logger.Log(message); } } } <file_sep>namespace PrintService.Template { /// <summary> /// Define the print object /// </summary> public interface IPrintObject { void Print(bool printNows); int Intervel(); } } <file_sep>using System.Collections.Generic; using System.IO; using System.Web.Script.Serialization; namespace PrintService.UI { /// <summary> /// Load lanaguage /// </summary> public class Language { private Dictionary<string, string> languages = null; private const string DefaultLanguageHint = "Default(En_US)"; private string languageHint = ""; private static Language instance = null; /// <summary> /// single instance mode /// </summary> /// <returns></returns> public static Language I { get { if (instance == null) { instance = new Language(); } return instance; } } public Language() { } /// <summary> /// 更改语言 /// </summary> /// <param name="languageFile"></param> public void ChangLanguage(string languageFilePath) { try { if (File.Exists(languageFilePath)) { var json = File.ReadAllText(languageFilePath); var serializer = new JavaScriptSerializer(); this.languages = (Dictionary<string, string>)serializer.Deserialize<Dictionary<string, string>>(json); this.languageHint = this.languages.ContainsKey("name") ? this.languages["name"] : "Unkonwn Language"; } } catch { } } /// <summary> /// Get the lanaguage name /// </summary> /// <returns></returns> public string Hint() { return this.languages == null ? DefaultLanguageHint : this.languageHint; } /// <summary> /// Get UI text with giving /// </summary> /// <param name="textKey"></param> /// <param name="defaultText"></param> /// <returns></returns> public string Text(string textKey, string defaultText) { if (this.languages != null && this.languages.ContainsKey(textKey)) { return this.languages[textKey]; } return defaultText; } } } <file_sep>using PrintService.Utility; using System; using Telerik.Reporting; namespace PrintService.Template { public abstract class PdfPrintBase : Telerik.Reporting.Report, IPrintObject { public void Print(bool printNow) { this.SetReportData(); var filePath = this.GeneratePdf(this); } public string file_name { get; set; } public string print_type { get; set; } public int print_interval { get; set; } /// <summary> /// Let child set their own data /// </summary> public abstract void SetReportData(); /// <summary> /// Generate pdf file /// </summary> /// <param name="report"></param> /// <returns></returns> protected string GeneratePdf(IReportDocument report) { FileHelper.CreateDir(ReportGenerator.FileSavePath); string fullPath = ReportGenerator.FileSavePath + "\\" + FileHelper.CleanInvalidFileName(this.file_name) + ".pdf"; Exception exportException; ReportGenerator.SaveReport(report, fullPath, out exportException, "PDF"); if (exportException != null) { throw exportException; } return fullPath; } public int Intervel() { return this.print_interval; } } } <file_sep>namespace PrintService.Update { public enum StepEnum { OnPrepare = 0, OnCheck = 1, OnBackup = 2, OnDownload = 3, OnUpdate = 4, OnRecover = 5 } public enum UpdateType { NewFile = 1, NewVersion = 2, DeleteFile = 3 } } <file_sep>using PrintService.Common; using PrintService.UI; using PrintService.Utility; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace PrintService.Update { public class UpdateWorker { public VoidStringDelegate OnUpdateStarted = null; private UpdateTimer timer = null; /// <summary> /// Process Handler /// </summary> private OnUpdateProcessed updateProcessedHandler = null; /// <summary> /// IChecker /// </summary> private IUpdateChecker updateChecker = null; private List<UpdateItem> updateItem = null; private const string UpdatePath = "/temp/update/"; private const string BackupPath = "/temp/backup/"; /// <summary> /// Indicate that if the update process was needed /// </summary> private bool needUpdate = false; private bool inProgress = false; /// <summary> /// Simplify construct using lamuda expresion /// </summary> /// <param name="checker"></param> public UpdateWorker(IUpdateChecker checker) { this.updateChecker = checker; this.timer = new UpdateTimer(this); } public void SetUpdateProcessedHandler(OnUpdateProcessed handler) { this.updateProcessedHandler = handler; } /// <summary> /// Start update progress /// </summary> public void StartProgress() { if (this.inProgress) { return; } this.inProgress = true; try { this.Prepare(); this.CheckUpdateList(); if (this.needUpdate) { var msg = Language.I.Text("update_started", "Update progress started."); this.OnUpdateStarted?.Invoke(msg); } this.BackUp(); this.DownloadFile(); } catch { this.CleanUpOnError(); } finally { this.inProgress = false; } } /// <summary> /// Fire the update event /// </summary> /// <param name="step"></param> /// <param name="message"></param> private void FireEvent(StepEnum step, string message) { this.updateProcessedHandler?.Invoke(step, message); } /// <summary> /// Check current state /// </summary> /// <returns></returns> public bool NeedUpdate() { return this.needUpdate; } public void Prepare() { var uri = AppSettingHelper.GetOne("UpdateServer"); ThrowHelper.TryThrow("" != uri, StepEnum.OnPrepare, Language.I.Text("empty_update_uri", "Can not get update url!")); this.updateChecker.SetURI(uri); } /// <summary> /// Check update file list /// </summary> public void CheckUpdateList() { try { this.FireEvent(StepEnum.OnCheck, Language.I.Text("getting_list", "Fetching update file list!")); var cp = new VersionComparer(); this.updateItem = cp.CompareVersion(this.GetLocalFileVersion(), this.updateChecker.GetUpdateItems()); this.needUpdate = this.updateItem.Count > 0; this.FireEvent(StepEnum.OnCheck, "关系列表获取完成,共" + this.updateItem.Count + "个文件需要更新"); } catch (UpdateException e) { this.needUpdate = false; this.FireEvent(StepEnum.OnCheck, e.Message); throw; } catch (Exception ex) { this.needUpdate = false; this.FireEvent(StepEnum.OnCheck, "获取更新文件列表失败"); } } /// <summary> /// Get the local file info /// </summary> /// <returns></returns> private Dictionary<string, string> GetLocalFileVersion() { var localFileVerInfos = new Dictionary<string, string>(); var curruentDir = Environment.CurrentDirectory + "\\"; DirectoryInfo dirInfo = new DirectoryInfo(curruentDir); foreach (FileInfo file in dirInfo.GetFiles("*dll")) { localFileVerInfos.Add(file.Name, FileVersionInfo.GetVersionInfo(file.FullName).FileVersion); } return localFileVerInfos; } /// <summary> /// Start download the updating file /// </summary> public void DownloadFile() { if (!this.needUpdate) { return; } var updateFileFolder = Environment.CurrentDirectory + UpdatePath; FileHelper.CreateDir(updateFileFolder); FileHelper.DeleteFilesInDir(updateFileFolder); try { foreach (var item in this.updateItem) { this.updateChecker.GetUpdateFIle(item, updateFileFolder); } } catch (UpdateException e) { this.needUpdate = false; this.FireEvent(e.GetStep(), e.Message); throw; } catch (Exception ex) { this.needUpdate = false; var msg = Language.I.Text("download_error", "Someting wrony when downloading update files"); this.FireEvent(StepEnum.OnDownload, msg); } } /// <summary> /// Do the backup task /// </summary> public void BackUp() { if (!this.needUpdate) { return; } var backupFileFolder = Environment.CurrentDirectory + BackupPath; FileHelper.CreateDir(backupFileFolder); FileHelper.DeleteFilesInDir(backupFileFolder); try { foreach (var item in this.updateItem) { File.Copy(item.FullPath(), backupFileFolder); } } catch (UpdateException e) { this.needUpdate = false; this.FireEvent(e.GetStep(), e.Message); throw; } catch (Exception ex) { this.needUpdate = false; var msg = Language.I.Text("backup_error", "Someting wrony when backing up update files"); this.FireEvent(StepEnum.OnBackup, msg); } } /// <summary> /// Do the update work /// Kill this /// </summary> /// <returns></returns> public void DoUpdate() { if (!this.needUpdate) { return; } } /// <summary> /// Clean files when update error /// </summary> private void CleanUpOnError() { var updateFileFolder = Environment.CurrentDirectory + UpdatePath; FileHelper.DeleteFilesInDir(updateFileFolder); var backupFileFolder = Environment.CurrentDirectory + BackupPath; FileHelper.DeleteFilesInDir(backupFileFolder); } } } <file_sep>using PrintService.Common; using PrintService.Server; using PrintService.UI; using System; using System.Collections.Generic; using System.Windows.Forms; namespace PrintServer2.UI { public partial class Logs : Form { private LogContainer logContainer = null; public Logs() { InitializeComponent(); this.Text = Language.I.Text("title_log", "Print Logs"); } public void SetLoger(LogContainer logContainer) { this.logContainer = logContainer; this.logContainer.OnLogging = this.OnLogging; foreach (var log in logContainer.GetLogs()) { this.listTemplates.Items.Add(log); } } private void OnLogging(string logMaeesage) { if (this.listTemplates.InvokeRequired) { this.listTemplates.Invoke(new PrinterChanged(this.OnLogging), logMaeesage); } else { this.listTemplates.Items.Add(logMaeesage); } } protected override void OnClosed(EventArgs e) { this.logContainer.OnLogging = null; } } } <file_sep>using PrintService.Common; using PrintService.UI; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace PrintService.Template { public class TemplateContainer { public TemplateLoaded TemplateLoaded = null; private Dictionary<string, Type> container = null; private Dictionary<string, List<TemplateDesc>> templateDescContainer = null; public static TemplateContainer instance = null; public static TemplateContainer GetInstance() { if (instance == null) { instance = new TemplateContainer(); } return instance; } public Dictionary<string, Type> GetTemplateList() { return this.container; } public TemplateContainer() { this.container = new Dictionary<string, Type>(); this.templateDescContainer = new Dictionary<string, List<TemplateDesc>>(); } /// <summary> /// Get template type /// </summary> /// <param name="typeName"></param> /// <returns></returns> public Type GetTemplateType(string typeName) { if (!this.container.ContainsKey(typeName)) { throw new Exception(Language.I.Text("unknown_template", "Unknown template plage check your data.")); } return this.container[typeName]; } /// <summary> /// Get the decription of the template /// </summary> /// <param name="templateName"></param> /// <returns></returns> public List<TemplateDesc> GetTemplateDesc(string templateName) { if (!this.templateDescContainer.ContainsKey(templateName)) { var templateDesc = new List<TemplateDesc>(); var properties = this.GetTemplateType(templateName).GetProperties(BindingFlags.Instance & BindingFlags.Public); foreach (var p in properties) { var attributes = p.GetCustomAttributes(typeof(TemplateParaAttribute), true); if (attributes.Length > 0) { var target = (TemplateParaAttribute)attributes[0]; templateDesc.Add(new TemplateDesc() { ParaName = p.Name, ParaType = target.GetParaType(), Demo = target.GetDemo() }); } } this.templateDescContainer.Add(templateName, templateDesc); return templateDesc; } throw new Exception(Language.I.Text("template_desc_error", "Can not found the desc of this template.")); } /// <summary> /// Scan all dll in current executing folder to find supported template /// </summary> public void SacnTemplate() { var files = Directory.GetFiles(Environment.CurrentDirectory, "*.dll"); foreach (var fileName in files) { var foundTemplates = Assembly.LoadFile(fileName).GetTypes().Where<Type>(x => x.IsSubclassOf(typeof(PdfPrintBase)) && x.IsAbstract == false); foreach (var template in foundTemplates) { var templateName = template.Name; if (!container.ContainsKey(templateName)) { container.Add(templateName, template); try { this.TemplateLoaded ?.Invoke(templateName); } catch { } } } } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Diagnostics; using System.Drawing.Printing; using System.Threading; using HTTPServerLib; using PrintService.Common; using PrintService.Template; using PrintService.UI; using PrintService.Update; using PrintService.Utility; namespace PrintService.Server { public class PrintServer { private List<string> availablePrinterNames = new List<string>(); private string selectedPrinterName = ""; public PrinterLoaded OnPrinterLoaded = null; public PrinterChanged OnPrinterChanged = null; public PrintServerLogging OnPrintServerLogged = null; public OnPrintStatistics OnStatisticsStateChanged = null; public OnPrintModeChanged OnPrintModeChanged = null; private readonly HTTPServer HttpServer = null; private readonly Thread ServerThread = null; private LogContainer logContainer = null; private PrintStatistics printStatistics = null; private UpdateWorker updateWorker = null; private IEngin printEngin = null; private bool PrintNow = true; private bool _requestStop = false; private int port = 4050; private int GetServerPort() { var portString = AppSettingHelper.GetOne("ServerPort", this.port.ToString()); int.TryParse(portString, out this.port); return this.port; } public int GetWorkingPort() { return this.port; } public PrintServer() { string rootPath = Environment.CurrentDirectory; this.HttpServer = new HTTPServer("0.0.0.0", this.GetServerPort()); this.HttpServer.SetRoot(rootPath); this.HttpServer.OnPostRequestReceived = this.OnPrintRequestReceived; this.HttpServer.Logger = new FileLogger(); this.printEngin = PrintObjectFactory.GetEngin(AppSettingHelper.GetOne("engin", "PDF")); this.printEngin.Initialize(); this.logContainer = new LogContainer(); this.printStatistics = new PrintStatistics(); this.ServerThread = new Thread(new ThreadStart(HttpServerThread)); this.OnPrintServerLogged = delegate (string maeesage) { Console.WriteLine(maeesage); }; this.updateWorker = new UpdateWorker(UpdateCheckerProvider.GetChcker()); } public void LoadPrinters() { this.availablePrinterNames.Clear(); foreach (var printer in PrinterSettings.InstalledPrinters) { this.availablePrinterNames.Add(printer.ToString()); } OnPrinterLoaded?.Invoke(availablePrinterNames); string defaultPrinter = ReadPrinterName(); this.selectedPrinterName = defaultPrinter; if (!string.IsNullOrEmpty(defaultPrinter)) { if (this.availablePrinterNames.Contains(defaultPrinter)) { this.SelectPrinter(defaultPrinter); } else { SafeFireLoging("上次使用的打印机器:" + defaultPrinter + " 已经无效,请重新选择打印机"); } } if (this.availablePrinterNames.Count == 0) { this.SafeFireLoging("打印机加载失败,未找到可用打印机,您可以查看点击查看文件"); } else { this.SafeFireLoging("打印机加载成功,当前可用打印机数量:" + availablePrinterNames.Count); } } private void StartServer() { if (!ServerThread.IsAlive) { this._requestStop = false; ServerThread.Start(); StartSerialPrintThread(); SafeFireLoging("服务线程已启动,正在尝试打开服务..."); } } public void SetPrintNow(bool printNow) { this.PrintNow = printNow; try { this.OnPrintModeChanged?.Invoke(this.PrintNow); } catch { } } public bool GetPrintMode() { return this.PrintNow; } private void HttpServerThread() { try { SafeFireLoging("服务已启动,您现在可以打印..."); HttpServer.Start(); } catch (Exception ex) { SafeFireLoging("出现异常,服务已关闭:" + ex.Message); HttpServer.Logger.Log(ex.ToString()); } } public void StopServer() { try { HttpServer.Stop(); HttpServer?.Stop(); _requestStop = true; this.printEvent.Set(); SafeFireLoging(Language.I.Text("stoped", "Server was stoped")); } catch (Exception ex) { SafeFireLoging(Language.I.Text("stoped", "Server was stoped")); HttpServer.Logger.Log(ex.ToString()); } } /// <summary> /// Return the print engin /// </summary> /// <returns></returns> public IEngin GetEngin() { return this.printEngin; } /// <summary> /// Get loger /// </summary> /// <returns></returns> public LogContainer GetLoger() { return this.logContainer; } /// <summary> /// Get statistics object /// </summary> /// <returns></returns> public PrintStatistics GetStatistics() { return this.printStatistics; } /// <summary> /// 获取已经选择的打印机 /// </summary> /// <returns></returns> public string GetSelectedPrinterName() { return this.selectedPrinterName; } private Thread serialPrinThread = null; private void StartSerialPrintThread() { try { serialPrinThread = new Thread(new ThreadStart(SerialPrintThread)); serialPrinThread.Start(); SafeFireLoging("同步打印线程开启成功,当接请求需要同步打印时系统将请求接受顺序打印!"); } catch (Exception e) { SafeFireLoging("同步打印线程开启失败,当前不支持顺序打印!"); HttpServer.Logger.Log(e.ToString()); } } private string OnPrintRequestReceived(HttpRequest request, string jsonBody) { try { ThreadPool.QueueUserWorkItem(new WaitCallback(PrintWithThread), request); SafeFireLoging(Language.I.Text("add_succeed", "Add task succeed")); return Language.I.Text("request_accepted", "Print request acceepted."); } catch (Exception e) { HttpServer.Logger.Log(e.ToString()); return Language.I.Text("request_error", "Print request was not acceepted."); ; } } private object _locker = new object(); private void PrintWithThread(object objectPara) { try { HttpRequest httpRequest = objectPara as HttpRequest; if (httpRequest != null) { IPrintObject model = this.printEngin.GetPrintModel(httpRequest.Body); if (model.Intervel() <= 0) { //不要求顺序打印 DoPrintJobWithModel(model); } else { DoPrintJonWithModelSerial(model); } } else { var message = Language.I.Text("type_error", "Current parameter was not acctpeetable"); SafeFireLoging(message); } } catch (Exception ex) { SafeFireLoging(Language.I.Text("err_print", "Error:") + ex.Message); HttpServer.Logger.Log(ex.ToString()); } SafeFirsStatistics(); } ManualResetEvent printEvent = new ManualResetEvent(false); private void SerialPrintThread() { while (true && !this._requestStop) { IPrintObject nextModl = PrintQueue.PopAJob(); if (nextModl == null) { printEvent.WaitOne(); } else { DoPrintJobWithModel(nextModl); Thread.Sleep(nextModl.Intervel() * 1000); } } } public void StopSerialPrint() { printEvent.Set(); } private void DoPrintJobWithModel(IPrintObject model) { model.Print(this.PrintNow); } private void DoPrintJonWithModelSerial(IPrintObject model) { PrintQueue.AddJob(model); printEvent.Set(); } /// <summary> /// 开启流程 /// </summary> public void StartProcess() { this.LoadPrinters(); this.StartServer(); } private void SafeFireLoging(string message) { try { message = DateTime.Now.ToString() + ": " + message; this.logContainer.AddLog(message); OnPrintServerLogged?.Invoke(message); } catch (Exception ex) { HttpServer.Logger.Log(ex.ToString()); } } private void SafeFirsStatistics() { try { OnStatisticsStateChanged?.Invoke(this.printStatistics); } catch (Exception ex) { SafeFireLoging(Language.I.Text("statistics", "Update statistics error!")); HttpServer.Logger.Log(ex.ToString()); } } public void SelectPrinter(string printerName) { try { if (this.availablePrinterNames.Contains(printerName) && !string.IsNullOrEmpty(printerName)) { this.selectedPrinterName = printerName; OnPrinterChanged?.Invoke(this.selectedPrinterName); var printLog = Language.I.Text("printer_selected", "Printer selected and this printer will be used when next start!"); SafeFireLoging(printLog); WritPrinterName(printerName); } else { SafeFireLoging(Language.I.Text("invalid_printer", "Printer was invalid!")); } } catch (Exception ex) { SafeFireLoging(Language.I.Text("invalid_printer", "Printer was invalid!")); HttpServer.Logger.Log(ex.ToString()); } } private void PrintFile(string shortFile) { bool succeed = false; try { this.OpenFile(shortFile); succeed = true; } catch (Exception ex) { this.SafeFireLoging(Language.I.Text("unknown_error", "Unknown error!")); HttpServer.Logger.Log(ex.ToString()); } this.printStatistics.Printed(succeed); this.SafeFirsStatistics(); } public void PrintFile(List<string> files) { foreach (string file in files) { this.PrintFile(file); } } private string ReadPrinterName() { string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); foreach (string key in config.AppSettings.Settings.AllKeys) { if (key == ConfKeyName) { return config.AppSettings.Settings[key].Value.ToString(); } } return null; } private const string ConfKeyName = "SelectedPrinterName"; private void WritPrinterName(string newPrinterName) { string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); bool exist = false; foreach (string key in config.AppSettings.Settings.AllKeys) { if (key == ConfKeyName) { exist = true; } } if (exist) { config.AppSettings.Settings.Remove(ConfKeyName); } config.AppSettings.Settings.Add(ConfKeyName, newPrinterName); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); } private void OpenFile(string shortFile) { try { ProcessStartInfo info = new ProcessStartInfo(); info.Verb = "print"; Process p = new Process(); info.FileName = shortFile; info.CreateNoWindow = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.Arguments = this.selectedPrinterName; info.WindowStyle = ProcessWindowStyle.Hidden; p.StartInfo = info; p.Start(); p.WaitForInputIdle(); //File.Delete(shortFile); } catch (Win32Exception win32Exception) { var msg = Language.I.Text("reader_require", "Pdf reader was required, please install and set is as default."); this.SafeFireLoging(msg); throw; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HTTPServerLib { [AttributeUsage(AttributeTargets.Method)] class RouteAttribute:Attribute { public RouteMethod Method { get; set; } public string RoutePath { get; set; } } } <file_sep>using PrintService.Template; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace PrintServer2.UI { public partial class ShowTemplateDesc : Form { public ShowTemplateDesc() { InitializeComponent(); } public void SetList(List<TemplateDesc> desc) { foreach (var d in desc) { var msg = d.ParaName + " type [" + d.ParaType + "], Demo:" + d.Demo; this.listTemplateDesc.Items.Add(msg); } } } } <file_sep>using System; using System.Configuration; using HTTPServerLib; namespace PrintService.Server { public class FileLogger : ILogger { public FileLogger() { this.log = log4net.LogManager.GetLogger("loginfo"); var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + ConfigurationManager.AppSettings["log4net"]; var fi = new System.IO.FileInfo(path); log4net.Config.XmlConfigurator.Configure(fi); } private log4net.ILog log = null; public void Log(object message) { log.Info(message.ToString()); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Runtime.InteropServices; namespace HTTPServerLib { public static class ResponseHelper { public static HttpResponse FromFile(this HttpResponse response, string fileName) { if (!File.Exists(fileName)) { response.SetContent("<html><body><h1>404 - Not Found</h1></body></html>"); response.StatusCode = "404"; response.Content_Type = "text/html"; return response; } var content = File.ReadAllBytes(fileName); var contentType = GetMimeFromFile(fileName); response.SetContent(content); response.Content_Type = contentType; response.StatusCode = "200"; return response; } public static HttpResponse FromXML(this HttpResponse response, string xmlText) { response.SetContent(xmlText); response.Content_Type = "text/xml"; response.StatusCode = "200"; return response; } public static HttpResponse FromXML<T>(this HttpResponse response, T entity) where T : class { return response.FromXML(""); } public static HttpResponse FromJSON(this HttpResponse response, string jsonText) { response.SetContent(jsonText); response.Content_Type = "text/json"; response.StatusCode = "200"; return response; } public static HttpResponse FromJSON<T>(this HttpResponse response, T entity) where T : class { return response.FromJSON(""); } public static HttpResponse FromText(this HttpResponse response, string text) { response.SetContent(text); response.Content_Type = "text/plain"; response.StatusCode = "200"; return response; } private static string GetMimeFromFile(string filePath) { IntPtr mimeout; if (!File.Exists(filePath)) throw new FileNotFoundException(string.Format("File {0} can't be found at server.", filePath)); int MaxContent = (int)new FileInfo(filePath).Length; if (MaxContent > 4096) MaxContent = 4096; byte[] buf = new byte[MaxContent]; using (FileStream fs = File.OpenRead(filePath)) { fs.Read(buf, 0, MaxContent); fs.Close(); } int result = FindMimeFromData(IntPtr.Zero, filePath, buf, MaxContent, null, 0, out mimeout, 0); if (result != 0) throw Marshal.GetExceptionForHR(result); string mime = Marshal.PtrToStringUni(mimeout); Marshal.FreeCoTaskMem(mimeout); return mime; } [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)] static extern int FindMimeFromData(IntPtr pBC, [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer, int cbSize, [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed, int dwMimeFlags, out IntPtr ppwzMimeOut, int dwReserved); } } <file_sep>using System.Collections.Generic; namespace PrintService.Template { public interface IEngin { IPrintObject GetPrintModel(string printData); List<string> GetTemplates(); void Initialize(); List<TemplateDesc> GetTemplateDesc(string templateName); } } <file_sep> using PrintService.Template; namespace ReportTemplates.Transport { /// <summary> /// Summary description for PickOrderProductLabel. /// </summary> public partial class SinglePageDemo : PdfPrintBase { public SinglePageDemo() { InitializeComponent(); } [TemplatePara("String", "RBRB81612221333")] public string after_sale_no; [TemplatePara("String", "<NAME>")] public string reciver; [TemplatePara("String", "13585860114")] public string tel; [TemplatePara("String", "ShangHaiChina ")] public string address; [TemplatePara("String", "The Main distribute center")] public string warehouse_name; [TemplatePara("String", "RBRB81612221333")] public string supplier_code; public override void SetReportData() { barCodeNumber.Value = this.after_sale_no; txtNumber.Value = this.after_sale_no; txtNumber2.Value = this.after_sale_no; txtName.Value = this.reciver; txtTel.Value = this.tel; txtAddress.Value = this.address; txtWarehouseName.Value = this.warehouse_name; txtSupplierCode.Value = this.supplier_code; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using NUnit.Framework; using PrintService.Utility; namespace Test { [TestFixture] public class TestShareFolder { private string testPath = "\\\\192.168.2.47\\TestShare"; private string tempPath = Environment.CurrentDirectory + "\\temp"; [SetUp] public void Connect() { ShareFolderHelper.ConnectShareFolder(testPath, "xiangbohua", "xiangbohua1"); FileHelper.CreateDir(tempPath); } [TestCase] public void TestListDIr() { var files = Directory.GetFiles(testPath); Assert.AreNotEqual(files.Length, 0); } [TestCase] public void TestCopyFile() { var files = Directory.GetFiles(testPath); Assert.AreNotEqual(files.Length, 0); var filePath = files[0]; var fileName = Path.GetFileName(filePath); var newPath = this.tempPath + "\\" + fileName; File.Copy(filePath, newPath); Assert.True(File.Exists(newPath)); File.Delete(newPath); } [TearDown] public void Disconnect() { ShareFolderHelper.Disconnect(testPath); } } } <file_sep>using PrintService.Server; using System; using System.Windows.Forms; namespace PrintServer2.UI { internal class TrayEventHander { private PrintServer printServer = null; /// <summary> /// Let the hanlder hold a server object and then all those click event will be processed in this class /// </summary> /// <param name="printServer"></param> public TrayEventHander(PrintServer server) { this.printServer = server; } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void RefreshPrinter_Click(object sender, EventArgs e) { this.printServer.LoadPrinters(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void SelectPrinter_Click(object sender, EventArgs e) { var menuItem = (MenuItem)sender; this.printServer.SelectPrinter(menuItem.Tag.ToString()); } /// <summary> /// when exit menu clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Exit_Click(object sender, EventArgs e) { this.printServer.StopServer(); Application.Exit(); } internal void SupportedTemplates_Click(object sender, EventArgs e) { Templates formTemplate = new Templates(); formTemplate.SetList(this.printServer); formTemplate.Show(); } internal void PrintMode_Click(object sender, EventArgs e) { var printNow = (MenuItem)sender; this.printServer.SetPrintNow(!printNow.Checked); } internal void ShowLog_Click(object sender, EventArgs e) { Logs logForm = new Logs(); logForm.SetLoger(this.printServer.GetLoger()); logForm.Show(); } } } <file_sep>using PrintService.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace PrintService.Update { public class UpdateTimer { private UpdateWorker updateWoker = null; private Timer updateTimer = null; /// <summary> /// Update period unit : hour /// </summary> private decimal updatePeriod = 1; public UpdateTimer(UpdateWorker woker) { this.updateWoker = woker; this.updateTimer = new Timer(this.OnUpdate, null, 10000, this.GetUpdatePeriod()); } private int GetUpdatePeriod() { var periodString = AppSettingHelper.GetOne("UpdatePeriod", this.updatePeriod.ToString()); decimal.TryParse(periodString, out this.updatePeriod); if (this.updatePeriod < (decimal)0.1) { this.updatePeriod = (decimal)0.1; } //return (int)(this.updatePeriod * 1000 * 3600); return 60000; } private void OnUpdate(object state) { this.updateWoker.StartProgress(); } } } <file_sep>using System; namespace PrintService.Update { public class UpdateException : Exception { private StepEnum step = 0; public StepEnum GetStep() { return this.step; } public UpdateException(StepEnum onStep, string message) : base(message) { this.step = onStep; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HTTPServerLib { public class HttpService : HttpServer { private List<ServiceModule> m_modules; public HttpService(string ipAddress, int port) : base(ipAddress, port) { m_modules = new List<ServiceModule>(); } /// <summary> /// 注册模块 /// </summary> /// <param name="module">ServiceModule</param> public void RegisterModule(ServiceModule module) { this.m_modules.Add(module); } /// <summary> /// 卸载模块 /// </summary> /// <param name="module"></param> public void RemoveModule(ServiceModule module) { this.m_modules.Remove(module); } public override void OnDefault(HttpRequest request, HttpResponse response) { base.OnDefault(request, response); } public override void OnGet(HttpRequest request, HttpResponse response) { ServiceRoute route = ServiceRoute.Parse(request); ServiceModule module = m_modules.FirstOrDefault(m => m.SearchRoute(route)); if (module != null){ var result = module.ExecuteRoute(route); } } public override void OnPost(HttpRequest request, HttpResponse response) { base.OnPost(request, response); } } } <file_sep>using PrintServer2.Properties; using PrintService.Utility; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace PrintServer2 { public partial class Main : Form { private NotifyIcon notifyIcon = null; private bool _finalExit = false; public Main() { InitializeComponent(); this.InitialTray(); } /// <summary> /// Try to get icon for task bar /// first: try to find a icon file named logo.icon in folder Resources. if not found then use the build-in icon /// </summary> /// <returns></returns> private Icon GetTaskBarIcon() { var filePath = Environment.CurrentDirectory + "\\logo.ico"; var logo = File.Exists(filePath); if (logo) { return new Icon(filePath); } return Resources._default; } private void InitialTray() { //实例化一个NotifyIcon对象 notifyIcon = new NotifyIcon(); //托盘图标气泡显示的内容 notifyIcon.BalloonTipText = AppSettingHelper.GetOne("IconHint", "Print server was runing in backgroud"); //托盘图标显示的内容 notifyIcon.Text = AppSettingHelper.GetOne("HideHint", "Click icon to open main window"); notifyIcon.Icon = this.GetTaskBarIcon(); //true表示在托盘区可见,false表示在托盘区不可见 notifyIcon.Visible = true; //气泡显示的时间(单位是毫秒) notifyIcon.ShowBalloonTip(2000); //notifyIcon.MouseClick += notifyIcon_MouseClick; MenuItem reciveNoti = new MenuItem("接收通知"); //reciveNoti.Click += reciveNoti_Click; MenuItem stopNoti = new MenuItem("暂停通知"); //stopNoti.Click += about_Click; MenuItem exit = new MenuItem("退出"); //exit.Click += new EventHandler(exit_Click); ////关联托盘控件 //注释的这一行与下一行的区别就是参数不同,setting这个参数是为了实现二级菜单 //MenuItem[] childen = new MenuItem[] { setting, help, about, exit }; MenuItem[] childen = new MenuItem[] { reciveNoti, stopNoti, exit }; notifyIcon.ContextMenu = new ContextMenu(childen); //窗体关闭时触发 this.FormClosing += this.Main_FormClosing; } /// <summary> /// 窗体关闭的单击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Main_FormClosing(object sender, FormClosingEventArgs e) { if (!_finalExit) { e.Cancel = true; this.Hide(); } } } } <file_sep>using PrintService.UI; using PrintService.Utility; using System; using System.Collections.Generic; namespace PrintService.Update { public interface IUpdateChecker { /// <summary> /// Prepare the update services /// </summary> void Prepare(); /// <summary> /// Set file uri /// </summary> /// <param name="uri"></param> void SetURI(string uri); /// <summary> /// Set verify information /// </summary> /// <param name="user"></param> /// <param name="psd"></param> void SetVerify(string user, string psd); /// <summary> /// List the remote file version /// </summary> /// <returns></returns> Dictionary<string, string> GetUpdateItems(); /// <summary> /// Get file /// </summary> /// <param name="item"></param> /// <param name="savingPath"></param> void GetUpdateFIle(UpdateItem item, string savingPath); /// <summary> /// Chean the update services /// </summary> void CleanUpdateServices(); } public class UpdateCheckerProvider { private static Dictionary<string, IUpdateChecker> SupportedChecker = new Dictionary<string, IUpdateChecker> { { "web", new UpdateCheckerWeb()}, { "file", new UpdateCheckerFile()}, }; public static IUpdateChecker GetChcker() { var checkerName = AppSettingHelper.GetOne("Updater", "web"); if (SupportedChecker.ContainsKey(checkerName)) { return SupportedChecker[checkerName]; } var msg = Language.I.Text("known_checker", "Unsupported updater name"); throw new Exception(msg); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HTTPServerLib { public static class HeadersHelper { public static string GetDescription(this Enum value) { var valueType = value.GetType(); var memberName = Enum.GetName(valueType, value); if (memberName == null) return null; var fieldInfo = valueType.GetField(memberName); var attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)); if (attribute == null) return null; return (attribute as DescriptionAttribute).Description; } } }<file_sep>using System; using System.Collections.Generic; namespace PrintService.Update { public class VersionComparer { public List<UpdateItem> CompareVersion(Dictionary<string, string> localInfo, Dictionary<string, string> serverInfo) { var result = new List<UpdateItem>(); //检查远端文件,如果本地没有表示是新的文件, foreach (KeyValuePair<string, string> remoteFileVersion in serverInfo) { if (!localInfo.ContainsKey(remoteFileVersion.Key)) { //远端有,本地没有:新增文件 var upItem = new UpdateItem() { FileName = remoteFileVersion.Key, UpdateType = UpdateType.NewFile, Version = remoteFileVersion.Value }; result.Add(upItem); } else { //远端文件在本地有,比较版本 if (this.CheckFileVersion(localInfo[remoteFileVersion.Key], remoteFileVersion.Value)) { var upItem = new UpdateItem() { FileName = remoteFileVersion.Key, UpdateType = UpdateType.NewVersion, Version = remoteFileVersion.Value }; result.Add(upItem); } } } //比较本地文件是否在远端文件中出现,没有则视为需要删除的文件 foreach (KeyValuePair<string, string> localFileVersion in localInfo) { if (!serverInfo.ContainsKey(localFileVersion.Key)) { //远端文件列表中未出现本地文件 var upItem = new UpdateItem() { FileName = localFileVersion.Key, UpdateType = UpdateType.DeleteFile, Version = localFileVersion.Value }; result.Add(upItem); } } return result; } /// <summary> /// 文件是否需要更新 /// </summary> /// <param name="localV">本地版本</param> /// <param name="remoteV">远端版本</param> /// <returns>true 需要更新</returns> /// <returns>false 不需要更新</returns> protected bool CheckFileVersion(string localV, string remoteV) { if (string.IsNullOrEmpty(localV) || string.IsNullOrEmpty(remoteV)) return true; Version local = Version.Parse(localV); Version remote = Version.Parse(remoteV); return remote.CompareTo(local) > 0; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HTTPServerLib { public enum Protocols { Http = 0, Https = 1 } } <file_sep># print_server2 A print service using a build-in HTTP server <file_sep>using PrintService.Common; using PrintService.UI; using PrintService.Utility; using System; using System.Collections.Generic; using System.IO; namespace PrintService.Update { public class UpdateCheckerFile : IUpdateChecker { private string updateFolder = null; private string user; private string psd; private string tempCheckPath = Environment.CurrentDirectory + "/temp/checking/"; public void CleanUpdateServices() { ShareFolderHelper.Disconnect(this.updateFolder); } public void GetUpdateFIle(UpdateItem item, string savingPath) { File.Move(this.tempCheckPath + item.FileName, savingPath + item.FileName); } public Dictionary<string, string> GetUpdateItems() { Dictionary<string, string> fileInfoDictionary = new Dictionary<string, string>(); try { var files = Directory.GetFiles(updateFolder); foreach (var f in files) { var fileName = Path.GetFileName(f); File.Copy(updateFolder + fileName, this.tempCheckPath + fileName); } foreach (string info in files) { string[] filenameAndVer = info.Split(new char[2] { '%', '%' }, StringSplitOptions.RemoveEmptyEntries); if (filenameAndVer.Length == 2) fileInfoDictionary.Add(filenameAndVer[0], filenameAndVer[1]); else { fileInfoDictionary.Add(filenameAndVer[0], ""); } } } catch (Exception ex) { throw; } return fileInfoDictionary; } public void Prepare() { try { ShareFolderHelper.ConnectShareFolder(updateFolder, this.user, this.psd); } catch (Exception e) { ThrowHelper.TryThrow(false, StepEnum.OnCheck, Language.I.Text("checking_error", "Can not connect the share folder")); } } public void SetURI(string uri) { this.updateFolder = uri; if (!this.updateFolder.StartsWith("\\\\")) { this.updateFolder = "\\\\" + this.updateFolder; } if (!this.updateFolder.EndsWith("/")) { this.updateFolder = this.updateFolder + "/"; } } public void SetVerify(string user, string psd) { this.user = user; this.psd = psd; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PrintService.Template { [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] public class TemplateParaAttribute : Attribute { private string ParaType; private string Demo; public string GetDemo() { return this.Demo; } public string GetParaType() { return this.ParaType; } public TemplateParaAttribute(string paraType, string demo) { this.ParaType = paraType; this.Demo = demo; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace HTTPServerLib { public class ServiceModule { public bool SearchRoute(ServiceRoute route) { return true; } public ActionResult ExecuteRoute(ServiceRoute route) { var type = this.GetType(); var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance); methods = methods.Where(m => m.ReturnType == typeof(ActionResult)).ToArray(); if (methods == null || methods.Length <= 0) return null; var method = methods.FirstOrDefault(m => { var attributes = m.GetCustomAttributes(typeof(RouteAttribute), true); foreach (object attribute in attributes) { if (attribute == null || attribute.GetType() == typeof(RouteAttribute)) return false; RouteAttribute actualAttribute = (RouteAttribute)attribute; if (actualAttribute.Method == route.Method && actualAttribute.RoutePath == route.RoutePath) return true; } return false; }); if (method == null) return null; return (ActionResult)method.Invoke(this, new object[] { }); } } } <file_sep>using PrintService.Common; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace PrintService.Utility { public class ShareFolderHelper { /// <summary> /// Check the connectivity to the remote share folder /// </summary> /// <param name="path"></param> /// <returns></returns> public static void ConnectShareFolder(string path) { ConnectShareFolder(path, "", ""); } /// <summary> /// Check the connectivity to the remote share folder /// </summary> /// <param name="path"></param> /// <returns></returns> public static void ConnectShareFolder(string path, string userName, string passWord) { Process proc = new Process(); try { proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.CreateNoWindow = true; proc.Start(); string dosLine = @"net use " + path + " /User:" + userName + " " + passWord + " /PERSISTENT:YES"; proc.StandardInput.WriteLine(dosLine); proc.StandardInput.WriteLine("exit"); while (!proc.HasExited) { proc.WaitForExit(1000); } string errormsg = proc.StandardError.ReadToEnd(); proc.StandardError.Close(); if (string.IsNullOrEmpty(errormsg)) { throw new Exception(errormsg); } } finally { proc.Close(); proc.Dispose(); } } /// <summary> /// Disconnect the share folder /// </summary> /// <param name="path"></param> /// <returns></returns> public static void Disconnect(string path) { Process proc = new Process(); try { proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.CreateNoWindow = true; proc.Start(); string dosLine = @"net use " + path + " /del"; proc.StandardInput.WriteLine(dosLine); proc.StandardInput.WriteLine("exit"); while (!proc.HasExited) { proc.WaitForExit(1000); } string errormsg = proc.StandardError.ReadToEnd(); proc.StandardError.Close(); if (!string.IsNullOrEmpty(errormsg)) { throw new Exception(errormsg); } } finally { proc.Close(); proc.Dispose(); } } } } <file_sep>using PrintService.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PrintService.Server { public class PrintStatistics { public OnPrintStatistics OnPrint = null; private int total = 0; private int succeed = 0; private object _locker = new object(); public int Total { get { return this.total; } } public int Succeed { get { return this.succeed; } } public int Errors { get { return this.total - this.succeed; } } public void Printed(bool succeed) { lock (this._locker) { this.total++; if (succeed) { this.succeed++; } try { this.OnPrint?.Invoke(this); } catch { } } } } } <file_sep>using Newtonsoft.Json; using Newtonsoft.Json.Linq; using PrintService.UI; using System; using System.Collections.Generic; using System.Web.Script.Serialization; namespace PrintService.Template { /// <summary> /// Build print model /// </summary> public class PdfEngin : IEngin { public IPrintObject GetPrintModel(string modelData) { JObject jo = (JObject)JsonConvert.DeserializeObject(modelData); string print_type = jo["print_type"].ToString(); Type modelType = TemplateContainer.GetInstance().GetTemplateType(print_type); if (modelType == null) { throw new Exception(Language.I.Text("err_unknown_template", "Error:Unknown Template")); } JavaScriptSerializer serializer = new JavaScriptSerializer(); IPrintObject model = (IPrintObject)serializer.Deserialize(modelData, modelType); return model; } public List<TemplateDesc> GetTemplateDesc(string templateName) { throw new NotImplementedException(); } public List<string> GetTemplates() { var tList = new List<string>(); foreach (var tName in TemplateContainer.GetInstance().GetTemplateList().Keys) { tList.Add(tName); } return tList; } public void Initialize() { TemplateContainer.GetInstance().SacnTemplate(); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; namespace PrintService.Update { public class UpdateCheckerWeb : IUpdateChecker { private string updateUrl = null; private string user; private string psd; public void CleanUpdateServices() { } public void GetUpdateFIle(UpdateItem item, string savingPath) { } public Dictionary<string, string> GetUpdateItems() { Dictionary<string, string> fileInfoDictionary = new Dictionary<string, string>(); //try //{ // List<string> fileVersionInfo = client.GetUpdateFileList(string.Empty).ToList(); // foreach (string info in fileVersionInfo) // { // string[] filenameAndVer = info.Split(new char[2] { '%', '%' }, StringSplitOptions.RemoveEmptyEntries); // if (filenameAndVer.Length == 2) // fileInfoDictionary.Add(filenameAndVer[0], filenameAndVer[1]); // else // { // fileInfoDictionary.Add(filenameAndVer[0], ""); // } // } //} //catch (Exception ex) //{ // throw; //} return fileInfoDictionary; } public void Prepare() { } public void SetURI(string uri) { this.updateUrl = uri; } public void SetVerify(string user, string psd) { this.user = user; this.psd = psd; } } }
cb1d7dc05273554491f8d18a195ff1a73e08a2af
[ "Markdown", "C#" ]
53
C#
xiangbohua/PrintServer2
aaa62745d3cb886888c449f7ce748686b81ac03b
e79cae8131162d24f72cf2524ac07716eccdffdc
refs/heads/master
<repo_name>rbravo86/toyocosta_ipad<file_sep>/scripts/js/index.js document.addEventListener('DOMContentLoaded', onReady, false); document.addEventListener('touchmove',function(e){e.preventDefault();}, false); function onReady() { $('.menu').live('touchstart', bgSwitcherOn); $('.menu').live('touchend', bgSwitcherOff); $('#catalogo').live('touchstart', function() {setTimeout(catalogoLoad,100)}); $('#video_promo').live('touchstart', function() {setTimeout(vidLoad,100)}); $('#video_menu').live('touchstart', function() {setTimeout(vidLoad,100)}); $("#video_player").bind("ended", function() { $('#video_inicial').hide(); //$('#menu_principal').show(); $("#main").show(); }); $('#volver_menu_form').live('touchstart', function() {setTimeout(menuForm,100)}); $('#boton1').live('touchstart', function() {setTimeout(exterioresShow,100)}); $('#boton2').live('touchstart', function() {setTimeout(chasisShow,100)}); $('#boton5').live('touchstart', function() {setTimeout(interioresShow,100)}); $('#boton3').live('touchstart', function() {setTimeout(seguridadShow,100)}); $('#boton4').live('touchstart', function() {setTimeout(mecanicaShow,100)}); $('#volver_seccion').live('touchstart', function() {setTimeout(volverSeccion,100)}); $('#fotos_btn_main').live('touchstart', function() {setTimeout(loadGaleria,100)}); $('#contenedor_next').live('touchstart', function() {setTimeout(nextGaleria,100)}); } function loadGaleria( ) { $("#chasis_content").hide(); $("#mecanica_content").hide(); $("#seguridad_content").hide(); $("#interior_content").hide(); $("#exterior_content").hide(); $('#menu_secciones').hide(); $('#main').hide(); $('#galeria_fotos').show(); } function volverSeccion() { $("#chasis_content").hide(); $("#mecanica_content").hide(); $("#seguridad_content").hide(); $("#interior_content").hide(); $("#exterior_content").hide(); $('#menu_secciones').hide(); catalogoLoad(); } function chasisShow() { $('#btn_chasis').hide(); $('#btn_chasis').css("left","-50%"); $('#btn_chasis').show("fast"); $("#chasis_content").show( function() { $('#btn_chasis').animate({left: "5.82%"}, 800); }); $('#menu_secciones').show(); $("#main").hide(); $("#menu_principal").hide(); $("#boton1").hide(); $("#boton2").hide(); $("#boton3").hide(); $("#boton4").hide(); $("#boton5").hide(); } function mecanicaShow() { $('#btn_mecanica').hide(); $('#btn_mecanica').css("left","-50%"); $('#btn_mecanica').show("fast"); $("#mecanica_content").show(function(){ $('#btn_mecanica').animate({left: "5.82%"}, 800); } ); $('#menu_secciones').show(); $("#main").hide(); $("#menu_principal").hide(); $("#boton1").hide(); $("#boton2").hide(); $("#boton3").hide(); $("#boton4").hide(); $("#boton5").hide(); } function seguridadShow () { $('#btn_seguridad').hide(); $('#btn_seguridad').css("left","-50%"); $('#btn_seguridad').show("fast"); $("#seguridad_content").show(function(){ $('#btn_seguridad').animate({left: "5.82%"}, 800); } ); $('#menu_secciones').show(); $("#main").hide(); $("#menu_principal").hide(); $("#boton1").hide(); $("#boton2").hide(); $("#boton3").hide(); $("#boton4").hide(); $("#boton5").hide(); } function interioresShow() { $('#btn_interior').hide(); $('#btn_interior').css("left","-50%"); $('#btn_interior').show("fast"); $("#interior_content").show(function(){ $('#btn_interior').animate({left: "5.82%"}, 800); } ); $('#menu_secciones').show(); $("#main").hide(); $("#menu_principal").hide(); $("#boton1").hide(); $("#boton2").hide(); $("#boton3").hide(); $("#boton4").hide(); $("#boton5").hide(); } function exterioresShow() { $('#btn_exterior').hide(); $('#btn_exterior').css("left","-50%"); $('#btn_exterior').show(); $("#exterior_content").show(function(){ $('#btn_exterior').animate({left: "5.82%"}, 800); }); $('#menu_secciones').show(); $("#main").hide(); $("#menu_principal").hide(); $("#boton1").hide(); $("#boton2").hide(); $("#boton3").hide(); $("#boton4").hide(); $("#boton5").hide(); } function menuForm() { $("#main").show(); $("#menu_principal").hide(); $("#boton1").hide(); $("#boton2").hide(); $("#boton3").hide(); $("#boton4").hide(); $("#boton5").hide(); } function vidLoad() { $('#menu_principal').hide(); $('#main').hide(); $('#video_inicial').show(); } function bgSwitcherOn(e) { this.style.backgroundImage = "url(img/bg_touch.jpg)"; //$('#catalogo').live('touchstart', catalogoLoad); } function bgSwitcherOff(e) { this.style.backgroundImage = ""; //printObject(e); } function catalogoLoad() { $("#main").hide(); $("#menu_principal").show(); $("#boton1").fadeIn(2000); $("#boton2").fadeIn(2000); $("#boton3").fadeIn(2000); $("#boton4").fadeIn(2000); $("#boton5").fadeIn(2000); } //**************************** // SHOW OBJECT CONTENT //**************************** function printObject(o) { var out = ''; for (var p in o) { out += p + ': ' + o[p] + '\n'; } alert(out); } //************************************* ////// NO ZOOM DOUBLE TAP //************************************* $("body").nodoubletapzoom(); (function($) { $.fn.nodoubletapzoom = function() { if($("html.touch").length == 0) return; $(this).bind('touchstart', function preventZoom(e){ var t2 = e.timeStamp; var t1 = $(this).data('lastTouch') || t2; var dt = t2 - t1; var fingers = e.originalEvent.touches.length; $(this).data('lastTouch', t2); if (!dt || dt > 500 || fingers > 1){ return; // not double-tap } e.preventDefault(); // double tap - prevent the zoom // also synthesize click events we just swallowed up $(this).trigger('click'); }); }; })(jQuery); //****************************************************** document.addEventListener('touchmove', function(event) { event.preventDefault(); if(event.pageX < posxInicial) { if((posxInicial-event.pageX) >= (screen.width*0.20)) { //document.getElementById('content_promo').className = "izq"; mueveIzq('content_promo', function () { document.getElementById('content_promo2').className = 'bloque principal';}); } }else{ if((posxInicial < event.pageX)) { if((event.pageX-posxInicial) >= (screen.width*0.20)) { mueveDerecha('content_promo2', function () { document.getElementById('content_promo').className = 'bloque principal';}); } } posxInicial = 0; } //alert("evento"+event.pageX +"posInicial"+posxInicial); }, false); <file_sep>/nbproject/private/private.properties index.file=index.php url=http://localhost/toyocosta_ipad/
6f5cde42fa941f8b7cfe3a2151b44c7869babcff
[ "JavaScript", "INI" ]
2
JavaScript
rbravo86/toyocosta_ipad
5e054d023ad4c68f325408cd8e363166249a0327
cea7087164514b2cc8f1ed60284c339280aedac8
refs/heads/master
<file_sep>export class ScrapStockHistory { public symbol_code?: string; }<file_sep>import { CustomResponse } from '../models/GeneralModels'; import { SignUpRequestModel } from '../models/AccountsModels'; import { AccountsDbHelper } from '../helpers/DbHelpers/AccountsDbHelper'; import { BunyanHelper } from '../helpers/BunyanHelper'; import { GlobalHelper } from '../helpers/GlobalHelper'; import * as path from 'path'; import e = require('express'); import { request as urllibRequest, RequestOptions, HttpClientResponse } from "urllib"; import { ProceduresDbHelper } from '../helpers/DbHelpers/ProceduresDbHelper'; import { CompaniesDbHelper, CompaniesSingleRow } from '../helpers/DbHelpers/CompaniesDbHelper'; import { ScrapCompanyDetails } from '../models/CompanyModels'; export class CompanyController { private globalHelper: GlobalHelper; private companiesDbHelper: CompaniesDbHelper; private globalConfig: any; constructor() { this.globalHelper = new GlobalHelper(); this.companiesDbHelper = new CompaniesDbHelper(); this.globalConfig = this.globalHelper.getConfig("global"); } public async scrapCompanyDetails(req: ScrapCompanyDetails): Promise<CustomResponse> { var customResponse = new CustomResponse(); try { const urlToRequest: string = "https://indiawealth.in/api/v1/explore/stocks/?type=all&sortKey=mCap&sortOrder=desc&offset=0&limit=20&category=all&searchFor=" + req.symbol_code; var requestHeaders = { headers: { "accept": "application/json, text/plain, */*", "accept-language": "en-US,en;q=0.9", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", referer: "https://www.indmoney.com/stocks/all/?sortKey=name&shouldReverse=0&selectedCategoryId=all&page=1&query=INFY", }, method: "GET", } as RequestOptions; await urllibRequest(urlToRequest, requestHeaders) .then( async (value: HttpClientResponse<any>) => { var responseBody = JSON.parse(value.data.toString()); const responseSymbol = responseBody["data"][0]["symbol"]; const responseMarketExchange = responseBody["data"][0]["exchange"]; const responseCompanyName = responseBody["data"][0]["name"]; const responseCompanySector = responseBody["data"][0]["sector"]; const responseCompanyIsIn = responseBody["data"][0]["isin"]; const responseCompanyMfSector = responseBody["data"][0]["mfSector"]; const responseCompanyCode = responseBody["data"][0]["companyCode"]; const singleCompanyRow = { company_symbol_code: responseSymbol, company_name: responseCompanyName, company_sector: responseCompanySector, market_exchange: responseMarketExchange, isin: responseCompanyIsIn, company_mf_sector: responseCompanyMfSector, other_data: { indmoney_company_code: responseCompanyCode } } as CompaniesSingleRow; var insertCompanyResult = await this.companiesDbHelper.insertCompany(singleCompanyRow); if (insertCompanyResult.isError) { customResponse.error_code = 500; customResponse.error_messages = insertCompanyResult.result instanceof Array ? 'Scrapped Successfully but, failed to Store Company Details' : insertCompanyResult.result; customResponse.result = null; } else { // Successfully inserted the user row customResponse.error_code = 200; customResponse.result = responseBody; } }, (reason: any) => { console.error(reason); customResponse.error_code = 500; customResponse.error_messages = 'Failed to Scrap Company Details'; customResponse.result = null; } ) .catch( (error: any) => { console.error(error); customResponse.error_code = 500; customResponse.error_messages = 'Something went wrong'; customResponse.result = null; } ); } catch (error) { BunyanHelper.errorLogger.error(error); console.error(error); customResponse.error_code = 500; customResponse.error_messages = "Something went wrong"; customResponse.result = error; } finally { return customResponse; } } } <file_sep>-- MySQL dump 10.13 Distrib 8.0.20, for Win64 (x86_64) -- -- Host: 127.0.0.1 Database: nse_data -- ------------------------------------------------------ -- Server version 8.0.20 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!50503 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `companies` -- DROP TABLE IF EXISTS `companies`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `companies` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `company_symbol_code` varchar(45) NOT NULL, `market_exchange` varchar(45) NOT NULL, `company_name` varchar(45) DEFAULT NULL, `company_sector` varchar(45) DEFAULT NULL, `isin` varchar(45) DEFAULT NULL, `company_mf_sector` varchar(45) DEFAULT NULL, `other_data` json DEFAULT NULL, `dead` tinyint(1) NOT NULL DEFAULT '0', `modified_dtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `created_dtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `company_symbol_code_UNIQUE` (`company_symbol_code`), KEY `comapnies_dead_index` (`dead`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `stocks_history` -- DROP TABLE IF EXISTS `stocks_history`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `stocks_history` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `company_id` int unsigned NOT NULL, `on_date` datetime NOT NULL, `open_price` decimal(14,6) DEFAULT NULL, `high_price` decimal(14,6) DEFAULT NULL, `low_price` decimal(14,6) DEFAULT NULL, `close_price` decimal(14,6) DEFAULT NULL, `per` decimal(14,6) DEFAULT NULL, `volume` int DEFAULT NULL, `dead` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `stocks_history_dead` (`dead`), KEY `FK_stock_history_to_company_id` (`company_id`), CONSTRAINT `FK_stock_history_to_company_id` FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7839 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping events for database 'nse_data' -- -- -- Dumping routines for database 'nse_data' -- /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-05-23 21:34:13 <file_sep>export class GetCompanyDetails { public symbol_code?: string; } export class ScrapCompanyDetails { public symbol_code?: string; } <file_sep>import { MySQLHelper } from '../MySQLHelper'; import { GlobalHelper } from '../GlobalHelper'; import { BunyanHelper } from "../BunyanHelper"; import { DbHelperReturn } from '../../models/GeneralModels'; export class StockHistoryDbHelper { private globalHelper: GlobalHelper; private globalConfig: any; constructor() { this.globalHelper = new GlobalHelper(); this.globalConfig = this.globalHelper.getConfig("global"); } public async insertStockHistory( stockHistorySingleRow: StocksHistorySingleRow ): Promise<DbHelperReturn> { var insertStockHistoryReturn = new DbHelperReturn(); try { let sqlQuery = "" + "INSERT INTO `stocks_history`" + "(" + "`company_id`," + "`on_date`," + "`open_price`," + "`high_price`," + "`low_price`," + "`close_price`," + "`per`," + "`volume`," + "`dead`" + ")" + "VALUES" + "(" + "?," + "(SELECT STR_TO_DATE(?,'%Y-%m-%d'))," + "?," + "?," + "?," + "?," + "?," + "?," + "? " + ")"; if (this.globalConfig["settings"]["log_verbose"]) { BunyanHelper.activityLogger.info(sqlQuery); } let onDateValueString = ""; if (stockHistorySingleRow.on_date != null) { onDateValueString = ((stockHistorySingleRow.on_date.getFullYear()) + "-" + (stockHistorySingleRow.on_date.getMonth() + 1) + "-" + (stockHistorySingleRow.on_date.getDate())).toString(); } else { BunyanHelper.activityLogger.error("on_date is null"); } let results = await MySQLHelper.executeQuery(sqlQuery, [ stockHistorySingleRow.company_id, onDateValueString, stockHistorySingleRow.open_price, stockHistorySingleRow.high_price, stockHistorySingleRow.low_price, stockHistorySingleRow.close_price, stockHistorySingleRow.per, stockHistorySingleRow.volume, stockHistorySingleRow.dead == null ? 0 : stockHistorySingleRow.dead ]); if (results[0].affectedRows > 0) { insertStockHistoryReturn.isError = false; } else { insertStockHistoryReturn.isError = true; } insertStockHistoryReturn.result = results; } catch (error) { BunyanHelper.errorLogger.error(error); console.error(error); insertStockHistoryReturn.isError = true; insertStockHistoryReturn.result = error; } finally { return insertStockHistoryReturn; } } public async getStockHistory(companyId: number, orderDir: "asc" | "desc", limit: number): Promise<DbHelperReturn> { var getUserByReturn = new DbHelperReturn(); try { let sqlQuery: string = "select * from `stocks_history` where `company_id` = ? and `dead` = ? order by `on_date` " + orderDir + " limit " + limit; var results = await MySQLHelper.executeQuery(sqlQuery, [companyId, 0]); if (results[0].length > 0) { getUserByReturn.isError = false; } else { getUserByReturn.isError = true; } getUserByReturn.result = results; } catch (error) { BunyanHelper.errorLogger.error(error); console.error(error); getUserByReturn.isError = true; getUserByReturn.result = error; } finally { return getUserByReturn; } } } export class StocksHistorySingleRow { public id?: number; public company_id?: number; public on_date?: Date; public open_price?: number; public high_price?: number; public low_price?: number; public close_price?: number; public per?: number; public volume?: number; public dead?: number; }<file_sep>import { MySQLHelper } from '../MySQLHelper'; import { GlobalHelper } from '../GlobalHelper'; import { BunyanHelper } from "../BunyanHelper"; import { DbHelperReturn } from '../../models/GeneralModels'; export class CompaniesDbHelper { private globalHelper: GlobalHelper; private globalConfig: any; constructor() { this.globalHelper = new GlobalHelper(); this.globalConfig = this.globalHelper.getConfig("global"); } public async insertCompany( companySingleRow: CompaniesSingleRow ): Promise<DbHelperReturn> { var insertCompanyReturn = new DbHelperReturn(); try { let sqlQuery = "" + "INSERT INTO `companies`" + "(" + "`company_symbol_code`," + "`market_exchange`," + "`company_name`," + "`company_sector`," + "`isin`," + "`company_mf_sector`," + "`other_data`," + "`dead`" + ")" + "VALUES" + "(" + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?" + ")"; if (this.globalConfig["settings"]["log_verbose"]) { BunyanHelper.activityLogger.info(sqlQuery); } var results = await MySQLHelper.executeQuery(sqlQuery, [ companySingleRow.company_symbol_code?.toUpperCase(), companySingleRow.market_exchange?.toUpperCase(), companySingleRow.company_name, companySingleRow.company_sector?.toUpperCase(), companySingleRow.isin?.toUpperCase(), companySingleRow.company_mf_sector, JSON.stringify(companySingleRow.other_data), companySingleRow.dead == null ? 0 : companySingleRow.dead ]); if (results[0].affectedRows > 0) { insertCompanyReturn.isError = false; } else { insertCompanyReturn.isError = true; } insertCompanyReturn.result = results; } catch (error) { BunyanHelper.errorLogger.error(error); console.error(error); insertCompanyReturn.isError = true; insertCompanyReturn.result = error; } finally { return insertCompanyReturn; } } public async getCompanyBy(condition: "id" | "company_symbol_code", conditionValue: string, dead: 0 | 1): Promise<DbHelperReturn> { var getUserByReturn = new DbHelperReturn(); try { let sqlQuery: string = ""; switch (condition) { case "id": sqlQuery = "SELECT * FROM `companies` where `companies`.`id` = ? and `companies`.`dead` = ?"; break; case "company_symbol_code": sqlQuery = "SELECT * FROM `companies` where `companies`.`company_symbol_code` = ? and `companies`.`dead` = ?"; break; default: throw "Invalid condition"; } var results = await MySQLHelper.executeQuery(sqlQuery, [conditionValue, dead]); if (results[0].length > 0) { getUserByReturn.isError = false; } else { getUserByReturn.isError = true; } getUserByReturn.result = results; } catch (error) { BunyanHelper.errorLogger.error(error); console.error(error); getUserByReturn.isError = true; getUserByReturn.result = error; } finally { return getUserByReturn; } } } export class CompaniesSingleRow { public id?: number; public company_symbol_code?: string; public market_exchange?: string; public company_name?: string; public company_sector?: string; public isin?: string; public company_mf_sector?: string; public other_data?: CompaniesOtherDataJson; public dead?: number; public modified_dtm?: Date; public created_dtm?: Date; } export class CompaniesOtherDataJson { public indmoney_company_code?: number; }<file_sep># NSE Stocks Data Scrapper This project will provide you NSE Stocks data scrapping simple API developed using Node, Typescript, Express JS. <img src="https://repository-images.githubusercontent.com/266292612/8ce6be00-9d53-11ea-937c-8dfb73a190be" alt="node-express-typescript-nse-data-extract-scrap" /> ### How to debug and run the project. - Make a new folder in root of project with name **build** - `npm install` - `npm install typescript -g` - Open VSCode Debug Panel, Select **Windows_Clean_Debug** or **Linux_Clean_Debug** and Hit Run (Or F5 Shortcut) > For production build make **false** to `inlineSourceMap` and `inlineSources` in _tsconfig.json_ ### [Postman](https://www.postman.com/) API - Postman Collection Exported API _.json_ file is in **postman** directory. - Import or drag and drop to your postman app. - First run `company/scrap_company_details`. - Second run `stock/scrap_stock_history`. ### Contributing > To get started... 1. 🍴 Fork this repo! 2. 👯 Clone this repo to your local machine using `https://github.com/pishangujeniya/nse-stocks-data-scrapper.git` 3. 🔨 Hack away! 4. 🔃 Create a new pull request ## Support Reach out to me at one of the following places! - Website at <a href="http://pishangujeniya.com" target="_blank">`pishangujeniya.com`</a> - LinkedIn at <a href="https://www.linkedin.com/in/pishangujeniya/" target="_blank">`pishangujeniya`</a> --- ## Donations <a href="http://pishangujeniya.com"><img src="https://www.worldfuturecouncil.org/wp-content/uploads/2018/09/Donate-Button-HEART.png" title="Donate ClipSync Developer" alt="Donate ClipSync Developer" width="170px" height="60px"></a> > Donate me on _+91 88 66 33 01 05_ via <a href="http://paytm.com" target="_blank">**PayTm**</a> --- ## License [![License](http://img.shields.io/:license-mit-blue.svg?style=flat-square)](https://github.com/pishangujeniya/clipsync-windows/blob/master/LICENSE) <file_sep>import { CustomResponse } from '../models/GeneralModels'; import { BunyanHelper } from '../helpers/BunyanHelper'; import { GlobalHelper } from '../helpers/GlobalHelper'; import * as path from 'path'; import e = require('express'); import { request as urllibRequest, RequestOptions, HttpClientResponse } from "urllib"; import { CompaniesDbHelper, CompaniesSingleRow, CompaniesOtherDataJson } from '../helpers/DbHelpers/CompaniesDbHelper'; import { ScrapStockHistory } from '../models/StockHistoryModels'; import { StocksHistorySingleRow, StockHistoryDbHelper } from '../helpers/DbHelpers/StockHistoryDbHelper'; export class StockHistoryController { private globalHelper: GlobalHelper; private companiesDbHelper: CompaniesDbHelper; private stockHistoryDbHelper: StockHistoryDbHelper; private globalConfig: any; constructor() { this.globalHelper = new GlobalHelper(); this.companiesDbHelper = new CompaniesDbHelper(); this.stockHistoryDbHelper = new StockHistoryDbHelper(); this.globalConfig = this.globalHelper.getConfig("global"); } public async scrapStockHistory(req: ScrapStockHistory): Promise<CustomResponse> { var customResponse = new CustomResponse(); try { if (req.symbol_code != null) { let companyDetails = await this.companiesDbHelper.getCompanyBy("company_symbol_code", req.symbol_code, 0); if (companyDetails.isError) { customResponse.error_code = 404; customResponse.error_messages = 'No such company found, please try scraping company details first'; customResponse.result = null; } else { let companyDetailsRow = companyDetails.result[0][0] as CompaniesSingleRow; const companyId = companyDetailsRow.id; const companySymbolCode = companyDetailsRow.company_symbol_code; const indMoneyCompanyCode = companyDetailsRow.other_data?.indmoney_company_code; const currentDate = new Date(); let onDateValueString = ((currentDate.getFullYear()) + "-" + (currentDate.getMonth() + 1) + "-" + (currentDate.getDate())).toString(); const urlToRequest: string = "https://indiawealth.in/api/v1/explore/stocksHistory/" + (indMoneyCompanyCode?.toString()) + "/?format=json&start_date=1971-01-01&end_date=" + onDateValueString; var requestHeaders = { headers: { "accept": "application/json, text/plain, */*", "accept-language": "en-US,en;q=0.9", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", }, method: "GET", timeout: 50000 } as RequestOptions; await urllibRequest(urlToRequest, requestHeaders) .then( async (value: HttpClientResponse<any>) => { var responseBody = JSON.parse(value.data.toString()); if (companyId != null && companySymbolCode != null) { let companyStockHistory = await this.stockHistoryDbHelper.getStockHistory(companyId, "desc", 1) let lastOnDate = new Date("1971-01-01"); if (companyStockHistory.isError) { // Means its already not their } else { let lastOnDateInstant = (companyStockHistory.result[0][0] as StocksHistorySingleRow).on_date; if (lastOnDateInstant != undefined) { lastOnDate = lastOnDateInstant; } } for (let index = 0; index < responseBody["data"]["stockGraph"].length; index++) { const responseSingleStocksHistory = responseBody["data"]["stockGraph"][index]; const onDate = new Date(responseSingleStocksHistory["date"] + " 00:00:00"); const closePrice = responseSingleStocksHistory["value"]; const highPrice = responseSingleStocksHistory["highPrice"]; const lowPrice = responseSingleStocksHistory["lowPrice"]; const volume = responseSingleStocksHistory["volume"]; const openPrice = responseSingleStocksHistory["openPrice"]; const per = responseSingleStocksHistory["per"]; const singleStockHistoryRow = { company_id: companyId, on_date: onDate, open_price: openPrice, high_price: highPrice, low_price: lowPrice, close_price: closePrice, volume: volume, per: per } as StocksHistorySingleRow; if (lastOnDate.getTime() < onDate.getTime()) { var insertCompanyResult = await this.stockHistoryDbHelper.insertStockHistory(singleStockHistoryRow); if (insertCompanyResult.isError) { BunyanHelper.errorLogger.error('Scrapped Successfully but, failed to Store Stock History'); BunyanHelper.errorLogger.error(responseSingleStocksHistory); } } else { // console.log("Skipped"); // "Skipped for Inserting because last entry date is more than the current going to entry" } } customResponse.error_code = 200; customResponse.error_messages = 'Scrapped Successfully'; customResponse.result = responseBody; } else { customResponse.error_code = 500; customResponse.error_messages = 'Failed to Get Company id'; customResponse.result = null; } }, (reason: any) => { BunyanHelper.errorLogger.error(reason); console.error(reason); customResponse.error_code = 500; customResponse.error_messages = 'Failed to Scrap Stock History'; customResponse.result = null; } ) .catch( (error: any) => { BunyanHelper.errorLogger.error(error); console.error(error); customResponse.error_code = 500; customResponse.error_messages = 'Something went wrong'; customResponse.result = null; } ); } } else { customResponse.error_code = 400; customResponse.error_messages = 'Company Symbol Code needed'; customResponse.result = null; } } catch (error) { BunyanHelper.errorLogger.error(error); console.error(error); customResponse.error_code = 500; customResponse.error_messages = "Something went wrong"; customResponse.result = error; } finally { return customResponse; } } }
e07cdd116463356195505fdfd5417e59a6ddbeb5
[ "Markdown", "SQL", "TypeScript" ]
8
TypeScript
maheshcharig/nse-stocks-data-scrapper
ada6be6f9de4ea76fdee50ff28d29fd60d2b5014
5897bb018ecaa4d81ab3e32d6e8b9381fe2c64f2
refs/heads/master
<repo_name>thinktwise/hipoint<file_sep>/localedit.js String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return 'yawas'+hash; }; function save(e) { var obj = {}; obj[keyName] = {title:title.value.trim(),labels:labels.value.trim(),annotations:annotations.value.trim()}; chrome.storage.sync.set(obj,function() { window.close(); }); } let r = new URLSearchParams(window.location.search); let docurl = r.get('url'); var keyName = docurl.hashCode(); var obj = {}; obj[keyName] = null; document.addEventListener('DOMContentLoaded', function () { document.querySelector('#save').addEventListener('click', save); chrome.storage.sync.get(obj,function(items) { if (items[keyName]) { title.value = items[keyName].title; labels.value = items[keyName].labels; annotations.value = items[keyName].annotations; } }); }); <file_sep>/README.md ![picture1](doc/thinktwise.png) # Hipoint, the smart highlighter The aim is to allow user to highlight and assign up to 4 different 'categories' to the highlighted text. The actual combination of this 4 categories results into 2^4 = 16 different posibilities. In order to visually display such a variety of posible combinations, we opted to colour the borders of the highlighted text (please see picture 1). Each side (top, right, bottom, left) has a color (on/off). If the color is off, that border will be painted in "thin gray". Otherwise, will be painted in "thick YELLOW/RED/BLUE/GREEN" ![picture1](doc/wheel.png) As a vehicle for the user to assign/unassign categories to a highlighted text, we used a *popover* library called **tippy** (https://kabbouchi.github.io/) Here you can see **tippy** and **Hipointer** in action. ![picture2](doc/tippy_sample.png)
8e650a7ada5a48d5a709bb7683c0c5bdd092c155
[ "JavaScript", "Markdown" ]
2
JavaScript
thinktwise/hipoint
e59e736db7f3c9290d666b44c941bc07315e6b9c
6b3cef68560b6676936518316ddba2ca3a6e15e3
refs/heads/master
<file_sep>using System; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Configuration; namespace Allegro { public class Global : HttpApplication { internal static string APP_NAME; internal static string BASE_URL; internal static string MACH_PATH; public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Proxy", // Route name "proxy/", // URL with parameters new { controller = "Allegro", action = "Proxy" } // Parameter defaults ); routes.MapRoute( "Put map", // Route name "putMap/", // URL with parameters new { controller = "Allegro", action = "PutMap" } // Parameter defaults ); routes.MapRoute( "Get Map", // Route name "getMap/{id}", // URL with parameters new { controller = "Allegro", action = "GetMap" } // Parameter defaults ); } protected void Application_Start() { //put db in memory? AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); var mach = Environment.MachineName; switch (mach) { case "DRCWA": case "DRC10": case "DRC09": MACH_PATH = "gis.oregonmetro.gov"; break; case "DRC05": MACH_PATH = "qagis"; break; case "DRC06": MACH_PATH = "devgis"; break; default: MACH_PATH = "localhost"; break; } APP_NAME = ConfigurationManager.AppSettings["APP_NAME"]+"/"; BASE_URL= "//" + MACH_PATH + "/" + APP_NAME; } } }<file_sep> using System; using System.Data.SQLite; using System.IO; using System.Linq; using System.Net; using System.Web.Mvc; namespace Allegro.Controllers { public class AllegroController : Controller { //proxy/%2F%2Flibrary.oregonmetro.gov%2Frlisdiscovery%2Fcouncil1993.zip [AcceptVerbs(HttpVerbs.Get)] public ActionResult Proxy() { var request = Server.UrlDecode(Request.QueryString["url"]); //return Content(request); if (request.ToUpper().IndexOf("HTTP") != -1) { var webRequest = HttpWebRequest.Create(request) as HttpWebRequest; // Important! Keeps the request from blocking after the first time! webRequest.KeepAlive = false; webRequest.Credentials = CredentialCache.DefaultCredentials; using (HttpWebResponse backendResponse = (HttpWebResponse) webRequest.GetResponse()) { Stream receiveStream = backendResponse.GetResponseStream(); // Clear whatever is already sent Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); // Copy headers // Check if header contains a contenth-lenght since IE // goes bananas if this is missing bool contentLenghtFound = false; foreach (string header in backendResponse.Headers) { if (string.Compare(header, "CONTENT-LENGTH", true) == 0) { contentLenghtFound = true; } Response.AppendHeader(header, backendResponse.Headers[header]); } // Copy content byte[] buff = new byte[1024]; long length = 0; int bytes; while ((bytes = receiveStream.Read(buff, 0, 1024)) > 0) { length += bytes; Response.OutputStream.Write(buff, 0, bytes); } // Manually add content-lenght header to satisfy IE if (!contentLenghtFound) { Response.AppendHeader("Content-Length", length.ToString()); } Response.AppendHeader("ContentType", "application/x-zip-compressed"); Response.AppendHeader("Content-Disposition", "attachment; filename=" + backendResponse.ResponseUri.LocalPath.Split('/').Last()); receiveStream.Close(); backendResponse.Close(); Response.Flush(); Response.Close(); } } else //FTP { FtpWebRequest webRequest = FtpWebRequest.Create(request) as FtpWebRequest; // Important! Keeps the request from blocking after the first time! webRequest.KeepAlive = false; //webRequest.Credentials = CredentialCache.DefaultCredentials; using (FtpWebResponse backendResponse = (FtpWebResponse) webRequest.GetResponse()) { Stream receiveStream = backendResponse.GetResponseStream(); // Clear whatever is already sent Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); // Copy headers // Check if header contains a contenth-lenght since IE // goes bananas if this is missing bool contentLenghtFound = false; foreach (string header in backendResponse.Headers) { if (string.Compare(header, "CONTENT-LENGTH", true) == 0) { contentLenghtFound = true; } Response.AppendHeader(header, backendResponse.Headers[header]); } // Copy content byte[] buff = new byte[1024]; long length = 0; int bytes; while ((bytes = receiveStream.Read(buff, 0, 1024)) > 0) { length += bytes; Response.OutputStream.Write(buff, 0, bytes); } // Manually add content-lenght header to satisfy IE if (!contentLenghtFound) { Response.AppendHeader("Content-Length", length.ToString()); } Response.AppendHeader("ContentType", "application/x-zip-compressed"); Response.AppendHeader("Content-Disposition", "attachment; filename=" + backendResponse.ResponseUri.LocalPath.Split('/').Last()); receiveStream.Close(); backendResponse.Close(); Response.Flush(); Response.Close(); } } return Content("Yay"); } [AcceptVerbs(HttpVerbs.Get)] public ActionResult PutMap() { var path = Server.MapPath("..")+@"\data\maps.sqlite"; var json = Request.Params["map"]; var id = Guid.NewGuid().ToString().Substring(0, 8); var maps = new SQLiteConnection( @"Data Source="+path+";"); maps.Open(); var dcmd = "insert into maps (json, id) values ('" + json + "', '" + id + "');"; using (var cmd = maps.CreateCommand()) { cmd.CommandText = dcmd; cmd.ExecuteNonQuery(); } return Content(id); } [AcceptVerbs(HttpVerbs.Get)] public ActionResult GetMap(string id) { var path = Server.MapPath("..") + @"\data\maps.sqlite"; var maps = new SQLiteConnection(@"Data Source="+path+";"); maps.Open(); string foo=""; using (var cmd = maps.CreateCommand()) { cmd.CommandText = "select json from maps where id = '"+id+"'"; using (var rdr = cmd.ExecuteReader()) { while (rdr.Read()) { foo = rdr.GetString(0); } } } return Json(foo, JsonRequestBehavior.AllowGet); } } }<file_sep>config.layers.push({ 'name': 'RISE Points', 'url': './data/RISE/points.json', 'type': 'geojson', 'source': 'RISE', 'icon': './img/metro_logo.png', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/zoning.png', 'symbolField': 'type', 'theme': 'General' }, { 'name': 'TOD Revitalization Projects', 'url': 'data/RISE/TOD_revitalization_projects.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'TOD' }, { 'name': 'Local Share', 'url': 'data/RISE/parks_and_natural_areas_local_share.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'Parks and Natural Areas' }, { 'name': 'Sites and Bond Acquisitions', 'url': 'data/RISE/parks_and_natural_areas_sites_bond_acquisitions.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'Parks and Natural Areas' }, { 'name': 'Planned Trails', 'url': '//gis.oregonmetro.gov/services/transit/trailsPlanned/tilejson', 'type': 'tilejson', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/trails.png', 'source': 'RISE', 'theme': 'Transportation', 'zIndex': 75 }, { 'name': 'Existing Trails on Land', 'url': '//gis.oregonmetro.gov/services/transit/trailsExisting/tilejson', 'type': 'tilejson', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/trails.png', 'source': 'RISE', 'theme': 'Transportation', 'zIndex': 75 }, { 'name': 'Conceptual Trails', 'url': '//gis.oregonmetro.gov/services/transit/trailsConceptual/tilejson', 'type': 'tilejson', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/trails.png', 'source': 'RISE', 'theme': 'Transportation', 'zIndex': 75 }, { 'name': 'Bond Identified Trails', 'url': '//gis.oregonmetro.gov/services/transit/bondIdentified/tilejson', 'type': 'tilejson', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/trails.png', 'source': 'RISE', 'theme': 'Transportation', 'zIndex': 75 }, { 'name': 'MTIP Feb 2005 Buffer', 'url': 'data/RISE/mtip_buffer_02_05.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'Transportation' }, { 'name': 'MTIP Apr 2007 Buffer', 'url': 'data/RISE/mtip_buffer_04_07.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'Transportation' }, { 'name': 'MTIP Jun 2009 Buffer', 'url': 'data/RISE/mtip_buffer_06_09.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'Transportation' }, { 'name': 'MTIP Aug 2011 Buffer', 'url': 'data/RISE/mtip_buffer_08_11.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'Transportation' }, { 'name': 'RFFA', 'url': 'data/RISE/rffa.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'Transportation' }, { 'name': 'RFFA Buffer', 'url': 'data/RISE/rffa_buffer.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'Transportation' }, { 'name': 'Community Development Grants', 'url': 'data/RISE/community_development_grants.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'General' }, { type: 'heatmap', theme: 'General', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: './data/rise/cdg.png', source: 'RISE', name: 'Community Development Grants heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'General', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/ceg.png', source: 'RISE', name: 'Community Enhancement Grants heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'Major Studies', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/ils.png', source: 'RISE', name: 'Industrial Lands Study heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'Transportation', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/mtb02_05.png', source: 'RISE', name: 'MTIP February 2005 heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'Transportation', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/mtb04_07.png', source: 'RISE', name: 'MTIP April 2007 heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'Transportation', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/mtb06_09.png', source: 'RISE', name: 'MTIP June 2009 heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'Transportation', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/mtb08_11.png', source: 'RISE', name: 'MTIP August 2011 heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'Parks and Natural Areas', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/local.png', source: 'RISE', name: 'Local Share Investments heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'Parks and Natural Areas', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/sites.png', source: 'RISE', name: 'Sites and Bond Acquisitions heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'Transportation', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/rffa_buffer.png', source: 'RISE', name: 'Regional Flexible Fund Allocation heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'Major Studies', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/sw_corr.png', source: 'RISE', name: 'Southwest Corridor Study heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'TOD', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.1787600372, 45.6955761882], step: 0.0008000000, file: 'data/rise/tod.png', source: 'RISE', name: 'TOD Revitalization Projects heatmap', width: 1330, height: 708 }, { type: 'heatmap', theme: 'General', thumb: 'img/heatmap.jpg', nodata: 0, ul: [-123.51819289449999, 46.0676384925], step: 0.000885099, file: 'data/rise/points.png', source: 'RISE', name: 'Direct Assets heatmap', width: 1330, height: 708 }, { 'name': 'Community Enhancement Grants', 'url': 'data/RISE/community_enhancement_grants.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'General' }, { 'name': 'Industrial Lands Study', 'url': 'data/RISE/industrial_lands_study.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'Major Studies' }, { 'name': 'SW Corridor Data Collection', 'url': 'data/RISE/SW_Corridor_data_collection.zip', 'type': 'shapefile', 'thumb': '//library.oregonmetro.gov/rlisdiscovery/browse_graphic/placeholder.png', 'source': 'RISE', 'theme': 'Major Studies' } );
a3e8e854ac893805a05235f18800d79647f9bc6a
[ "JavaScript", "C#" ]
3
C#
highedweb/hackathon-2014
88b84fd5704e7da1c62938f1827842c5c23496b8
21b30427711fe7c1b857447a49c18813ab247d21
refs/heads/master
<file_sep>var wave1 = $('#feel-the-wave').wavify({ height: 80, bones: 4, amplitude: 60, color: '#B289EF', speed: .15 }); var wave2 = $('#feel-the-wave-two').wavify({ height: 60, bones: 3, amplitude: 40, color: 'rgba(150, 97, 255, .8)', speed: .25 }); var colors = ['rgba(255, 281, 75, .8)', '#dc75ff', '#9d9ade', '#6cd7ee', '#aceeae']
c490b63ab277111ab01eb98e4e0c113fb09ef439
[ "JavaScript" ]
1
JavaScript
yajindragautam/hymlo-sindhu-melamchi
f000c3bce96d160059655b1ec86b3f37c7649617
9bd239c22ae7e2344f1bc5e880bc6a34d43f0d10
refs/heads/master
<file_sep>board=[" ", " ", " ", " ", " ", " ", " ", " ", " "] def position_taken? (board, position) if board[position]=="X" true elsif board[position]=="O" true else board[position]==" " false end end #this was surprisingly easy lol. it took me a second to understand that since we are comparing the array, that position did not need to alter value, and could be used in conjuntion without modifying in regards as plugging it in directly to board array.
5b74eed35cc953afca101dbebfa6fac643d729dd
[ "Ruby" ]
1
Ruby
sigkapphi/ttt-6-position-taken-rb-q-000
0f976ea6784e8532a78645b354ab49268a344dfc
717d7bffbe1321ff5581e4f8a6933f798e43a711
refs/heads/master
<repo_name>jcsmata/ProjectEuler<file_sep>/src/problems/Problem005.java package problems; public class Problem005 { /** * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? **/ public static void main(String[] args) { double number = 2520; double result = 0; boolean divisible = false; while(!divisible) { number++; for(int i = 1; i <= 20; i++) { result = number / i; //System.out.println(result); if(result == (int) result) { if(i == 20) divisible = true; } else break; } } System.out.printf("%.0f",number); } } <file_sep>/README.md ProjectEuler ============ Problem 001: Multiples of 3 and 5 Problem 002: Even Fibonacci numbers Problem 003: Largest prime factor Problem 004: Largest palindrome product Problem 005: Smallest multiple <file_sep>/src/problems/Problem004.java package problems; public class Problem004 { /** * A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. * Find the largest palindrome made from the product of two 3-digit numbers. */ public static void main(String[] args) { // TODO Auto-generated method stub int maxPalindrome = 0; int number1 = 100; int number2 = 100; while(number1 < 999) { while(number2 < 999) { if(isPalindrome(number1*number2)) { maxPalindrome = Math.max(maxPalindrome, number1*number2); } number2++; } number2=100; number1++; } System.out.print(maxPalindrome); } private static boolean isPalindrome(int number) { char[] numberA = String.valueOf(number).toCharArray(); boolean isPalindrome = true; for(int i = 0; i <= Math.floorDiv(numberA.length,2); i++) { if(numberA[i] != numberA[numberA.length-1-i]) { isPalindrome = false; break; } } return isPalindrome; } } <file_sep>/src/problems/Problem002.java package problems; public class Problem002 { /* * Each new term in the Fibonacci sequence is generated by adding the previous two terms. * By starting with 1 and 2, the first 10 terms will be: * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... * By considering the terms in the Fibonacci sequence whose values do not exceed four million, * find the sum of the even-valued terms. */ public static void main(String[] args) { // TODO Auto-generated method stub int fibA = 1, fibB = 2, fibT = 0; int stoppingMark = 4000000; while (fibA < stoppingMark && fibB < stoppingMark) { fibT = fibA + fibB; fibA = fibB; fibB = fibT; if(isEven(fibT)) { } } } public static boolean isEven(int x) { if((x % 2) == 0) return true; else return false; } }
2d8ece611bf24b7742256446deccea295771975d
[ "Markdown", "Java" ]
4
Java
jcsmata/ProjectEuler
165931a0a1a07d294c46ce32e758527912a3c26c
f04991082731afcdfcd64040f55046fa633be736
refs/heads/master
<file_sep>(function (window) { 'use strict'; function Controller(view, model, options) { this.view = view; this.model = model; this.defaultsSwap = new this._defaults; this.options = extendObject(this.defaultsSwap, options); this.stepIndex = 0; } Controller.prototype = { _defaults:function () { return { value:{} } }, _init:function () { this._initEvents(); }, _initEvents:function () { var self = this; [].forEach.call( document.body.querySelectorAll('[data-toggle="demo"]'), function (ev) { ev.addEventListener('click', function () { self._startDemo(); } ); }); }, _toggleYouTubePlayer:function () { document.querySelector('#canvas-stage').style.display = 'block'; document.querySelector('#player').style.display = 'none'; }, _initYouTubePlayer:function () { var self = this; var player; var tag = document.createElement('script'); var firstScriptTag = document.getElementsByTagName('script')[0]; tag.src = "https://www.youtube.com/iframe_api"; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); document.querySelector('#canvas-stage').style.display = 'none'; window.onYouTubeIframeAPIReady = function () { player = new YT.Player('player', { height:self.canvas.height, width:self.canvas.width, videoId:self.data.steps[self.stepIndex+1].video, events:{ 'onReady':onPlayerReady, 'onStateChange':onPlayerStateChange } }); } function onPlayerReady(event) { event.target.playVideo(); } function onPlayerStateChange(event) { if (event.data === 0) { self.view.canvasExtension._goTo(self.stepIndex+1); self.stepIndex = self.view.canvasExtension._getIndex(); self._toggleYouTubePlayer(); } } }, _startDemo:function () { var self = this; document.querySelector('#modal').className = 'in'; document.querySelector('#overlay').className = 'in'; this.data = this.model.getData(); this.canvas = this.view.canvasExtension._init(this.data, 0); this.canvas.addEventListener('click', function (event) { self._onCanvasClick.call(self, event) }, false); }, _onCanvasClick:function (event) { event.preventDefault(); this.stepIndex = this.view.canvasExtension._getIndex(); if (this.data.steps[this.stepIndex].url) window.open(this.data.steps[this.stepIndex].url); else if (this.data.steps[this.stepIndex+1].video) { this._initYouTubePlayer(); } else if (!this.data.steps[this.stepIndex].blocked) this.view.canvasExtension._goTo(this.stepIndex); } } window.app.Controller = Controller; })(window);<file_sep>(function (window) { 'use strict'; function View() { var self = this; this.step = 0; } View.prototype = { canvasExtension:{ mouse:{ x:-99999, y:-99999 }, particles:{ shape:[], text:[], path:[], all:[] }, shape:{}, swapText:[], colors:['#fff', '#e13123'], _init:function (data, step) { this.storage = data; this.data = this.storage.steps[step]; this.step = step; this.canvasContainer = document.querySelector('#canvas-stage'); this.canvas = document.createElement('canvas'); this.canvas.width = this.canvasContainer.offsetWidth; this.canvas.height = this.canvasContainer.offsetHeight; this.canvasContainer.appendChild(this.canvas); if (!!(this.canvas.getContext && this.canvas.getContext('2d'))) { this.context = this.canvas.getContext('2d'); this._createParticles(); document.body.style.cursor = "pointer"; this._initEvents(); return this.canvas; } }, _goTo:function (step) { this.step = step + 1; this.data = this.storage.steps[this.step]; this._refresh(); }, _getIndex:function () { return this.step; }, _onMouseMove:function (event) { event.preventDefault(); this.mouse.x = event.pageX - ( scrollX() + this.canvas.getBoundingClientRect().left ); this.mouse.y = event.pageY - ( scrollY() + this.canvas.getBoundingClientRect().top ); if (this.data.drawing) this._drawPath(); }, _onWindowResize:function () { this.canvas.width = this.canvasContainer.offsetWidth; this.particles.all = []; this._createShapeParticles(); this._createTextParticles(); }, _initEvents:function () { var self = this; window.onresize = this._onWindowResize.bind(this); this.canvas.addEventListener('mousemove', function (event) { self._onMouseMove.call(self, event) }, false); }, _createParticles:function () { var self = this; this._createShapeParticles(); this._createTextParticles(); this._renderLoop(); }, _refresh:function () { this.particles = { shape:[], text:[], path:[], all:[] }; this._clear(); this._createShapeParticles(); this._createTextParticles(); }, _drawPath:function () { if (this.pathStarted && this.pathFinished) { this.pathStarted = this.pathFinished = false; this._goTo(4); } if ((this.mouse.x > this.imgX + 110 && this.mouse.x < this.imgX + 130) && (this.mouse.y > this.imgY && this.mouse.y < this.imgY + 20)) this.pathStarted = true; if ((this.mouse.x > this.imgX2 - 110 && this.mouse.x < this.imgX2 - 90) && (this.mouse.y > this.imgY2 - 40 && this.mouse.y < this.imgY2 - 20)) this.pathFinished = true; if ((this.mouse.x > this.imgX && this.mouse.x < this.imgX2) && (this.mouse.y > this.imgY && this.mouse.y < this.imgY2) && (this.pathStarted)) this.particles.path.push({ x:this.mouse.x, y:this.mouse.y, x1:this.mouse.x, y1:this.mouse.y, hasBorn:true, ease:1, bornSpeed:0, alpha:1, maxAlpha:1, radius:2, maxRadius:2, color:'#fff', interactive:false }); }, _generateText:function () { this.context.font = this.data.fontSize + 'px Arial, sans-serif'; this.context.fillStyle = 'rgb(255, 255, 255)'; this.context.textAlign = 'center'; var text = this.data.text.toUpperCase(); this.context.fillText( text, this.canvas.width * 0.5, this.canvas.height - 70 ); if (this.data.textSmall) { this.context.font = this.data.fontSize - 25 + 'px Arial, sans-serif'; this.context.fillText( this.data.textSmall.toUpperCase(), this.canvas.width * 0.5, this.canvas.height - 10 ); } }, _grabParticlesFromCanvas:function () { var generated = []; var surface = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height); for (var width = 0; width < surface.width; width += this.data.density) { for (var height = 0; height < surface.height; height += this.data.density) { var color = surface.data[(height * surface.width * 4) + (width * 4) - 1]; if (color === 255) { var radius = getRandom(this.data.shape.radius.min, 30); var hasBorn = radius > 0 || radius < 12 ? false : true; var color = this.colors[~~(Math.random() * this.colors.length)]; generated.push({ x:getRandom(-this.canvas.width, this.canvas.width * 2), y:getRandom(0, 500), x1:width, y1:height, hasBorn:hasBorn, ease:0.04 + Math.random() * 0.06, bornSpeed:0.07 + Math.random() * 0.07, alpha:0, maxAlpha:0.4 + Math.random() * 0.4, radius:radius, maxRadius:this.data.shape.radius.max || 8, orbit:8, angle:0.1, color:color, interactive:false }); } } } return generated; }, _createShapeParticles:function () { var self = this; var surface; self.img = new Image(); self.img.onload = function () { self.imgX = self.canvas.width / 2 - self.img.width / 2; self.imgX2 = self.imgX + self.img.width; self.imgY = 30; self.imgY2 = self.imgY + self.img.height; self.context.drawImage(self.img, self.imgX, 30); self.particles.shape = self._grabParticlesFromCanvas(); self._clear(); } self.img.src = this.data.shape.src; }, _createTextParticles:function () { this._generateText(); this.particles.text = this._grabParticlesFromCanvas(); }, _clear:function () { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); }, _updateTransition:function () { var self = this; if (!self.data.drawing) [].forEach.call(this.particles.all, function (particle, index) { if (particle.interactive) { particle.x += ((self.mouse.x + Math.sin(particle.angle) * 60) - particle.x) * 0.08; particle.y += ((self.mouse.y + Math.sin(particle.angle) * 60) - particle.y) * 0.08; } else { particle.x += ((particle.x1 + Math.sin(particle.angle) * 2) - particle.x) * 0.08; particle.y += ((particle.y1 + Math.sin(particle.angle) * 2) - particle.y) * 0.08; } particle.angle += getRandom(1, 8) / 100; }) else [].forEach.call(this.particles.all, function (particle, index) { particle.x = particle.x1; particle.y = particle.y1; particle.angle += getRandom(1, 8) / 100; }) }, _update:function () { var self = this; this._updateTransition(); this.particles.all = this.particles.shape.concat( this.particles.text, this.particles.path ); [].forEach.call(this.particles.all, function (particle, index) { particle.alpha += (particle.maxAlpha - particle.alpha) * 0.05; if (particle.hasBorn) { particle.radius += (0 - particle.radius) * particle.bornSpeed; if (Math.round(particle.radius) === 0) particle.hasBorn = false; } else { particle.radius += (particle.maxRadius - particle.radius) * particle.bornSpeed; if (Math.round(particle.radius) === particle.maxRadius) particle.hasBorn = true; } }); [].forEach.call(this.particles.shape, function (particle, index) { if (distanceTo(self.mouse, particle) <= 5 && (self.data.drawing == true)) { if (self.pathStarted) { self.particles.path = []; self._createShapeParticles(); } self.pathStarted = self.pathFinished = false; } else distanceTo(self.mouse, particle) <= particle.radius + 60 ? particle.interactive = true : particle.interactive = false; }); }, _render:function () { var context = this.context; [].forEach.call(this.particles.all, function (particle, index) { context.save(); context.globalAlpha = particle.alpha; context.fillStyle = particle.color; context.beginPath(); context.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2); context.fill(); context.restore(); }); }, _renderLoop:function () { this._clear(); this._update(); this._render(); requestAnimFrame(this._renderLoop.bind(this)); } } } window.app.View = View; }) (window); <file_sep>(function () { 'use strict'; function App(options) { this.model = new app.Model(); this.view = new app.View(); this.controller = new app.Controller(this.view, this.model); this.controller._init(); } var brendApp = new App(); })();
17fe30f9e0d4fe58aa50c1d4c3939ee0c62d5cca
[ "JavaScript" ]
3
JavaScript
iuriikozuliak/challenge
f653f75e07751fad90835a9a7cf6267277d21723
3e39c56ca9a123283161ead743645943b105a27c
refs/heads/main
<file_sep> const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; const Constraint = Matter.Constraint; var backgroundImage; var boy; var tree; var stone; var ground; var mango1,mango2,mango3,mango4,mango5,mango6,mango7,mango8,mango9,mango10,mango11 var boyHit; function preload() { backgroundImage = loadImage("groundA.jpg"); } function setup() { createCanvas(1200, 800); engine = Engine.create(); world = engine.world; //Create the Bodies Here. boy = new Boy(200,596); tree = new Tree(900,350,30,300); mango1 = new Mango(1110,250,15); mango2 = new Mango(800,200,15); mango3 = new Mango(800,280,15); mango4 = new Mango(1000,250,15); mango5 = new Mango(670,300,15); mango6 = new Mango(970,190,15); mango7 = new Mango(870,340,15); mango8 = new Mango(870,230,15); mango9 = new Mango(880,130,15); mango10 = new Mango(820,130,15); mango11 = new Mango(990,100,15); stone = new Stone(150,650,15); boyHit = new Launcher(stone.body,{x:150,y:500}); Engine.run(engine); } function draw() { rectMode(CENTER); background(backgroundImage); boy.display(); tree.display(); mango1.display(); mango2.display(); mango3.display(); mango4.display(); mango5.display(); mango6.display(); mango7.display(); mango8.display(); mango9.display(); mango10.display(); mango11.display(); stone.display(); boyHit.display(); detectCollision(stone,mango1); detectCollision(stone,mango2); detectCollision(stone,mango3); detectCollision(stone,mango4); detectCollision(stone,mango5); drawSprites(); } function mouseDragged(){ Matter.Body.setPosition(stone.body,{x:mouseX,y:mouseY}); } function mouseReleased(){ boyHit.fly(); } function detectCollision(lstone,lmango){ mangoBodyPosition=lmango.body.position stoneBodyPosition=lstone.body.position var distance=dist(stoneBodyPosition.x,stoneBodyPosition.y,mangoBodyPosition.x,mangoBodyPosition.y) if(distance<=lmango.r+lstone.r){ Matter.Body.setStatic(lmango.body,false); } } function keyPressed(){ if(keyCode === 32){ Matter.Body.setPosition(stone.body,{x:235,y:420}) boyHit.attach(stone.body); } }
3270e93df027536d33e177a3e1ce0630a638508d
[ "JavaScript" ]
1
JavaScript
SmitParikh1234/Project-28
80acf5d0f96f47dfd86f6710e658e8744b9a73c9
9818c13ca9047311ef1cb0365a571ca2815071c5
refs/heads/master
<repo_name>ErinClark/td_b2bquote_uk<file_sep>/scraper.py # -*- coding: utf-8 -*- import sys from bs4 import BeautifulSoup from splinter import Browser import time import urllib import requests from datetime import datetime import scraperwiki import os reload(sys) # Reload does the trick! sys.setdefaultencoding('UTF8') def get_soup(url): #html = open('b2b source code.txt', 'r') html = urllib.urlopen(url) #print html.read() soup = BeautifulSoup(html, "lxml") print soup.prettify() return soup def get_tender_id(url): id = url[url.find('tender_id=')+9:url.find('&ln')] return id def get_tender_soup(soup): table = soup.find('div', id="last_logged_in_tender_list_container") tender_soup = table.findAll('div', {"class":"row"}) return tender_soup def get_url(soup, portal): print soup.findAll('a', {"class":"more-info"}) url = portal + soup.find('a', {"class":"more-info"})['href'] return url def get_info(soup, tag): info = soup.find(tag).text return info def get_val(soup, text, text2): ds = soup.find('p', {"class":"reference"}).text if not ds.find(text)==-1: print ds.find(text) dl = ds[ds.find(text)+len(text):].strip() elif not ds.find(text2)==-1: dl = ds[ds.find(text2)+len(text2):].strip() else: dl = '' val = dl[:dl.find('nestcell')-1] print text, ' : ', val return val def get_detail(soup, text, text2): ds = soup.find('p', {"class":"reference"}).text dl = ds[ds.find(text)+len(text):].strip() detail = dl[:dl.find('nestcell')-1] print text, ' : ', detail return detail def get_location(soup, text): ds = soup.find('p', {"class":"reference"}).text location = ds[ds.find(text)+len(text):].strip() return location if __name__ == '__main__': todays_date = str(datetime.now()) portal = "https://www.b2bquote.co.uk/" soup = get_soup(portal) tender_soup = get_tender_soup(soup) for t in tender_soup: #tender_url = get_url(t, portal) #tender_id = get_tender_id(tender_url) title = get_info(t, 'h3') b2b_ref_no = get_detail(t, 'B2B Ref No:', '') type = get_detail(t, 'Type:', '') est_value_gbp = get_val(t, 'Value (£): Estimated cost excluding VAT:', 'Value (£):') location = get_location(t, 'Location :') ''' def get_soup(url): html = urllib.urlopen(url) soup = BeautifulSoup(html, "lxml") return soup def get_login(url): browser = Browser("phantomjs", service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any']) browser.visit(url) time.sleep(2) print browser.url return browser browser.find_by_id('email').first.fill('<EMAIL>') browser.find_by_id('password').first.fill('<PASSWORD>') browser.find_by_value('Login').first.click() #print browser.find_by_value('Login').visible time.sleep(10) print browser.url #browser.click_link_by_href("https://www.b2bquote.co.uk/supplier-search-for-tenders") time.sleep(1) browser.select('status', "") browser.find_by_value("Search for Tenders").first.click() time.sleep(2) print browser.url '''
99b491e2257225ca255d331ba9052cd3921c72bf
[ "Python" ]
1
Python
ErinClark/td_b2bquote_uk
ef83660b439db32e1d9ff9025b6df661c19093f5
24747268ef9961b53dabfe95be77fc32561b19e0
refs/heads/master
<repo_name>kubo0180/plainpx<file_sep>/config/environment.rb # Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Plainpx::Application.initialize! <file_sep>/test/functional/pxes_controller_test.rb require 'test_helper' class PxesControllerTest < ActionController::TestCase setup do @px = pxes(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:pxes) end test "should get new" do get :new assert_response :success end test "should create px" do assert_difference('Px.count') do post :create, px: { description: @px.description, gmaps: @px.gmaps, image_url: @px.image_url, latitude: @px.latitude, longitude: @px.longitude, title: @px.title, user_name: @px.user_name } end assert_redirected_to px_path(assigns(:px)) end test "should show px" do get :show, id: @px assert_response :success end test "should get edit" do get :edit, id: @px assert_response :success end test "should update px" do put :update, id: @px, px: { description: @px.description, gmaps: @px.gmaps, image_url: @px.image_url, latitude: @px.latitude, longitude: @px.longitude, title: @px.title, user_name: @px.user_name } assert_redirected_to px_path(assigns(:px)) end test "should destroy px" do assert_difference('Px.count', -1) do delete :destroy, id: @px end assert_redirected_to pxes_path end end <file_sep>/app/controllers/pxes_controller.rb class PxesController < ApplicationController # GET /pxes # GET /pxes.json def index @pxes = Px.all(:order => "updated_at DESC") respond_to do |format| format.html # index.html.erb format.json { render json: @pxes } end end # GET /pxes/1 # GET /pxes/1.json def show @px = Px.find(params[:id]) @comment = @px.comments.build respond_to do |format| format.html # show.html.erb format.json { render json: @px } end end # GET /pxes/new # GET /pxes/new.json def new @px = Px.new respond_to do |format| format.html # new.html.erb format.json { render json: @px } end end # GET /pxes/1/edit def edit @px = Px.find(params[:id]) end # POST /pxes # POST /pxes.json def create @px = Px.new(params[:px]) respond_to do |format| if @px.save format.html { redirect_to @px, notice: 'Px was successfully created.' } format.json { render json: @px, status: :created, location: @px } else format.html { render action: "new" } format.json { render json: @px.errors, status: :unprocessable_entity } end end end # PUT /pxes/1 # PUT /pxes/1.json def update @px = Px.find(params[:id]) respond_to do |format| if @px.update_attributes(params[:px]) format.html { redirect_to @px, notice: 'Px was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @px.errors, status: :unprocessable_entity } end end end # DELETE /pxes/1 # DELETE /pxes/1.json def destroy @px = Px.find(params[:id]) @px.destroy respond_to do |format| format.html { redirect_to pxes_url } format.json { head :no_content } end end end <file_sep>/test/unit/helpers/pxes_helper_test.rb require 'test_helper' class PxesHelperTest < ActionView::TestCase end <file_sep>/app/models/px.rb class Px < ActiveRecord::Base attr_accessible :description, :gmaps, :image_url, :latitude, :longitude, :title, :user_name, :image has_many :comments validate :title, :user_name, presence: true validates :image_url, allow_blank: true, format: { with: %r{\.(gif|jpg|png)$}i, message: 'is not image file. Please set the image file.' } has_attached_file :image, styles: { square: '220x220#', medium: '480x480>'}, :default_url => "/images/:style/missing.png" end
8da7727f85244fb0937a3db865fec8162f88567f
[ "Ruby" ]
5
Ruby
kubo0180/plainpx
9b5c498b79e5df7f72422e8cf5c0bc46b4cba133
5d90d0152fb54b9c9da8938563e0ea8b47272f3b
refs/heads/master
<file_sep>import React, { Component } from "react"; import { editUser, cancelEdit, saveEdit, deleteUser } from "../../actions/users"; import { connect } from "react-redux"; import "./UserItem.css"; class UserItem extends Component { constructor(props) { super(props); this.state = { name: this.props.user.name, email: this.props.user.email, date: this.props.user.date, }; } handleEdit = (id) => { this.props.dispatch(this.props.editUser(id)); }; handleChange = (e) => { this.setState({ [e.target.name]: e.target.value, }); }; handleCancelEdit = (e) => { e.preventDefault(); this.props.dispatch(this.props.cancelEdit()); this.setState({ name: this.props.user.name, email: this.props.user.email, date: this.props.user.date, }); }; handleSaveEdit = (e) => { e.preventDefault(); const { name, email, date } = this.state; this.props.dispatch(this.props.saveEdit(this.props.user.id, name, email, date)); }; handleDelete = (id) => { this.props.dispatch(this.props.deleteUser(id)); }; render() { const { user, editableUserNumber } = this.props; let isEditable = editableUserNumber === user.id; return ( <div className="item-container"> <form className={isEditable ? "item" : "optional"}> <div className="form_input"> User name <input className="input-box" type="text" name="name" value={this.state.name} onChange={this.handleChange} autoComplete="off" /> <br /> Email <input className="input-box" type="email" name="email" value={this.state.email} onChange={this.handleChange} autoComplete="off" /> <br /> </div> <div> <button className="btn" onClick={this.handleSaveEdit}> Save </button> <button className="btn" onClick={this.handleCancelEdit}> Cancel </button> </div> </form> <div className={isEditable ? "optional" : "item"}> <div> <h1>User name : {user.name}</h1> <h2>Email : {user.email}</h2> <h2>DOJ : {user.date}</h2> </div> <div> <button className="btn" onClick={() => this.handleEdit(user.id)}> Edit </button> <button className="btn" onClick={() => this.handleDelete(user.id)}> Delete </button> </div> </div> </div> ); } } const mapStateToProps = (state) => { return { editableUserNumber: state.users.editableUserNumber, }; }; const mapDispatchToProps = (dispatch) => { return { dispatch, editUser, cancelEdit, saveEdit, deleteUser, }; }; export default connect(mapStateToProps, mapDispatchToProps)(UserItem); <file_sep>import axios from "axios"; import { ADD_CATEGORY, GET_CATEGORIES, EDIT_CATEGORY, CANCEL_EDIT_CATEGORY, SAVE_EDIT_CATEGORY, DELETE_CATEGORY } from "./actionTypes"; export function addCategory(name, subcategory) { return async function (dispatch) { const subcat = subcategory.split(" "); const { data } = await axios.post("http://localhost:4000/categories/", { name, subcat }); dispatch({ type: ADD_CATEGORY, payload: data, }); }; } export function getCategories() { return async function (dispatch) { const { data } = await axios.get("http://localhost:4000/categories"); dispatch({ type: GET_CATEGORIES, payload: data, }); }; } export function editCategory(categoryID) { return { type: EDIT_CATEGORY, payload: categoryID, }; } export function cancelEdit() { return { type: CANCEL_EDIT_CATEGORY, }; } export function saveEdit(id, name, subcategory) { return async function (dispatch) { const subcat = subcategory.split(" "); await axios.put(`http://localhost:4000/categories/${id}`, { name, subcat }); dispatch({ type: SAVE_EDIT_CATEGORY, payload: { editableCategoryNumber: null, id, data: { name, subcat, }, }, }); }; } export function deleteCategory(id) { return async function (dispatch) { await axios.delete(`http://localhost:4000/categories/${id}`); dispatch({ type: DELETE_CATEGORY, payload: id, }); }; } <file_sep>import React, { Component } from "react"; import { addCategory } from "../../actions/category"; import { connect } from "react-redux"; class AddCategory extends Component { constructor() { super(); this.state = { name: "", subcategories: "", }; } handleChange = (e) => { this.setState({ [e.target.name]: e.target.value, }); }; handleAddCategory = (e) => { e.preventDefault(); const { name, subcategories } = this.state; this.props.dispatch(this.props.addCategory(name, subcategories)); this.setState({ name: "", subcategories: "", }); }; render() { return ( <div> <h1>Add Category</h1> <form> <input className="input-box" type="text" name="name" placeholder="Enter category" value={this.state.name} onChange={this.handleChange} autoComplete="off" /> <br /> <textarea className="input-box" type="textarea" name="subcategories" placeholder="Enter sub-categories separated by space" value={this.state.subcategories} onChange={this.handleChange} autoComplete="off" /> <br /> <button className="btn-add" onClick={this.handleAddCategory}> Add caegory </button> </form> </div> ); } } const mapStateToProps = (dispatch) => { return { dispatch, addCategory, }; }; export default connect(mapStateToProps)(AddCategory); <file_sep>import React from "react"; import "./App.css"; import { Switch, Route, Redirect } from "react-router-dom"; import Navbar from "../Navbar/Navbar"; import UserList from "../UserList/UserList"; import AddUser from "../AddUser/AddUser"; import { getUsers } from "../../actions/users"; import { getCategories } from "../../actions/category"; import { connect } from "react-redux"; import CategoryList from "../CategoryList/CategoryList"; import AddCategory from "../AddCategory/AddCategory"; class App extends React.Component { componentDidMount() { this.props.dispatch(this.props.getUsers()); this.props.dispatch(this.props.getCategories()); } render() { return ( <div className="App"> <Navbar /> <Switch> <Route path="/users" exact component={UserList} /> <Route path="/add-user" exact component={AddUser} /> <Route path="/category" exact component={CategoryList} /> <Route path="/add-category" exact component={AddCategory} /> <Redirect from="/" exact to="/users" /> </Switch> </div> ); } } const mapDispatchToProps = (dispatch) => { return { dispatch, getUsers, getCategories, }; }; export default connect(null, mapDispatchToProps)(App); <file_sep>import React, { Component } from "react"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import CategoryItem from "../CategoryItem/CategoryItem"; class CategoryList extends Component { constructor() { super(); this.state = { searchField: "", }; } handleSearch = (e) => { this.setState({ searchField: e.target.value, }); }; render() { const { categoryList } = this.props; console.log(categoryList); const { searchField } = this.state; const filteredList = categoryList.filter((category) => { return category.name.toLowerCase().includes(searchField.toLowerCase()); }); return ( <div> <Link to="/add-category"> <button>Add category</button> </Link> <br /> <input className="search" type="search" placeholder="Search" onChange={this.handleSearch} /> {filteredList.map((category) => ( <CategoryItem key={category.id} category={category} /> ))} </div> ); } } const mapStateToProps = (state) => { return { categoryList: state.category.categoryList, }; }; export default connect(mapStateToProps)(CategoryList); <file_sep>import React, { Component } from "react"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import UserItem from "../UserItem/UserItem"; import { CSVLink } from "react-csv"; import "./UserList.css"; const headers = [ { label: "Name", key: "name" }, { label: "Email", key: "email" }, { label: "Date of joining", key: "date" }, ]; class UserList extends Component { constructor() { super(); this.state = { searchField: "", }; } handleSearch = (e) => { this.setState({ searchField: e.target.value, }); }; render() { const { usersList } = this.props; const { searchField } = this.state; const filteredList = usersList.filter((user) => { return user.name.toLowerCase().includes(searchField.toLowerCase()) || user.date.toLowerCase().includes(searchField.toLowerCase()); }); return ( <div> <Link to="/add-user"> <button>Add User</button> </Link> <CSVLink data={usersList} headers={headers} filename={"user_data.csv"} className="btn-download"> Download CSV </CSVLink>{" "} <br /> <input className="search" type="search" placeholder="Search" onChange={this.handleSearch} /> {filteredList.map((user) => ( <UserItem key={user.id} user={user} /> ))} </div> ); } } const mapStateToProps = (state) => { return { usersList: state.users.usersList, }; }; export default connect(mapStateToProps)(UserList); <file_sep>import React, { Component } from "react"; import { connect } from "react-redux"; import { editCategory, cancelEdit, saveEdit, deleteCategory } from "../../actions/category"; import "./CategoryItem.css"; class CategoryItem extends Component { constructor(props) { super(props); this.state = { name: this.props.category.name, subcat: this.props.category.subcat.join(" "), }; } handleEdit = (id) => { this.props.dispatch(this.props.editCategory(id)); }; handleCancelEdit = (e) => { e.preventDefault(); this.props.dispatch(this.props.cancelEdit()); this.setState({ name: this.props.category.name, subcat: this.props.category.subcat.join(" "), }); }; handleChange = (e) => { this.setState({ [e.target.name]: e.target.value, }); }; handleSaveEdit = (e) => { e.preventDefault(); const { name, subcat } = this.state; this.props.dispatch(this.props.saveEdit(this.props.category.id, name, subcat)); }; handleDelete = (id) => { this.props.dispatch(this.props.deleteCategory(id)); }; render() { const { category, editableCategoryNumber } = this.props; let isEditable = editableCategoryNumber === category.id; let moreItemsPresent = category.subcat.length > 5; return ( <div className="item-container"> <form className={isEditable ? "item" : "optional"}> <div className="form_input"> Category name <input className="input-box" type="text" name="name" value={this.state.name} onChange={this.handleChange} autoComplete="off" /> <br /> Subcategories <textarea className="input-box" type="text" name="subcat" value={this.state.subcat} onChange={this.handleChange} autoComplete="off" /> <br /> </div> <div> <button className="btn" onClick={this.handleSaveEdit}> Save </button> <button className="btn" onClick={this.handleCancelEdit}> Cancel </button> </div> </form> <div className={isEditable ? "optional" : "item"}> <div> <h1>Category name : {category.name}</h1> <span>Subcategories : </span> {category.subcat.map((i, index) => { console.log(typeof i); if (i.length !== 0 && index < 5) return ( <span key={index} className="subcategory"> {i}{" "} </span> ); })} {moreItemsPresent ? <span> ... more {category.subcat.length - 5 - 1} items present</span> : null} </div> <div> <button className="btn" onClick={() => this.handleEdit(category.id)}> Edit </button> <button className="btn" onClick={() => this.handleDelete(category.id)}> Delete </button> </div> </div> </div> ); } } const mapStateToProps = (state) => { return { editableCategoryNumber: state.category.editableCategoryNumber, }; }; const mapDispatchToProps = (dispatch) => { return { dispatch, editCategory, cancelEdit, saveEdit, deleteCategory, }; }; export default connect(mapStateToProps, mapDispatchToProps)(CategoryItem); <file_sep>import { ADD_CATEGORY, GET_CATEGORIES, EDIT_CATEGORY, CANCEL_EDIT_CATEGORY, SAVE_EDIT_CATEGORY, DELETE_CATEGORY } from "../actions/actionTypes"; const initialState = { categoryList: [], editableCategoryNumber: null, }; export default function category(state = initialState, action) { switch (action.type) { case ADD_CATEGORY: return { ...state, categoryList: [...state.categoryList, action.payload], }; case GET_CATEGORIES: return { ...state, categoryList: action.payload, }; case EDIT_CATEGORY: return { ...state, editableCategoryNumber: action.payload, }; case CANCEL_EDIT_CATEGORY: return { ...state, editableCategoryNumber: null, }; case SAVE_EDIT_CATEGORY: return { ...state, editableCategoryNumber: action.payload.editableCategoryNumber, categoryList: state.categoryList.map((category) => { if (category.id === action.payload.id) { return { ...action.payload.data, id: category.id, }; } return category; }), }; case DELETE_CATEGORY: return { ...state, categoryList: state.categoryList.filter((category) => category.id !== action.payload), }; default: return state; } } <file_sep>import { ADD_USER, GET_USERS, EDIT_USER, CANCEL_EDIT, SAVE_EDIT, DELETE_USER } from "../actions/actionTypes"; const initialState = { usersList: [], editableUserNumber: null, }; export default function users(state = initialState, action) { switch (action.type) { case ADD_USER: return { ...state, usersList: [...state.usersList, action.payload], }; case GET_USERS: return { ...state, usersList: action.payload, }; case EDIT_USER: return { ...state, editableUserNumber: action.payload, }; case CANCEL_EDIT: return { ...state, editableUserNumber: null, }; case SAVE_EDIT: return { ...state, editableUserNumber: action.payload.editableUserNumber, usersList: state.usersList.map((user) => { if (user.id === action.payload.id) { return { ...action.payload.data, id: user.id, }; } return user; }), }; case DELETE_USER: return { ...state, usersList: state.usersList.filter((user) => user.id !== action.payload), }; default: return state; } } <file_sep>import axios from "axios"; import { ADD_USER, GET_USERS, EDIT_USER, CANCEL_EDIT, SAVE_EDIT, DELETE_USER } from "./actionTypes"; export function getUsers() { return async function (dispatch) { const { data } = await axios.get("http://localhost:4000/users"); dispatch({ type: GET_USERS, payload: data, }); }; } export function addUser(name, email) { return async function (dispatch) { const date = new Date().toLocaleDateString().toString(); const { data } = await axios.post("http://localhost:4000/users/", { name, email, date }); dispatch({ type: ADD_USER, payload: data, }); }; } export function editUser(userID) { return { type: EDIT_USER, payload: userID, }; } export function cancelEdit() { return { type: CANCEL_EDIT, }; } export function saveEdit(id, name, email, date) { return async function (dispatch) { await axios.put(`http://localhost:4000/users/${id}`, { name, email, date }); dispatch({ type: SAVE_EDIT, payload: { editableUserNumber: null, id, data: { name, email, date, }, }, }); }; } export function deleteUser(userID) { return async function (dispatch) { await axios.delete(`http://localhost:4000/users/${userID}`); dispatch({ type: DELETE_USER, payload: userID, }); }; }
c5e07022503b35f75480201178832c95c6def318
[ "JavaScript" ]
10
JavaScript
asyriac/admin-system
026393c23a1f00db5f3755751d6c9e7a16d0654f
430198cefed0ec1d3cca130705e021df6410c47b
refs/heads/master
<file_sep>package griup.beans; import java.util.ArrayList; public class User { String name; ArrayList<String> goalsList; public String getName() { return name; } public void setName(String name) { this.name = name; } public ArrayList<String> getGoalsList() { return goalsList; } public void setGoalsList(ArrayList<String> goalsList) { this.goalsList = goalsList; } @Override public String toString() { return "User [name=" + name + ", goalsList=" + goalsList + "]"; } public User(User user) { super(); this.name = user.getName(); this.goalsList = user.getGoalsList(); } public User() { } } <file_sep>package griup.ui; public class UIMain { public static void main(String[] args) { UIFrame uiframe=new UIFrame(); } } <file_sep># Adaptive-Applications--Polychrest Adaptive Grocery Item Notifier <file_sep>package griup.dummyui; import java.util.ArrayList; import java.util.List; import com.github.andrewoma.dexx.collection.HashMap; import griup.beans.Food; import griup.beans.Pattern; import griup.beans.Recommendation; import griup.beans.Shop; import griup.beans.Shopping; import griup.beans.User; import griup.middleware.Middleware; import griup.polychrest.Constants; import griup.polychrest.InteractWithOntology; public class DummyUI { public static void main(String[] args) { //createShoppingInstance(); InteractWithOntology io= new InteractWithOntology(); io.getAllUser(); io.getAll(); Shop lidlArtane=new Shop(); lidlArtane.setShopName("lidlArtane"); Food kiwi=new Food(); kiwi.setFoodName("kiwi"); User paras=new User (); paras.setName("shubham"); User user=new User(); Food food= new Food (); food.setFoodName("chickenLegs"); user.setName("shubham"); ArrayList<String> goalOld=new ArrayList<String>(); ArrayList<String> goalNew=new ArrayList<String>(); goalOld.add("veggie"); goalNew.add("nonVeg"); user.setGoalsList(goalOld); paras.setGoalsList(goalNew); //io.getFoodAtShop(shopName); io.updateUserGoal(user, paras); //io. getShoppingByUser( user); //io.getRecommendationListForUser(user); Shop shop= new Shop(); //io.getFoodAtShop("lidlArtane"); //io.getShopThatSellsFood("butter"); Shopping shopping=new Shopping(); shopping.setAtPrice(1f); shopping.setAtShop(lidlArtane); shopping.setAtDateTime("12:00"); shopping.setBought(kiwi); shopping.setQuantity(1); int shopingNo=(int)(Math.random()*10000); System.out.println(shopingNo); shopping.setShoppingName(user.getName()+"Shops"+shopingNo); io.insertShoppingInstance(user, shopping); Recommendation rec=io.getRecommendationForUserAndFoodPair(user, food); rec.setHasByWeeklyWeightage((float) 0.912312); rec.setHasUserInterest((float) 0.931231); rec.setHasWeeklyWeightage((float) 0.93123123); //io.updateRecommendationForUserAndFoodPair(user, food,io.getRecommendationForUserAndFoodPair(user, food), rec); //io.getRecommendationListForUser(user); //io.getFoodCategory(food); io.getUserGoals(user); //io.updateUserGoal(userOld, userNew); } public static void createShoppingInstance() { Shop lidlArtane=new Shop(); lidlArtane.setShopName("lidlArtane"); Food kiwi=new Food(); kiwi.setFoodName("kiwi"); User paras=new User (); paras.setName("paras"); Shopping shopping=new Shopping(); shopping.setAtPrice(1f); shopping.setAtShop(lidlArtane); shopping.setAtDateTime("12:00"); shopping.setBought(kiwi); shopping.setQuantity(1); Pattern pattern=new Pattern(0.3f, 0.1f, 0.6f); Middleware.insertShoppingInstance(paras,shopping, pattern); } public static void getRecommendation() { User paras=new User(); paras.setName("paras"); HashMap<Food,Recommendation> recommendationListForUser=Middleware.getRecommendationListForUser(paras); } }<file_sep>package griup.ui; import java.util.ArrayList; import java.util.List; import com.github.andrewoma.dexx.collection.HashMap; import griup.beans.Food; import griup.beans.Pattern; import griup.beans.Recommendation; import griup.beans.Shop; import griup.beans.Shopping; import griup.beans.User; import griup.middleware.Middleware; import griup.polychrest.Constants; import griup.polychrest.InteractWithOntology; public class DummyUI { public static void main(String[] args) { //createShoppingInstance(); InteractWithOntology io= new InteractWithOntology(); io.getAllUser(); io.getAll(); User user=new User(); user.setName("paras"); io. getShoppingByUser( user); io.getRecommendationListForUser(user); Shop shop= new Shop(); io.getFoodAtShop("lidlArtane"); io.getShopThatSellsFood("butter"); } public static void createShoppingInstance() { Shop lidlArtane=new Shop(); lidlArtane.setShopName("lidlArtane"); Food kiwi=new Food(); kiwi.setFoodName("kiwi"); User paras=new User (); paras.setName("paras"); Shopping shopping=new Shopping(); shopping.setAtPrice(1f); shopping.setAtShop(lidlArtane); shopping.setAtDateTime("12:00"); shopping.setBought(kiwi); shopping.setQuantity(1); Pattern pattern=new Pattern(0.3f, 0.1f, 0.6f); Middleware.insertShoppingInstance(paras,shopping, pattern); } public static void getRecommendation() { User paras=new User(); paras.setName("paras"); HashMap<Food,Recommendation> recommendationListForUser=Middleware.getRecommendationListForUser(paras); } }
e3f345d17d893b8452cd3286c31b77ce95dce9be
[ "Markdown", "Java" ]
5
Java
psspavan96/Adaptive-Applications--Polychrest
3c98fb01e02dfe6235e9e7246f4716ee0a737109
cbc251a431ecb33d702b720360e0a04b8a09e196
refs/heads/master
<repo_name>MdZakirHossainBhuiyan/ema-john-simple<file_sep>/src/components/ReviewItem/ReviewItem.js import React from 'react'; const ReviewItem = (props) => { const {name, quantity, key, price} = props.product; const reviewItemStyle={ borderBottom: '1px solid lightgray', margin: '5px 20px 5px 20px', } const buttonStyle = { border: '1px solid black', borderRadius: '5px', backgroundColor: '#f0c14b', width: '200px', marginBottom: '10px', marginLeft: '40px', } const tagStyle = { marginLeft: '40px', } return ( <div style={reviewItemStyle}> <h4 className="product-name">{name}</h4> <p style={tagStyle}>Quantity: {quantity}</p> <p style={tagStyle}><small>Price: {price}$</small></p> <br/> <button style={buttonStyle} onClick={() => props.removeProduct(key)}>Remove</button> </div> ); }; export default ReviewItem;<file_sep>/src/components/cart/Cart.js import React from 'react'; import './Cart.css'; const Cart = (props) => { const cart = props.cart; const totalPrice = cart.reduce((total, pr) => (total + pr.price*pr.quantity), 0); let shippingCost = 0; if(totalPrice>100){ shippingCost = 40; } else if(totalPrice>500){ shippingCost = 0; } else if(totalPrice<=100 && totalPrice>0){ shippingCost = 50; } let tax = (totalPrice/10); return ( <div className="displayCart"> <h4>Order Summary</h4> <p>Items Ordered: {cart.length}</p> <table> <tr> <th>Items: </th> <td>${totalPrice.toFixed(2)}</td> </tr> <tr> <th>Shipping & Handling: </th> <td>${shippingCost.toFixed(2)}</td> </tr> <tr> <th>Total before tax: </th> <td>${tax.toFixed(2)}</td> </tr> <tr> <th>Estimated tax: </th> <td>${totalPrice.toFixed(2)}</td> </tr> <tr className="totalPrice"> <th className="text-primary">Order Total: </th> <td>${(totalPrice + shippingCost + tax).toFixed(2)}</td> </tr> </table> <br/> { props.children } </div> ); }; export default Cart;<file_sep>/src/components/Login/firebase.config.js const firebaseConfig = { apiKey: "<KEY>", authDomain: "ema-jhon-shop-d63bc.firebaseapp.com", projectId: "ema-jhon-shop-d63bc", storageBucket: "ema-jhon-shop-d63bc.appspot.com", messagingSenderId: "757107965037", appId: "1:757107965037:web:7364fa93b548343ed05364", measurementId: "G-J57Y5PL08T" }; export default firebaseConfig;<file_sep>/README.md <h1>EMA-JOHN-SIMPLE</h1> ### a complete website based on react.
3ff4ab8c935ee65358b04d81420fb8ed91092f6a
[ "JavaScript", "Markdown" ]
4
JavaScript
MdZakirHossainBhuiyan/ema-john-simple
9330234b7db0d9dc6dea8c3c3cab5b488be9f8e4
1df7f97e50165a7e8646c01a7c3af8600e419c55
refs/heads/master
<repo_name>Amareis/async-graphql<file_sep>/async-graphql-derive/Cargo.toml [package] name = "async-graphql-derive" version = "1.14.12" authors = ["sunli <<EMAIL>>"] edition = "2018" description = "Macros for async-graphql" publish = true license = "MIT/Apache-2.0" documentation = "https://docs.rs/async-graphql/" homepage = "https://github.com/async-graphql/async-graphql" repository = "https://github.com/async-graphql/async-graphql" keywords = ["futures", "async", "graphql"] categories = ["network-programming", "asynchronous"] [lib] proc-macro = true [dependencies] async-graphql-parser = { path = "../async-graphql-parser", version = "1.14.2" } proc-macro2 = "1.0.6" syn = { version = "1.0.20", features = ["full", "extra-traits"] } quote = "1.0.3" Inflector = "0.11.4" proc-macro-crate = "0.1.4" <file_sep>/src/guard.rs //! Field guards use crate::{Context, FieldResult}; /// Field guard /// /// Guard is a precondition for a field that is resolved if `Ok(()` is returned, otherwise an error is returned. #[async_trait::async_trait] pub trait Guard { #[allow(missing_docs)] async fn check(&self, ctx: &Context<'_>) -> FieldResult<()>; } /// An extension trait for `Guard` pub trait GuardExt: Guard + Sized { /// Merge the two guards. fn and<R: Guard>(self, other: R) -> And<Self, R> { And(self, other) } } impl<T: Guard> GuardExt for T {} /// Guard for `GuardExt::and` pub struct And<A: Guard, B: Guard>(A, B); #[async_trait::async_trait] impl<A: Guard + Send + Sync, B: Guard + Send + Sync> Guard for And<A, B> { async fn check(&self, ctx: &Context<'_>) -> FieldResult<()> { self.0.check(ctx).await?; self.1.check(ctx).await } } <file_sep>/Cargo.toml [package] name = "async-graphql" version = "1.14.12" authors = ["sunli <<EMAIL>>"] edition = "2018" description = "A GraphQL server library implemented in Rust" publish = true license = "MIT/Apache-2.0" documentation = "https://docs.rs/async-graphql/" homepage = "https://github.com/async-graphql/async-graphql" repository = "https://github.com/async-graphql/async-graphql" keywords = ["futures", "async", "graphql"] categories = ["network-programming", "asynchronous"] readme = "README.md" [features] default = ["bson", "url", "chrono-tz"] [dependencies] async-graphql-parser = { path = "async-graphql-parser", version = "1.14.2" } async-graphql-derive = { path = "async-graphql-derive", version = "1.14.0" } anyhow = "1.0.26" thiserror = "1.0.11" async-trait = "0.1.30" serde = "1.0.104" serde_derive = "1.0.104" serde_json = "1.0.48" bytes = "0.5.4" Inflector = "0.11.4" base64 = "0.12.0" byteorder = "1.3.4" futures = "0.3.0" parking_lot = "0.10.0" chrono = "0.4.10" slab = "0.4.2" once_cell = "1.3.1" itertools = "0.9.0" tempfile = "3.1.0" httparse = "1.3.4" mime = "0.3.16" http = "0.2.1" fnv = "1.0.6" regex = "1.3.5" tracing = "0.1.13" indexmap = "1.3.2" async-stream = "0.2.1" multer = "1.2.0" log = "0.4.8" bson = { version = "0.14.1", optional = true } uuid = { version = "0.8.1", features = ["v4"] } url = { version = "2.1.1", optional = true } chrono-tz = { version = "0.5.1", optional = true } [dev-dependencies] async-std = { version = "1.5.0", features = ["attributes"] } serde = "1.0.104" serde_derive = "1.0.104" [workspace] members = [ "async-graphql-parser", "async-graphql-derive", "async-graphql-actix-web", "async-graphql-warp", "async-graphql-tide", # "async-graphql-lambda", "benchmark", ] <file_sep>/async-graphql-actix-web/Cargo.toml [package] name = "async-graphql-actix-web" version = "1.14.7" authors = ["sunli <<EMAIL>>"] edition = "2018" description = "async-graphql for actix-web" publish = true license = "MIT/Apache-2.0" documentation = "https://docs.rs/async-graphql/" homepage = "https://github.com/async-graphql/async-graphql" repository = "https://github.com/async-graphql/async-graphql" keywords = ["futures", "async", "graphql"] categories = ["network-programming", "asynchronous"] [dependencies] async-graphql = { path = "..", version = "1.14.0" } actix-web = "2.0.0" actix-web-actors = "2.0.0" actix = "0.9.0" actix-rt = "1.0.0" futures = "0.3.0" bytes = "0.5.4" serde_json = "1.0.48" <file_sep>/async-graphql-tide/Cargo.toml [package] name = "async-graphql-tide" version = "1.14.10" authors = ["vkill <<EMAIL>>"] edition = "2018" description = "async-graphql for tide" publish = true license = "MIT/Apache-2.0" documentation = "https://docs.rs/async-graphql/" homepage = "https://github.com/async-graphql/async-graphql" repository = "https://github.com/async-graphql/async-graphql" keywords = ["futures", "async", "graphql"] categories = ["network-programming", "asynchronous"] [dependencies] async-graphql = { path = "..", version = "1.14.0" } tide = "0.9.0" async-trait = "0.1.30" serde_json = "1.0.51" futures = "0.3.4" async-std = "1.5.0" [dev-dependencies] smol = { version = "0.1.10", features = ["tokio02"] } reqwest = "0.10.4"
431e720105f5b34b89928db27ae4092080623836
[ "TOML", "Rust" ]
5
TOML
Amareis/async-graphql
b2f8e7138abb356d990fb7f79f03efa8bd6d7fd4
31e873708223679da0c9451887d62d459a67f364
refs/heads/master
<file_sep> #Donation Analytics README # Table of Contents 1. [Solution Approach](README.md#approach) 2. [Solution Design](README.md#solution-design) 3. [Data structure considerations ](README.md#datastructures) 4. [Software/package dependencies ](README.md#dependencies) # Solution Approach This program is likely to handle large volume of data. Based on the requirement, and looking at few files in the FEC links provided, it is very evident that the Data Structure design is the key. This program iterates through the history of donor transactions, and with the requirement of computing running percentiles, data cannot be a small set any point of time - it accumulates. Python is a very powerful language and is known for its versatile features. This program mainly exploits the datastructure support and a few python packages/modules. # Solution Design - Donor_Analytics : A simple main class with methods to process input file line by line - Main method to process a line - Validation methods - Other methods to compute totals etc. - File operations - Display progress bar - helpful since application runs for longer time to produce the output - Key uses "**|**" . Since this key can be used as-is as part of the output, we can minimize any unnecessary str operations while writing to output file How is the data structure constructed? Master donor list is created with all valid donors - Dictlist(dict). This uses key as **NAME|ZIPCODE**. This is a Dictlist of Dictlists as shown below. YEAR is the key for the nested inner Dictlist. A structure of Dictlist of dicts could have been an alternative, however, this approach provides more flexibility for any future requirements. Sample Input data (showing only required fields). Please note that donor O'REGAN has multiple transactions for YR2017 > C00496679|O'REGAN, KATHLEEN|92253|12042016|110 > C00496679|O'REGAN, KATHLEEN|92253|12042017|25 > C00496679|<NAME>|92253|12042017|20 > C00496680|WESTWOOD, ROBERT|92270|12042017|100 Sample datastructure for Master donor list built during processing. As you can see, querying on NAME|ZIP will fetch a list of the values. NOTE: The inner Dictlist is being used as a mere dict in this program and can be extended further for any future enhancements. {**"<NAME>|92253"**: [{'2016': [{'amount': 110, 'cmte_id': 'C00496679'}]}, {'2017': [{'amount': 25, 'cmte_id': 'C00496679'}]}, {'2017': [{'amount': 20, 'cmte_id': 'C00496679'}]}], **'WESTWOOD, ROBERT|92270'**: [{'2017': [{'amount': 100, 'cmte_id': 'C00496680'}]}]} Repeat donor list is built for repeat donors. This uses key **CMTE_ID|ZIP_CODE|YEAR**. This ultimatately converts to the output. Sample of datastructure for Repeat donor list shown below: > {'**C00496679|92253|2017**': [{'amount': 25, 'total_amount': 25, 'percentile_amount': 25, 'no_of_transactions': 1}, {'amount': 20, 'total_amount': 45, 'percentile_amount': 20, 'no_of_transactions': 2}]} The following points was considered while picking the Datastructure - key based for faster look-up - highly efficient inserts - mutable - inplace updates - nested # Data structure considerations Upon trying various built-in Data Structures, I have created Dictlist(dict). Below are the options considered before making the decision. a. DataFrames : While this was robust, Dataframe append was not found to be suitable. Would have worked best perhaps if it was a one-time load and read-only-processing b. Dictionary : This was the next option. However, the challenge here is with valid duplicate keys [NAME|ZIP] which cannot be added into plain dict. Hence it was subclassed. # Software/package dependencies 1. This program uses Python 3.6 Run.sh: python3.6 ./src/donation- analytics.py ./input/itcont.txt ./input/percentile.txt ./o utput/repeat_donors.txt 2. The following packages are used, and needs to be installed using pip install - numpy v1.14.0 - pyyaml v3.12 - tqdm v4.19.5 3. The following modules are imported - import numpy as np - from sys import argv - import time - import math - import yaml - import mmap - from tqdm import * <file_sep>''' Insight Donation Analytics coding Challenge This program takes a file listing individual campaign contributions for multiple years, determine which ones came from repeat donors, calculate and ouput the info in the specified file and format For each recipient, zip code and calendar year, calculate these three values for contributions coming from repeat donors: total dollars received total number of contributions received donation amount in a given percentile Note : if a donor had previously contributed to any recipient listed in the input file in any prior calendar year, that donor is considered a repeat donor @author: <NAME> Created on 9-Feb-2018 ''' import numpy as np from sys import argv import time import math import yaml import mmap from tqdm import * """ Donorlist is a dict subclass. A dictionary cannot save records with duplicate keys, hence had to adapt to the needs of this challenge. If a row with duplicate key is added, it stores the values for that key as a list """ class Donorlist(dict): def __setitem__(self, key, value): try: self[key] except KeyError: super(Donorlist, self).__setitem__(key, []) self[key].append(value) """ Class Donation_Analytics This is the main class that handles the data and the processing. Data is held mainly in two Donorlist objects - one for Master donor list, and one for Repeat donor list For more details on the data structure used, please refer to the README document Attributes: Constants for position of interested fields in the CSV for extraction master_donor_dict (type Donorlist) repeat_donor_dict (type Donorlist) Methods: process_data This is the main method to read the input line by line. Invokes process_input_record for further processing process_input_record This processes one line of input data at a time, identifies repeat donors, generate keys and mainly builds the data structures for master donor list and repeat donor list. add_to_master_donor_list Inserts a record into the master donor list look-up data structure. Master donor list is a Donorlist of Donorlists. For a specific key, it saves a Donorlist as the value add_to_repeat_donor_dict Inserts record into repeat donor list. After it processes one record, it writes to output, one line at a time get_percentile_totals_transactions Mainly calculates the aggregates and percentile for the repeat donors Others.. Validation methods """ class Donation_Analytics(): # Constants - Denote required positions in the input file CMTE_ID = 0 NAME = 7 ZIP_CODE = 10 TRANSACTION_DATE = 13 TRANSACTION_AMOUNT = 14 OTHER_ID = 15 #Initialize few attributes def __init__(self, input_file=None, percentile_file=None, output_file=None): self.input_file = input_file self.output_file = output_file self.percentile_file = percentile_file self.master_donor_dict = Donorlist() self.repeat_donor_dict = Donorlist() #Fetch percentile value from the input file def get_percentile_value(self, percentile_file): try: file = open(percentile_file) for line in file: percentile_val = int(line.strip()) if (percentile_val in range(1,100)): return percentile_val except: print("Please provide a valid Percentile file") raise Exception """ Add a record in master_donor_dict (donor_key is NAME|ZIP_CODE , transaction amount ) Since master donor list is a Donorlist of Donorlists, this method creates a donorlist and adds it to the master list For more details on datastructure, please refer to the README file """ def add_to_master_donor_list(self, donor_key,cmte_id, year, transaction_amount): donor = Donorlist() #The inner Dictlist uses YEAR as key donor[year] = {"amount": transaction_amount, "cmte_id":cmte_id} self.master_donor_dict[donor_key] = donor return """ Add a record in repeat_donor_dict (repeat_donor_key is CMTE_ID| , transaction amount ) Since master donor list is a Donorlist of Donorlists, this method creates a donorlist and adds it to the master list For more details on datastructure, please refer to the README file """ # Add a record in repeat_donor_dict (key is cmte_id, name and zipcode ) def add_to_repeat_donor_dict(self, repeat_donor_key, transaction_amount, percentile_val): (percentile_amount, total_amount_by_repeat_donors, no_of_transactions) = self.get_percentile_totals_transactions(repeat_donor_key, transaction_amount, percentile_val) self.repeat_donor_dict[repeat_donor_key] = {"amount":transaction_amount, "total_amount":total_amount_by_repeat_donors,"percentile_amount":percentile_amount, "no_of_transactions":no_of_transactions} # Output the first 3 fields from the repeat_donor_key and append percentile, total and no_of_transactions percentile_amount = str(self.round_to_whole_dollar(percentile_amount)) repeat_donor_string_output = "|".join([repeat_donor_key,percentile_amount,str(total_amount_by_repeat_donors),str(no_of_transactions)]) #write to repeat donor output file print(repeat_donor_string_output, file=self.output_file_fp) return # This method validates the transaction date def is_transaction_date_valid(self, transaction_date): try: time.strptime(transaction_date, '%m%d%Y') except ValueError: return False return True # This method validates zip code (Only the first 5 digits are used here) def validate_zip(self, zip): if(zip != None): return len(zip) == 5 return False #This method rounds up or down the percentile amount # 0.5 and above will be upper whole dollar # Anything less than 0.5 will be the lower whole dollar def round_to_whole_dollar(self, any_number): if (float(any_number) % 1) >= 0.5: return(math.ceil(any_number)) else: return(round(any_number)) """ process_input_record (cmte_id, name, zip_code, year, transaction_amount, percentile_val) This processes one line of input data at a time, identifies repeat donors, generate keys and mainly builds the data structures for master donor list and repeat donor list. For master donor, the key NAME|ZIP_CODE is created. The inner donorlist uses key YEAR For repeat donor the key CMTE_ID|ZIP_CODE|YEAR is created """ def process_input_record(self, cmte_id, name, zip_code, year, transaction_amount, percentile_val): #create donor key for current record from file donor_key = name + '|' + zip_code try: #create donor key for the current record repeat_donor_key = cmte_id + '|' + zip_code + '|' + year #Checks if repeat donor : If he is repeat donor the donor key should exist in master donor list if(self.master_donor_dict[donor_key]): # Current donor is a repeat donor. But check whether record is listed out of order # Eg., Lets say a record for the key NAME|ZIP calendar year 2017 is already processed. # Now, the current record has calendar year 2015 for the same donor -- Skip this record if not (self.is_data_listed_out_of_order(donor_key,year)): #valid record to output - Add the repeat donor to repeat donor list self.add_to_repeat_donor_dict(repeat_donor_key, transaction_amount, percentile_val) #add current donor to master donor list self.add_to_master_donor_list(donor_key,cmte_id, year, transaction_amount) else: #Current donor is NOT a repeat donor, just add to master donor list self.add_to_master_donor_list(donor_key,cmte_id, year, transaction_amount) except KeyError: #Indicates that this is the first occurance of the valid donor . Add to master donor list self.add_to_master_donor_list(donor_key,cmte_id, year, transaction_amount) return # This method returns the number repeat donors for a CMTE_ID|ZIP|YEAR key. # It simply is the number of records by key in the repeat donor list def get_number_of_repeat_donor_transactions_byKey(self, repeat_donor_key): return len(self.repeat_donor_dict[repeat_donor_key]) #This method checks if data is out of order. # Eg., Lets say a record for the key NAME|ZIP calendar year 2017 is already processed. # Now, the current record has calendar year 2015 for the same donor -- Need to Skip record def is_data_listed_out_of_order(self, donor_key, current_record_year): year_list = [] # NOTE : master donor list is Dictlist of Dictlists. # Get all values for key NAME|ZIP from master donor list - this returns a list of Dictlist # the Key for the inner Dictlist is YEAR. Get the Max_value of Keys # Let's say current record has calendar year 2015, the Maximum year key returned is 2017 # The current record being processed ie, calendar year 2015 needs to be skipped try: for row in self.master_donor_dict[donor_key]: for key in row: year_list.append(int(key)) current_record_year = int(current_record_year) #Most recent calendar year where a transaction was processed for NAME|ZIP key (a donor) max_year = max(year_list) # Check calendar year of the transaction date in the Current record if(current_record_year < max_year): return True else: return False except: raise (Exception("Failed while checking for year disorder")) # This method calculates the percentile amount for the repeat donor record to be output def get_percentile_totals_transactions(self, repeat_donor_key, amount, percentile_val): #Initialize as default value with the contribution amount of current repeat donor list_of_contribution_amounts = [amount] #Initialize as default value with one transaction for the current repeat donor no_of_transactions = 1 #calculate totals, transactions and percentile if there are more repeat donors with key CMTE_ID|ZIP|YEAR #Check of this record happens to be the first repeat donor for the key CMTE_ID|ZIP|YEAR try: repeat_donors = self.repeat_donor_dict[repeat_donor_key] except KeyError: return (amount,amount,no_of_transactions) #Find the total contributions of the repeat donors by key for item in repeat_donors: temp_amount = item["amount"] amount += temp_amount list_of_contribution_amounts.append(temp_amount) #Calculate percentile amount for all transactions by repeat donor for CMTE_ID|ZIP|YEAR based on percentile value provided percentile_amount = np.percentile(np.array(list_of_contribution_amounts),percentile_val, interpolation='nearest') # Get # of transactions for CMTE_ID|ZIP|YEAR no_of_repeat_donors = self.get_number_of_repeat_donor_transactions_byKey(repeat_donor_key) no_of_transactions += no_of_repeat_donors return (percentile_amount,amount,no_of_transactions) """ process_data This is the main method to read the input line by line. Invokes process_input_record for further processing Reads input file line by line, tokenizes, invokes few validations and method process_input_recod """ def process_data(self): if self.input_file is None: print("Input file not provided") return if self.percentile_file is None: print("Percentile file not provided") return try: # get the percentile value from input percentile file percentile_val = self.get_percentile_value(percentile_file) # gets file handlers for input data and output files self.input_file_fp = open(self.input_file, 'r') self.output_file_fp = open(self.output_file, 'w') # Repeats for every line read from input data file . # Since the process may take longer for huge files, a progress bar has been added using the tqdm module # This takes a few extra seconds since calculates the progress and does i/o too at intervals # for line in self.input_file_fp: for line in tqdm(self.input_file_fp, total=self.get_num_lines()): #split into tokens by delimiter | fields = line.strip().split('|') #required fields for processing #recipient cmte_id = fields[self.CMTE_ID] #donor name = fields[self.NAME] #zip code of donor, only first 5 digits are required zip_code = fields[self.ZIP_CODE][:5] # transaction occured date transaction_date = fields[self.TRANSACTION_DATE] #transaction amount read as either float or whole amounts using yaml transaction_amount = yaml.load(fields[self.TRANSACTION_AMOUNT]) #other id --> elimination criteria - not individual donor other_id = fields[self.OTHER_ID] # Validate the fields if other_id.strip() == '' and cmte_id != '' and transaction_amount != '' : if self.is_transaction_date_valid(transaction_date): # The last 4 digits of the year is needed year = transaction_date[-4:] #process the record self.process_input_record(cmte_id, name, zip_code, year, transaction_amount, percentile_val) except FileNotFoundError as f: print("Please provide valid Input files.. : ", f) except Exception as e: print("Aborted data processing ", e) except Error as e: print ("Aborting data processing ", e) finally: #cleanup code if(self.input_file_fp): self.input_file_fp.close() if(self.output_file_fp): self.output_file_fp.close() return # This is to support the progress bar display. It gets the total lines from input file. # Based on number of lines processed, it displays rate of progress def get_num_lines(self): fp = open(self.input_file, "r+") buf = mmap.mmap(fp.fileno(), 0) lines = 0 while buf.readline(): lines += 1 return lines """ Main funtion for this Donation analysis. Process the command line arguments which is the input, percentile and the output files Instanciate the main class, and calls its main method to process data """ if __name__ == "__main__": if (len(argv) < 4): print('Invalid : Please provide valid command line arguments') exit(1) # parse command line arguments (script, input_file, percentile_file, output_file) = argv print("Processing data for Donation Analytics. It may take some time, please wait..") analyzer = Donation_Analytics(input_file, percentile_file, output_file) analyzer.process_data() print("Processing data for Donation Analytics COMPLETE!")
5cf9e03670e63203af5e58289c36bed4cd0a3106
[ "Markdown", "Python" ]
2
Markdown
shailacdi/donation-analytics
adcc240d08afc36127183d084f5e967aaa0b3e8f
76ff0f63d72186cb708dad33d44c256e6af4b709
refs/heads/master
<file_sep># LoginKotlin Mi primer Login creado con Kotlin -<NAME> 216776041 <file_sep>package martinez.jimenez.loginkotlin import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btLogin.setOnClickListener { val user = etUsr.text.toString() val pass = etPass.text.toString() if (user.equals("") and pass.equals("")){ mensaje("Debes rellenar los campos!!") } else if (user.equals("")){ mensaje("Falta el usuario!") } else if (pass.equals("")){ mensaje("Ingresa tu contraseña") } else{ if (user.equals("set") and pass.equals("<PASSWORD>")){ mensaje("Bienvenido: $user") }else{ mensaje("No te conozco >:c") etUsr.setText("") etPass.setText("") etUsr.requestFocus() //pa ingresar usuario de nuevo } } } } override fun onStart() { super.onStart() Log.wtf("ejemplo", "creo que estoy en onstart") } override fun onResume() { super.onResume() Log.wtf("ejemplo", "creo que estoy en Onresume") } override fun onRestart() { super.onRestart() Log.wtf("ejemplo", "creo que estoy en OnRestart") } override fun onPause() { super.onPause() Log.wtf("ejemplo","creo que estoy en onPause") } override fun onStop() { super.onStop() Log.wtf("ejemplo","creo que estoy en onStop") } override fun onDestroy() { super.onDestroy() Log.wtf("ejemplo", "creo que estoy en onDestroy") } fun mensaje(mensaje:String) { Toast.makeText(this,mensaje, Toast.LENGTH_LONG).show() } }
d11aa655b91511939100c3274864cda2c0bedf27
[ "Markdown", "Kotlin" ]
2
Markdown
MussgoKing/LoginKotlin
202941339563c415512aad7c06cc9e71a0297d6e
39cbe45b10f8b986fca7a7c4fec997e42a9dc9d5
refs/heads/main
<file_sep>import placeholderPicture from '../images/2.jpg'; import presentPicture from '../images/present.jpg'; export const calendarContent = [ { idd: 0, title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture, contentImage: presentPicture, }, { idd: 1, title: "December 2", description: "Lahjacontent tähän", image: placeholderPicture, contentImage: presentPicture, }, { idd: 2, title: "December 3", description: "Lahjacontent tähän", image: placeholderPicture, contentImage: presentPicture, }, { idd: 3, title: "December 4", description: "Lahjacontent tähän", image: placeholderPicture, contentImage: presentPicture, }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, { title: "December 1", description: "Lahjacontent tähän", image: placeholderPicture }, ];<file_sep>import React from 'react'; // import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; const Footer = () => { return ( <footer className="text-center text-lg-start bg-dark text-muted"> <section className="footer-main"> <div className="container text-center text-md-start"> <div className="row p-3"> <div className="col-md-3 col-lg-4 col-xl-3 mx-auto mb-1"> <h6 className="text-uppercase fw-bold mb-2"> About </h6> <p> Coolest christmas calendar ever made :D </p> </div> </div> </div> </section> </footer> ) } export default Footer;
8ad44e7a60699147d25e399fa202ce53a9b89862
[ "JavaScript" ]
2
JavaScript
Lalikki/Joulukalenteri
fe0012dee94e70d91b8ba7b0dbdc78f476b04c01
473b88ca652cb16e84756795076faf61febb5e5a
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using SharpStrap.Helpers; using SharpStrap.Modules; namespace Tests.Modules { public class ErrorModule : SharpStrap.Modules.BaseModule { public override async Task<ModuleResult> Run(IDictionary<string, string> variables, ColoredTextWriter output) { await Task.Delay(1); // add something awaitable to make this an async task like all other tasks var result = new ModuleResult(ModuleResultStates.Error, new List<string>(), "no command run"); return result; } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace SharpStrap.Helpers { internal interface IModuleFinder { string TrimEnd { get; } string TrimStart { get; } string Prefix { get; } string Suffix { get; } IEnumerable<(string Name, Type Type)> GetAllModulesForModulesNamespace(); } internal class ModuleFinder : IModuleFinder { public string TrimEnd { get; set; } public string TrimStart { get; set; } public string Prefix { get; set; } public string Suffix { get; set; } public IEnumerable<(string Name, Type Type)> GetAllModulesForModulesNamespace() { var types = GetAllTypes("SharpStrap.Modules"); var tuples = new List<(string Name, Type Type)>(types.Count()); foreach(var t in types) { var name = t.Name; if(name.EndsWith(this.TrimEnd)) name = name.Substring(0, name.Length - this.TrimEnd.Length); if(name.StartsWith(this.TrimStart)) name = name.Substring(TrimStart.Length, name.Length - this.TrimStart.Length); name = $"{Prefix}{name}{Suffix}"; tuples.Add((name, t)); } return tuples; } private IEnumerable<Type> GetAllTypes(string name) { return AppDomain .CurrentDomain .GetAssemblies() .SelectMany(a => a.GetTypes()) .Where(t => t.IsClass == true && t.IsAbstract == false && t.Namespace != null && t.Name.EndsWith(TrimEnd) && t.Namespace.EndsWith(name) ); } internal static ModuleFinder CreateDefault() { var moduleFinder = new ModuleFinder { Prefix = "tag:yaml.org,2002:", Suffix = "", TrimStart = "", TrimEnd = "Module" }; return moduleFinder; } } }<file_sep>using System; using System.Collections.Generic; using SharpStrap.Helpers; namespace Tests.Helpers { public class DummyTextFileOutput : ITextFileOutput { public Dictionary<string, string> Contents { get; private set; } = new Dictionary<string, string>(); public void WriteAllLines(string path, IEnumerable<string> lines) { if(Contents.ContainsKey(path)) Contents.Remove(path); Contents.Add(path, string.Join(Environment.NewLine, lines)); } public void WriteAllText(string path, string text) { if(Contents.ContainsKey(path)) Contents.Remove(path); Contents.Add(path, text); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using SharpStrap.Modules; namespace DocsGenerator { // // This is whole tool is merely a proof of concept and requires some serious rework! // Do not use this in production! // class Program { private const string sharpStrapAssemblyName = "../src/bin/Debug/netcoreapp2.0/sharpstrap.dll"; private const string modulesSourceCodeFolder = "../src/Modules"; private const string modulesFileFilter = "*Module.cs"; private const string ModuleNameSpaceEndsWith = "Modules"; private const string ModuleClassNameEndsWith = "Module"; private const string baseModuleClassName = "BaseModule"; private static string templateFilename = string.Empty; private static string manualFilename = string.Empty; //private static readonly Dictionary<string, ClassCodeInfo> analysis = new Dictionary<string, ClassCodeInfo>(); private static readonly List<ClassPropertyComment> classPropertyCodeInfos = new List<ClassPropertyComment>(); private static readonly List<ClassComment> classCodeInfos = new List<ClassComment>(); private static readonly List<string> PropertyNameBlacklist = new List<string>() { "Id", "Description", "AllowError", "Command", "Arguments", "Output", "WorkingDirectory", "RequiresElevation" }; private static readonly List<string> ClassNameBlacklist = new List<string>() { "BaseModule", "ShellModule" }; /// <summary> /// Returns all the files that contain module source code. /// </summary> /// <returns></returns> private static IEnumerable<string> GetModuleFilenames() { return System.IO.Directory.GetFiles(modulesSourceCodeFolder, modulesFileFilter); } private static IEnumerable<Type> GetModulesTypes() { var reflection = new ReflectionHelper(); var types = reflection.GetClassesFromNamespaceMatching(sharpStrapAssemblyName, ModuleNameSpaceEndsWith, ModuleClassNameEndsWith); return types; } static void Main(string[] args) { if(args.Length != 2) { Console.WriteLine("This tool requires exactly two parameters:"); Console.WriteLine("1. filename of the markdown template"); Console.WriteLine("2. filename of the output"); return; } if(System.IO.File.Exists(args[0]) == false) { Console.WriteLine($"The file '{args[0]}' does not exist."); return; } templateFilename = args[0]; if(System.IO.File.Exists(args[1])) { Console.WriteLine("The destination file exists, overwrite? [y/N]"); var key = Console.ReadKey().KeyChar; if(key != 'y' && key != 'Y') return; } manualFilename = args[1]; var moduleFiles = GetModuleFilenames(); Console.WriteLine("Found the following code files to run through the code analysis:"); foreach(var file in moduleFiles) Console.WriteLine(file); Console.WriteLine("Preparing code analysis for all source code files."); foreach(var file in moduleFiles) { var analysis = SourceCodeInfo.FromSourceCodeFile(file); if(analysis.HasErrors) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Compilation of '{file}' resulted in the following errors:"); Console.WriteLine(string.Join(Environment.NewLine, analysis.ErrorMessages)); } foreach(var c in analysis.ClassPropertyComments) classPropertyCodeInfos.Add(c); foreach(var c in analysis.ClassComments) classCodeInfos.Add(c); } var types = GetModulesTypes(); Console.WriteLine("Found the following module classes in the assembly:"); foreach(var t in types) Console.WriteLine(t.Name); foreach(var type in types.Where(t => t.IsAbstract == false)) { GetCommentsForClassProperties(type); } var manual = FillMarkdownTemplate(System.IO.File.ReadAllLines(templateFilename)); System.IO.File.WriteAllText(manualFilename, manual); } static IEnumerable<string> GetCommentsForClassProperties(Type t) { var reflection = new ReflectionHelper(); Console.WriteLine($"Starting work on '{t.Name}'."); var baseClasses = reflection.GetBaseClasses(t, baseModuleClassName, true); var properties = baseClasses.SelectMany(c => reflection.GetPropertiesForClass(c)).Distinct().Except(PropertyNameBlacklist); int propertyDocumentationTagsFound = 0; foreach(var p in properties) { var info = classPropertyCodeInfos.Find(x => x.PropertyName == p); if(info == null) Console.WriteLine($"Could not find info for '{t.Name}.{p}' in the class code infos."); else if(string.IsNullOrWhiteSpace(info.RawComment)) Console.WriteLine("<no documentation>"); else propertyDocumentationTagsFound++; } Console.WriteLine($"Class description:{Environment.NewLine}{classCodeInfos.Find(c => c.ClassName == t.Name).CleanedMergedDocumentationTags} "); Console.WriteLine($"Found {propertyDocumentationTagsFound} documentation tag{(propertyDocumentationTagsFound == 1 ? "" : "s")}."); return properties; } static string FillMarkdownTemplate(string template) { var lines = template.Split(Environment.NewLine); return FillMarkdownTemplate(lines); } static string FillMarkdownTemplate(string[] template) { const string templateStart = "{{"; const string templateEnd = "}}"; var templateConfig = new List<string>(); int counter = 0; while(counter < template.Length && template[counter] != templateStart) counter++; int templateStartLine = counter; counter++; if(counter == template.Length) { Console.WriteLine($"Could not find template start '{templateStart}' in template file."); return string.Join(Environment.NewLine, template); } while(counter < template.Length && template[counter] != templateEnd) { templateConfig.Add(template[counter]); counter++; } int templateEndLine = counter; Console.WriteLine("=== Template Config Start ==="); foreach(var line in templateConfig) Console.WriteLine(line); Console.WriteLine("=== Template Config End ==="); var config = ParseTemplateConfig(templateConfig); var filledTemplate = FillTemplate(config); var manual = template .Take(templateStartLine) .Append(filledTemplate) .ToList(); manual.AddRange(template.Skip(templateEndLine + 1).TakeWhile(_ => true)); while(string.IsNullOrWhiteSpace(manual.Last())) manual.RemoveAt(manual.Count() - 1); var joinedManual = string.Join(Environment.NewLine, manual); Console.WriteLine(joinedManual); return joinedManual; } static TemplateConfig ParseTemplateConfig(IEnumerable<string> content) { var joined = string.Join(Environment.NewLine, content); var config = Newtonsoft.Json.JsonConvert.DeserializeObject<TemplateConfig>(joined); return config; } static string FillTemplate(TemplateConfig config) { var builder = new System.Text.StringBuilder(); foreach(var cci in classCodeInfos.Where(x => ClassNameBlacklist.Contains(x.ClassName) == false && x.IsAbstract == false)) { builder.AppendLine($"{config.ModulePrefix}{cci.ClassName}{config.ModuleSuffix}"); foreach(var pair in cci.CleanedDocumentationTags) builder.AppendLine($"{config.ModuleDescriptionPrefix}{pair.Value}{config.ModuleDescriptionSuffix}"); //var type = Type.GetType($"{cci.Namespace}, {cci.ClassName}"); var assembly = (typeof(SharpStrap.Modules.BaseModule)).Assembly; //var type = assembly.GetType("{cci.Namespace}, {cci.ClassName}"); var type = assembly.GetTypes().First(t => t.Name == cci.ClassName); if(type == null) Console.WriteLine($"Could not find type for: {cci.Namespace}, {cci.ClassName}"); else Console.WriteLine("Found type."); var properties = GetCommentsForClassProperties(type); var filteredProperties = properties.Select(y => classPropertyCodeInfos.Find(x => x.ClassName == cci.ClassName && x.PropertyName == y)); var propertyAdded = false; foreach(var cpci in filteredProperties) { builder.AppendLine($"{config.ModulePropertyPrefix}{cpci.PropertyName}{config.ModulePropertySuffix}"); if(cpci.CleanedDocumentationTags.ContainsKey("summary")) { //builder.AppendLine($"{config.ModulePropertyPrefix}{cpci.PropertyName}{config.ModulePropertySuffix}"); builder.AppendLine($"{config.ModulePropertyDescriptionPrefix}{cpci.CleanedDocumentationTags["summary"]}{config.ModulePropertyDescriptionSuffix}"); } else builder.AppendLine("No summary available for this property."); builder.AppendLine(); propertyAdded = true; } if(propertyAdded == false) builder.AppendLine(); } return builder.ToString(); } } }<file_sep>using System; using SharpStrap.Helpers; namespace Tests.Helpers { public class DummyTextFileInput : ITextFileInput { public string[] Content { get; private set; } public DummyTextFileInput(string [] content) { this.Content = content; } public string[] ReadAllLines(string filename) { return this.Content; } public string ReadAllText(string filename) { return String.Join(Environment.NewLine, this.Content); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FakeItEasy; using FluentAssertions; using SharpStrap.Helpers; using SharpStrap.Modules; using Tests.Helpers; using Tests.Modules; using Xunit; namespace Tests { public class BootstrapTests { /* private const string ErrorLogName = "error.log"; private const string SuccessLogName = "succes.log"; private Bootstrap CreateSuccessModuleBootstrap(int packageCount, int modulePerPackageCount) { var cascadedModules = new List<List<BaseModule>>(packageCount); for(int j = 0; j < packageCount; ++j) { var successModules = new List<BaseModule>(modulePerPackageCount); for(int i = 0; i < modulePerPackageCount; ++i) successModules.Add(new SuccessModule()); cascadedModules.Add(successModules); } return CreateBootstrapWithCascadedList(cascadedModules); } private Bootstrap CreateErrorModuleBootstrap(int packageCount, int modulePerPackageCount) { var cascadedModules = new List<List<BaseModule>>(packageCount); for(int j = 0; j < packageCount; ++j) { var errorModules = new List<BaseModule>(modulePerPackageCount); for(int i = 0; i < modulePerPackageCount; ++i) errorModules.Add(new ErrorModule()); cascadedModules.Add(errorModules); } return CreateBootstrapWithCascadedList(cascadedModules); } private Bootstrap CreateBootstrapWithCascadedList(IEnumerable<IEnumerable<BaseModule>> cascadedModules) { int packageCounter = 0; var packages = new List<Package>(); foreach(var list in cascadedModules) { var package = new Package { Name = $"Package #{packageCounter.ToString().PadLeft(3)}", Modules = list }; packageCounter++; } var bootstrap = new Bootstrap { Packages = packages, ErrorLogFilename = ErrorLogName, SuccessLogFilename = SuccessLogName }; return bootstrap; } [Fact] public async Task Run_WithSuccessConfiguration_ReturnsSuccess() { int packageCount = 2; int modulePerPackageCount = 2; var bootstrap = CreateSuccessModuleBootstrap(packageCount, modulePerPackageCount); var input = A.Fake<IIODefinition>(); A.CallTo(() => input.TextReader.Read()).Returns('y'); var textInput = A.Fake<ITextFileInput>(); var textOutput = A.Fake<ITextFileOutput>(); var result = await bootstrap.Run(input, textInput, textOutput, false); result.Should().BeTrue(); } [Fact] public async Task Run_WithErrorConfiguration_ReturnsError() { int packageCount = 2; int modulePerPackageCount = 2; var bootstrap = CreateErrorModuleBootstrap(packageCount, modulePerPackageCount); var input = A.Fake<IIODefinition>(); A.CallTo(() => input.TextReader.Read()).Returns('y'); var textInput = A.Fake<ITextFileInput>(); var textOutput = A.Fake<ITextFileOutput>(); var result = await bootstrap.Run(input, textInput, textOutput, false); result.Should().BeFalse(); } [Fact] public async Task Run_WithSucessConfiguration_WritesSuccessLog() { int packageCount = 2; int moduleCount = 3; var bootstrap = CreateSuccessModuleBootstrap(packageCount, moduleCount); bootstrap.ErrorLogFilename = "error.log"; var input = A.Fake<IIODefinition>(); A.CallTo(() => input.TextReader.Read()).Returns('y'); var textInput = new DummyTextFileInput(new string[] {}); var textOutput = new DummyTextFileOutput(); var result = await bootstrap.Run(input, textInput, textOutput, false); result.Should().Be(true); textOutput.Contents[ErrorLogName].Should().HaveLength(0); textOutput.Contents[SuccessLogName].Length.Should().BeGreaterThan(0); } [Fact] public async Task Run_WithErrorConfiguration_WritesErrorLog() { } [Fact] public async Task Run_WithMixedConfiguration_WritesSuccessAndErrorLog() { } [Fact] public async Task Run_WithSuccessConfigurationTwice_WritesSuccessLog() { // IMPORTANT: this needs to run a mixture of failing and succeeding packages on the first run and only successfull packages on the second } */ } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using SharpStrap.Helpers; namespace SharpStrap.Modules { /// <summary> /// Read a single variable from the command prompt (user input). /// </summary> public class ReadVariableModule : ShellModule { private const string ReadCommand = "read"; private const string PromptCommand = "echo"; private const string VariableShellPrefix = "$"; private const string CommandDelimter = ";"; protected override bool RedirectStandardOutput => true; protected override bool SkipVariableReplacement => true; /// <summary> /// Name of the new variable. /// </summary> public string VariableName { get; set; } public ReadVariableModule() { // } public ReadVariableModule(string variableName) : this() { this.VariableName = variableName; } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { if(string.IsNullOrWhiteSpace(this.VariableName)) throw new InvalidOperationException("Cannot run ReadVariableModule without a variable name."); SetCommandAndArguments(ReadCommand, $"{VariableName} {CommandDelimter} {PromptCommand} {VariableShellPrefix}{VariableName}"); } protected override IDictionary<string, string> ReturnVariables() { // Since read is ended by hitting return an additional empty line will be added at the end! return new Dictionary<string, string>() { { this.VariableName, this.Output.Reverse().Skip(1).First() } }; } } }<file_sep>using System; using System.IO; using System.Linq; using SharpStrap.Modules; using YamlDotNet.Core; using YamlDotNet.Serialization; namespace SharpStrap.Helpers { internal class BootstrapDeserializer { private readonly IModuleFinder moduleFinder; public BootstrapDeserializer(IModuleFinder moduleFinder) { this.moduleFinder = moduleFinder; } public bool Validate(string filename) { if(System.IO.File.Exists(filename) == false) { Console.WriteLine($"The given file does not exist."); return false; } var deserializer = CreateDefaultDeserializer(); try { using(var reader = File.OpenText(filename)) { var bootstrap = deserializer.Deserialize<Bootstrap>(reader); Console.WriteLine("File parsed succesfully."); } } catch(YamlException ex) { Console.WriteLine($"There is at least one error in the file:"); Console.WriteLine($"{ex.Message}"); if(ex.InnerException != null) Console.WriteLine(ex.InnerException.Message); Console.WriteLine("Config file:"); Console.WriteLine(" ... |"); const int marginLines = 3; var startLine = Math.Max(0, ex.Start.Line - marginLines); var numberOfRelevantLines = ex.End.Line - ex.Start.Line + 2 * marginLines + 1; var relevantConfigFileContent = File.ReadAllLines(filename).Skip(startLine).Take(numberOfRelevantLines).ToArray(); for(int i = 0; i < numberOfRelevantLines; ++i) { var paddedLineNumber = (i + startLine).ToString().PadLeft(4); var currentLine = i + startLine; if(currentLine >= ex.Start.Line && currentLine <= ex.End.Line) { Console.Out.Flush(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"{paddedLineNumber} >|{relevantConfigFileContent[i]}"); } else { Console.Out.Flush(); Console.ResetColor(); Console.WriteLine($"{paddedLineNumber} |{relevantConfigFileContent[i]}"); } } Console.WriteLine(" ... |"); return false; } return true; } internal Deserializer CreateDefaultDeserializer() { var mappings = this.moduleFinder.GetAllModulesForModulesNamespace(); var builder = new DeserializerBuilder(); foreach(var mapping in mappings) { System.Diagnostics.Debug.WriteLine($"Added custom tag for yaml mapping: {mapping.Name} - {mapping.Type.Name}"); builder = builder.WithTagMapping(mapping.Name, mapping.Type); } return builder.Build(); } } }<file_sep>using System; using System.IO; using System.Text; namespace SharpStrap.Helpers { public abstract class ColoredTextWriter : TextWriter { public abstract void SetForegroundColor(ConsoleColor color); public abstract void SetBackgroundColor(ConsoleColor color); public abstract void ResetColors(); } public class ConsoleWriter : ColoredTextWriter { public override void WriteLine(string value) { Console.WriteLine(value); } public override void WriteLine() { Console.WriteLine(); } public override Encoding Encoding => Console.OutputEncoding; public override void ResetColors() { Console.Out.Flush(); Console.ResetColor(); } public override void SetBackgroundColor(ConsoleColor color) { Console.Out.Flush(); Console.BackgroundColor = color; } public override void SetForegroundColor(ConsoleColor color) { Console.Out.Flush(); Console.ForegroundColor = color; } public override void Flush() { Console.Out.Flush(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace DocsGenerator { internal abstract class BaseComment { public string ClassName { get; set; } public string Namespace { get; set; } private string rawComment; public string RawComment { get { return rawComment; } set { rawComment = value; if(string.IsNullOrWhiteSpace(value)) { XmlComment = new XDocument(); DocumentationElements = new List<XElement>(0); } else { XmlComment = XDocument.Parse(value); DocumentationElements = XmlComment.Elements().First().Elements(); CleanedDocumentationTags = new Dictionary<string, string>(); foreach(var element in DocumentationElements) { string val = element.Value .TrimStart() .TrimStart(Environment.NewLine.ToCharArray()) .TrimEnd() .TrimEnd(Environment.NewLine.ToCharArray()); CleanedDocumentationTags.Add(element.Name.LocalName, val); } } } } public XDocument XmlComment { get; private set; } public IEnumerable<XElement> DocumentationElements { get; private set; } = new List<XElement>(); public IDictionary<string, string> CleanedDocumentationTags { get; private set; } = new Dictionary<string, string>(); public string CleanedMergedDocumentationTags => CleanedDocumentationTags == null ? null : string.Join(System.Environment.NewLine, CleanedDocumentationTags); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using SharpStrap.Helpers; namespace SharpStrap.Modules { public class Package { /// <summary> /// Name of this package. Needs to be unique. /// </summary> public string Name { get; set; } /// <summary> /// Description of this package (optional). /// </summary> public string Description { get; set; } /// <summary> /// Gets/sets if this package is mission ciritical. /// Bootstrapping will stop if this fails. /// </summary> public bool IsCritical { get; set; } /// <summary> /// Gets/sets wether this package will be run even it has been previously finished. /// </summary> public bool IgnoreAlreadySolved { get; set; } /// <summary> /// Actual working modules of this package. /// </summary> public IEnumerable<BaseModule> Modules { get; set; } = new List<BaseModule>(); /// <summary> /// Gets/sets wether this package depends on any other package. /// </summary> public IEnumerable<string> Requires { get; set; } = new List<string>(); /// <summary> /// Stores variables within the scope of this package. /// Variables can only be strings as they are read from the command line as strings. /// </summary> /// <typeparam name="string">Name of the variable.</typeparam> /// <typeparam name="string">Content of the variable.</typeparam> public IDictionary<string, string> Variables { get; set; } = new Dictionary<string, string>(); public async Task Run(ColoredTextWriter output, IDictionary<string, string> variables) { foreach(var variable in variables) this.Variables.Add(variable.Key, variable.Value); output.SetForegroundColor(ConsoleColor.Yellow); output.WriteLine($"Starting work on '{Name}'"); output.ResetColors(); foreach(var module in Modules) { var result = await module.Run(this.Variables, output); if(result.State != ModuleResultStates.Success) { output.SetForegroundColor(ConsoleColor.DarkYellow); output.WriteLine("Command run:"); output.WriteLine(result.CommandRun); output.WriteLine("Output:"); output.WriteLine(string.Join(Environment.NewLine, result.Output)); output.ResetColors(); if(module.AllowError) { output.SetForegroundColor(ConsoleColor.Yellow); output.WriteLine($"{module.GetType().Name} failed! Since it is marked with 'AllowError' the rest of the package will be run."); output.ResetColors(); } else { output.SetForegroundColor(ConsoleColor.Red); output.WriteLine($"{module.GetType().Name} failed for package {this.Name}! This package is marked to fail on any module error. Stopping run of this package."); output.ResetColors(); throw new ShellCommandException(result.Output); } } else { foreach(var pair in result.Variables) { if(this.Variables.ContainsKey(pair.Key)) { output.WriteLine($"Replacing value '{this.Variables[pair.Key]}' of '${pair.Key}' with '{pair.Value}'."); this.Variables[pair.Key] = pair.Value; } else { output.WriteLine($"Adding '{pair.Key}' to variable store."); this.Variables.Add(pair.Key, pair.Value); } } } } output.SetForegroundColor(ConsoleColor.Green); output.WriteLine($"Finished '{this.Name}' successfully."); output.ResetColors(); } public bool CanRun(IEnumerable<string> finishedPackages) { return this.Requires.Except(finishedPackages).Any() == false; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace DocsGenerator { public class ReflectionHelper { internal IList<Type> GetBaseClasses<T>(string oldestAncestor, bool addInitialClass, IList<Type> accumulator = null) { return GetBaseClasses(typeof(T), oldestAncestor, addInitialClass, accumulator); } internal IList<Type> GetBaseClasses(Type type, string oldestAncestor, bool addInitialClass, IList<Type> accumulator = null) { if(accumulator == null) accumulator = new List<Type>(); if(addInitialClass) accumulator.Add(type); if (type.BaseType.Name == oldestAncestor) { // no need to traverse deeper accumulator.Add(type.BaseType); return accumulator; } else if(type.BaseType != null) { var baseClass = type.BaseType; accumulator.Add(baseClass); return GetBaseClasses (baseClass, oldestAncestor, false, accumulator); } else { throw new ArgumentException($"There is no base class named '{oldestAncestor}'."); } } internal IEnumerable<string> GetPropertiesForClass<T>() { return GetPropertiesForClass(typeof(T)); } internal IEnumerable<string> GetPropertiesForClass(Type type) { var unfilteredProperties = type.GetProperties(BindingFlags.Public); var properties = unfilteredProperties.Where(p => p.GetSetMethod() != null && p.CanWrite == true); var propertyNames = properties.Select(p => p.Name); return propertyNames; } internal IEnumerable<Type> GetClassesFromNamespaceMatching(string filename, string nameSpace, string classNameEndsWith) { var types = Assembly.LoadFrom(filename).GetTypes(); var filtered = types.Where(t => t.IsClass == true && t.Name.EndsWith(classNameEndsWith) && t.Namespace != null && t.Namespace.EndsWith(nameSpace) ); return filtered; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using FakeItEasy; using FakeItEasy.Sdk; using FluentAssertions; using SharpStrap.Helpers; using SharpStrap.Modules; using Tests.Modules.Shims; using Xunit; namespace Tests.Helpers { public class PackageStorageTests { private const string DummyPackageNameTemplate = "Package #{0}"; private const int DummyPackageCount = 5; private IEnumerable<Package> CreateDefaultPackages() { var packages = new List<Package>(DummyPackageCount); for(var i = 0; i < DummyPackageCount; ++i) packages.Add(new Package() { Name = string.Format(DummyPackageNameTemplate, i), Description = "Dummy package for unit tests." }); return packages; } [Fact] public void InitFromLogFileAndPackages_WithNullPackageNames_AddsAllPackagesNotEvaluated() { var packages = CreateDefaultPackages(); var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(null, packages); storage.OrderedPackages[PackageEvaluationStates.NotEvaluated].Count.Should().Be(packages.Count()); } [Fact] public void InitFromLogFileAndPackages_WithEmptyPackageNames_AddsAllPackagesAsNotEvaluated() { var packages = CreateDefaultPackages(); var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(new LogEntry[0], packages); storage.OrderedPackages[PackageEvaluationStates.NotEvaluated].Count.Should().Be(packages.Count()); } [Fact] public void InitFromLogFileAndPackages_WithPackageNamesAndContents_AddsPackagesAsSolved() { var packages = CreateDefaultPackages(); var solvedPackages = packages.Count() / 2; var unsolvedPackages = packages.Count() - solvedPackages; var textOutput = A.Fake<ITextFileOutput>(); var successfulPackageNames = packages .Take(solvedPackages) .Select(x => new LogEntry { Name = x.Name, Status = PackageStorage.DefaultSuccessSate.ToString()}) .ToArray(); var storage = new TestablePackageStorage(successfulPackageNames, packages); storage.OrderedPackages[PackageEvaluationStates.PreviouslyRun].Count.Should().Be(solvedPackages); storage.OrderedPackages[PackageEvaluationStates.NotEvaluated].Count.Should().Be(unsolvedPackages); } [Fact] public void InitFromLogFileAndPackages_WithDifferentPackageNames_AddsAllPackagesAsNotEvaluated() { var packages = CreateDefaultPackages(); var textOutput = A.Fake<ITextFileOutput>(); var successfulPackageNames = packages .Select(p => new LogEntry { Name = p.Name + "ABC", Status = PackageStorage.DefaultSuccessSate.ToString() }) .ToArray(); var storage = new TestablePackageStorage(successfulPackageNames, packages); storage.OrderedPackages[PackageEvaluationStates.Solved].Count.Should().Be(0); storage.OrderedPackages[PackageEvaluationStates.NotEvaluated].Count.Should().Be(packages.Count()); } /* In its current state this test is broken as it requires the MarkPackageSolved-method. [Fact] public void GetNextPackage_WithCorrectSetup_CanBeCalledNumberOfPackagesTimes() { var packages = CreateDefaultPackages(); var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(textOutput, new string[0], packages); int counter = 0; Package p; while ((p = storage.GetNextPackage()) != null && counter < packages.Count() + 2) // prevent infinite loops { storage.MarkPackageSolved(p); counter++; } counter.Should().Be(packages.Count()); } */ [Fact] public void GetNextPackage_WithNoPackages_ReturnsNull() { var packages = new List<Package>(0); var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(new LogEntry[0], new Package[0]); var result = storage.GetNextPackage(); result.Should().BeNull(); } [Fact] public void GetNextPackage_WithUnmetRequirements_ThrowsArgumentException() { var packages = new List<Package> { new Package { Name = "DummyPackage #1", Requires = new string[] { "non-existing-package" }, } }; var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(new LogEntry[0], packages); var result = storage.GetNextPackage(); result.Should().BeNull(); storage.OrderedPackages[PackageEvaluationStates.UnmetDependency].Should().Contain(packages.First()); storage.OrderedPackages[PackageEvaluationStates.NotEvaluated].Should().NotContain(packages.First()); } [Fact] public void MarkPackageSolved_WithNullPackage_ThrowsArgumentException() { var packages = CreateDefaultPackages(); var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(new LogEntry[0], packages); Assert.Throws<ArgumentException>(() => storage.MarkPackageSolved(null)).Message.Should().Contain("Cannot mark 'null' as solved."); } [Fact] public void MarkPackageSolved_WithNonExistingPackage_ThrowsArgumentException() { var packages = CreateDefaultPackages(); var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(new LogEntry[0], packages); Assert.Throws<ArgumentException>(() => storage.MarkPackageSolved(new Package())).Message.Should().Contain("does not exist in the storage."); } [Fact] public void MarkPackageSolved_WithPackageInCorrectState_Runs() { var packages = CreateDefaultPackages().ToArray(); var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(new LogEntry[0], packages); var p = storage.GetNextPackage(); storage.MarkPackageSolved(packages.First()); storage.OrderedPackages[PackageEvaluationStates.Solved].Should().Contain(packages.First()); } [Fact] public void MarkPackageFailed_WithNullPackage_ThrowsArgumentException() { var packages = CreateDefaultPackages(); var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(new LogEntry[0], packages); Assert.Throws<ArgumentException>(() => storage.MarkPackageFailed(null)).Message.Should().Contain("Cannot mark 'null' as solved."); } [Fact] public void MarkPackageFailed_WithNonExistingPackage_ThrowsArgumentException() { var packages = CreateDefaultPackages(); var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(new LogEntry[0], packages); Assert.Throws<ArgumentException>(() => storage.MarkPackageFailed(new Package())).Message.Should().Contain("does not exist in the storage."); } [Fact] public void MarkPackageFailed_WithPackageInCorrectState_Runs() { var packages = CreateDefaultPackages().ToArray(); var textOutput = A.Fake<ITextFileOutput>(); var storage = new TestablePackageStorage(new LogEntry[0], packages); var p = storage.GetNextPackage(); storage.MarkPackageFailed(packages.First()); storage.OrderedPackages[PackageEvaluationStates.Failed].Should().Contain(packages.First()); } // TODO: Add test for LogResult. } }<file_sep>using System; using System.Collections.Generic; namespace SharpStrap.Modules { public enum ModuleResultStates { Success = 0, Error = 1 } public class ModuleResult { public ModuleResultStates State { get; private set; } public IEnumerable<string> Output { get; private set; } = new List<string>(); public IDictionary<string, string> Variables { get; private set; } = new Dictionary<string, string>(); public string CommandRun { get; private set; } public ModuleResult(ModuleResultStates state, IEnumerable<string> output, string commandRun) { this.Output = output; this.State = state; this.CommandRun = commandRun; } public ModuleResult(ModuleResultStates state, IEnumerable<string> output, string commandRun, IDictionary<string, string> variables) : this(state, output, commandRun) { this.Variables = variables; } } }<file_sep>#!/usr/bin/env bash sudo dbus-launch echo $(whoami) echo $(which sudo) echo "=== /app ===" ls /app echo "=== /mnt/yaml ===" ls /mnt/yaml dotnet /app/sharpstrap.dll /mnt/yaml/complete.yaml <file_sep>using System; using System.Collections.Generic; using System.Linq; using SharpStrap.Helpers; namespace SharpStrap.Modules { /// <summary> /// Evaluates a shell command and stores its content in a variable. /// </summary> public class ShellEvaluateModule : ShellModule { protected override bool RedirectStandardOutput => true; protected override bool SkipVariableReplacement => false; /// <summary> /// Name of the variable the contents will be stored in. /// </summary> public string VariableName { get; set; } /// <summary> /// Gets/sets wether only the last line of the output is used as return value. /// </summary> public bool LastLineOnly { get; set; } = true; /// <summary> /// Gets/sets wether empty lines at the end of the output will be trimmed. /// </summary> public bool TrimEmpty { get; set; } = true; protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { if(string.IsNullOrWhiteSpace(this.VariableName)) throw new InvalidOperationException("Cannot run ReadVariableModule without a variable name."); } protected override IDictionary<string, string> ReturnVariables() { var dict = new Dictionary<string, string>(1); if(this.Output == null || this.Output.Count == 0) throw new ShellCommandException(new List<string>(1), $"{nameof(ShellEvaluateModule)} has no output."); while(this.Output.Count > 0 && string.IsNullOrWhiteSpace(this.Output.Last()) && this.TrimEmpty) this.Output = this.Output.Reverse().Skip(1).Reverse().ToList(); if(LastLineOnly) { dict.Add(this.VariableName, this.Output.Reverse().Skip(TrimEmpty ? 0 : 1).First()); } else { var squashedOutput = string.Join(Environment.NewLine, this.Output); dict.Add(this.VariableName, squashedOutput); } return dict; } private bool IsOutputEmpty() { if(this.Output == null) return false; if(this.TrimEmpty) { return this.Output.Count(line => string.IsNullOrWhiteSpace(line) == false) != 0; } else { return this.Output.Count != 0; } } } }<file_sep>using System; namespace SharpStrap.Helpers { public static class ExtensionMethods { public static bool IsNullOrWhiteSpace(this string s) { return string.IsNullOrWhiteSpace(s); } public static bool IsNotNullOrWhiteSpace(this string s) { return string.IsNullOrWhiteSpace(s) == false; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Ninject; using SharpStrap.Helpers; using SharpStrap.Modules; using YamlDotNet.Core; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; namespace SharpStrap { class Program { static async Task Main(string[] args) { var kernel = InitKernel(); var bootstrapDeserializer = kernel.Get<BootstrapDeserializer>(); var moduleFinder = kernel.Get<IModuleFinder>(); var cliValidator = kernel.Get<CLIValidator>(); if(cliValidator.Validate(args) == false) return; var overrideUserDecision = args.First() == "-y"; var configFilename = args.Last(); if(bootstrapDeserializer.Validate(configFilename) == false) return; await Run(configFilename, overrideUserDecision, bootstrapDeserializer); } private static async Task Run(string configFilename, bool overrideUserDecision, BootstrapDeserializer bootstrapDeserializer) { using(var reader = File.OpenText(configFilename)) { var deserializer = bootstrapDeserializer.CreateDefaultDeserializer(); try{ var bootstrap = deserializer.Deserialize<Bootstrap>(reader); var ioDefinition = new ConsoleIODefinition(); await bootstrap.Run( new PackageInformationPrinter(ioDefinition), new FileBootstrapStatusLogger(), new ConsoleIODefinition(), new FrameworkTextFileInput(), new FrameworkTextFileOutput(), overrideUserDecision); } catch(IOException ex) { Console.WriteLine("Encountered an exception while trying to parse the yaml file:"); Console.WriteLine(ex.Message); } } } private static IKernel InitKernel() { var kernel = new StandardKernel(new Helpers.SharpStrapModule()); return kernel; } } } <file_sep>using System; using System.Collections.Generic; using SharpStrap.Helpers; namespace SharpStrap.Modules { /// <summary> /// Base module to interact with the gnome config manager. /// </summary> public abstract class GSettingsModule : ShellModule { protected const string GSettingsCommand = "gsettings"; /// <summary> /// Schema of the setting. /// </summary> public string Schema { get; set; } /// <summary> /// Key of the setting. /// </summary> public string Key { get; set; } public abstract string Action { get; } } /// <summary> /// Writes a dconf setting. /// </summary> public class GSettingsSetModule : GSettingsModule { /// <summary> /// Value to set. Will be written to the settings using double quotes. /// </summary> public string Value { get; set; } public override string Action => "set"; public GSettingsSetModule() { // } public GSettingsSetModule(string key, string value) : this() { // } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { SetCommandAndArguments(GSettingsCommand, $"{Action} {Key} \"{Value}\""); } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using System.IO; using System.Reflection.Metadata; using SharpStrap.Helpers; using System.Runtime.InteropServices; using YamlDotNet.Serialization; namespace SharpStrap.Modules { /// <summary> /// Holds all information for a complete bootstrap process. /// </summary> [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] // public needed bc of yaml deserialization public class Bootstrap { /// <summary> /// Input device, usually the console. /// </summary> private IIODefinition ioDefinition; /// <summary> /// List of packages that will be run. Needed for deserialization but emptied afterwards. /// </summary> [YamlMember(Alias = "Packages", ApplyNamingConventions = false)] public List<Package> RawPackages { get; set; } = new List<Package>(); /// <summary> /// Filename for the logfile containing the successful packages. No file will be written if it's empty. /// </summary> public string LogFilename { get; set; } = "bootstrap.log"; /// <summary> /// Global variables are injected into every package that is executed. /// </summary> public IDictionary<string, string> GlobalVariables { get; set; } = new Dictionary<string, string>(); /// <summary> /// List of packages that will be run at the end of the bootstrap process. Regular packages may not depend on these. /// </summary> [YamlMember(Alias = "CleanupPackages", ApplyNamingConventions = false)] public List<Package> RawCleanupPackages { get; set; } = new List<Package>(); /// <summary> /// Used to read text files from the local filesystem. /// </summary> private ITextFileInput textFileInput; /// <summary> /// Used to write text files to the local filesystem. /// </summary> private ITextFileOutput textFileOutput; /// <summary> /// Contains all packages and their current states (run successfully, failed, ...). /// </summary> private PackageStorage packages; /// <summary> /// Contains all packages and their current states for the cleanup operation. /// </summary> private PackageStorage cleanupPackages; /// <summary> /// Reads and writes the status of the bootstrap operation into a specific storage. /// </summary> private IBootstrapStatusLogger statusLogger; /// <summary> /// Used to write various information to the ui. /// </summary> private IPackageInformationPrinter packageInformationPrinter; /// <summary> /// Initializes and runs the bootstrap process. /// </summary> /// <param name="input">Device that provides user input.</param> /// <param name="output">Device with display capabilities.</param> /// <param name="columnCount">Number of columns the output devices can render.</param> /// <param name="overrideUserDecision">Override the user interaction asking for confirmation.</param> /// <returns></returns> public async Task<bool> Run(IPackageInformationPrinter packageInformationPrinter, IBootstrapStatusLogger statusLogger, IIODefinition ioDefinition, ITextFileInput textFileInput, ITextFileOutput textFileOutput, bool overrideUserDecision = false) { this.textFileInput = textFileInput; this.textFileOutput = textFileOutput; this.ioDefinition = ioDefinition; this.statusLogger = statusLogger; this.packageInformationPrinter = packageInformationPrinter; InitPackageStorages(); AddDefaultVariables(); var dryRunSuccess = DryRunPackages(); if (dryRunSuccess == false) return false; if(InitPackageOperation(overrideUserDecision)) { this.packageInformationPrinter.PrintPackageSummary(this.packages.PreviouslyRun, this.packages.Unsolved); await RunAllPackages(this.packages); WriteLog(); await RunAllPackages(this.cleanupPackages); } else { return false; } // Print the user feedback. this.packageInformationPrinter.PrintResults(this.packages.PreviouslyRun, this.packages.Solved, this.packages.Unsolved); return true; } private void InitPackageStorages() { var logEntries = statusLogger.LoadOldLog(this.LogFilename); this.packages = new PackageStorage(logEntries, this.RawPackages); this.RawPackages.Clear(); this.packages.ValidatePackages(); this.cleanupPackages = new PackageStorage(null, RawCleanupPackages); } private void AddDefaultVariables() { this.GlobalVariables.Add("username", Environment.UserName); var envHome = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "HOMEPATH" : "HOME"; var home = Environment.GetEnvironmentVariable(envHome); this.GlobalVariables.Add("homedir", home); this.GlobalVariables.Add("~", home); } private bool DryRunPackages() { var (dryRunSuccess, dryRunError) = this.packages.DryRunDependencies(); if (dryRunSuccess == false) { this.ioDefinition.TextWriter.WriteLine("Execution stopped because the dry run was not successful."); this.ioDefinition.TextWriter.WriteLine(dryRunError); return false; } else { return true; } } /// <summary> /// Displays a summary of the deserialized packages. Includes all packages, even the previously completed ones. /// </summary> /// <param name="overrideUserDecision"></param> /// <returns></returns> private bool InitPackageOperation(bool overrideUserDecision) { this.packageInformationPrinter.PrintDetailedPackageSummary(packages.All); if(overrideUserDecision) { return true; } else { this.ioDefinition.TextWriter.WriteLine(); this.ioDefinition.TextWriter.WriteLine("Do you want to continue? (y/N)"); char readChar = (char)0; while(char.IsLetter(readChar) == false && char.IsNumber(readChar) == false) readChar = (char)this.ioDefinition.TextReader.Read(); this.ioDefinition.TextWriter.WriteLine(); return readChar == 'y' || readChar == 'Y'; } } private async Task RunAllPackages(PackageStorage packageStorage) { Package package = null; while ((package = packageStorage.GetNextPackage()) != null) { try { await package.Run(this.ioDefinition.TextWriter, this.GlobalVariables); packageStorage.MarkPackageSolved(package); } catch (ShellCommandException ex) { this.ioDefinition.TextWriter.WriteLine($"Encountered an {ex.GetType().Name} with: {ex.Message}"); packageStorage.MarkPackageFailed(package); if(package.IsCritical) { this.ioDefinition.TextWriter.WriteLine("Bootstrapping won't continue as this is a critical package."); return; } } } } /// <summary> /// Checks if the requirements for the given package have been installed. /// </summary> /// <param name="p"></param> /// <returns></returns> private bool ValidateRequirementsMet(Package p, IEnumerable<Package> solvedPackages) { return p.Requires.Except(solvedPackages.Where(d => d.Name != null).Select(d => d.Name)).Any() == false; } private void WriteLog() { try { this.statusLogger.SaveNewLog(this.LogFilename, this.packages.GetLogResult()); } catch (UnauthorizedAccessException) { this.ioDefinition.TextWriter.SetBackgroundColor(ConsoleColor.Red); this.ioDefinition.TextWriter.WriteLine("Could not write a log file because write access was denied."); this.ioDefinition.TextWriter.ResetColors(); } } } }<file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace DocsGenerator { /// <summary> /// Uses Roslyn to create in-memory compilations of code files. /// </summary> internal class SourceCodeInfo { // A tutorial for the code analysis toolkit can be found here: // https://docs.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/get-started/semantic-analysis private IEnumerable<ClassDeclarationSyntax> classSyntaxes; private Compilation compilation; private SyntaxTree tree; private CompilationUnitSyntax root; /// <summary> /// List of error messages that are a result of the compilation process. /// </summary> public IReadOnlyCollection<string> ErrorMessages { private set; get; } /// <summary> /// Returns wether there are compilation errors. /// </summary> public bool HasErrors => ErrorMessages == null ? false : ErrorMessages.Count > 0; public IEnumerable<ClassComment> ClassComments { private set; get; } public IEnumerable<ClassPropertyComment> ClassPropertyComments { private set; get; } private SourceCodeInfo() { } /// <summary> /// Creates a class instance from a source code file. /// Will build a <see cref="Compilation"/>, a <see cref="SyntaxTree"> and a <see cref="CompilationUnitSyntax"/>. /// </summary> /// <param name="filename">Source code file.</param> /// <returns>Instance of ClassCodeInfo.</returns> internal static SourceCodeInfo FromSourceCodeFile(string filename) { if(System.IO.File.Exists(filename) == false) throw new System.IO.FileNotFoundException($"The file '{filename}' could not be found."); //var fileContent = AppendDummyMainToCodeFromFile(filename); var fileContent = System.IO.File.ReadAllText(filename); var tree = CSharpSyntaxTree.ParseText(fileContent, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_1)); var compilationRoot = tree.GetCompilationUnitRoot(); var classes = compilationRoot .Members .OfType<NamespaceDeclarationSyntax>() .SelectMany( x => x.Members.OfType<ClassDeclarationSyntax>() ); var dd = typeof(Enumerable).GetTypeInfo().Assembly.Location; var coreDir = System.IO.Directory.GetParent(dd); var code = new SourceCodeInfo(); code.classSyntaxes = classes; code.compilation = CSharpCompilation .Create("DocsGeneratorDynamic") .WithOptions(CreateDefaultCompilerOptions()) .AddSyntaxTrees(tree) .AddReferences( MetadataReference.CreateFromFile(typeof(string).Assembly.Location), MetadataReference.CreateFromFile("../src/bin/Debug/netcoreapp2.0/sharpstrap.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "mscorlib.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.Core.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.Linq.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.Diagnostics.Process.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.IO.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.ComponentModel.Primitives.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.ComponentModel.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.Collections.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.Console.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.Runtime.Extensions.dll"), MetadataReference.CreateFromFile(coreDir.FullName + System.IO.Path.DirectorySeparatorChar + "System.Runtime.dll") ); var compilationResult = code.compilation.GetDiagnostics(); var compilationErrors = compilationResult.Where(x => x.Severity == DiagnosticSeverity.Error).Select(x => x.GetMessage()); code.ErrorMessages = new ReadOnlyCollection<string>(compilationErrors.ToList()); code.root = compilationRoot; code.tree = tree; code.LoadClassAndPropertyComments(); return code; } private static CSharpCompilationOptions CreateDefaultCompilerOptions() { var options = (new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); return options; } private static string AppendDummyMainToCodeFromFile(string filename) { // TODO: check if necessary as compilation is set to produce a dll var dummyMain = @"class DummyClass1234567890 { public static int Main() { return 0; } }"; var content = System.IO.File.ReadAllLines(filename); int currentLine = content.Length - 1; while(currentLine >= 0 && content[currentLine].EndsWith('}') == false) currentLine--; content[currentLine] = content[currentLine].TrimEnd('}'); var newContent = content.Take(currentLine).ToList(); newContent.Add(dummyMain); newContent.Add("}"); return string.Join(Environment.NewLine, newContent); } private void LoadClassAndPropertyComments() { var model = this.compilation.GetSemanticModel(this.tree); var propertyComments = new List<ClassPropertyComment>(); var classComments = new List<ClassComment>(); var classes = this.root.DescendantNodes().OfType<ClassDeclarationSyntax>(); foreach(var c in classes) { var symbol = model.GetDeclaredSymbol(c); Console.WriteLine(symbol.Name); classComments.Add(new ClassComment() { ClassName = symbol.Name, RawComment = symbol.GetDocumentationCommentXml(), IsAbstract = symbol.IsAbstract, Namespace = symbol.ContainingNamespace.Name }); var properties = c.DescendantNodes().OfType<PropertyDeclarationSyntax>(); foreach(var p in properties) { var propertySymbol = model.GetDeclaredSymbol(p); var comment = propertySymbol.GetDocumentationCommentXml(); propertyComments.Add(new ClassPropertyComment{ ClassName = symbol.Name, PropertyName = propertySymbol.Name, RawComment = comment }); } } this.ClassComments = classComments; this.ClassPropertyComments = propertyComments; } } } <file_sep>using System; namespace SharpStrap.Modules { /// <summary> /// Fallback module for commands that are not yet implemented or too rare to warrant an implementation. /// Set the command and arguments using the "Command" and "Argument" properties. /// </summary> public class GenericShellModule : ShellModule { public GenericShellModule() { // } public GenericShellModule(string command, string argument) : base(command, argument) { // } protected override void PreExecution(System.Collections.Generic.IDictionary<string, string> variables, Helpers.ColoredTextWriter output) { if(string.IsNullOrWhiteSpace(this.Command)) throw new InvalidOperationException("Cannot run a shell command with a command."); } } }<file_sep>int main(int argc, char** args) { // tag::test[] int i = 0; // end::test[] } <file_sep>using System; using System.Collections.Generic; using SharpStrap.Helpers; namespace SharpStrap.Modules { /// <summary> /// Base module for control system services. /// </summary> public abstract class ServiceModule : ShellModule { protected const string ServiceCommand = "systemctl"; protected abstract string ServiceSubCommand { get; } /// <summary> /// Names of the services to act on. /// </summary> public IEnumerable<string> ServiceNames { get; set; } = new List<string>(); public ServiceModule() : base() { // } public ServiceModule(params string[] serviceNames) : this() { this.ServiceNames = serviceNames; } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { this.SetCommandAndArguments(ServiceCommand, this.ServiceSubCommand + " " + String.Join(" ", this.ServiceNames)); } } /// <summary> /// Starts a service. /// </summary> public class ServiceStartModule : ServiceModule { protected override string ServiceSubCommand => "start"; } /// <summary> /// Stops a service. /// </summary> public class ServiceStopModule : ServiceModule { protected override string ServiceSubCommand => "stop"; } } <file_sep>using System; namespace SharpStrap.Modules { /// <summary> /// Base module for git operations. /// </summary> public abstract class GitModule : ShellModule { private const string GitCommand = "git"; protected override void PreExecution(System.Collections.Generic.IDictionary<string, string> variables, Helpers.ColoredTextWriter output) { SetCommandAndArguments(GitCommand, CreateArgument()); } protected abstract string CreateArgument(); } /// <summary> /// Clones a git repository. /// </summary> public class GitCloneModule : GitModule { private const string SubCommand = "clone"; /// <summary> /// Repository url. /// </summary> public string Url { get; set; } /// <summary> /// Folder to clone into. Will be cloned to working directory using the repository name in case it's empty. /// </summary> public string Target { get; set; } public GitCloneModule() { // } public GitCloneModule(string url) { this.Url = url; } protected override string CreateArgument() { return SubCommand + " " + this.Url + " " + this.Target; } } }<file_sep>using System; namespace SharpStrap.Modules { /// <summary> /// Creates a filesystem link. /// </summary> public class LinkModule : ShellModule { private const string LinkCommand = "ln"; private const string UseSymbolicLinkArgument = "-s"; /// <summary> /// Create a symbolic link. /// </summary> public bool UseSymbolicLink { get; set; } = true; /// <summary> /// File to create a link to. /// </summary> public string Source { get; set; } /// <summary> /// Name of the link. /// </summary> public string Target { get; set; } public LinkModule() { // } public LinkModule(string source, string target, bool useSymbolicLink = true) { this.UseSymbolicLink = useSymbolicLink; this.Source = source; this.Target = target; } protected override void PreExecution(System.Collections.Generic.IDictionary<string, string> variables, Helpers.ColoredTextWriter output) { if(string.IsNullOrWhiteSpace(Source)) throw new InvalidOperationException("Cannot use LinkModule without a Source."); // Target may be null as the source name will be used instead. SetCommandAndArguments(LinkCommand, CreateArgument()); } private string CreateArgument() { if(this.UseSymbolicLink) return $"{UseSymbolicLinkArgument} {Source} {Target}"; else return $"{Source} {Target}"; } } }<file_sep>Overview ======== This project is meant to help you bootstrap your Fedora (for now, other distro could be implemented easily) installation. Instead of writing a bash script with tons of commands you simply write a yaml file. [![build status](https://dev.azure.com/b0wter/SharpStrap/_apis/build/status/Generate%20Releases)](https://dev.azure.com/b0wter/SharpStrap) Packages -------- A package is a collection of modules that for a meaningful action together. For instance: installing VS code is done like this: - Name: vs_code Description: Imports the microsoft repo key and installs vs code. Requires: - base_package_install_and_update Modules: - !!KeyImport RequiresElevation: true Url: https://packages.microsoft.com/keys/microsoft.asc - !!FileCopy RequiresElevation: true Filenames: - $bootstrapdir/vscode.repo Target: /etc/yum.repos.d/ - !!PackageUpdate RequiresElevation: true - !!PackageInstall RequiresElevation: true PackageNames: - code - !!GenericShell Description: Installs vs code addons from the specified file. Command: $bootstrapdir/install_code_addons Arguments: $bootstrapdir/code_addons.txt Module ------ A module is a single action, like updating the installed packages or install new packages. A list of predefined modules will be added in the near future but there is a fallback generic shell module that allows for the execution of any shell command. Tutorial ======== Variables --------- You can define variables in different ways: * use the ```ReadVariable```-Module to read a variable from the command line (user input) * use the ```ShellEvaluate```-Module to store the results of a command in a variable * define a global variable by adding an entry to the ```GlobalVariables``` property of the root config object * define a package-wide variable by adding an entry to the ```Variables``` property of a package. To use a variable you simple prefix it the a ```$```. For example: - !!ReadVariable VariableName: hostname reads user input to the ```hostname``` variable. Use it like this: - !!GenericShell Command: ssh-keygen Arguments: -t ed25519 -f id_ed25519_$hostname WorkingDirectory: $homedir/.ssh/ A couple of variables are predefined: * homedir - stores the home directory of the current user * username - stores the name of the current user Packages -------- Packages are collection of modules to perform a single task like installing importing a new repository and installing software from it. Packages have the following properties: * ```Name``` - a name should be set for every package; this allows it to be referenced by other packages and will be used for user output * ```Description``` - an optional description of what this package does * ```IsCritical``` - marks this package as critical meaning that the bootstrap process will stop if this package fails * ```IgnoreAlreadySolved``` - a previously run pacakge will not be run again (by default); setting this to true will make sure this package runs always * ```Modules``` (Array) - contains a list of modules that need to be run for this package * ```Requires``` (Array) - contains a list of package names that need to run before this package can run * ```Variables``` (Ass. Array) - contains a list of variables for this package Modules ------- As of now all modules are run as shell commands. This is done to allow each command to have its priviledge level set. Individual commands can be elevated using the ```RequiresElevation``` property. ### Properties for all modules ### Every module has at least the following properties: * ```Id``` - name for this module, this will * ```AllowError``` - if this is set to true the package will continue to run even if this module fails * ```SkipVariableReplacement``` - if this is set to true variables will not be used for modules ShellModules (which almost all modules are based on) have more properties: * ```RequiresElevation``` - runs this module using ```sudo``` * ```WorkingDirectory``` - sets the working directory for this module <file_sep>namespace DocsGenerator { internal class ClassComment : BaseComment { public bool IsAbstract { get; set; } } }<file_sep>using System; using System.Collections.Generic; using SharpStrap.Helpers; namespace SharpStrap.Modules { public abstract class PackageBaseModule : ShellModule { protected const string PackageManagerCommand = "dnf"; } public abstract class PackageWithPackageNameBaseModule : PackageBaseModule { /// <summary> /// List of package names to work with. /// </summary> public IList<string> PackageNames { get; set; } = new List<string>(); /// <summary> /// File to load the PackageNames from. /// </summary> public string SourceFile { get; set; } protected void AddPackagesFromFile(IDictionary<string, string> variables) { if(SourceFile.IsNullOrWhiteSpace()) return; var filename = ReplaceVariablesInString(this.SourceFile, variables); if(PackageNames != null) PackageNames = new List<string>(); if(System.IO.File.Exists(filename) == false) throw new ArgumentException($"The source file '{filename}' for a '{this.GetType().Name}' does not exist."); var names = System.IO.File.ReadAllLines(filename); foreach(var name in names) PackageNames.Add(name); } } /// <summary> /// Updates currently installed packages. /// </summary> public class PackageUpdateModule : PackageBaseModule { private const string PackageManagerArgument = "update -y"; public PackageUpdateModule() { this.RequiresElevation = true; } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { SetCommandAndArguments(PackageManagerCommand, PackageManagerArgument); } } /// <summary> /// Installs a set of packages. /// </summary> public class PackageInstallModule : PackageWithPackageNameBaseModule { private const string PackageManagerArgument = "install -y"; public PackageInstallModule() : base() { // } public PackageInstallModule(params string[] packageNames) : this() { this.RequiresElevation = true; } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { AddPackagesFromFile(variables); this.SetCommandAndArguments(PackageManagerCommand, CreateArgument()); } private string CreateArgument() { return $"{PackageManagerArgument} {(string.Join(" ", this.PackageNames))}"; } } /// <summary> /// Removes a set of packages. /// </summary> public class PackageRemovalModule : PackageWithPackageNameBaseModule { private const string PackageManagerArgument = "remove -y"; public PackageRemovalModule() : base() { // } public PackageRemovalModule(params string[] packageNames) : this() { this.RequiresElevation = true; this.Arguments += " " + string.Join(" ", packageNames); } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { AddPackagesFromFile(variables); this.SetCommandAndArguments(PackageManagerCommand, CreateArgument()); } private string CreateArgument() { return $"{PackageManagerArgument} {(string.Join(" ", this.PackageNames))}"; } } /// <summary> /// Imports a repository using the package manager (dnf). /// </summary> public class PackageImportModule : PackageBaseModule { private const string PackageManagerArgument = "config-manager --add-repo"; /// <summary> /// Url to import as a repository. /// </summary> public string Url { get; set; } public PackageImportModule() : base() { // } public PackageImportModule(string url) : this() { this.RequiresElevation = true; } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { SetCommandAndArguments(PackageManagerCommand, CreateArgument()); } private string CreateArgument() { return $"{PackageManagerArgument} {this.Arguments} {this.Url}"; } } /// <summary> /// Import keys into the local storage. /// </summary> public class KeyImportModule : ShellModule { private const string PackageManagerCommand = "rpm"; private const string PackageManagerArgument = "--import"; /// <summary> /// Url of the key to import. /// </summary> public string Url { get; set; } public KeyImportModule() { // } public KeyImportModule(string url) : this() { this.Url = url; } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { if(string.IsNullOrWhiteSpace(this.Url)) throw new InvalidOperationException("Cannot import an empty url."); SetCommandAndArguments(PackageManagerCommand, PackageManagerArgument + " " + this.Url); } } /// <summary> /// Import a repository using rpm. /// </summary> public class RepositoryImportModule : ShellModule { private const string PackageManagerCommand = "rpm"; private const string PackageManagerArgument = "-Uvh"; /// <summary> /// Url of the repository to import. /// </summary> public string Url { get; set; } public RepositoryImportModule() { // } public RepositoryImportModule(string url) : this() { this.Url = url; } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { if(string.IsNullOrWhiteSpace(this.Url)) throw new InvalidOperationException("Cannot import an empty url."); SetCommandAndArguments(PackageManagerCommand, PackageManagerArgument + " " + this.Url); } } } <file_sep>using System; using System.IO; namespace SharpStrap.Helpers { /// <summary> /// Defines a set of parameters required to write colored output on a device with a max column count. /// </summary> public interface IIODefinition { ColoredTextWriter TextWriter { get; } int ColumnWidth { get; } TextReader TextReader { get; } } /// <summary> /// Uses the framework's console functions to write colored text to the user's terminal. /// </summary> public class ConsoleIODefinition : IIODefinition { public ColoredTextWriter TextWriter { get; private set; } public int ColumnWidth => Console.BufferWidth; public TextReader TextReader => Console.In; public ConsoleIODefinition() { this.TextWriter = new ConsoleWriter(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using SharpStrap.Modules; namespace SharpStrap.Helpers { public interface IPackageInformationPrinter { /// <summary> /// Prints a short summary of packages that have been run previously and will be run now. /// </summary> /// <param name="previouslyRunPackages"></param> /// <param name="packagesToRun"></param> void PrintPackageSummary(IEnumerable<Package> previouslyRunPackages, IEnumerable<Package> packagesToRun); /// <summary> /// Prints the name, description and module count for each package. /// </summary> /// <param name="packages"></param> void PrintDetailedPackageSummary(IEnumerable<Package> packages); /// <summary> /// Prints a result list (name & state). /// </summary> /// <param name="previouslyRun"></param> /// <param name="solved"></param> /// <param name="unsolved"></param> void PrintResults(IEnumerable<Package> previouslyRun, IEnumerable<Package> solved, IEnumerable<Package> unsolved); } public class PackageInformationPrinter : IPackageInformationPrinter { /// <summary> /// Number of columns reserved for the names of the packages. /// </summary> private const int PackageNameWidth = 40; /// <summary> /// Number of columns reserved for the number of operations per package. /// </summary> private const int PackageModuleCountWidth = 3; /// <summary> /// Number of columns reserved for the IsCritical flag output. /// </summary> private const int PackageIsCriticalWidth = 8; private IIODefinition ioDefinition; public PackageInformationPrinter(IIODefinition ioDefinition) { this.ioDefinition = ioDefinition; } /// <summary> /// Prints a human readable summary of all packages and their details. /// </summary> /// <param name="packages"></param> public void PrintDetailedPackageSummary(IEnumerable<Package> packages) { int noOfPackages = packages.Count(); int noOfModules = packages.Sum(p => p.Modules.Count()); this.ioDefinition.TextWriter.WriteLine($"This bootstrap configuration contains {noOfPackages} Packages with a total of {noOfModules} operations."); this.ioDefinition.TextWriter.WriteLine(); this.ioDefinition.TextWriter.WriteLine($"{"NAME".PadRight(PackageNameWidth)} {"OPS".PadRight(PackageModuleCountWidth)} {"CRITICAL".PadRight(PackageIsCriticalWidth)} DESCRIPTION"); this.ioDefinition.TextWriter.WriteLine(new String('=', this.ioDefinition.ColumnWidth)); int remainingWidth = this.ioDefinition.ColumnWidth - PackageNameWidth - PackageModuleCountWidth - PackageIsCriticalWidth - 3; foreach(var package in packages) { string paddedName; if(package.Name.Length > PackageNameWidth) paddedName = package.Name.Substring(0, PackageNameWidth -3 ) + "..."; else paddedName = package.Name.PadRight(PackageNameWidth); var paddedModuleCount = package.Modules.Count().ToString().PadLeft(PackageModuleCountWidth); var paddedIsCritical = package.IsCritical.ToString().PadRight(PackageIsCriticalWidth); string paddedDescription; if(package.Description != null && package.Description.Length > remainingWidth && remainingWidth - 3 > 0) paddedDescription = package.Description.Substring(0, remainingWidth - 3) + "..."; else paddedDescription = package.Description; this.ioDefinition.TextWriter.WriteLine($"{paddedName} {paddedModuleCount} {paddedIsCritical} {paddedDescription}"); } } /// <summary> /// Prints a short summary of packages that have been run previously and will be run now. /// </summary> /// <param name="previouslyRunPackages"></param> /// <param name="packagesToRun"></param> public void PrintPackageSummary(IEnumerable<Package> previouslyRunPackages, IEnumerable<Package> packagesToRun) { this.ioDefinition.TextWriter.WriteLine($"The following packages have been finished previously and will not be run:"); foreach(var package in previouslyRunPackages) this.ioDefinition.TextWriter.WriteLine(package.Name); this.ioDefinition.TextWriter.WriteLine($"The following packages will be run:"); foreach(var package in packagesToRun) this.ioDefinition.TextWriter.WriteLine(package.Name); } /// <summary> /// Prints a short summary of each package and its result (success, failure, previously run). /// </summary> /// <param name="previouslyRun"></param> /// <param name="solved"></param> /// <param name="unsolved"></param> public void PrintResults(IEnumerable<Package> previouslyRun, IEnumerable<Package> solved, IEnumerable<Package> unsolved) { this.ioDefinition.TextWriter.WriteLine(); PrintResultSummary(previouslyRun, solved, unsolved); PrintResultHeader(); PrintResultsFor(previouslyRun.Select(l => l.Name), "PREV"); PrintResultsFor(solved.Select(l => l.Name) , "SUCCESS", ConsoleColor.Green); PrintResultsFor(unsolved.Select(l => l.Name) , "FAILED", ConsoleColor.Red); this.ioDefinition.TextWriter.ResetColors(); } private void PrintResultSummary(IEnumerable<Package> previouslyRun, IEnumerable<Package> solved, IEnumerable<Package> unsolved) { this.ioDefinition.TextWriter.WriteLine($"{unsolved.Count()} packages have not been run due to errors or unmet requirements."); this.ioDefinition.TextWriter.WriteLine($"{solved.Count()} packages have been run successfully."); this.ioDefinition.TextWriter.WriteLine($"{previouslyRun.Count()} packages have been run previously and will not be run again."); } private void PrintResultHeader() { this.ioDefinition.TextWriter.WriteLine(); this.ioDefinition.TextWriter.WriteLine($"{"NAME".PadRight(PackageNameWidth)} {"RESULT".PadRight(PackageModuleCountWidth)}"); this.ioDefinition.TextWriter.WriteLine(new String('=', this.ioDefinition.ColumnWidth)); } private void PrintResultsFor(IEnumerable<string> packageNames, string status, ConsoleColor resultColor = ConsoleColor.White) { const int columnWidth = 7; string paddedStatus = status.PadRight(columnWidth).ToUpper(); if(paddedStatus.Length > columnWidth) paddedStatus = paddedStatus.Substring(0, columnWidth - 3) + "..."; foreach(var name in packageNames) { var packageName = string.IsNullOrWhiteSpace(name) ? "no name?" : name; var paddedPackageName = packageName.PadRight(PackageNameWidth); this.ioDefinition.TextWriter.WriteLine($"{paddedPackageName} {paddedStatus}"); } } } }<file_sep>using System; using System.IO; using System.Linq; namespace SharpStrap.Helpers { internal class CLIValidator { private IModuleFinder moduleFinder; private BootstrapDeserializer boostrapDeserializer; public CLIValidator(IModuleFinder moduleFinder, BootstrapDeserializer bootstrapDeserializer) { this.moduleFinder = moduleFinder; this.boostrapDeserializer = bootstrapDeserializer; } internal bool Validate(string[] args) { if(args.Length == 1 && args[0] == "modules") { PrintAllKnownModules(); return false; } if(args.Length == 2 && args[0] == "validate") { boostrapDeserializer.Validate(args[1]); return false; } if((args.Length != 1 && args.Length != 2) || File.Exists(args.Last()) == false) { Console.WriteLine("This tool requires at least parameter (config file). You may add the '-y' option before the filename to autorun the bootstrap."); return false; } return true; } private void PrintAllKnownModules() { Console.WriteLine("List of all available modules:"); foreach(var module in moduleFinder.GetAllModulesForModulesNamespace()) Console.WriteLine($"{module.Type.Name}"); } } }<file_sep>using System; using Ninject.Modules; namespace SharpStrap.Helpers { public class SharpStrapModule : NinjectModule { public override void Load() { Bind<IIODefinition>().To<ConsoleIODefinition>().InSingletonScope(); Bind<ITextFileInput>().To<FrameworkTextFileInput>().InSingletonScope(); Bind<ITextFileOutput>().To<FrameworkTextFileOutput>().InSingletonScope(); Bind<IModuleFinder>().ToMethod(x => ModuleFinder.CreateDefault()).InSingletonScope(); } } }<file_sep># Bootstrap file ## Overview of Packages and Modules Bootstrap files are written as yaml files. For details have a look at the [Wikipedia article][1]. To validate a config file you can run the ```validate``` subcommand followed by a filename, e.g.: dotnet run validate myconfig.yaml A config file consists of packages which contain modules. A package is used to describe a unit of work. E.g., you might want to install Visual Studio Code. This consists of multiple steps: 1. Import the repository key from Microsoft. 2. Add the Microsoft repository. 3. Update the package manager index. 4. Install the VS Code package. 5. Install some extensions for VS Code. Each of these steps is represented by a module. The modules are run in the order in which they are listed in their parent package. Default settings for packages/modules make sure that a package fails if any module fails (execution is aborted as soon as a module fails) and that the bootstrap process continues if a package fails. After running (successful or not) a bootstrap process two files are written to the current working directory: 1. bootstrap.success 2. bootstrap.error The first contains a list of all packages that finished successfully and the second contains the names of the packages that failed. If you run the boostrap process again (with these files present) any package that is listed in ```bootstrap.success``` will *not* be run again. This helps you debug your config and trying again. ## Variables For more complex operations you can make use of variables. These can be defined globally on the configuration root level or on a package level. To use the variable ```MyVariable``` you simply use ```$MyVariable``` as a placeholder for a property. E.g.: - !!FolderCreation Foldernames: - $MyFirstFolder - $MySecondFolder - /opt/android_studio This will replace the string ```$MyFirstFolder``` with whatever is stored in the given variable. Note that any new definition of a variable will overwrite its previous definition (except when overring global variables in a package). ### Default variables There are a number of default variables: * _homedir_ contains to the home directory of the user * _~_ will be expanded to _$homedir_ * _username_ contains the name of the current user ## Packages A package has the following propertes: #### Name (string) A name should be given to every package and needs to be unique. The name is used for the progress output and to validate the requirements of a package (see below). #### Description (string) A description is an optional field that is used to describe what the package does. #### IsCritical (bool) If a package is marked as critical the bootstrap process will abort if the package fails. This is useful if for packages that install base packages or perform system updates. #### IgnoreAlreadySolved (bool) If this is set to true the package will run again even if it completed successfully in a previous run. #### Modules (array of modules) Contains all the modules necessary to complete this package. #### Requires (array of string) List of packages (identified by name) that need to run before this package will be run. This is useful if you want to make sure that base packages and system updates have been applied before doing any other work. #### Variables (associative array) List of variables which are defined for this package. ## Modules {{ { ModulePrefix: "### ", ModulePropertyPrefix: "*", ModulePropertySuffix: "*" } }} [1]: https://en.wikipedia.org/wiki/YAML <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using SharpStrap.Helpers; namespace SharpStrap.Modules { /// <summary> /// Module that runs a shell command. /// </summary> public abstract class ShellModule : BaseModule { private const string ElevationPrefix = "sudo"; private const string ShellCommand = "/usr/bin/bash"; protected virtual bool RedirectStandardOutput => false; /// <summary> /// Command to run. /// </summary> public string Command { get; set; } /// <summary> /// Arguments for the command. /// </summary> public string Arguments { get; set; } /// <summary> /// Gets/sets wether this command requires elevation. /// </summary> public bool RequiresElevation { get; set; } /// <summary> /// Output of this command. /// </summary> /// <typeparam name="string"></typeparam> public IList<string> Output { get; set; } = new List<string>(); /// <summary> /// Working directory for the process. /// </summary> public string WorkingDirectory { get; set; } public ShellModule() { // Empty constructor for deserialization. } public ShellModule(string command, string argument) { this.Command = command; this.Arguments = argument; } protected void SetCommandAndArguments(string command, string argument) { this.Command = command; this.Arguments = argument; } public async override Task<ModuleResult> Run(IDictionary<string, string> variables, ColoredTextWriter output) { PreExecution(variables, output); string elevationPrefix = this.RequiresElevation ? ElevationPrefix : string.Empty; string workingDirectory = ReplaceVariablesInString(this.WorkingDirectory, variables); if(string.IsNullOrWhiteSpace(workingDirectory) == false && System.IO.Directory.Exists(workingDirectory) == false) throw new InvalidOperationException($"The given working directory '{this.WorkingDirectory}' does not exist."); var startInfo = new ProcessStartInfo { FileName = ReplaceVariablesInString(ShellCommand, variables), Arguments = ReplaceVariablesInString($"-c {CreateProcessCommand()}", variables), WorkingDirectory = ReplaceVariablesInString(this.WorkingDirectory, variables), RedirectStandardOutput = this.RedirectStandardOutput }; var result = await RunProcessAsTask(startInfo); PostExecution(variables, output); return new ModuleResult( (result == 0 ? ModuleResultStates.Success : ModuleResultStates.Error), this.Output, $"{startInfo.FileName} {startInfo.Arguments}", ReturnVariables() ); } protected abstract void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output); protected virtual void PostExecution(IDictionary<string, string> variables, ColoredTextWriter output) { // can be overriden in other modules in case they need to clean some work up } private string CreateProcessCommand() { return $"\"{(this.RequiresElevation ? ElevationPrefix : string.Empty)} {Command} {Arguments}\""; } protected Task<int> RunProcessAsTask(ProcessStartInfo startInfo) { var tcs = new TaskCompletionSource<int>(); var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true }; process.Exited += (sender, args) => { tcs.SetResult(process.ExitCode); process.Dispose(); }; process.OutputDataReceived += (sender, args) => { this.Output.Add(args.Data); }; process.Start(); if(startInfo.RedirectStandardOutput) process.BeginOutputReadLine(); return tcs.Task; } } }<file_sep>using System; using System.IO; namespace SharpStrap.Helpers { /// <summary> /// Interface for reading text files. /// </summary> public interface ITextFileInput { string ReadAllText(string filename); string[] ReadAllLines(string filename); } /// <summary> /// Provides the (text) contents of file using the native framework methods. /// </summary> public class FrameworkTextFileInput : ITextFileInput { public string[] ReadAllLines(string filename) { return File.ReadAllLines(filename); } public string ReadAllText(string filename) { return File.ReadAllText(filename); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; namespace SharpStrap.Modules { /// <summary> /// Base module for folder operations. /// </summary> public abstract class FolderModule : ShellModule { protected const string WorkOnParentsArguments = "-p"; protected abstract string FolderCommand { get; } /// <summary> /// List of foldernames to work on. /// </summary> public IEnumerable<string> Foldernames { get; set; } /// <summary> /// Removes/creates parent folders if true. /// </summary> public bool WorkOnParents { get; set; } public FolderModule() { // } public FolderModule(params string[] folderNames) { this.Foldernames = folderNames; } public FolderModule(bool workOnParents, params string[] folderNames) : this(folderNames) { this.WorkOnParents = workOnParents; } protected override void PreExecution(IDictionary<string, string> variables, Helpers.ColoredTextWriter output) { ThrowIfNoFolderSet(); SetCommandAndArguments(FolderCommand, CreateArgument()); } protected void ThrowIfNoFolderSet() { if(this.Foldernames.Count() == 0) throw new InvalidOperationException("At least one folder name must be supplied to create this module."); } protected string CreateArgument() { if(this.WorkOnParents) return $"{WorkOnParentsArguments} {string.Join(" ", this.Foldernames)}"; else return $"{string.Join(" ", this.Foldernames)}"; } } /// <summary> /// Creates folders. /// </summary> public class FolderCreationModule : FolderModule { protected override string FolderCommand => "mkdir"; } /// <summary> /// Removes (empty) folders. /// </summary> public class FolderRemovalModule : FolderModule { protected override string FolderCommand => "rmdir"; } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using SharpStrap.Modules; namespace SharpStrap.Helpers { public enum PackageEvaluationStates { /// <summary> /// Requirements have not been checked. /// </summary> NotEvaluated, /// <summary> /// Package can be run. /// </summary> Ready, /// <summary> /// Requirements have not been met but /// </summary> UnmetDependency, /// <summary> /// There are unsatisfiable requirements. /// </summary> Unresolvable, /// <summary> /// The package has been run successfully. /// </summary> Solved, /// <summary> /// The package has been run and failed. /// </summary> Failed, /// <summary> /// The package has been solved during a previous run. /// </summary> PreviouslyRun } public class PackageStorage { private const PackageEvaluationStates DefaultPackageState = PackageEvaluationStates.NotEvaluated; public const PackageEvaluationStates DefaultSuccessSate = PackageEvaluationStates.Solved; public const PackageEvaluationStates DefaultFailedState = PackageEvaluationStates.Failed; /// <summary> /// Returns all packages. /// </summary> public IEnumerable<Package> All { get { var values = Enum.GetValues(typeof(PackageEvaluationStates)).Cast<PackageEvaluationStates>(); return values.SelectMany(value => this.packagePool[value]); } } /// <summary> /// Returns all packages that have been run and succeeded. /// </summary> public IEnumerable<Package> Solved => packagePool[DefaultSuccessSate]; /// <summary> /// Returns all packages that have not been solved yet (all except solved and previously run). /// </summary> public IEnumerable<Package> Unsolved => All.Except(Solved).Except(PreviouslyRun); /// <summary> /// Returns all packages that have been run previously. /// </summary> public IEnumerable<Package> PreviouslyRun => packagePool[PackageEvaluationStates.PreviouslyRun]; protected readonly Dictionary<PackageEvaluationStates, IList<Package>> packagePool; public PackageStorage(IEnumerable<LogEntry> logEntries, IEnumerable<Package> packages) { // set private variables this.packagePool = new Dictionary<PackageEvaluationStates, IList<Package>>(); // populate the dictionary with all values of the PackageEvaluationStates enum foreach (var value in Enum.GetValues(typeof(PackageEvaluationStates)).Cast<PackageEvaluationStates>()) packagePool.Add(value, new List<Package>()); // add the packages to the package pool if (logEntries == null) logEntries = new LogEntry[0]; logEntries = logEntries.ToList(); // assign a matching evaluation state to the packages foreach(var package in packages) if(logEntries.Any(entry => entry.Name == package.Name && string.Equals(entry.Status, DefaultSuccessSate.ToString(), StringComparison.InvariantCultureIgnoreCase))) packagePool[PackageEvaluationStates.PreviouslyRun].Add(package); else if(logEntries.Any(entry => entry.Name == package.Name && string.Equals(entry.Status, PackageEvaluationStates.PreviouslyRun.ToString(), StringComparison.InvariantCultureIgnoreCase))) packagePool[PackageEvaluationStates.PreviouslyRun].Add(package); else packagePool[DefaultPackageState].Add(package); } /// <summary> /// Evaluates all packages in the pool and returns a package that is ready to run. /// Returns null if there is no package available. /// </summary> /// <returns></returns> public Package GetNextPackage() { EvaluatePackages(); return this.packagePool[PackageEvaluationStates.Ready].FirstOrDefault(); } /// <summary> /// Runs basic validation on the packages (dependency checking, setting fallback names). /// </summary> /// <returns></returns> public (bool, string) ValidatePackages() { AddMissingNamesForAllPackages(); return CheckForNonExistingRequirements(); } /// <summary> /// Adds placeholder names for packages which don't specify a name. /// </summary> private void AddMissingNamesForAllPackages() { var packagesWithoutName = this.All.Where(p => string.IsNullOrWhiteSpace(p.Name)).ToList(); for(var i = 0; i < packagesWithoutName.Count; ++i) packagesWithoutName[i].Name = $"<Unnamed Package #{i}>"; } /// <summary> /// Returns whether all requirements exist as packages in the current pool. /// </summary> /// <returns></returns> private (bool state, string reason) CheckForNonExistingRequirements() { var requirements = this.All.SelectMany(p => p.Requires).Distinct(); var names = this.All.Select(p => p.Name); var nonExistingNames = requirements.Where(r => names.Contains(r) == false).ToList(); if (nonExistingNames.Any()) return (false, $"The following requirements are listed but do not exist: {string.Join(", ", nonExistingNames)}."); else return (true, string.Empty); } /// <summary> /// Marks a package as solved in the internal package pool. /// </summary> /// <param name="p"></param> public void MarkPackageSolved(Package p) { MarkPackageAs(p, PackageEvaluationStates.Solved); } /// <summary> /// Marks a package as failed in the internal package pool. /// </summary> /// <param name="p"></param> public void MarkPackageFailed(Package p) { MarkPackageAs(p, PackageEvaluationStates.Failed); } /// <summary> /// Moves a package from one state to another. /// </summary> /// <param name="p"></param> /// <param name="newState"></param> /// <exception cref="ArgumentException"></exception> private void MarkPackageAs(Package p, PackageEvaluationStates newState) { if(p == null) throw new ArgumentException($"Cannot mark 'null' as solved."); if (this.packagePool[PackageEvaluationStates.Ready].Contains(p)) { this.packagePool[PackageEvaluationStates.Ready].Remove(p); this.packagePool[newState].Add(p); } else { var (found, state) = TryGetEvaluationStateForPackage(p, DefaultPackageState); if(found) throw new ArgumentException($"The package '{p.Name}' is not in the 'Ready'-state and thus cannot be marked solved. It was found in the '{state}'-state."); else throw new ArgumentException($"The package '{p.Name}' does not exist in the storage."); } } /// <summary> /// Check whether the dependencies for all packages can be met. /// </summary> /// <returns></returns> public (bool, string) DryRunDependencies() { var requirements = this.packagePool[PackageEvaluationStates.NotEvaluated].Select(p => (p.Name, p.Requires)).ToList(); var solved = requirements.Where(r => r.Requires.Any() == false) .Union(this.packagePool[PackageEvaluationStates.PreviouslyRun] .Select(p => (p.Name, (IEnumerable<string>) (new string[0])))) .ToList(); while(requirements.Count() != 0) { var solvable = requirements.Where(p => !p.Requires.Except(solved.Where(d => d.Name != null).Select(d => d.Name)).Any()); if (!solvable.Any()) return (false, $"Requirements not met: {string.Join(", ", requirements.Select(r => r.Name))}"); solved.AddRange(solvable); requirements.RemoveAll(r => solvable.Contains(r)); } return (true, string.Empty); } /// <summary> /// Searches the complete packagePool dictionary for the state of a package. Returns false if the package is not found. /// </summary> /// <param name="p"></param> /// <param name="fallback"></param> /// <returns></returns> private (bool, PackageEvaluationStates) TryGetEvaluationStateForPackage(Package p, PackageEvaluationStates fallback) { foreach(var state in Enum.GetValues(typeof(PackageEvaluationStates)).Cast<PackageEvaluationStates>()) if (this.packagePool[state].Contains(p)) return (true, state); return (false, fallback); } /// <summary> /// Iterates through all remaining packages and checks if their requirements have been met. /// </summary> private void EvaluatePackages() { var packagesToCheck = GetAllPackagesToCheck().ToArray(); foreach (var package in packagesToCheck) { var newState = CheckPackageState(package); var (found, currentState) = TryGetEvaluationStateForPackage(package, DefaultPackageState); if (found) { this.packagePool[currentState].Remove(package); this.packagePool[newState].Add(package); } else { throw new InvalidOperationException($"Encountered an error while trying to evaluate all package states: Could not find the current state for a package."); } } } /// <summary> /// Returns all packages that need to be run (Ready, NotEvaluated, UnmetDepedency). /// </summary> /// <returns></returns> private IEnumerable<Package> GetAllPackagesToCheck() { return this.packagePool[PackageEvaluationStates.Ready] .Union(packagePool[PackageEvaluationStates.NotEvaluated]) .Union(packagePool[PackageEvaluationStates.UnmetDependency]); } /// <summary> /// Refreshes the <see cref="DefaultPackageState"/> for the given package. /// </summary> /// <param name="package"></param> /// <returns></returns> private PackageEvaluationStates CheckPackageState(Package package) { if(package.Requires.Any() == false) return PackageEvaluationStates.Ready; if(package.Requires .Any( r => this.packagePool[PackageEvaluationStates.Unresolvable].Any(p => p.Name == r) || this.packagePool[PackageEvaluationStates.Failed].Any(p => p.Name == r))) { // At least one requirement for this package is unsatisfiable. return PackageEvaluationStates.Unresolvable; } var solvedPackageNames = this.packagePool[PackageEvaluationStates.Solved].Select(p => p.Name); if(package.Requires.Except(solvedPackageNames).Any() == false) return PackageEvaluationStates.Ready; else return PackageEvaluationStates.UnmetDependency; } /// <summary> /// Gets a list of log entries based on whether they ran successfully or not. /// </summary> public IEnumerable<LogEntry> GetLogResult() { return Enum.GetValues(typeof(PackageEvaluationStates)) .Cast<PackageEvaluationStates>() .SelectMany(state => this.packagePool[state].Select(package => (state, package))) .Select(x => new LogEntry {Name = x.package.Name, Status = x.state.ToString()}); } } }<file_sep>FROM microsoft/dotnet:sdk AS build-env WORKDIR /app # Copy csproj and restore as distinct layers COPY *.csproj ./ RUN dotnet restore # Copy everything else and build COPY . ./ RUN dotnet publish -c Release -o out # Build runtime image FROM library/fedora:28 # Import dotnet runtime since this is a regular Fedora. RUN rpm -Uvh https://packages.microsoft.com/config/rhel/7/packages-microsoft-prod.rpm RUN dnf update -y RUN dnf install -y dotnet-sdk-2.1.202 libstdc++ libunwind icu libicu libicu-devel sudo dbus openssh git wget firefox findutils compat-openssl10 # Add a non-admin user with sudo priviledges. RUN useradd -ms /bin/bash dotnetuser RUN usermod -aG wheel dotnetuser RUN echo "dotnetuser:dotnet"|chpasswd # Copy the application to the new container. WORKDIR /app COPY --from=build-env /app/out . COPY scripts/entry_point /app/entry_point RUN chmod +x /app/entry_point && \ mkdir -p /mnt/yaml && \ chmod -R 777 /mnt/yaml && \ chown dotnetuser /app/entry_point USER dotnetuser ENTRYPOINT ["/app/entry_point"] <file_sep>using System; using System.Collections.Generic; namespace SharpStrap.Helpers { public interface ITextFileOutput { void WriteAllText(string path, string text); void WriteAllLines(string path, IEnumerable<string> lines); } public class FrameworkTextFileOutput : ITextFileOutput { public void WriteAllLines(string path, IEnumerable<string> lines) { System.IO.File.WriteAllLines(path, lines); } public void WriteAllText(string path, string text) { System.IO.File.WriteAllText(path, text); } } }<file_sep>using System; namespace SharpStrap.Modules { /// <summary> /// Downloads remote files and saves it locally. /// </summary> public class DownloadModule : ShellModule { private const string DownloadCommand = "wget"; private const string TargetFileNameArgument = "-O"; /// <summary> /// Url to download the file from. /// </summary> public string Url { get; set; } /// <summary> /// Filename for the download. If not set the remote filename will be used instead. /// </summary> public string Target { get; set; } /// <summary> /// Custom user agent. /// </summary> public string UserAgent { get; set; } public DownloadModule() { // } public DownloadModule(string url, string targetFilename = null) : this() { this.Url = url; this.Target = targetFilename; } protected override void PreExecution(System.Collections.Generic.IDictionary<string, string> variables, Helpers.ColoredTextWriter output) { SetCommandAndArguments(DownloadCommand, CreateArgument()); } private string CreateArgument() { string args = string.Empty;; if(string.IsNullOrWhiteSpace(this.UserAgent)) args = $"--user-agent=\"{this.UserAgent}\""; if(string.IsNullOrWhiteSpace(this.Target)) return $"{args} {Url}"; else return $"{args} {TargetFileNameArgument} {Target} {Url}"; } } }<file_sep>using System; using System.Collections.Generic; namespace SharpStrap.Helpers { public class ShellCommandException : Exception { public IEnumerable<string> Output { get; private set; } public ShellCommandException(IEnumerable<string> output) { this.Output = output; } public ShellCommandException(IEnumerable<string> output, string message) : base(message) { this.Output = output; } } }<file_sep>using System; namespace SharpStrap.Modules { /// <summary> /// Module to print a given text. /// </summary> public class PromptModule : ShellModule { private const string PromptCommand = "echo"; /// <summary> /// Text to pront. /// </summary> public string Text { get; set; } /// <summary> /// Color of the text. /// </summary> public string Color { get; set; } = "White"; protected override void PreExecution(System.Collections.Generic.IDictionary<string, string> variables, Helpers.ColoredTextWriter output) { SetCommandAndArguments(PromptCommand, Text); var color = ColorNameToConsoleColor(this.Color); output.SetForegroundColor(color); } private ConsoleColor ColorNameToConsoleColor(string colorName) { switch(colorName.ToLower()) { case "white": return ConsoleColor.White; case "black": return ConsoleColor.Black; case "blue": return ConsoleColor.Blue; case "cyan": return ConsoleColor.Cyan; case "gray": return ConsoleColor.Gray; case "green": return ConsoleColor.Green; case "magenta": return ConsoleColor.Magenta; case "red": return ConsoleColor.Red; case "yellow": return ConsoleColor.Yellow; default: throw new ArgumentException($"The color '{this.Color}' is unknown."); } } protected override void PostExecution(System.Collections.Generic.IDictionary<string, string> variables, Helpers.ColoredTextWriter output) { output.ResetColors(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using SharpStrap.Helpers; namespace SharpStrap.Modules { /// <summary> /// Base module for file operations. /// </summary> public abstract class FileModule : ShellModule { // TODO: Move the redundant properties into this base class. protected abstract string FileOperation { get; } /// <summary> /// List of files to work on / to use as source. /// </summary> public IEnumerable<string> Filenames { get; set; } public FileModule() { // } public FileModule(IEnumerable<string> filenames) : this() { this.Filenames = filenames; } } /// <summary> /// Deletes files or folders. /// </summary> public class FileRemovalModule : FileModule { private const string ForceArgument = "-f"; private const string RecursiveArgument = "-r"; protected override string FileOperation => "rm"; /// <summary> /// Forces the removal of write-protected files. /// </summary> public bool Force{ get; set; } /// <summary> /// If the filename points to a folder it will be deleted recursively. /// </summary> public bool Recursive { get; set; } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { var argument = GetSpecialArguments() + " " + string.Join(" ", this.Filenames); SetCommandAndArguments(FileOperation, argument); } protected string GetSpecialArguments() { var force = Force ? ForceArgument : ""; var recursive = Recursive ? RecursiveArgument : ""; return $"{force} {recursive}"; } } /// <summary> /// Copies files or folders. /// </summary> public class FileCopyModule : FileModule { private const string ForceArgument = "-f"; private const string RecursiveArgument = "-r"; protected override string FileOperation => "cp"; /// <summary> /// Forces the file to be copied even if the destination cannot be opened. /// </summary> public bool Force{ get; set; } /// <summary> /// If the filename points to a folder it will be copied recursively. /// </summary> public bool Recursive { get; set; } /// <summary> /// Target filename/folder. /// </summary> public string Target { get; set; } public FileCopyModule() { // } public FileCopyModule(string target, IEnumerable<string> filenames) : base(filenames) { this.Target = target; } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { var argument = GetSpecialArguments() + " " + string.Join(" ", this.Filenames) + " " + Target; SetCommandAndArguments(this.FileOperation, argument); } protected string GetSpecialArguments() { var force = Force ? ForceArgument : ""; var recursive = Recursive ? RecursiveArgument : ""; return $"{force} {recursive}"; } } /// <summary> /// Moves files of folders. /// </summary> public class FileMoveModule : FileModule { private const string ForceArgument = "-f"; private const string RecursiveArgument = "-r"; protected override string FileOperation => "mv"; /// <summary> /// Forces the file to copied even if the destination cannot be opened. /// </summary> public bool Force{ get; set; } /// <summary> /// If the filename points to a folder it will be copied recursively. /// </summary> public bool Recursive { get; set; } /// <summary> /// Target filename/folder. /// </summary> public string Target { get; set; } public FileMoveModule() { // } public FileMoveModule(string target, IEnumerable<string> filenames) : base(filenames) { this.Target = target; } protected override void PreExecution(IDictionary<string, string> variables, ColoredTextWriter output) { var argument = GetSpecialArguments() + " " + string.Join(" ", this.Filenames) + " " + Target; SetCommandAndArguments(this.FileOperation, argument); } protected string GetSpecialArguments() { var force = Force ? ForceArgument : ""; var recursive = Recursive ? RecursiveArgument : ""; return $"{force} {recursive}"; } } }<file_sep>using System; using System.Text; using SharpStrap.Helpers; namespace Tests.Helpers { public class LogFileOutputWriter : ColoredTextWriter { public override Encoding Encoding => Encoding.UTF8; public override void ResetColors() { // } public override void SetBackgroundColor(ConsoleColor color) { // } public override void SetForegroundColor(ConsoleColor color) { // } } }<file_sep>using System; using System.Collections.Generic; using FluentAssertions; using SharpStrap.Modules; using Xunit; namespace Tests.Modules { public class PackageTests { #region CanRun Tests [Fact] public void CanRun_WithValidParameters_ReturnsTrue() { const string p1Name = "A1", p2Name = "B2", p3Name = "C3"; var package = new Package { Name = "Dummy Package", Requires = new List<string> { p1Name, p2Name, p3Name } }; var toTest = new List<string> { p1Name, p2Name, p3Name }; var result = package.CanRun(toTest); result.Should().BeTrue(); } [Fact] public void CanRun_WithTooManyParameters_ReturnsTrue() { const string p1Name = "A1", p2Name = "B2", p3Name = "C3"; var package = new Package { Name = "Dummy Package", Requires = new List<string> { p1Name, p2Name, p3Name } }; var toTest = new List<string> { p1Name, p2Name, p3Name, "extra 1", "extra 2" }; var result = package.CanRun(toTest); result.Should().BeTrue(); } [Fact] public void CanRun_WithInvalidParameters_ReturnsFalse() { const string p1Name = "A1", p2Name = "B2", p3Name = "C3"; var package = new Package { Name = "Dummy Package", Requires = new List<string> { p1Name, p2Name, p3Name } }; var toTest = new List<string> { p1Name, "wrong", p3Name }; var result = package.CanRun(toTest); result.Should().BeFalse(); } [Fact] public void CanRun_WithTooFewParameters_ReturnsFalse() { const string p1Name = "A1", p2Name = "B2", p3Name = "C3"; var package = new Package { Name = "Dummy Package", Requires = new List<string> { p1Name, p2Name, p3Name } }; var toTest = new List<string> { p1Name, p3Name }; var result = package.CanRun(toTest); result.Should().BeFalse(); } [Fact] public void CanRun_WithEmptyParameters_ReturnsTrue() { const string p1Name = "A1", p2Name = "B2", p3Name = "C3"; var package = new Package { Name = "Dummy Package", Requires = new List<string>() }; var result = package.CanRun(new List<string> { p1Name, p2Name, p3Name }); result.Should().BeTrue(); } #endregion } }<file_sep>using System; namespace SharpStrap.Modules { /// <summary> /// Lists the contents of a folder. /// </summary> public class FolderContentListModule : ShellModule { private const string ListCommand = "ls -la"; /// <summary> /// Path of the folder whose contents will be listed. /// </summary> public string Path { get; set; } public FolderContentListModule() { // } public FolderContentListModule(string path) { this.Path = path; } protected override void PreExecution(System.Collections.Generic.IDictionary<string, string> variables, Helpers.ColoredTextWriter output) { SetCommandAndArguments(ListCommand, Path); } } }<file_sep>[source,cs] ---- include::../src/Modules/DownloadModule.cs[tags=properties] ---- [source,c] ---- include::test.cpp[tags=test] ---- <file_sep>using System.Collections.Generic; using System.Runtime.CompilerServices; using SharpStrap.Helpers; using SharpStrap.Modules; namespace Tests.Modules.Shims { public class TestablePackageStorage : PackageStorage { public IDictionary<PackageEvaluationStates, IList<Package>> OrderedPackages => this.packagePool; public TestablePackageStorage(IEnumerable<LogEntry> logEntries, IEnumerable<Package> packages) : base(logEntries, packages) { // } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.Design; using System.IO; using System.Linq; namespace SharpStrap.Helpers { /// <summary> /// Abstract definition of a status log entry. /// </summary> public class LogEntry { public string Name { get; set; } public string Status { get; set; } } /// <summary> /// Reads and persists status of the bootstrap operation. /// </summary> public interface IBootstrapStatusLogger { IEnumerable<LogEntry> LoadOldLog(string logFilename); void SaveNewLog(string logFilename, IEnumerable<LogEntry> entries); } /// <summary> /// Reads and writes status log files to the local filesystem. /// </summary> public class FileBootstrapStatusLogger : IBootstrapStatusLogger { public IEnumerable<LogEntry> LoadOldLog(string logFilename) { if (System.IO.File.Exists(logFilename) == false) return new LogEntry[0]; var entries = new List<LogEntry>(); using (var reader = File.OpenText(logFilename)) { var line = string.Empty; var currentStatus = string.Empty; while ((line = reader.ReadLine()) != null) { if(string.IsNullOrWhiteSpace(line)) continue; if (line.StartsWith("[") && line.EndsWith("]")) currentStatus = line.Substring(1, line.Length - 2); else entries.Add(new LogEntry() { Name = line, Status = currentStatus }); } } return entries; } /// <summary> /// Writes a log file to the local file system. Contains the state of each package. /// </summary> /// <example> /// The resulting log file looks like this: /// /// [Solved] /// Package #1 /// Package #2 /// ... /// /// [Failed] /// Package #5 /// Package #6 /// ... /// /// </example> /// <param name="logFilename"></param> /// <param name="entries"></param> public void SaveNewLog(string logFilename, IEnumerable<LogEntry> entries) { var isFirst = true; using (var writer = File.CreateText(logFilename)) { var groupedEntries = entries.GroupBy(x => x.Status); foreach (var group in groupedEntries) { var header = $"{(isFirst ? string.Empty : Environment.NewLine)}[{group.Key}]"; isFirst = false; writer.WriteLine(header); foreach(var value in group) writer.WriteLine((value.Name)); } } } } }<file_sep>using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using SharpStrap.Helpers; namespace SharpStrap.Modules { public abstract class BaseModule { /// <summary> /// Unique Id of this module. /// </summary> public string Id { get; set; } /// <summary> /// Description of this module. /// </summary> public string Description { get; set; } /// <summary> /// Performs the action this module is intended to do. Requires previous setup. /// </summary> public abstract Task<ModuleResult> Run(IDictionary<string, string> variables, ColoredTextWriter output); /// <summary> /// Gets/sets if this module is allowed to fail. /// If it is true the package will continue to be executed. /// </summary> public bool AllowError { get; set; } /// <summary> /// Skips the replacement of variables for this module. /// </summary> protected virtual bool SkipVariableReplacement { get; } = false; /// <summary> /// Can be overriden to supply arguments back to the package. Default implementation yields an empty dictionary. /// </summary> protected virtual IDictionary<string, string> ReturnVariables() { return new Dictionary<string, string>(); } protected virtual string ReplaceVariablesInString(string s, IDictionary<string, string> variables) { if(string.IsNullOrWhiteSpace(s)) return s; if(this.SkipVariableReplacement) return s; // ~ is a special variable that is a placeholder for $homedir but doesn't use a dollar sign. // That's why it needs special treatment. s = s.Replace("~", "$homedir"); foreach(var pair in variables) { s = s.Replace($"${pair.Key}", pair.Value); } return s; } } } <file_sep>namespace DocsGenerator { public class TemplateConfig { public string ModulePrefix { get; set; } public string ModuleSuffix { get; set; } public string ModuleDescriptionPrefix { get; set; } public string ModuleDescriptionSuffix { get; set; } public string ModulePropertyPrefix { get; set; } public string ModulePropertySuffix { get; set; } public string ModulePropertyDescriptionPrefix { get; set; } public string ModulePropertyDescriptionSuffix { get; set; } } }
b0c1d08a1c64764b5783720fb0b6f792f0bd8efe
[ "Markdown", "Dockerfile", "AsciiDoc", "C#", "C++", "Shell" ]
52
C#
b0wter/sharpstrap
ab29e7aef3ad99b15ad5d64fb8b691fdf7682f4f
c3876e04c7aa4ad2fa1f7736f9dc864fa137a040
refs/heads/master
<file_sep><?php namespace app\models; use yii\base\Model; use Yii; /** * Signup form * * RegForm is the model behind the registration form. */ class RegisterForm extends Model { public $username; public $email; public $password; public $verifyCode; /** * @return array the validation rules. */ public function rules() { return [ [['username', 'email', 'password'], 'required'], ['username', 'match', 'pattern' => '#^[\w_-]+$#i'], [['username', 'password','email'], 'filter', 'filter' => 'trim'], ['username', 'string', 'min' => 3, 'max' => 255], ['username', 'unique', 'targetClass' => User::className(),'message' => 'Это имя занято.'], ['email', 'email'], ['email', 'unique', 'targetClass' => User::className(), 'message' => 'Эта почта уже зарегистрирована.'], ['verifyCode', 'captcha'] ]; } public function attributeLabels() { return [ 'username' => 'Имя', 'email' => 'Эл.почта', 'password' => '<PASSWORD>', 'verifyCode' => 'Код с картинки', ]; } /** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function reg() { if ($this->validate()) { $user = new User(); $user->username = $this->username; $user->email = $this->email; $user->setPassword($this->password); $user->generateAuthKey(); $user->role = User::ROLE_USER; $user->created_at = date(); $user->save(); return $user; } return null; } }<file_sep><?php /* @var $this yii\web\View */ $this->title = 'My Yii Application'; ?> <!-- Slider --> <div class="site-index"> <ul id="slide"> <li> <figure> <img src="../www/images/frontend/image-1.jpg" alt="" /> <figcaption> <h1>Первая картинка</h1> </figcaption> </figure> </li> <li> <figure> <img src="../www/images/frontend/image-2.jpg" alt="" /> <figcaption> <h1>Вторая картинка</h1> </figcaption> </figure> </li> <li> <figure> <img src="../www/images/frontend/image-3.jpg" alt="" /> <figcaption> <h1>Третья картинка</h1> </figcaption> </figure> </li> </ul> </div> <file_sep><?php namespace app\models; use Yii; use yii\behaviors\TimestampBehavior; /** * User is the model behind the user data. */ class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface { /** * @return const roles */ const ROLE_ADMIN = 1; const ROLE_USER = 0; public $password; /** * @return table name */ public static function tableName() { return 'user'; } public function behaviors() { return [ TimestampBehavior::className(), ]; } /** * @return array the validation rules. */ public function rules() { return [ [['username', 'email'], 'required'], ['username', 'match', 'pattern' => '#^[\w_-]+$#i'], [['username', 'password','email'], 'filter','filter' => 'trim'], ['username', 'string', 'min' => 2, 'max' => 255], ['username', 'unique', 'targetClass' => self::className(),'message' => 'Это имя занято.'], ['email', 'email'], ['email', 'unique', 'message' => 'Эта почта уже зарегистрирована.'], ['email', 'unique', 'targetClass' => self::className(), 'message' => 'Эта почта уже зарегистрирована.'], ['role', 'in', 'range' => [self::ROLE_USER, self::ROLE_ADMIN]], ]; } /** * verification of role */ public static function isUserAdmin($username) { if (static::findOne(['username' => $username, 'role' => self::ROLE_ADMIN])) { return true; } else { return false; } } public function attributeLabels() { return [ 'id' => 'ID', 'username' => '<NAME>', 'email' => 'Email', 'created_at' => 'Создан', ]; } /** * */ public static function findIdentity($id) { return static::findOne(['id' => $id]); } public static function findIdentityByAccessToken($token, $type = null) { return null; } /** * get ID */ public function getId() { return $this->getPrimaryKey(); } /** * Get "remember me" authentication key */ public function getAuthKey() { return $this->auth_key; } /** * Validate "remember me" authentication key */ public function validateAuthKey($authKey) { return $this->getAuthKey() === $authKey; } /** * Finds user by email */ public static function findByEmail($email) { return static::findOne(['email' => $email]); } /** * Validates password */ public function validatePassword($password) { return Yii::$app->security->validatePassword($password, $this->password_hash); } /** * Generates password hash from password and sets it to the model */ public function setPassword($password) { $this->password_hash = Yii::$app->security->generatePasswordHash($password); } /** * Generates "remember me" authentication key */ public function generateAuthKey() { $this->auth_key = Yii::$app->security->generateRandomString(); } /** * Generate authentication key alltime before save user */ public function beforeSave($insert) { if (parent::beforeSave($insert)) { if ($insert) { $this->generateAuthKey(); } return true; } return false; } } <file_sep><?php namespace app\controllers; use Yii; use yii\filters\AccessControl; use yii\web\Controller; use yii\filters\VerbFilter; use app\models\LoginForm; use app\models\RegForm; use app\models\User; use yii\base\InvalidParamException; use yii\data\SqlDataProvider; /** * controller for User, RegForm, LoginFrom models and index,user,reg,login views */ class SiteController extends \yii\web\Controller { /** * behaviors */ public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['logout', 'reg', 'log'], 'rules' => [ [ 'actions' => ['logout'], 'allow' => true, 'roles' => ['@'], ], [ 'actions' => ['reg'], 'allow' => true, 'roles' => ['?'], ], [ 'actions' => ['log'], 'allow' => true, 'roles' => ['@'], 'matchCallback' => function ($rule, $action) { return User::isUserAdmin(Yii::$app->user->identity->username); } ], ], ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'logout' => ['post'], ], ], ]; } public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, ], ]; } public function actionIndex() { return $this->render('index'); } /** * action for RegForm model and reg view */ public function actionRegister() { $model = new RegisterForm(); if($model->load(Yii::$app->request->post())){ if($user = $model->reg()){ if(Yii::$app->getUser()->login($user)) return $this->goHome(); }else{ Yii::$app->session->setFlash('error', 'Возникла ошибка при регистрации'); Yii::error('Ошибка при регистрации'); return $this->refresh(); } } return $this->render( 'reg', [ 'model' => $model ] ); } /** * action for LoginForm model and login view */ public function actionLogin() { if (!Yii::$app->user->isGuest) { return $this->goHome(); } $model = new LoginForm(); /** * login for role_admin */ if($model->load(Yii::$app->request->post()) && $model->loginAdmin()){ return $this->goBack(); } /** * login for role_user */ elseif($model->load(Yii::$app->request->post()) && $model->login()) { return $this->goBack(); } else{ return $this->render( 'login', [ 'model' => $model, ]); } } /** * action for logout */ public function actionLogout() { Yii::$app->user->logout(); return $this->goHome(); } /** * action for User model and user view */ public function actionUser() { if(!Yii::$app->user->isGuest) { $count = Yii::$app->db->createCommand('SELECT COUNT(*) FROM user') ->queryScalar(); /** * create data access object * @return object */ $dataProvider = new SqlDataProvider([ 'sql' => 'select * from user', 'totalCount' => $count, 'pagination' => [ 'pageSize' => 3, ], 'sort' => [ 'attributes' => [ 'username' => [ 'asc' => ['username' => SORT_ASC], 'desc' => ['username' => SORT_DESC], 'default' => SORT_ASC, 'label' => 'Имя пользователя', ], 'email' => [ 'asc' => ['email' => SORT_ASC], 'desc' => ['email' => SORT_DESC], 'default' => SORT_ASC, 'label' => 'Email', ], 'created_at' => [ 'asc' => ['created_at' => SORT_ASC], 'desc' => ['created_at' => SORT_DESC], 'default' => SORT_ASC, 'label' => 'Создан', ], ], ], ]); /** * get model,sort,pagination objects * @return object */ $provider = $dataProvider->getModels(); $sort = $dataProvider->getSort(); $pagination = $dataProvider->getPagination(); return $this->render('user', [ 'provider' => $provider, 'sort' => $sort, 'pagination' => $pagination, ]); /** * doing redirect if user is guest */ }else { $this->redirect('index.php'); } } } <file_sep><!-- Страница пользователей --> <?php use yii\helpers\Html; use yii\widgets\LinkPager; use yii\widgets\Pjax; /* @var $this yii\web\View */ /* @var $model app\models\User */ $this->title = 'Пользователи'; ?> <div class="site-user"> <h1><?= Html::encode($this->title) ?></h1> <!-- Ajax requests begin--> <? Pjax::begin(['enablePushState' => false]); ?> <table> <tr> <!-- Links of sort--> <td><?=$sort->link('username')?></td> <td><?=$sort->link('email')?></td> <td><?=$sort->link('created_at')?></td> </tr> <? foreach($provider as $user){ echo '<tr><td>' . $user['username'] . '</td><td>' . $user['email'] . '</td><td>' . date('d-m-Y H:i:s', $user['created_at']) .'</td></tr>'; } /* Pagination*/ echo LinkPager::widget([ 'pagination' => $pagination, ]); Pjax::end(); /* Ajax requests end*/ ?> </table> <div>
4a318a8c1178fd5ea6af1760bfb86187d581791e
[ "PHP" ]
5
PHP
egorlost/egor
f3209adee0fc4c9acb2c99a7166df3c960bbc2be
c026078cfb13ec1699b8f3a9c1b4d50887b420cc
refs/heads/main
<repo_name>felipemg-cit/alura-clean-architecture<file_sep>/src/test/java/br/com/alura/school/domain/student/EmailTest.java package br.com.alura.school.domain.student; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class EmailTest { @Test public void shouldNotCreateAnEmailWithAnInvalidAddress(){ assertThrows(IllegalArgumentException.class, () -> new Email(null)); assertThrows(IllegalArgumentException.class, () -> new Email("felipematheus@123")); assertThrows(IllegalArgumentException.class, () -> new Email("felipematheusgmail.com")); assertThrows(IllegalArgumentException.class, () -> new Email("<EMAIL>")); assertThrows(IllegalArgumentException.class, () -> new Email("<EMAIL>aaaaaa")); } @Test public void shouldCreateAnEmailWithAValidAddress(){ assertDoesNotThrow(() -> new Email("<EMAIL>")); assertDoesNotThrow(() -> new Email("<EMAIL>")); assertDoesNotThrow(() -> new Email("<EMAIL>")); assertDoesNotThrow(() -> new Email("<EMAIL>")); assertDoesNotThrow(() -> new Email("<EMAIL>")); assertDoesNotThrow(() -> new Email("<EMAIL>")); } }<file_sep>/src/main/java/br/com/alura/school/infrastructure/student/PasswordEncryptorWithMD5.java package br.com.alura.school.infrastructure.student; import br.com.alura.school.domain.student.PasswordEncryptor; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class PasswordEncryptorWithMD5 implements PasswordEncryptor { @Override public String encryptPassword(String password){ try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] bytes = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error generating password"); } } @Override public boolean isEncryptedPassword(String encryptedPassword, String password){ return encryptedPassword.equals(encryptPassword(password)); } } <file_sep>/src/test/java/br/com/alura/school/domain/student/PhoneNumberTest.java package br.com.alura.school.domain.student; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class PhoneNumberTest { @Test public void shouldNotCreateAPhoneNumberWithAnInvalidDDD(){ assertThrows(IllegalArgumentException.class, ()-> new PhoneNumber(null, "12345678")); assertThrows(IllegalArgumentException.class, ()-> new PhoneNumber(null, "")); assertThrows(IllegalArgumentException.class, ()-> new PhoneNumber("", "")); assertThrows(IllegalArgumentException.class, ()-> new PhoneNumber("1", "123456789")); assertThrows(IllegalArgumentException.class, ()-> new PhoneNumber("100", "1234567890")); } @Test public void shouldNotCreateAPhoneNumberWithAnInvalidNumber(){ assertThrows(IllegalArgumentException.class, ()-> new PhoneNumber("01", null)); assertThrows(IllegalArgumentException.class, ()-> new PhoneNumber("01", "")); assertThrows(IllegalArgumentException.class, ()-> new PhoneNumber("01", "1")); assertThrows(IllegalArgumentException.class, ()-> new PhoneNumber("01", "1234567890")); } @Test public void shouldCreateAPhoneNumberWithAValidDDDAndNumber(){ String d= "01"; String n= "123456789"; assertDoesNotThrow(()-> new PhoneNumber("01", "123456789")); assertDoesNotThrow(()-> new PhoneNumber("01", "12345678")); PhoneNumber test = new PhoneNumber(d, n); assertEquals(d, test.getDdd()); assertEquals(n, test.getNumber()); } }<file_sep>/src/main/java/br/com/alura/school/infrastructure/student/StudentsRepositoryInMemory.java package br.com.alura.school.infrastructure.student; import br.com.alura.school.domain.student.CPF; import br.com.alura.school.domain.student.Student; import br.com.alura.school.domain.student.StudentNotFound; import br.com.alura.school.domain.student.StudentsRepository; import java.util.ArrayList; import java.util.List; public class StudentsRepositoryInMemory implements StudentsRepository { private List<Student> enrolled = new ArrayList<>(); @Override public void enroll(Student student){ this.enrolled.add(student); } @Override public Student findByCPF(CPF cpf){ return this.enrolled.stream() .filter(a -> a.getCpf().equals(cpf.getNumber())) .findFirst() .orElseThrow(() -> new StudentNotFound(cpf)); } @Override public List<Student> getAllEnrolledStudents(){ return this.enrolled; } } <file_sep>/src/main/java/br/com/alura/school/EnrollStudentByCommandLine.java package br.com.alura.school; import br.com.alura.school.application.student.enroll.EnrollStudent; import br.com.alura.school.application.student.enroll.EnrollStudentDto; import br.com.alura.school.infrastructure.student.StudentsRepositoryInMemory; public class EnrollStudentByCommandLine { public static void main(String[] args) { /* StudentFactory factory = new StudentFactory(); Student student = factory.withNameCPFEmail("<NAME>", "123.456.798-10", "<EMAIL>") .createStudent(); StudentsRepository repository = new StudentsRepositoryInMemory(); */ String name = "<NAME>"; String cpf = "123.456.789-10"; String email = "<EMAIL>"; EnrollStudent enrollStudent = new EnrollStudent(new StudentsRepositoryInMemory()); enrollStudent.execute(new EnrollStudentDto(name, cpf, email)); } } <file_sep>/src/main/java/br/com/alura/school/infrastructure/student/StudentsRepositoryWithJDBC.java package br.com.alura.school.infrastructure.student; import br.com.alura.school.domain.student.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class StudentsRepositoryWithJDBC implements StudentsRepository { private final Connection connection; public StudentsRepositoryWithJDBC(Connection connection){ this.connection = connection; } @Override public void enroll(Student student){ try{ String sql = "INSERT INTO STUDENT VALUES (?, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, student.getCpf()); preparedStatement.setString(2, student.getName()); preparedStatement.setString(3, student.getEmail()); preparedStatement.execute(); sql = "INSERT INTO PHONENUMBERS VALUES (?, ?)"; preparedStatement = connection.prepareStatement(sql); for (PhoneNumber phoneNumber: student.getPhoneNumbers()) { preparedStatement.setString(1, phoneNumber.getDdd()); preparedStatement.setString(2, phoneNumber.getNumber()); preparedStatement.execute(); } }catch (SQLException e){ throw new RuntimeException(e); } } @Override public Student findByCPF(CPF cpf){ try { String sql = "SELECT id, nome, email FROM Student WHERE cpf = ?"; PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1, cpf.getNumber()); ResultSet rs = ps.executeQuery(); boolean encontrou = rs.next(); if (!encontrou) { throw new StudentNotFound(cpf); } String nome = rs.getString("nome"); Email email = new Email(rs.getString("email")); Student encontrado = new Student(cpf, nome, email); Long id = rs.getLong("id"); sql = "SELECT ddd, numero FROM TELEFONE WHERE Student_id = ?"; ps = connection.prepareStatement(sql); ps.setLong(1, id); rs = ps.executeQuery(); while (rs.next()) { String numero = rs.getString("numero"); String ddd = rs.getString("ddd"); encontrado.setPhoneNumber(ddd, numero); } return encontrado; } catch (SQLException e) { throw new RuntimeException(e); } } @Override public List<Student> getAllEnrolledStudents(){ try { String sql = "SELECT id, cpf, nome, email FROM Student"; PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery(); List<Student> Students = new ArrayList<>(); while (rs.next()) { CPF cpf = new CPF(rs.getString("cpf")); String nome = rs.getString("nome"); Email email = new Email(rs.getString("email")); Student Student = new Student(cpf, nome, email); Long id = rs.getLong("id"); sql = "SELECT ddd, numero FROM TELEFONE WHERE Student_id = ?"; PreparedStatement psTelefone = connection.prepareStatement(sql); psTelefone.setLong(1, id); ResultSet rsTelefone = psTelefone.executeQuery(); while (rsTelefone.next()) { String numero = rsTelefone.getString("numero"); String ddd = rsTelefone.getString("ddd"); Student.setPhoneNumber(ddd, numero); } Students.add(Student); } return Students; } catch (SQLException e) { throw new RuntimeException(e); } } }
bed84146cc4971b775ad59473123d0aeb2e442ac
[ "Java" ]
6
Java
felipemg-cit/alura-clean-architecture
2db919511e402a78c8d4d7419c0ef78e00092c4f
584ce363663e1541ef4b05c6b1e6146aea09ef88
refs/heads/master
<repo_name>kobe-cxk/spring-boot-quick<file_sep>/spring-boot-quick/config/application.properties #logging.level.com.huawei = trace #logging.file=springboot.log #logging.file=G:/springboot.log #logging.file.path=/spring/log/springboot.log #logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} === [%thread] %-5level === %logger{50} === %msg%n #logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} === [%thread] %-5level === %logger{50} === %msg%n #server.port=8084<file_sep>/spring-boot-quick/target/classes/config/application.properties ##logging.level.com.huawei = trace ##logging.file=springboot.log ##logging.file=G:/springboot.log ##logging.file.path=/spring/log/springboot.log ##logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} === [%thread] %-5level === %logger{50} === %msg%n ##logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} === [%thread] %-5level === %logger{50} === %msg%n #server.port=8081<file_sep>/spring-boot-quick/src/main/java/com/huawei/springbootquick/controller/HelloController.java package com.huawei.springbootquick.controller; import com.huawei.springbootquick.pojo.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @Controller public class HelloController { private Logger logger = LoggerFactory.getLogger(HelloController.class); @RequestMapping("/success") public String success(HttpServletRequest http,Map<String, Object> map){ logger.info("调用开始==="); map.put("hello","你好"); map.put("hello2","<h1>你好呀</h1>"); map.put("users", Arrays.asList("张三","李四","王五")); map.put("userAges", Arrays.asList("18","19","20")); map.put("uList", Arrays.asList("18","19","20","","123","123","123","123","123","123","123","123","123","123","123","123","123","123","123","123","123","123","123","123","23","123","123")); http.getSession().setAttribute("zwq","我媳妇"); User user = new User("zwq",18,"guangzhou","qq"); User user2 = new User("zwq2",18,"guangzhou","qq"); User user3 = new User("zwq3",18,"guangzhou","qq"); User user4 = new User("zwq4",18,"guangzhou","qq"); List list = new ArrayList<User>(); list.add(user); list.add(user2); list.add(user3); list.add(user4); map.put("userList",list); map.put("user",user); logger.info("调用结束==="); return "success"; } @RequestMapping("user2") public String user2(String name,int age){ System.out.println(name); System.out.println(age); return "B"; } }
39d0550733e96d6433db4c5896f00dc49c2e373d
[ "Java", "INI" ]
3
INI
kobe-cxk/spring-boot-quick
341bf8eaafacdc158e6e1b36fa5067cebff1a5cb
f13c55f560ebd52e36728a640ac15bcf6091945e
refs/heads/master
<repo_name>harpershapiro/MoltenSampleBackend<file_sep>/routes/Post.js const { pseudoRandomBytes } = require("crypto"); const express = require("express"); const router = express.Router(); const Post = require("../models/post.model"); router.route("/").get(function (req, res) { Post.find(function (err, posts) { if (err) { console.log(err); } else { res.json(posts); } }); }); router.route("/:id").get(function (req, res) { let id = req.params.id; Post.findbyId(id, function (err, post) { res.json(post); }); }); //update one router.route("/update/:id").post(function (req, res) { let id = req.params.id; Post.findById(id, function (err, post) { if (!post) { res.status(404).send("data is not found"); } else { post.post_url = req.body.post_url; //post.post_img_url = req.body.post_img_url; post.img_ext = req.body.img_ext; post.pack_ext = req.body.pack_ext; post.post_date = req.body.post_date; post.post_submitter = req.body.post_submitter; post.post_accepter = req.body.post_accepter; post.post_desc = req.body.post_desc; post.post_size = req.body.post_size; post .save() .then((post) => { res.json("Post updated"); }) .catch((err) => { res.status(400).send("Update not possible"); }); } }); }); router.route("/delete/:id").delete(function (req, res) { let id = req.params.id; Post.findByIdAndDelete(id, function (err, post) { if (!post) { res.status(404).send("data is not found"); } else { res.json("Post deleted."); } }); }); router.route("/add").post(function (req, res) { let post = new Post(req.body); post .save() .then((post) => { res.status(200).json({ post: "Post added successfully" }); }) .catch((err) => { res.status(400).send("Adding new post failed"); }); }); module.exports = router; <file_sep>/index.js //var download= require("./download.js")//import download from ('./download.js'); //download().then(console.log("downloaded")) { /* <html> <body> <form ref='uploadForm' id='uploadForm' action='/upload' method='post' encType="multipart/form-data"> <input type="file" name="sampleFile" /> <input type='submit' value='Upload!' /> </form> <img src="/images/daffycolorado.JPG" /> </body> </html> */ } <file_sep>/models/user.model.js const mongoose = require("mongoose"); const Schema = mongoose.Schema; let User = new mongoose.Schema({ user_name: { type: String, }, user_pass: { type: String, select: false, }, user_roles: { type: [], default: ["user"], }, }); User.methods.findByUsername = (name, cb) => { return this.model("User").find({ username: name }, cb); }; module.exports = mongoose.model("User", User); <file_sep>/routes/Files.js const express = require("express"); const router = express.Router(); const AWS = require("aws-sdk"); const fs = require("fs"); const path = require("path"); const s3 = new AWS.S3({ accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }); var uploadsDir = require("path").join(__dirname, "../uploads"); router.use(express.static(uploadsDir)); //UPLOADS//////////////////////////////////////////////////////////////////////////////// router.post("/upload/remote", function (req, res) { if (!req.files || Object.keys(req.files).length === 0) { res.status(400).send("No files were uploaded."); return; } let uploadFile = req.files.file; let fileSize = req.files.file.size; let uploadPartialPath = req.body.filename; let uploadPath; let uploadType = uploadFile.mimetype; console.log("type: " + uploadFile.mimetype); console.log("req.files >>>", req.files); const params = { Bucket: "moltenbucket", Key: uploadPartialPath, Body: uploadFile.data, }; s3.upload(params, (s3Err, data) => { if (s3Err) throw s3Err; console.log(`File uploaded at ${data.Location}`); }); res.json({ file: `${req.body.filename}`, size: `${fileSize}` }); }); router.post("/upload/local", function (req, res) { if (!req.files || Object.keys(req.files).length === 0) { res.status(400).send("No files were uploaded."); return; } let uploadFile = req.files.file; let fileSize = req.files.file.size; let uploadPartialPath = req.body.filename; let uploadPath; let uploadType = uploadFile.mimetype; console.log("type: " + uploadFile.mimetype); console.log("req.files >>>", req.files); uploadPath = __dirname + "/../uploads/" + uploadPartialPath; console.log(uploadPath); uploadFile.mv(uploadPath, function (err) { if (err) { return res.status(500).send(err); } console.log(`uploads/${req.body.filename}`); res.json({ file: `uploads/${req.body.filename}`, size: `${fileSize}` }); }); }); //FETCHING//////////////////////////////////////////////////////////////////////////////// router.route("/fetchImage/local/:file").get((req, res) => { let file = req.params.file; let fileLocation = path.join(`${uploadsDir}/images/`, file); console.log(`fetch image. filelocation: ${fileLocation}`); //res.send({image: fileLocation}); res.sendFile(`${fileLocation}`); }); router.get("/downloadPack/local/:file", (req, res) => { let file = req.params.file; let fileLocation = path.join(`${uploadsDir}/packs/`, file); console.log(`download pack. filelocation: ${fileLocation}`); res.sendFile(`${fileLocation}`); }); router.route("/fetchImage/remote/:file").get((req, res) => { let file = req.params.file; let fileKey = `images/${file}`; var params = { Bucket: "moltenbucket", Key: fileKey, }; //access bucket s3.getObject(params, (err, data) => { if (err) console.log(err, err.stack); else { let fileLocation = path.join(`${uploadsDir}/images/`, file); let image = data.Body; //write image to temp file and send fs.writeFile(fileLocation, image, (err) => { if (err) res.sendStatus(500); else { res.sendFile(`${fileLocation}`, (err) => { fs.unlink(fileLocation, () => console.log("Temp file deleted.")); }); } }); } }); //res.send({image: fileLocation}); }); router.get("/downloadPack/remote/:file", (req, res) => { let file = req.params.file; let fileKey = `packs/${file}`; var params = { Bucket: "moltenbucket", Key: fileKey, }; //access bucket s3.getObject(params, (err, data) => { if (err) console.log(err, err.stack); else { let fileLocation = path.join(`${uploadsDir}/packs/`, file); let pack = data.Body; //write pack to temp file and send fs.writeFile(fileLocation, pack, (err) => { if (err) res.sendStatus(500); else { res.sendFile(`${fileLocation}`, (err) => { fs.unlink(fileLocation, () => console.log("Temp file deleted.")); }); } }); } }); //res.sendFile(`${fileLocation}`); }); //DELETING//////////////////////////////////////////////////////////////////////////////// router.delete("/deleteImage/local/:file", (req, res) => { let file = req.params.file; let fileLocation = path.join(`${uploadsDir}/images/`, file); console.log("deleting " + fileLocation); fs.unlink(fileLocation, () => res.json("Image deleted.")); }); router.delete("/deletePack/local/:file", (req, res) => { let file = req.params.file; let fileLocation = path.join(`${uploadsDir}/packs/`, file); console.log("deleting " + fileLocation); fs.unlink(fileLocation, () => res.json("Pack deleted.")); }); router.delete("/deleteImage/remote/:file", (req, res) => { let file = req.params.file; let fileKey = `images/${file}`; var params = { Bucket: "moltenbucket", Key: fileKey, }; s3.deleteObject(params, (err, data) => { if (err) console.log(err, err.stack); else res.json("Image deleted."); }); }); router.delete("/deletePack/remote/:file", (req, res) => { let file = req.params.file; let fileKey = `packs/${file}`; var params = { Bucket: "moltenbucket", Key: fileKey, }; s3.deleteObject(params, (err, data) => { if (err) console.log(err, err.stack); else res.json("Pack deleted."); }); }); module.exports = router; <file_sep>/server.js require("dotenv/config"); const express = require("express"); const app = express(); const bodyParser = require("body-parser"); const cors = require("cors"); const mongoose = require("mongoose"); const fileUpload = require("./node_modules/express-fileupload/lib/index"); const ApiRouter = require("./routes/Api.js"); const MONGO_URI = process.env.MONGO_URI; console.log(MONGO_URI); const PORT = process.env.PORT; //aka BACK_PORT in frontend app.use(fileUpload()); app.use(cors()); app.use(bodyParser.json()); //DB connection mongoose .connect(MONGO_URI, { useNewUrlParser: true }) .then(() => { const connection = mongoose.connection; connection.once("open", function () { console.log("MongoDB connection established successfully."); }); }) .catch((e) => { console.log("Could not connect to MongoDB."); console.log(e); }); app.use("/molten", ApiRouter); app.listen(PORT, function () { console.log("Server is running on Port: " + PORT); }); <file_sep>/routes/Submission.js const express = require("express"); const router = express.Router(); const Submission = require("../models/submission.model"); //get all router.route("/").get(function (req, res) { Submission.find(function (err, submissions) { if (err) { console.log(err); } else { res.json(submissions); } }); }); //get one router.route("/:id").get(function (req, res) { let id = req.params.id; Submission.findbyId(id, function (err, submission) { res.json(submission); }); }); //update one router.route("/update/:id").post(function (req, res) { let id = req.params.id; Submission.findById(id, function (err, submission) { if (!submission) { res.status(404).send("data is not found"); } else { submission.submission_url = req.body.submission_url; submission.img_ext = req.body.img_ext; submission.pack_ext = req.body.pack_ext; //submission.submission_img_url = req.body.submission_img_url; submission.submission_title = req.body.submission_title; submission.submission_user = req.body.submission_user; submission.submission_date = req.body.submission_date; submission.submission_desc = req.body.submission_desc; submission.submission_size = req.body.submission_size; submission .save() .then((submission) => { res.json("Submission updated"); }) .catch((err) => { res.status(400).send("Update not possible"); }); } }); }); router.route("/delete/:id").delete(function (req, res) { let id = req.params.id; Submission.findByIdAndDelete(id, function (err, submission) { if (!submission) { res.status(404).send("data is not found"); } else { res.json("Submission deleted."); } }); }); router.route("/add").post(function (req, res) { let submission = new Submission(req.body); submission .save() .then((submission) => { res.status(200).json({ submission: "Submission added successfully" }); }) .catch((err) => { res.status(400).send("Adding new submission failed"); }); }); module.exports = router;
9d48d10c4ab9f769f4fb79272db4dd725108354d
[ "JavaScript" ]
6
JavaScript
harpershapiro/MoltenSampleBackend
312614dad308e95b03bd4cf2e3f951034a8c8f1a
f7465b6ecc41622287af0c5b636b215a074f69e7