language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C++
UTF-8
1,451
2.734375
3
[]
no_license
#include <iostream> using namespace std; unsigned int tree[40000000]; unsigned int lazy[40000000]; struct segment { unsigned int l,r; }; long update(int node, segment nint, segment range, int val) { //cout << node << endl; if(range.l<=nint.l && nint.r<=range.r) { lazy[node] += val; return tree[node] + lazy[node]; } segment left; left.l = nint.l; left.r = (nint.r+nint.l)/2; long L=0,R=0; if(range.l<=left.r) L = update(2*node, left, range, val); segment right; right.l = left.r+1; right.r = nint.r; if(right.l<=range.r) R = update(2*node+1, right, range, val); return (tree[node]=max(L,R))+lazy[node]; } long query(int node, segment nint, segment range) { //cout << node << endl; if(nint.l==nint.r) { tree[node] += lazy[node]; lazy[node] = 0; return tree[node]; } segment left; left.l = nint.l; left.r = (nint.r+nint.l)/2; long L=0,R=0; if(range.l<=left.r) L = query(2*node, left, range); segment right; right.l = left.r+1; right.r = nint.r; if(right.l<=range.r) R = query(2*node+1, right, range); tree[node] = max(L,R) + lazy[node]; lazy[2*node] += lazy[node]; lazy[2*node+1] += lazy[node]; lazy[node] = 0; return tree[node]; } int main() { int N,M,a,b,k; cin >> N; segment root, tmp; root.l=1,root.r=N; cin >> M; while(M--) { cin >> a >> b >> k; tmp.l = a, tmp.r = b; update(1, root, tmp, k); } cout << query(1, root, root) << endl; return 0; }
C#
UTF-8
1,899
2.625
3
[]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using HerosDB; using HerosWeb.Models; namespace HerosWeb.Controllers { public class SuperHeroController : Controller { private readonly ISuperHeroRepo _repo; //the argument for this constructor is passed in Startup.cs public SuperHeroController(ISuperHeroRepo repo) { _repo = repo; } public async Task<IActionResult> GetAllHeroes() { var superHeroes = await _repo.GetAllHeroesAsync(); return View(superHeroes); } public IActionResult GetHeroByName(string name) { var superHero = _repo.GetHeroByName(name); return View(superHero); } public ViewResult AddHero() { return View(); } [HttpPost] public IActionResult AddHero(SuperHero superHero) { if(ModelState.IsValid) { HerosDB.Models.SuperHero hero = new HerosDB.Models.SuperHero(); hero.Alias = superHero.Alias; hero.RealName = superHero.RealName; hero.HideOut = superHero.HideOut; _repo.AddAHeroAsync(hero); return Redirect("GetAllHeroes"); } else { return View(); } } public ViewResult UpdateHero(string name) { var superhero = _repo.GetHeroByName(name); SuperHero webHero = new SuperHero(); webHero.Alias = superhero.Alias; webHero.HideOut = superhero.HideOut; webHero.RealName = superhero.RealName; return View(webHero); } [HttpPost] public IActionResult UpdateHero(SuperHero superHero) { if (ModelState.IsValid) { HerosDB.Models.SuperHero hero = new HerosDB.Models.SuperHero(); hero.Alias = superHero.Alias; hero.RealName = superHero.RealName; hero.HideOut = superHero.HideOut; _repo.UpdateHero(hero); return Redirect("GetAllHeroes"); } else { return View(); } } } }
TypeScript
UTF-8
7,187
2.71875
3
[]
no_license
class JunkGenerator { private assets : AssetsManager = new AssetsManager(); private minNumber = 1; private maxNumber = 9; private counter = 0; private updateTimout = 60; private minPositionY = 185; private maxPositionY = 215; private minPositionX = 1100; private maxPositionX = 1150; private objectList:Array<ICollidable>; private BGList:Array<bgObjects>; private _game:Game; public level : number; constructor(game:Game, objList:Array<ICollidable>, bglist:Array<bgObjects>, lvl: number) { this.objectList = objList; this.BGList = bglist; this._game = game; this.level = lvl; console.log("JunkGenerator is activated..."); } private getRandomNumber(min, max) : number { let random = Math.floor(Math.random() * (max - min + 1) + min); return random; } private getRandomFloat(range:number) : number { let random = (Math.random() * range) + 0.2; return random; } public generateJunk(): void { switch(this.level){ case 1:{ this.generateLevel1(); break; } case 2:{ this.generateLevel2(); break; } } } private generateLevel1() : void{ this.counter++; if(this.counter > this.updateTimout){ let random = this.getRandomNumber(this.minNumber, this.maxNumber); let randomX = this.getRandomNumber(this.minPositionX, this.maxPositionX); let randomY = this.getRandomNumber(this.minPositionY, this.maxPositionY); let crateImg = this.assets.desObjects.Crate; // console.log("randomX junk =" + randomX); // console.log("randomY junk =" + randomY); let bush = new BackgroundObject({ imgSrc: this.assets.desObjects.Bush1, x: randomX, y: randomY, frameHeight: 145, frameWidth: 145 }, 1, this._game); let coin = new Coin(this._game, {imgSrc: this.assets.collectables.goldCoin, x: randomX, y: randomY, frameHeight: 16, frameWidth: 16, maxFrame: 7, animationSpeed: 10, speed: 5}); let Crate = new crate(this._game, { imgSrc: this.assets.desObjects.Crate, x: randomX, y: randomY, frameHeight: 101, frameWidth: 101, speed: 5 }); switch(random){ case 1: // console.log("Case 1 - Background Object"); this.objectList.push(coin); break; case 2: console.log("Case 2 - Coin Object"); this.objectList.push(coin); // console.log("Case 2 - Background Object"); // this.objectList.push(new BackgroundObject({ imgSrc: this.assets.desObjects.Bush1, x: randomX, y: randomY, frameHeight: 145, frameWidth: 80 })); break; case 3: // console.log("Case 3 - Destructable Object"); this.BGList.push(bush); break; case 4: // console.log("Case 4 - Coin Object"); this.objectList.push(coin); break; case 5: // console.log("Case 3 - Destructable Object"); this.objectList.push(Crate); break; case 6: // console.log("Case 4 - Coin Object"); this.objectList.push(coin); break; case 7: // console.log("Case 4 - Coin Object"); this.BGList.push(bush); break; case 8: // console.log("Case 3 - Destructable Object"); this.BGList.push(bush); break; case 9: // console.log("Case 4 - Coin Object"); this.objectList.push(Crate); break; } // console.log("JunkGenerator Updater...."); this.counter = 0; } } private generateLevel2() : void{ this.counter++; var minPositionY = 0; var maxPositionY = 15; if(this.counter > this.updateTimout){ let random = this.getRandomNumber(this.minNumber, this.maxNumber); let randomX = this.getRandomNumber(this.minPositionX, this.maxPositionX); let randomY = this.getRandomNumber(this.minPositionY, this.maxPositionY); let randomYTree = this.getRandomNumber(minPositionY, maxPositionY); let crateImg = this.assets.desObjects.Crate; // console.log("randomX junk =" + randomX); // console.log("randomY junk =" + randomY); let bush = new BackgroundObject({ imgSrc: this.assets.winterObjects.Tree2_1, x: randomX, y: 30, frameHeight: 280, frameWidth: 228 }, 1, this._game); let coin = new Coin(this._game, {imgSrc: this.assets.collectables.goldCoin, x: randomX, y: randomY, frameHeight: 16, frameWidth: 16, maxFrame: 7, animationSpeed: 5, speed: 5}); let Crate = new crate(this._game, { imgSrc: this.assets.winterObjects.IceBoxSmall, x: randomX, y: 225, frameHeight: 50, frameWidth: 50, speed: 5 }); switch (random) { case 1: // console.log("Case 1 - Background Object"); this.objectList.push(coin); break; case 2: console.log("Case 2 - Coin Object"); this.objectList.push(coin); // console.log("Case 2 - Background Object"); // this.objectList.push(new BackgroundObject({ imgSrc: this.assets.desObjects.Bush1, x: randomX, y: randomY, frameHeight: 145, frameWidth: 80 })); break; case 3: // console.log("Case 3 - Destructable Object"); this.BGList.push(bush); break; case 4: // console.log("Case 4 - Coin Object"); this.objectList.push(coin); break; case 5: // console.log("Case 3 - Destructable Object"); this.objectList.push(Crate); break; case 6: // console.log("Case 4 - Coin Object"); this.objectList.push(coin); break; case 7: // console.log("Case 4 - Coin Object"); this.BGList.push(bush); break; case 8: // console.log("Case 3 - Destructable Object"); this.BGList.push(bush); break; case 9: // console.log("Case 4 - Coin Object"); this.objectList.push(Crate); break; } // console.log("JunkGenerator Updater...."); this.counter = 0; } } }
C++
UTF-8
319
3.25
3
[]
no_license
#include<iostream> #include<string> #include<algorithm> #include<list> using namespace::std; int main() { list<string> lis{ "Pratice ", "makes ", "perfect." }; auto co1 = count(lis.cbegin(), lis.cend(), "make"); auto co2 = count(lis.cbegin(), lis.cend(), "makes "); cout << co1 << " " << co2 << endl; return 0; }
Markdown
UTF-8
679
2.53125
3
[]
no_license
# Crypto Communism `crypto-communism` is a service to seize your bourgeois bitcoins in exchange of presenting you and the all the proletarian ears around, the glorious anthem of the Motherland! Can I hear a _Ура_? ## How to install First clone the repository and go to its folder with: ```sh git clone https://github.com/ggviana/crypto-communism.git cd crypto-communism ``` Then install the dependencies: ```sh npm install ``` Now you are ready to start the _Революция_! ## How to use Run this command: ```sh npm start ``` And ask your comrades to send their bitcoins to the address below: `mwGWwmdZTwBJAnVpQWABnLYKo1GmS5T5CL` ![Pay up!](resources/wallet.png)
Java
UTF-8
4,437
2.890625
3
[]
no_license
package Actors; import java.io.Serializable; import java.util.Calendar; import Media.PhysicalMedia; import Utilities.*; /** * This class deals with the librarian and stores all the information about them. * */ public class Librarian implements Serializable{ private String ID; private String FirstName; private String LastName; private Calendar birthDate; private Address Address; private String phoneNumber; private String password; private Boolean isAdmin; /** * Constructor * @param iD * @param firstName * @param lastName * @param birthDate * @param address * @param phoneNumber */ public Librarian(String iD, String firstName, String lastName, Calendar birthDate, Utilities.Address address, String phoneNumber, Boolean admin) { super(); ID = iD; FirstName = firstName; LastName = lastName; this.birthDate = birthDate; Address = address; this.phoneNumber = phoneNumber; this.password = (firstName+lastName); this.isAdmin = admin; } /** * Getters & setters */ public String getFirstName() { return FirstName; } public void setFirstName(String firstName) { FirstName = firstName; } public String getLastName() { return LastName; } public Boolean getAdmin() { return isAdmin; } public void setLastName(String lastName) { LastName = lastName; } public String getID() { return this.ID; } public String getPassword() { return this.password; } /** * This function returns media for customer * @param media - media to be returned * @param customer - customer to remove the media from */ public void returnMedia(PhysicalMedia media , Customer customer) { customer.removeMediaOwned(media); //removes media & updates media status & associated customer media.moveQueue(); //Possibly take someone from queue to hold the book for 1 week } /** * This function adds media to customers account or places book on hold for them * @param media * @param currentDate * @param holdOrTake - String that is either "hold" or "take" depends what student wants if book is available now * @return String - message */ public String addMediaOwned(Customer customer,PhysicalMedia media,String holdOrTake) { if (customer.getIsBlackListed() == false && customer.getNumMediaOwned() < customer.getMaxMedia() && !media.getStatus().toString().equals("unavailable")) { //No one has the media on hold (and obviously no one has it because customer just took it from shelf) if (media.getCustomer() == null && media.getLineUp().size() == 0) { media.setCustomer(customer); //set media to customer that will take it or hold it if (holdOrTake.equals("take")) { Calendar retDate = media.calcReturnDate(); //either 2 wks or 2h customer.addMediaOwned(media, retDate); //add media to customer account & ret date media.getStatus().setInUse(); //set new status to media return "Media was issued to customer and added to customer's : " + customer.getID() + " account"; } if (holdOrTake.equals("hold")) { customer.addMediaOnHold(media); //add media to customer's holds for 1 week from now return "Media is put on hold by customer: " + customer.getID(); } } //If media is held by some other customer (& there's a possible queue or no queue) AND customer isn't holding same item // multiple times else if (media.getCustomer() != null && media.getCustomer() != customer && media.getLineUp().isInLine(customer) == false) { media.getLineUp().addToLine(customer); //customer added to queue for media return "Customer " + customer.getID() + " was put on queue in position: " + media.getLineUp().size(); } } return "Unable to issue a book to the customer: " + customer.getID(); } /** * This function is for librarian to set faculty blacklisted (allows to do it only if overdue fees are 50.0) * @param faculty */ public void makeBlackListed(Customer faculty) { if (faculty.getFeesOwned() == 50.0 && faculty.getTag()) { faculty.setIsBlackListed(true); } } /** * moves media from holds to media borrowed by customer if conditions are satisfied. * @param media * @param customer * @return String - message */ public String removeFromHoldsToPickup(PhysicalMedia media, Customer customer) { return customer.moveFromHoldToOwned(media); } }
Java
UTF-8
424
3.3125
3
[]
no_license
import java.util.*; import java.math.*; public class No373 { public static void main(String[] args) { // 標準入力から読み込む際に、Scannerオブジェクトを使う。 Scanner s = new Scanner(System.in); long a = s.nextLong(); long b = s.nextLong(); long c = s.nextLong(); long d = s.nextLong(); System.out.println((((a * b) % d) * c % d)); } }
Markdown
UTF-8
2,216
2.828125
3
[ "MIT" ]
permissive
# chetcd Config-helpers for etcd. The aim is to have some common etcd-client use cases wrapper in an elegant API. ## Dir watcher A dir watcher will simply watch a (directory) key recursively. We can attach key observers to receive these changes via native golang channels. A typical usage would be if we have a directory for all our config values of the application. We want to watch all those config values and react on them to update our live instance. ### Quick Start #### Source `go get -u github.com/coreos/etcd` `go get -u github.com/francoishill/chetcd` #### Usage ``` package main import ( "fmt" "github.com/coreos/etcd/client" "github.com/francoishill/chetcd" "log" "time" ) func main() { cfg := client.Config{ Endpoints: []string{"http://127.0.0.1:2379"}, Transport: client.DefaultTransport, HeaderTimeoutPerRequest: time.Second, // set timeout per request to fail fast when the target endpoint is unavailable } c, err := client.New(cfg) if err != nil { log.Fatal(err) } keysAPI := client.NewKeysAPI(c) foodirWatcher := chetcd.NewDirWatcher(keysAPI, "/foodir") bar1ConfigValue, err := foodirWatcher.GetObservedConfigValue("/bar1") if err != nil { log.Fatal(err) } bar2ConfigValue, err := foodirWatcher.GetObservedConfigValue("/bar2") if err != nil { log.Fatal(err) } go func() { for { select { case b1 := <-bar1ConfigValue.ChangesChannel(): fmt.Printf("Bar 1 changed from '%s' to '%s'\n", b1.OldNode.Value, b1.NewNode.Value) break case b2 := <-bar2ConfigValue.ChangesChannel(): fmt.Printf("Bar 2 changed from '%s' to '%s'\n", b2.OldNode.Value, b2.NewNode.Value) break } } }() //The delay to wait when we receive `watcher.Next()` errors. This could be because the etcd server is down. delayOnError := 30 * time.Second errChan := foodirWatcher.WatchDir(delayOnError) for er := range errChan { fmt.Printf("DIR WATCH ERROR: %s, watcher: %q\n", er.Error(), foodirWatcher) } } ```
Java
UTF-8
725
2.28125
2
[]
no_license
package br.com.michelmilezzi.DemoApp.domain; import java.math.BigDecimal; import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class OperacoesMatematicasTests { @Test public void somaTests() { BigDecimal vl1 = (BigDecimal.valueOf(5)); BigDecimal vl2 = (BigDecimal.valueOf(10)); BigDecimal vl3 = (BigDecimal.valueOf(15)); Assertions.assertThat(OperacoesMatematicas.somar(vl1, vl2, vl3)) .isEqualByComparingTo(BigDecimal.valueOf(30)); } }
Markdown
UTF-8
9,113
2.59375
3
[ "MIT" ]
permissive
--- layout: post title: Password strength with NLP date: 2016-11-13 14:27:25 categories: Metis --- **Latent Semantic Analysis re-imagined** [Account takeover](http://www.darkreading.com/endpoint/anatomy-of-an-account-takeover-attack/a/d-id/1324409) attacks are [incredibly lucrative](http://www.trendmicro.com/cloud-content/us/pdfs/security-intelligence/white-papers/wp-follow-the-data.pdf) for criminals. The average stolen credit card can be bought and sold on the dark web for pennies, while compromised accounts fetch $3-$20 each depending upon what is accessible through them. Additionally the extent of possible damage to the victim is far greater; accounts can be drained, identities stolen personal data scrapped, the list goes on. Firms have conflicting incentives when it comes to pushing strength. Any friction in the customer acquisition pipeline is universally abhorred, and as is the case, there is a real resistance to implementing strong measures. At the same time, High profile account takeovers, are incredibly damaging to a firms reputation, not to mention bottom line, as fraudulent attacks from a previously trusted source are next to impossible to prevent. The *fine line* balancing act present in everything related to security and fraud prevention is certainly in full force here. **Going further:** Another thing that can be harmful to websites or companies is "*throwawawy accounts*". Depending upon the industry these accounts can be high risk for fraudulent, or otherwise undesirable activity. Passwords can provide a unique and candid view of a user that may differ from what is provided in the visible fields. Being able to capture this signal without compromising on security is valuable for detecting anomalies in your order stream or accounts that you may want to be wary of. Some of these techniques are already commonly employed on username and email as discussed [here.](https://simility.com/quantifying-insight-data-scientists-translate-hunch-probability-identify-potential-email-fraud/) **Problem:** Password strength is pretty universally bad. Passwords that are difficult to crack are difficult to remember, just as passwords that are easy to remember are easy to crack. I'm setting out to build a novel method for quantifying strength in a password utilizing an approach rooted in Natural language processing. **Data:** I am utilizing a dataset which includes 10 million username password combinations which were scrapped from various high profile data leaks shared on various paste sites. For now I am focusing on just passwords, however future iterations can apply these same techniques to a username password pair, in an effort to strengthen the combination. ### Process: **Data cleaning:** Passwords are ranked by the frequency at which they occur within the dataset. Which is assumed to be representative of what will be encountered in a live use case. The passwords which represent 50% of the accounts within the set are selected as our 'common passwords'. This leaves us with 30,000 passwords, with 10 million initial observations, the fact that 50% of the unique passwords is a 99.7% decrease in the size of the dataset highlights just how bad passwords are, and why it is that cracking tools are effective. **NLP Processing:** Our passwords are then transformed into a vector space utilizing [TFIDF](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) to split them up into their 15,000 most common 1,2,3,and 4 grams. We then perform dimensionality reduction with [LSI](https://en.wikipedia.org/wiki/Latent_semantic_analysis) so as to create a 500 dimension common password vector space. This space is saved as a model, and a querying pipeline is put into place for future testing. When a potential password is queried, It goes through the same steps as the original password sets, It is processed through TFIDF, we convert it into the same vector space using an LSI transform, and the cosine distance is calculated for the resulting 1x500 vector. The results are sorted in descending order and the top 25 are selected. For each selected similar password, it's degree of similarity, and it's frequency in the original dataset is used to scale the entropy score of the password. **Content based metrics:** I didn't stop at similarity. One thing that I have noticed in going through these sets is that people like to use rows of keys as they appear on the keyboard. Many of the top most common passwords in the dataset contain this type of pattern. Now the LSI model will do a pretty good job of decrementing the score when this is present, I wanted to further boost this effect for a couple of reasons. * It's a lazy way of creating a "strong" password (in the eyes of most available plug-ins) * It's indicative of throwaway accounts. As I mentioned above, passwords can be used as signal when it comes to identifying fraudulent or otherwise less than ideal activity, the obvious risk to this is that you don't want to reveal the plain text passwords to anyone, including your fraud analyst. Capturing aggregate metrics like keyboard distance allows you to save the signal in a way that's not susceptible to reverse engineering. In order to do this I built arrays representing the location of each key on a standard qwerty keyboard, and created a Euclidean distance function to return how far each character is from it's neighbors. A median score is then generated for the password as a whole. With relatively few exceptions, this works well in distinguishing content rich passwords from those trying to hack the password policy requirements. Again this is used to scale the baseline entropy score. Here is a diagram for how data flows through my system: ![image](/images/dataFlowNLP.png) ### Testing: 1. A user inputs a password to test. 2. That password has it's baseline entropy calculated. 3. The password is converted into the LSI test space and has it's similarity entropy scaler returned. 4. The password has it's euclidean keyboard distance processed, and an entropy scaler is returned. 5. The password has some content and character ratios checked which return their own entropy scalers. 6. All entropy scalers are applied to the original baseline entropy, and from that a relative score out of 250 is returned. 7. Any weak points within the password are reported back to the user to guide them in creating more secure passwords. ![image](/images/password.png) ### Future steps: * Benchmarking against the existing plug-ins, such as: * [The Password Meter](http://www.passwordmeter.com/) * [ Bootstrap JQuery](http://scripts.jakweb.ch/pi/) * [Javascript password meter](http://archive.geekwisdom.com/dyn/passwdmeter.html) * [Rich password widget](http://www.html-form-guide.com/demos/password-widget/sample-reg-form.php) * [jQuery Complexify](https://danpalmer.me/jquery-complexify) * [Beautiful Password strength meter](http://demo.tutorialzine.com/2012/06/beautiful-password-strength-indicator/) * Benchmarking against existing password [Cracking software](http://sectools.org/tag/pass-audit/) * This will hopefully identify weaknesses to my approach * Expand upon the existing password database to build a more complete 'common' list. * There are many existing word lists available such as [this](https://wiki.skullsecurity.org/Passwords) which power many of the password cracking tools out there. Adding those within our LSI space should increase accuracy. * Build in similarity metrics for username as well. It's yet unclear if username can be used to predict password, although I would hypothesize it can. With a little testing this could be determined, and if we reject the Null, this kind of functionality could be added, as username is something that would likely be known in an attack scenario. * Work towards making it more performant. * Once the ground truth that we'll get out of the benchmarking is known, we can begin making adjustments to the size and scope of the vector space we're using, this should go a long way in making the tool lighter weight. * Code cleanup and packaging for easy implementation and added flexibility and tuning. ### Conclusions: I'm quite pleased with the results I'm able to achieve with this tool. I've never seen an NLP approach to building stronger passwords, and for a week and a half's worth of work, the product I made shows good viability. I'm fascinated by this space, and the challenges surrounding nailing good balance on that thin line between security and ease of use. Password related metrics are underutilized in the fraud detection space in my opinion, and I believe this goes a long way in building a good solution to maintain both security and signal. There's still work to be done, but I'm very pleased with the results. **Update 03.28.17**: I've added to and refactored this project, most important addition is a method for extracting secure features from a password prior to encryption for fraud analysis. Take a look at the [project repository](https://github.com/kmix27/LsiPasswordStrength) for more.
Java
UTF-8
1,545
3.515625
4
[]
no_license
package Pieces; import Chess.Move; import Chess.Player; /*********************************************************************** * This Class handles all operations for the queen chess piece * @author Troy Madsen and Grant Postma * @version 1.0 **********************************************************************/ public class Queen extends ChessPiece { /******************************************************************* * This is the Constructor for the Queen * * @param player the player this piece belongs too ******************************************************************/ public Queen(Player player) { super(player); } /******************************************************************* * returns the type of this piece * * @return whatever the name of the piece is ******************************************************************/ @Override public String type() { return "Queen"; } /******************************************************************* * Checks if attempted move is valid for this piece * * @param move the attempted move * @param board the board the piece exists on * * @return whether or not the piece can perform this move ******************************************************************/ @Override public boolean isValidMove(Move move, IChessPiece[][] board) { if ((new Rook(owner)).isValidMove(move, board) || (new Bishop(owner)).isValidMove(move, board)) return true; return false; } }
C++
UTF-8
299
2.609375
3
[]
no_license
#include <math.h> double sum() { float e=1e-4; float rez = 0; float si = 0; int k = 0; int sign = 1; do { k++; si = 1./(k * k * k); rez += sign*si; sign *= -1; } while (si >= e); double a = round(rez*10000)/10000; return a; }
C
GB18030
1,522
3.5
4
[]
no_license
/* 룺10 1 7 5 10 13 15 10 5 16 8 7 迪ʼҡ start=begin x=1Ȼ 17 start=up x=2 75½ start=down x=3 510 start=up x=4 1013ޱ仯 1315ޱ仯 510½ start=down x=5 105½ޱ仯 516 start=up x=6 168½ start=down x=7 */ #include<stdio.h> int main() { int i,n; printf("Ԫظ"); scanf("%d",&n); int a[n]; printf(""); for(i=0;i<n;i++) { scanf("%d",&a[i]); } int begin=0,up=1,down=-1; int x=1; //ӵ2ʼ int start=begin; for(i=1;i<n;i++) { switch(start) { case 0: if(a[i-1]<a[i]) { start=up; x++; } else if(a[i-1]>a[i]) { start=down; x++; }; break; case 1: if(a[i-1]>a[i]) { start=down; x++; } break; case -1: if(a[i-1]<a[i]) { start=up; x++; } break; } } printf("ҡиΪ%d",x); return 0; }
C++
GB18030
938
3.515625
4
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> //һһʱ临ӶΪO(n), ռ临ӶΪO(1)㷨жǷΪĽṹ //һͷָA뷵һboolֵǷΪĽṹ֤Сڵ900 struct ListNode { int val; struct ListNode *next; }; bool chkPalindrome(ListNode* A) { ListNode* fast, *slow; if (A == NULL || A->next == NULL) { return true; } fast = slow = A; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; } fast = slow->next; ListNode* cur = fast->next; while (cur) { ListNode* next = cur->next; cur->next = fast; slow->next = cur; fast->next = NULL; fast = cur; cur = next; } slow = A; while (fast) { if (fast->val != slow->val) { return false; } fast = fast->next; slow = slow->next; } return true; }
C#
UTF-8
725
3.4375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fizzBuzz { class Program { static void Main(string[] args) { //challenge input FizzBuzz(20); FizzBuzz(100); } /// <summary> /// Fizz Buzz /// </summary> public static void FizzBuzz(int limit) { for(int i = 1; i <= limit; i++) { if(i % 3 == 0 || i % 5 == 0) { Console.WriteLine(i % 15 == 0 ? "FizzBuzz" : (i % 3 == 0 ? "Fizz" : "Buzz")); continue; } Console.WriteLine(i); } } } }
Java
UTF-8
238
2.390625
2
[]
no_license
package izgledaplikacije; public class Global{ private static int index = 0; public static int getVar(){ return Global.index; } public static void setVar(int var){ Global.index = var; } }
C#
IBM852
2,955
2.65625
3
[]
no_license
using System; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using System.Threading; using GHIElectronics.NETMF.FEZ; using GHIElectronics.NETMF.Hardware; namespace ChickenCoopAutomation { /// <summary> /// Allows to receive infrared data using a receiver like TSOP312 /// </summary> public class InfraredReceiver : IDisposable { #region Delegates public delegate void InfraredDataHandler(object sender, uint[] _pulseWidths, int _pulseCount); #endregion /// <summary> /// Minimum number of pulses (high or low) that must occur in order to generate DataReceived event /// </summary> public const int MinPulseCount = 20; /// <summary> /// Maximum number of pulses (high or low) that can occur in one data packet /// </summary> public const int MaxPulseCount = 255; /// <summary> /// Received data is considered complete if this time (ms) has elapsed and no more pulses were received. /// </summary> public const int ReceiveTimeout = 10; private readonly Timer _notifyDataReceivedTimer; private readonly InterruptPort _infraredPort; private DateTime _lastInterruptTime; private uint[] _pulseWidths; private int _pulseCount; public InfraredReceiver(Cpu.Pin infraredReceiverPin) { _infraredPort = new InterruptPort(infraredReceiverPin, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth); _infraredPort.OnInterrupt += OnInfraredInterrupt; _lastInterruptTime = DateTime.Now; _pulseWidths = new uint[MaxPulseCount]; _notifyDataReceivedTimer = new Timer(NotifyDataReceived, null, int.MaxValue, 0); } public event InfraredDataHandler DataReceived = delegate { }; private void OnInfraredInterrupt(uint data1, uint data2, DateTime time) { var pulseWidth = (int)time.Subtract(_lastInterruptTime).Ticks / 10; // s _lastInterruptTime = time; _notifyDataReceivedTimer.Change(ReceiveTimeout, 0); // first interrupt of a new data packet - pulseWidth cannot be calculated if (data2 == 0 && _pulseCount <= 0) return; if (_pulseCount < MaxPulseCount) { _pulseWidths[_pulseCount] = (uint)pulseWidth; _pulseCount++; } } private void NotifyDataReceived(object state) { if (_pulseCount >= MinPulseCount) { DataReceived(this, _pulseWidths, _pulseCount); } _pulseCount = 0; _pulseWidths = new uint[MaxPulseCount]; } #region IDisposable Members public void Dispose() { _infraredPort.ClearInterrupt(); _infraredPort.Dispose(); } #endregion } }
C
UTF-8
1,019
2.53125
3
[]
no_license
/* This example project demonstrates the usage of the AVR ADC noise reduction. The project is based on the ATMega324PB Xplained Pro. */ #include <asf.h> #include <avr/sleep.h> #define NOISE_REDUCTION 1 volatile uint8_t adc_buffer_count; volatile uint16_t adc_buffer[100]; ISR(ADC_vect) { adc_buffer[adc_buffer_count++] = ADC; #if !NOISE_REDUCTION ADCSRA |= 1 << ADSC; #endif } static void adc_init(void) { /* Internal 1v1 as ref */ ADMUX = 0 << REFS1 | 1 << REFS0 | 1 << MUX1 | 1 << MUX2 | 1 << MUX3 | 1 << MUX4; /* Enable ADC and interrupt. Set prescaler to 64 */ ADCSRA = 1 << ADEN | 1 << ADIE | 1 << ADPS2 | 1 << ADPS1 | 0 << ADPS0; /* Disable the digital input on the pin */ DIDR0 = 1 << ADC1D; } int main (void) { board_init(); set_sleep_mode(SLEEP_MODE_ADC); adc_init(); sleep_enable(); sei(); #if !NOISE_REDUCTION ADCSRA |= 1 << ADSC; #endif while(1) { #if NOISE_REDUCTION sleep_cpu(); #endif if (adc_buffer_count >= sizeof(adc_buffer)/2) { adc_buffer_count = 0; } } }
C
UTF-8
347
3.703125
4
[]
no_license
#include <stdio.h> int main(int argc, char *argv[]) { int n, i, resto; do { printf("Inserisci un numero > 1 : "); scanf("%d", &n); } while (n < 2); i = n - 1; do { resto = n % i; if (resto == 0) { printf("Il numero non è primo\n"); return 0; } i = i - 1; } while (i > 1); printf("Numero Primo\n"); return 0; }
C#
UTF-8
1,556
2.6875
3
[]
no_license
using System; using System.ComponentModel.DataAnnotations; namespace DigitalCoolBook.App.Models.TeacherViewModels { public class TeacherRegisterModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Required] [Display(Name="Confirm Password")] [DataType(DataType.Password)] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Required] [StringLength(50, ErrorMessage = "Name must be between 3 and 50 characters!", MinimumLength = 3)] public string Name { get; set; } [Required] [Display(Name = "Date of Birth")] public DateTime DateOfBirth { get; set; } [Required] [Display(Name = "Place of Birth")] [StringLength(100, ErrorMessage = "Must be between 3 and 100 characters!", MinimumLength = 3)] public string PlaceOfBirth { get; set; } [StringLength(20, ErrorMessage = "Must be between 3 and 20 characters!", MinimumLength = 1)] public string Sex { get; set; } [Display(Name = "Mobile Phone")] public int? MobilePhone { get; set; } [Required] public int Telephone { get; set; } [StringLength(50, ErrorMessage = "Username must be between 3 and 50 characters!", MinimumLength = 3)] public string Username { get; set; } } }
Ruby
UTF-8
1,785
3.765625
4
[]
no_license
require_relative './ai_player' class Game # ::deal_in_players is a factory method that: # 1) Takes in an array of cards # 2) deals cards in an alternating pattern & creates 2 AIPlayers # 3) return instance of Game def self.deal_in_players(deck) deck = [] deck2 =[] deck1 = true Card.all_cards.each do |card| if deck1 deck << card deck1 = false else deck2 << card deck1 = true end end Game.new(AIPlayer.new(deck),AIPlayer.new(deck2)) end def initialize(player1, player2) @player1 = player1 @player2 = player2 end # call do_battle until game is over def play unless @player1.out_of_cards? || @player2.out_of_cards? do_battle end end # 1. Players each take their top card # 2. If the cards' rank is the same, first, take an additional card # prisoner from each player. Then, repeat #do_battle. # 3. If the last drawn cards are different ranks, all the cards drawn in # this round are awarded to the drawer of the higher ranked card. def do_battle(prisoners = []) raise OutOfCardsError if @player1.out_of_cards? raise OutOfCardsError if @player2.out_of_cards? player1_card = @player1.take_card player2_card = @player2.take_card case player1_card<=> player2_card when 1 @player1.give_won_cards([player1_card, player2_card]) when 0 do_battle([player1_card, player2_card]) when -1 @player2.give_won_cards([player1_card, player2_card]) # end #@player2.give_won_cards([player1_card, player2_card]) end # if either of the players has run out of cards, the game is over def game_over? return true if @player1.out_of_cards? return true if @player2.out_of_cards? end end
Java
UTF-8
4,057
2.046875
2
[]
no_license
package com.android.audiorecorder.ui.activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.android.audiorecorder.R; import com.android.audiorecorder.dao.PersonalNewsDao; import com.android.audiorecorder.ui.data.req.PersonalAddNewsReq; import com.android.audiorecorder.ui.manager.HisPersonalCenterManager; import com.android.audiorecorder.utils.ActivityUtil; import com.android.library.ui.activity.BaseCompatActivity; import com.android.library.ui.utils.ToastUtils; import com.android.library.ui.view.RoundImageView; public class HisPersonalAddNewActivity extends BaseCompatActivity { private HisPersonalCenterManager mHisPersonalCenterManager; private RoundImageView ivHeaderIcon; private EditText mMessageEditText; private int whatAddNews; private int mUserId; private TextView mOptionTextView; private int mInputLength = 0; private String TAG = "HisPersonalCenterActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_his_personal_center_add_new); setActionBarBackground(R.drawable.lib_drawable_common_actionbar_background); setTitle(R.string.personal_center_add_new_message_title); initUI(); mHisPersonalCenterManager = new HisPersonalCenterManager(this); } @Override protected boolean initIntent() { mUserId = getIntent().getIntExtra(ActivityUtil.USER_ID, 0); if (mUserId <=0) { return false; } return true; } @Override protected boolean onHandleBiz(int what, int result, Object obj) { if (what == whatAddNews) { switch (result) { case HisPersonalCenterManager.RESULT_SUCCESS: PersonalNewsDao newsDao = new PersonalNewsDao(); PersonalAddNewsReq req = new PersonalAddNewsReq(); req.userId = mUserId; req.newsType = 0; req.newsContent = mMessageEditText.getText().toString(); newsDao.insertNewPersonalNews(activity, req); HisPersonalAddNewActivity.this.finish(); break; default: return false; } } return true; } private void initUI() { mMessageEditText = (EditText) findViewById(R.id.his_personal_center_add_new_message); mMessageEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { mInputLength = arg0.length(); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable editable) { if(mInputLength <=0) { if(mOptionTextView != null){ mOptionTextView.setEnabled(false); } } else { if(mOptionTextView != null){ mOptionTextView.setEnabled(true); } } } }); } @Override protected void setOptionView(TextView option) { option.setText(R.string.personal_center_add_new_message_submit); option.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String content = mMessageEditText.getText().toString(); if(content.length() ==0){ ToastUtils.showToast(R.string.personal_center_add_none_message); return ; } showWaitingDlg(); whatAddNews = mHisPersonalCenterManager.addPersonalNews(mUserId, 0, content, ""); } }); mOptionTextView = option; if(mInputLength==0){ option.setEnabled(false); } } @Override protected void onDestroy() { super.onDestroy(); hideWaitingDialog(); } }
C++
UTF-8
333
3
3
[]
no_license
/* isalpha example */ #include <stdio.h> #include <ctype.h> #include<conio.h> int main () { int i=0; char str[]="C++"; while (str[i]) { if (isalpha(str[i])) printf ("character %c is alphabetic\n",str[i]); else printf ("character %c is not alphabetic\n",str[i]); i++; } getch(); return 0; }
Python
UTF-8
6,555
2.515625
3
[]
no_license
from flask import Flask, render_template, request, redirect, url_for, session from flask_mysqldb import MySQL import MySQLdb.cursors import pymysql.cursors import os import re def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] = 'db_flask' mysql = MySQL(app) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # a simple page that says hello @app.route('/') @app.route('/', methods =['GET', 'POST']) def login(): msg = '' if request.method == 'POST' and 'username' in request.form and 'password' in request.form: username = request.form['username'] password = request.form['password'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM user WHERE username = % s AND password = % s', (username, password, )) account = cursor.fetchone() if account: session['loggedin'] = True session['id'] = account['id'] session['username'] = account['username'] msg = 'Logged in successfully !' # return render_template('index.html', msg = msg) return redirect(url_for('index')) else: msg = 'Incorrect username / password !' return render_template('login.html', msg = msg) @app.route('/logout') def logout(): session.pop('loggedin', None) session.pop('id', None) session.pop('username', None) return redirect(url_for('login')) @app.route('/register', methods =['GET', 'POST']) def register(): msg = '' if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form : username = request.form['username'] password = request.form['password'] email = request.form['email'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM user WHERE username = % s', (username, )) account = cursor.fetchone() if account: msg = 'Account already exists !' elif not re.match(r'[^@]+@[^@]+\.[^@]+', email): msg = 'Invalid email address !' elif not re.match(r'[A-Za-z0-9]+', username): msg = 'Username must contain only characters and numbers !' elif not username or not password or not email: msg = 'Please fill out the form !' else: cursor.execute('INSERT INTO user VALUES (NULL, % s, % s, % s)', (username, email, password, )) mysql.connection.commit() msg = 'You have successfully registered !' elif request.method == 'POST': msg = 'Please fill out the form !' return render_template('register.html', msg = msg) conn = cursor = None #fungsi koneksi database def openDb(): global conn, cursor conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='db_flask') cursor = conn.cursor() #fungsi untuk menutup koneksi def closeDb(): global conn, cursor cursor.close() conn.close() #fungsi view index() untuk menampilkan data dari database @app.route('/barang') def index(): openDb() container = [] sql = "SELECT * FROM barang" cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute(sql) results = cursor.fetchall() for data in results: container.append(data) closeDb() return render_template('index.html', container=container,) #fungsi view tambah() untuk membuat form tambah @app.route('/tambah', methods=['GET', 'POST']) def tambah(): if request.method == 'POST': nama = request.form['nama'] # nama = int(nama) print(nama, request.form['nama']) harga = re.sub("\D", '', request.form['harga']) stok = request.form['stok'] openDb() sql = "INSERT INTO barang (nama_barang, harga, stok) VALUES (%s, %s, %s)" val = (nama, harga, stok) cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute(sql, val) # conn.commit() mysql.connection.commit() closeDb() return redirect(url_for('index')) else: return render_template('tambah.html') #fungsi view edit() untuk form edit @app.route('/edit/<id_barang>', methods=['GET', 'POST']) def edit(id_barang): openDb() cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM barang WHERE id_barang=%s', [id_barang]) data = cursor.fetchone() if request.method == 'POST': id_barang = request.form['id_barang'] nama = request.form['nama'] harga = re.sub("\D", '', request.form['harga']) stok = request.form['stok'] sql = "UPDATE barang SET nama_barang=%s, harga=%s, stok=%s WHERE id_barang=%s" val = (nama, harga, stok, id_barang) cursor.execute(sql, val) # conn.commit() mysql.connection.commit() closeDb() return redirect(url_for('index')) else: closeDb() return render_template('edit.html', data=data) #fungsi untuk menghapus data @app.route('/hapus/<id_barang>', methods=['GET', 'POST']) def hapus(id_barang): openDb() cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('DELETE FROM barang WHERE id_barang=%s', [id_barang]) # conn.commit() mysql.connection.commit() closeDb() return redirect(url_for('index')) return app
Shell
UTF-8
186
3.40625
3
[]
no_license
#!/bin/bash user_exist() { for i in `more -1 /etc/passwd` do var1=$i var2=${var1%%\:*} if [ $var2==$1 ] then echo "The User Exists..!" exit fi done echo "No User Found..!!" } user_exist
Java
UTF-8
1,152
2.234375
2
[]
no_license
package com.backend.cash.controller; import com.backend.cash.model.User; import com.backend.cash.modelDTO.UserDTO; import com.backend.cash.service.interfaces.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping("/users") public class UserController { @Autowired private IUserService userService; @PostMapping("/") public ResponseEntity<?> save(@Valid @RequestBody User user){ UserDTO userDTO = userService.userSave(user); return new ResponseEntity(userDTO, HttpStatus.CREATED); } @GetMapping("/{id}") public ResponseEntity<User> getId(@PathVariable Long id){ UserDTO userDTO = userService.findById(id); return new ResponseEntity(userDTO, HttpStatus.OK); } @DeleteMapping("/delete/{id}") public ResponseEntity<User> deleteId(@PathVariable Long id){ userService.deleteById(id); return new ResponseEntity(HttpStatus.OK); } }
Java
UTF-8
53,740
1.929688
2
[]
no_license
package org.javenstudio.cocoka.graphics; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuffXfermode; import android.graphics.Shader; import android.graphics.Xfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Bitmap.CompressFormat; import android.graphics.PorterDuff.Mode; import android.graphics.Shader.TileMode; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.FloatMath; import org.javenstudio.cocoka.util.ApiHelper; import org.javenstudio.cocoka.util.BitmapHelper; import org.javenstudio.cocoka.util.BitmapHolder; import org.javenstudio.cocoka.util.BitmapPool; import org.javenstudio.cocoka.util.BitmapRef; import org.javenstudio.cocoka.util.Utilities; import org.javenstudio.cocoka.util.Utils; import org.javenstudio.cocoka.worker.job.JobCancelListener; import org.javenstudio.cocoka.worker.job.JobContext; import org.javenstudio.common.util.Logger; public class BitmapUtil { private static final Logger LOG = Logger.getLogger(BitmapUtil.class); //private static final boolean DEBUG = BaseDrawable.DEBUG; public static final int HDPI_THUMB_ICON_WIDTH = 120; public static final int HDPI_THUMB_ICON_HEIGHT = 120; public static final int HDPI_THUMB_STROCKWIDTH = 2; public static final float HDPI_THUMB_ICON_SCALE = 0.96f; public static final float HDPI_PREVIEW_BITMAP_SCALE = 0.85f; public static final int HDPI_SMALL_PREVIEW_WIDTH = 128; public static final int HDPI_SMALL_PREVIEW_HEIGHT = 128; public static final int THUMB_BACKGROUND_ALPHA = 128; public static final int THUMB_BAACKGROUND = Color.BLACK; //Color.WHITE; // Rotates the bitmap by the specified degree. // If a new bitmap is created, the original bitmap is recycled. public static BitmapRef rotate(BitmapHolder holder, BitmapRef b, int degrees) { if (degrees != 0 && b != null) { Matrix m = new Matrix(); m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2); try { BitmapRef b2 = BitmapRef.createBitmap(holder, b, 0, 0, b.getWidth(), b.getHeight(), m, true); if (b2 != null && b != b2) { b.recycle(); b = b2; } } catch (OutOfMemoryError ex) { // We have no memory to rotate. Return the original bitmap. Utilities.handleOOM(ex); } } return b; } public static BitmapRef rotateBitmap(BitmapHolder holder, BitmapRef source, int rotation, boolean recycle) { if (rotation == 0) return source; int w = source.getWidth(); int h = source.getHeight(); Matrix m = new Matrix(); m.postRotate(rotation); BitmapRef bitmap = BitmapRef.createBitmap(holder, source, 0, 0, w, h, m, true); if (recycle) source.recycle(); return bitmap; } public static BitmapRef createBitmap(BitmapHolder holder, byte[] data) { if (holder == null || data == null || data.length == 0) return null; try { BitmapRef bitmap = BitmapRef.decodeByteArray(holder, data, 0, data.length); if (bitmap != null) { bitmap.setDensity(Utilities.getDensityDpi(holder.getContext())); //BitmapRefs.onBitmapCreated(bitmap); } //Bitmap newbitmap = createScaledBitmap(bitmap, context, 120, 150); //if (newbitmap != bitmap && bitmap != null) // bitmap.recycle(); return bitmap; } catch (OutOfMemoryError ex) { Utilities.handleOOM(ex); return null; } } public static BitmapRef createBitmap(BitmapHolder holder, InputStream is) { if (holder == null || is == null) return null; try { long length = is.available(); float scale = (float)length / (512 * 1024); BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; if (scale > 1.5f) opt.inSampleSize = (int)(scale + 0.5f); BitmapRef bitmap = BitmapRef.decodeStream(holder, is, null, opt); if (bitmap != null) { bitmap.setDensity(Utilities.getDensityDpi(holder.getContext())); //BitmapRefs.onBitmapCreated(bitmap); } return bitmap; } catch (IOException ex) { if (LOG.isErrorEnabled()) LOG.error("createBitmap error: " + ex.toString(), ex); return null; } catch (OutOfMemoryError ex) { Utilities.handleOOM(ex); return null; } } public static BitmapRef createBitmap(BitmapHolder holder, Drawable d) { return createBitmap(holder, d, 0, 0); } public static BitmapRef createBitmap(BitmapHolder holder, Drawable d, int width, int height) { if (holder == null || d == null) return null; try { int bitmapWidth = width <= 0 ? d.getIntrinsicWidth() : width; int bitmapHeight = height <= 0 ? d.getIntrinsicHeight() : height; final BitmapRef output = BitmapRef.createBitmap(holder, bitmapWidth, bitmapHeight); if (output == null) return null; final Canvas canvas = new Canvas(output.get()); final Rect savedRect = d.getBounds(); d.setBounds(0, 0, bitmapWidth, bitmapHeight); d.draw(canvas); d.setBounds(savedRect); //BitmapRefs.onBitmapCreated(output); return output; } catch (OutOfMemoryError ex) { Utilities.handleOOM(ex); return null; } } public static BitmapRef createThumbBitmap(BitmapHolder holder, BitmapRef bitmap) { int color = Color.TRANSPARENT; //THUMB_BAACKGROUND; //color = Color.argb(THUMB_BACKGROUND_ALPHA, Color.red(color), Color.green(color), Color.blue(color)); return createThumbBitmap(holder, bitmap, color); } public static BitmapRef createThumbBitmap(BitmapHolder holder, BitmapRef bitmap, int color) { if (holder == null || bitmap == null) return null; final int thumbWidth = Utilities.getDisplaySize( holder.getContext(), HDPI_THUMB_ICON_WIDTH); final int thumbHeight = Utilities.getDisplaySize( holder.getContext(), HDPI_THUMB_ICON_HEIGHT); final int maxBitmapWidth = (int)(thumbWidth * HDPI_THUMB_ICON_SCALE); final int maxBitmapHeight = (int)(thumbHeight * HDPI_THUMB_ICON_SCALE); BitmapRef scaledBitmap = createRatioScaledBitmap(holder, bitmap, maxBitmapWidth, maxBitmapHeight); if (scaledBitmap == null) return bitmap; final int bitmapWidth = scaledBitmap.getWidth(); final int bitmapHeight = scaledBitmap.getHeight(); if (thumbWidth <= bitmapWidth || thumbHeight <= bitmapHeight) return scaledBitmap; BitmapRef thumb = scaledBitmap; try { final int strockWidth = HDPI_THUMB_STROCKWIDTH; final float bitmapLeft = (float)(thumbWidth - bitmapWidth) / 2.0f; final float bitmapTop = (float)(thumbHeight - bitmapHeight) / 2.0f; final float left = bitmapLeft - strockWidth; final float right = bitmapLeft + bitmapWidth + strockWidth; final float top = bitmapTop - strockWidth; final float bottom = bitmapTop + bitmapHeight + strockWidth; BitmapRef thumbTmp = BitmapRef.createBitmap(holder, thumbWidth, thumbHeight, Bitmap.Config.ARGB_4444); if (thumbTmp == null) return thumb; Canvas canvas = new Canvas(thumbTmp.get()); Paint paint = new Paint(); canvas.drawColor(color); paint.setColor(Color.DKGRAY); paint.setStyle(Paint.Style.FILL); //canvas.drawRoundRect(new RectF(left, top, right, bottom), 2, 2, paint); canvas.drawRect(left, top, right, bottom, paint); canvas.drawBitmap(scaledBitmap.get(), bitmapLeft, bitmapTop, paint); thumb = thumbTmp; thumb.setDensity(bitmap.getDensity()); //BitmapRefs.onBitmapCreated(thumb); if (scaledBitmap != bitmap && scaledBitmap != null) scaledBitmap.recycle(); } catch (OutOfMemoryError ex) { Utilities.handleOOM(ex); } return thumb; } public static BitmapRef createSmallBitmap(BitmapHolder holder, BitmapRef bitmap) { if (holder == null || bitmap == null) return null; final int thumbWidth = Utilities.getDisplaySize( holder.getContext(), HDPI_SMALL_PREVIEW_WIDTH); final int thumbHeight = Utilities.getDisplaySize( holder.getContext(), HDPI_SMALL_PREVIEW_HEIGHT); final int maxBitmapWidth = (int)(thumbWidth); final int maxBitmapHeight = (int)(thumbHeight); BitmapRef scaledBitmap = createRatioScaledBitmap(holder, bitmap, maxBitmapWidth, maxBitmapHeight); if (scaledBitmap == null) return bitmap; return scaledBitmap; } public static BitmapRef createPreviewBitmap(BitmapHolder holder, byte[] data) { BitmapRef bitmap = createBitmap(holder, data); return createPreviewBitmap(holder, bitmap); } public static BitmapRef createPreviewBitmap(BitmapHolder holder, InputStream is) { BitmapRef bitmap = createBitmap(holder, is); return createPreviewBitmap(holder, bitmap); } public static BitmapRef createPreviewBitmap(BitmapHolder holder, BitmapRef bitmap) { final int screenWidth = Utilities.getScreenWidth(holder.getContext()); final int screenHeight = Utilities.getScreenHeight(holder.getContext()); final int maxScaleWidth = (int)((float)screenWidth * HDPI_PREVIEW_BITMAP_SCALE); final int maxScaleHeight = (int)((float)screenHeight * HDPI_PREVIEW_BITMAP_SCALE); final int maxWidth = maxScaleWidth < maxScaleHeight ? maxScaleWidth : maxScaleHeight; final int maxHeight = maxWidth; return createPreviewBitmap(holder, bitmap, maxWidth, maxHeight); } public static BitmapRef createPreviewBitmap(BitmapHolder holder, BitmapRef bitmap, int maxWidth, int maxHeight) { if (holder == null || bitmap == null) return bitmap; //Bitmap savedBitmap = bitmap; bitmap = createRatioScaledBitmap(holder, bitmap, maxWidth, maxHeight); //if (savedBitmap != bitmap && savedBitmap != null) // savedBitmap.recycle(); return bitmap; } public static BitmapRef createRatioScaledBitmap(BitmapHolder holder, BitmapRef bitmap, int maxWidth, int maxHeight) { if (holder == null || bitmap == null) return bitmap; //Bitmap savedBitmap = bitmap; int bitmapWidth = bitmap.getWidth(); int bitmapHeight = bitmap.getHeight(); int width = -1, height = -1; if (bitmapWidth > maxWidth || bitmapHeight > maxHeight) { float bitmapRate = (float)bitmapWidth / (float)bitmapHeight; int width1 = maxWidth; int height1 = (int)(width1 / bitmapRate); int height2 = maxHeight; int width2 = (int)(height2 * bitmapRate); if (width1 <= maxWidth && height1 <= maxHeight) { width = width1; height = height1; } else { width = width2; height = height2; } } if (width > 0 && height > 0) bitmap = createScaledBitmap(holder, bitmap, width, height); return bitmap; } public static BitmapRef createScaledBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height) { return createScaledBitmap(holder, bitmap, width, height, 0, false); } public static BitmapRef createScaledBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int density) { return createScaledBitmap(holder, bitmap, width, height, density, false); } public static BitmapRef createScaledBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int density, boolean forceCreate) { return createScaledBitmap(holder, bitmap, width, height, density, FITTYPE_NONE, forceCreate); } public static BitmapRef createZoomOutScaledBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height) { return createScaledBitmap(holder, bitmap, width, height, 0, FITTYPE_ZOOMOUT, false); } public static BitmapRef createZoomOutScaledBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int density) { return createScaledBitmap(holder, bitmap, width, height, density, FITTYPE_ZOOMOUT, false); } public static BitmapRef createZoomInScaledBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height) { return createScaledBitmap(holder, bitmap, width, height, 0, FITTYPE_ZOOMIN, false); } public static BitmapRef createZoomInScaledBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int density) { return createScaledBitmap(holder, bitmap, width, height, density, FITTYPE_ZOOMIN, false); } public static int FITTYPE_NONE = 0; public static int FITTYPE_ZOOMOUT = 1; public static int FITTYPE_ZOOMIN = 2; public static BitmapRef createScaledBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int density, int fitType, boolean forceCreate) { if (bitmap == null || holder == null || width <= 0 || height <= 0) return forceCreate ? null : bitmap; int actualWidth = width; int actualHeight = height; int bitmapWidth = bitmap.getWidth(); int bitmapHeight = bitmap.getHeight(); int defaultDensity = bitmap.getDensity(); int targetDensity = density <= 0 ? defaultDensity : density; if (forceCreate == false && defaultDensity == targetDensity && actualWidth == bitmapWidth && actualHeight == bitmapHeight) return bitmap; //float scale = targetDensity / (float)defaultDensity; //if (targetDensity <= 0) // scale = 1.0f; //if (defaultDensity > 160) // bitmap by 160dpi? // scale *= (float) defaultDensity / 160.0f; if (fitType == FITTYPE_ZOOMOUT) { float actualRate = (float)actualWidth / (float)actualHeight; float bitmapRate = (float)bitmapWidth / (float)bitmapHeight; if (actualRate > bitmapRate) { actualWidth = (int)((float)actualHeight * bitmapRate); } else if (actualRate < bitmapRate) { actualHeight = (int)((float)actualWidth / bitmapRate); } } else if (fitType == FITTYPE_ZOOMIN) { float actualRate = (float)actualWidth / (float)actualHeight; float bitmapRate = (float)bitmapWidth / (float)bitmapHeight; if (actualRate < bitmapRate) { actualWidth = (int)((float)actualHeight * bitmapRate); } else if (actualRate > bitmapRate) { actualHeight = (int)((float)actualWidth / bitmapRate); } } try { BitmapRef endImage = BitmapRef.createScaledBitmap(holder, bitmap, actualWidth, actualHeight, true); if (endImage == null) return bitmap; if (targetDensity > 0) endImage.setDensity(targetDensity); //BitmapRefs.onBitmapCreated(endImage); return endImage; } catch (OutOfMemoryError e) { Utilities.handleOOM(e); return bitmap; } } public static BitmapRef createShaderBitmap(BitmapHolder holder, BitmapRef bitmap, int color) { if (bitmap == null || holder == null) return bitmap; int bitmapWidth = bitmap.getWidth(); int bitmapHeight = bitmap.getHeight(); int actualWidth = bitmapWidth; int actualHeight = bitmapHeight; int startX = 0; int startY = 0; actualWidth += startX * 2; actualHeight += startY * 2; BitmapRef original = createScaledBitmap(holder, bitmap, actualWidth, actualHeight, 0, true); if (original == null) return bitmap; Canvas canvas = new Canvas(original.get()); //canvas.setBitmap(original.get()); Paint paint = new Paint(); Shader saveShader = paint.getShader(); Xfermode saveMode = paint.getXfermode(); LinearGradient shader = new LinearGradient( actualWidth/2, 0, actualHeight/2, actualHeight, Color.argb(192, Color.red(color), Color.green(color), Color.blue(color)), Color.argb(128, Color.red(color), Color.green(color), Color.blue(color)), TileMode.CLAMP); paint.setShader(shader); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawRect(0, 0, actualWidth, actualHeight, paint); paint.setShader(saveShader); paint.setXfermode(saveMode); //canvas.drawBitmap(bitmap, startX, startY, paint); try { BitmapRef endImage = BitmapRef.createScaledBitmap(holder, original, actualWidth, actualHeight, true); if (endImage == null) return bitmap; endImage.setDensity(bitmap.getDensity()); //BitmapRefs.onBitmapCreated(endImage); if (original != bitmap) original.recycle(); return endImage; } catch (OutOfMemoryError e) { Utilities.handleOOM(e); return bitmap; } } public static BitmapRef createGrayBitmap(BitmapHolder holder, BitmapRef bitmap) { if (holder == null || bitmap == null) return bitmap; try { int w = bitmap.getWidth(), h = bitmap.getHeight(); int[] pix = new int[w * h]; bitmap.getPixels(pix, 0, w, 0, 0, w, h); int alpha = 0xFF<<24; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int color = pix[w * i + j]; int red = ((color & 0x00FF0000) >> 16); int green = ((color & 0x0000FF00) >> 8); int blue = color & 0x000000FF; color = (red + green + blue)/3; color = alpha | (color << 16) | (color << 8) | color; pix[w * i + j] = color; } } BitmapRef result = BitmapRef.createBitmap(holder, w, h, Bitmap.Config.RGB_565); if (result == null) return bitmap; result.setPixels(pix, 0, w, 0, 0, w, h); //BitmapRefs.onBitmapCreated(result); return result; } catch (OutOfMemoryError e) { Utilities.handleOOM(e); return bitmap; } } public static BitmapRef createRoundBitmap(BitmapHolder holder, BitmapRef bitmap) { if (holder == null || bitmap == null) return bitmap; final int width = bitmap.getWidth(); final int height = bitmap.getHeight(); float px = (float)width / 2.0f; float py = (float)height / 2.0f; return createRoundedCornerBitmap(holder, bitmap, 0, px, py); } public static BitmapRef createRoundedCornerBitmap(BitmapHolder holder, BitmapRef bitmap, float roundPixels) { return createRoundedCornerBitmap(holder, bitmap, 0, roundPixels, roundPixels); } public static BitmapRef createRoundedCornerBitmap(BitmapHolder holder, BitmapRef bitmap, int frameWidth, float roundPx, float roundPy) { if (holder == null || bitmap == null) return bitmap; final int width = bitmap.getWidth(); final int height = bitmap.getHeight(); if (frameWidth < 0 || frameWidth >= width / 2 || frameWidth >= height / 2) frameWidth = 0; try { BitmapRef output = BitmapRef.createBitmap(holder, width, height); if (output == null) return bitmap; final Canvas canvas = new Canvas(output.get()); final int color = 0xFF424242; if (roundPx < 0) roundPx = 0; if (roundPy < 0) roundPy = 0; final Paint paint = new Paint(); final Rect rect = new Rect(frameWidth, frameWidth, width - frameWidth, height - frameWidth); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPy, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap.get(), rect, rect, paint); output.setDensity(bitmap.getDensity()); //BitmapRefs.onBitmapCreated(output); return output; } catch (OutOfMemoryError ex) { Utilities.handleOOM(ex); return bitmap; } } public static BitmapRef createScaledCropBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height) { return createScaledCropBitmap(holder, bitmap, width, height, -1, -1); } public static BitmapRef createScaledCropBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int startX, int startY) { return createScaledCropBitmap(holder, bitmap, width, height, startX, startY, 0); } public static BitmapRef createScaledCropBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int startX, int startY, int density) { return createScaledCropFrameBitmap(holder, bitmap, width, height, startX, startY, width, height, density); } public static BitmapRef createCenterScaledCropFrameBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int outputWidth, int outputHeight) { return createScaledCropFrameBitmap(holder, bitmap, width, height, -1, -1, outputWidth, outputHeight, 0); } public static BitmapRef createScaledCropFrameBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int startX, int startY, int outputWidth, int outputHeight) { return createScaledCropFrameBitmap(holder, bitmap, width, height, startX, startY, outputWidth, outputHeight, 0); } public static BitmapRef createScaledCropFrameBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int startX, int startY, int outputWidth, int outputHeight, int density) { return createScaledCropFrameBitmap(holder, bitmap, width, height, startX, startY, outputWidth, outputHeight, density, true); } public static BitmapRef createScaledCropFrameBitmap(BitmapHolder holder, BitmapRef bitmap, int width, int height, int startX, int startY, int outputWidth, int outputHeight, int density, boolean autoScale) { if (holder == null || bitmap == null) return bitmap; final float bitmapWidth = bitmap.getWidth(); final float bitmapHeight = bitmap.getHeight(); float inputWidth = width; //Utilities.getDisplaySize(context, width); float inputHeight = height; //Utilities.getDisplaySize(context, height); if (inputWidth <= 0) inputWidth = bitmapWidth; if (inputHeight <= 0) inputHeight = bitmapHeight; float actualWidth = outputWidth; //Utilities.getDisplaySize(context, outputWidth); float actualHeight = outputHeight; //Utilities.getDisplaySize(context, outputHeight); if (actualWidth < inputWidth) actualWidth = inputWidth; if (actualHeight < inputHeight) actualHeight = inputHeight; float rate1 = bitmapWidth / bitmapHeight; float rate2 = inputWidth / inputHeight; if (rate1 >= rate2) { if (inputHeight > bitmapHeight || autoScale) { inputWidth = inputWidth * bitmapHeight / inputHeight; inputHeight = bitmapHeight; } } else { if (inputWidth > bitmapWidth || autoScale) { inputHeight = inputHeight * bitmapWidth / inputWidth; inputWidth = bitmapWidth; } } float wb = bitmapWidth / 2; float hb = bitmapHeight / 2; float wi = inputWidth / 2; float hi = inputHeight / 2; float left = wb - wi; float right = wb + wi; float top = hb - hi; float bottom = hb + hi; if (startX >= 0 && startY >= 0) { float endX = bitmapWidth - inputWidth; float endY = bitmapHeight - inputHeight; float beginX = startX; float beginY = startY; if (beginX > endX) beginX = endX; if (beginY > endY) beginY = endY; left = beginX; top = beginY; right = left + inputWidth; bottom = top + inputHeight; } float leftDst = 0, topDst = 0; float rightDst = actualWidth, bottomDst = actualHeight; if (actualWidth > inputWidth) { float w = (actualWidth - inputWidth)/ 2; leftDst = w; rightDst = w + inputWidth; } if (actualHeight > inputHeight) { float w = (actualHeight - inputHeight)/ 2; topDst = w; bottomDst = w + inputHeight; } int defaultDensity = bitmap.getDensity(); //int targetDensity = density <= 0 ? defaultDensity : density; try { BitmapRef output = BitmapRef.createBitmap(holder, (int)actualWidth, (int)actualHeight); if (output == null) return bitmap; final Canvas canvas = new Canvas(output.get()); final Paint paint = new Paint(); final Rect rectSrc = new Rect((int)left, (int)top, (int)right, (int)bottom); final RectF rectDst = new RectF(leftDst, topDst, rightDst, bottomDst); canvas.drawBitmap(bitmap.get(), rectSrc, rectDst, paint); output.setDensity(defaultDensity); //BitmapRefs.onBitmapCreated(output); return output; } catch (OutOfMemoryError ex) { Utilities.handleOOM(ex); return bitmap; } } protected static BitmapRef drawBubbleText(BitmapHolder holder, BitmapRef bitmap, String text) { return drawBubbleText(holder, bitmap, text, 0); } protected static BitmapRef drawBubbleText(BitmapHolder holder, BitmapRef bitmap, String text, int density) { if (holder == null || bitmap == null) return bitmap; final int bitmapWidth = bitmap.getWidth(); final int bitmapHeight = bitmap.getHeight(); int defaultDensity = bitmap.getDensity(); //int targetDensity = density <= 0 ? defaultDensity : density; try { final BitmapRef output = BitmapRef.createBitmap(holder, bitmapWidth, bitmapHeight); if (output == null) return bitmap; final Canvas canvas = new Canvas(output.get()); final Paint paint = new Paint(); canvas.drawBitmap(bitmap.get(), 0, 0, paint); final RectF rect = new RectF(10, 10, 60, 50); paint.setColor(Color.RED); canvas.drawRoundRect(rect, 20, 20, paint); paint.setColor(Color.YELLOW); paint.setTextSize(12); canvas.drawText(text, 20, 20, paint); output.setDensity(defaultDensity); //BitmapRefs.onBitmapCreated(output); return output; } catch (OutOfMemoryError ex) { Utilities.handleOOM(ex); return bitmap; } } public static BitmapRef drawFaceBitmaps(BitmapHolder holder, int width, int height, BitmapRef... bitmaps) { if (holder == null) return null; final int bitmapWidth = width; final int bitmapHeight = height; if (bitmapWidth <= 0 || bitmapHeight <= 0) return null; BitmapRef bitmapFrame = null; BitmapRef bitmap1 = null; BitmapRef bitmap2 = null; BitmapRef bitmap3 = null; BitmapRef bitmap4 = null; boolean isSingle = true; if (bitmaps != null && bitmaps.length > 0) { bitmapFrame = bitmaps[0]; if (bitmaps.length > 1) bitmap1 = bitmaps[1]; if (bitmaps.length > 2) { bitmap2 = bitmaps[2]; isSingle = false; } if (bitmaps.length > 3) { bitmap3 = bitmaps[3]; isSingle = false; } if (bitmaps.length > 4) { bitmap4 = bitmaps[4]; isSingle = false; } } //int density = 0; int defaultDensity = bitmapFrame != null ? bitmapFrame.getDensity() : 0; //int targetDensity = density <= 0 ? defaultDensity : density; try { final BitmapRef output = BitmapRef.createBitmap(holder, bitmapWidth, bitmapHeight); if (output == null) return null; final Canvas canvas = new Canvas(output.get()); final Paint paint = new Paint(); if (isSingle) { drawFaceBitmap(canvas, bitmapFrame, paint, 0, 0, height, height); drawFaceBitmap(canvas, bitmap1, paint, 0, 0, height, height); } else { float middle = height / 2; //final RectF rect = new RectF(0, 0, height, height); //paint.setColor(Color.BLACK); //canvas.drawRoundRect(rect, 4, 4, paint); drawFaceBitmap(canvas, bitmapFrame, paint, 0, 0, height, height); drawFaceBitmap(canvas, bitmap1, paint, 0, 0, middle, middle); drawFaceBitmap(canvas, bitmap2, paint, middle, 0, height, middle); drawFaceBitmap(canvas, bitmap3, paint, 0, middle, middle, height); drawFaceBitmap(canvas, bitmap4, paint, middle, middle, height, height); } if (defaultDensity > 0) output.setDensity(defaultDensity); //BitmapRefs.onBitmapCreated(output); return output; } catch (OutOfMemoryError ex) { Utilities.handleOOM(ex); return null; } } private static void drawFaceBitmap(Canvas canvas, BitmapRef bitmap, Paint paint, float startX, float startY, float width, float height) { if (canvas != null && paint != null && bitmap != null) { final Rect rectSrc = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectDst = new RectF(startX, startY, width, height); canvas.drawBitmap(bitmap.get(), rectSrc, rectDst, paint); } } public static BitmapRef createScaledCropBitmap(BitmapHolder holder, BitmapRef bitmap, int inWidth, int inHeight, int inFrameWidth) { return createScaledCropBitmap(holder, bitmap, inWidth, inHeight, inFrameWidth, false); } public static BitmapRef createScaledCropBitmap(BitmapHolder holder, BitmapRef bitmap, int inWidth, int inHeight, int inFrameWidth, boolean zoomOutput) { if (holder == null || bitmap == null) return null; final int inputWidth = bitmap.getWidth(); final int inputHeight = bitmap.getHeight(); final int frameWidth = inFrameWidth * 2; int outputWidth = inWidth; int outputHeight = inHeight; if (zoomOutput && (outputWidth > inputWidth || outputHeight > inputHeight)) { float outputRate = (float)outputWidth / (float)outputHeight; float inputRate = (float)inputWidth / (float)inputHeight; if (outputRate >= inputRate) { outputWidth = inputWidth; outputHeight = (int)((float)outputWidth / outputRate); } else { outputHeight = inputHeight; outputWidth = (int)((float)outputHeight * outputRate); } } int cropWidth = outputWidth - frameWidth; int cropHeight = outputHeight - frameWidth; BitmapRef savedInput = bitmap; if (inputWidth < outputWidth || inputHeight < outputHeight) bitmap = createZoomInScaledBitmap(holder, bitmap, outputWidth, outputHeight); BitmapRef output = createCenterScaledCropFrameBitmap(holder, bitmap, cropWidth, cropHeight, outputWidth, outputHeight); if (bitmap != null && savedInput != bitmap && output != bitmap) bitmap.recycle(); return output; } private static class DecodeCanceller implements JobCancelListener { private final BitmapFactory.Options mOptions; public DecodeCanceller(BitmapFactory.Options options) { mOptions = options; } @Override public void onCancel() { mOptions.requestCancelDecode(); } } @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB) public static void setOptionsMutable(BitmapFactory.Options options) { if (ApiHelper.HAS_OPTIONS_IN_MUTABLE) options.inMutable = true; } public static BitmapRef decode(BitmapHolder holder, JobContext jc, FileDescriptor fd, BitmapFactory.Options options) { if (options == null) options = new BitmapFactory.Options(); jc.setCancelListener(new DecodeCanceller(options)); setOptionsMutable(options); return ensureGLCompatibleBitmap(holder, BitmapRef.decodeFileDescriptor(holder, fd, null, options)); } public static void decodeBounds(BitmapHolder holder, JobContext jc, FileDescriptor fd, BitmapFactory.Options options) { Utils.assertTrue(options != null); options.inJustDecodeBounds = true; jc.setCancelListener(new DecodeCanceller(options)); BitmapRef.decodeFileDescriptor(holder, fd, null, options); options.inJustDecodeBounds = false; } public static BitmapRef decode(BitmapHolder holder, JobContext jc, byte[] bytes, BitmapFactory.Options options) { return decode(holder, jc, bytes, 0, bytes.length, options); } public static BitmapRef decode(BitmapHolder holder, JobContext jc, byte[] bytes, int offset, int length, BitmapFactory.Options options) { if (options == null) options = new BitmapFactory.Options(); jc.setCancelListener(new DecodeCanceller(options)); setOptionsMutable(options); return ensureGLCompatibleBitmap(holder, BitmapRef.decodeByteArray(holder, bytes, offset, length, options)); } public static void decodeBounds(BitmapHolder holder, JobContext jc, byte[] bytes, int offset, int length, BitmapFactory.Options options) { Utils.assertTrue(options != null); options.inJustDecodeBounds = true; jc.setCancelListener(new DecodeCanceller(options)); BitmapRef.decodeByteArray(holder, bytes, offset, length, options); options.inJustDecodeBounds = false; } public static BitmapRef decodeThumbnail(BitmapHolder holder, JobContext jc, File file, BitmapFactory.Options options, int targetSize, int type) { FileInputStream fis = null; try { fis = new FileInputStream(file); return decodeThumbnail(holder, jc, fis.getFD(), options, targetSize, type); } catch (Throwable ex) { if (LOG.isWarnEnabled()) LOG.warn(ex.toString(), ex); return null; } finally { Utils.closeSilently(fis); } } public static BitmapRef decodeThumbnail(BitmapHolder holder, JobContext jc, FileDescriptor fd, BitmapFactory.Options options, int targetSize, int type) { if (options == null) options = new BitmapFactory.Options(); jc.setCancelListener(new DecodeCanceller(options)); options.inJustDecodeBounds = true; BitmapRef.decodeFileDescriptor(holder, fd, null, options); if (jc.isCancelled()) return null; int w = options.outWidth; int h = options.outHeight; if (type == BitmapHelper.TYPE_MICROTHUMBNAIL) { // We center-crop the original image as it's micro thumbnail. In this case, // we want to make sure the shorter side >= "targetSize". float scale = (float) targetSize / Math.min(w, h); options.inSampleSize = computeSampleSizeLarger(scale); // For an extremely wide image, e.g. 300x30000, we may got OOM when decoding // it for TYPE_MICROTHUMBNAIL. So we add a max number of pixels limit here. final int MAX_PIXEL_COUNT = 640000; // 400 x 1600 if ((w / options.inSampleSize) * (h / options.inSampleSize) > MAX_PIXEL_COUNT) { options.inSampleSize = computeSampleSize( FloatMath.sqrt((float) MAX_PIXEL_COUNT / (w * h))); } } else { // For screen nail, we only want to keep the longer side >= targetSize. float scale = (float) targetSize / Math.max(w, h); options.inSampleSize = computeSampleSizeLarger(scale); } options.inJustDecodeBounds = false; setOptionsMutable(options); BitmapRef result = BitmapRef.decodeFileDescriptor(holder, fd, null, options); if (result == null) return null; // We need to resize down if the decoder does not support inSampleSize // (For example, GIF images) float scale = (float) targetSize / (type == BitmapHelper.TYPE_MICROTHUMBNAIL ? Math.min(result.getWidth(), result.getHeight()) : Math.max(result.getWidth(), result.getHeight())); if (scale <= 0.5) result = resizeBitmapByScale(holder, result, scale, true); return ensureGLCompatibleBitmap(holder, result); } /** * Decodes the bitmap from the given byte array if the image size is larger than the given * requirement. * * Note: The returned image may be resized down. However, both width and height must be * larger than the <code>targetSize</code>. */ public static BitmapRef decodeIfBigEnough(BitmapHolder holder, JobContext jc, byte[] data, BitmapFactory.Options options, int targetSize) { if (options == null) options = new BitmapFactory.Options(); jc.setCancelListener(new DecodeCanceller(options)); options.inJustDecodeBounds = true; BitmapRef.decodeByteArray(holder, data, 0, data.length, options); if (jc.isCancelled()) return null; if (options.outWidth < targetSize || options.outHeight < targetSize) return null; options.inSampleSize = computeSampleSizeLarger( options.outWidth, options.outHeight, targetSize); options.inJustDecodeBounds = false; setOptionsMutable(options); return ensureGLCompatibleBitmap(holder, BitmapRef.decodeByteArray(holder, data, 0, data.length, options)); } // TODO: This function should not be called directly from // DecodeUtils.requestDecode(...), since we don't have the knowledge // if the bitmap will be uploaded to GL. public static BitmapRef ensureGLCompatibleBitmap(BitmapHolder holder, BitmapRef bitmap) { if (bitmap == null || bitmap.getConfig() != null) return bitmap; BitmapRef newBitmap = bitmap.copy(holder, BitmapRef.getBitmapConfig(), false); bitmap.recycle(); return newBitmap; } public static BitmapRegionDecoder createBitmapRegionDecoder( JobContext jc, byte[] bytes, int offset, int length, boolean shareable) { if (offset < 0 || length <= 0 || offset + length > bytes.length) { throw new IllegalArgumentException(String.format( "offset = %s, length = %s, bytes = %s", offset, length, bytes.length)); } try { return BitmapRegionDecoder.newInstance( bytes, offset, length, shareable); } catch (Throwable t) { if (LOG.isWarnEnabled()) LOG.warn(t.toString(), t); return null; } } public static BitmapRegionDecoder createBitmapRegionDecoder( JobContext jc, String filePath, boolean shareable) { try { return BitmapRegionDecoder.newInstance(filePath, shareable); } catch (Throwable t) { if (LOG.isWarnEnabled()) LOG.warn(t.toString(), t); return null; } } public static BitmapRegionDecoder createBitmapRegionDecoder( JobContext jc, FileDescriptor fd, boolean shareable) { try { return BitmapRegionDecoder.newInstance(fd, shareable); } catch (Throwable t) { if (LOG.isWarnEnabled()) LOG.warn(t.toString(), t); return null; } } public static BitmapRegionDecoder createBitmapRegionDecoder( JobContext jc, InputStream is, boolean shareable) { try { return BitmapRegionDecoder.newInstance(is, shareable); } catch (Throwable t) { // We often cancel the creating of bitmap region decoder, // so just log one line. if (LOG.isWarnEnabled()) LOG.warn("requestCreateBitmapRegionDecoder: " + t); return null; } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static BitmapRef decode(BitmapHolder holder, JobContext jc, byte[] data, int offset, int length, BitmapFactory.Options options, BitmapPool pool) { if (pool == null) return decode(holder, jc, data, offset, length, options); if (options == null) options = new BitmapFactory.Options(); if (options.inSampleSize < 1) options.inSampleSize = 1; options.inPreferredConfig = BitmapRef.getBitmapConfig(); BitmapRef ref = (options.inSampleSize == 1) ? findCachedBitmap(holder, jc, data, offset, length, options, pool) : null; options.inBitmap = ref != null ? ref.get() : null; try { BitmapRef bitmap = decode(holder, jc, data, offset, length, options); if (options.inBitmap != null && options.inBitmap != bitmap.get()) { pool.recycle(BitmapRef.newBitmap(holder, options.inBitmap)); options.inBitmap = null; } return bitmap; } catch (IllegalArgumentException e) { if (options.inBitmap == null) throw e; if (LOG.isWarnEnabled()) LOG.warn("decode fail with a given bitmap, try decode to a new bitmap"); pool.recycle(BitmapRef.newBitmap(holder, options.inBitmap)); options.inBitmap = null; return decode(holder, jc, data, offset, length, options); } } // This is the same as the method above except the source data comes // from a file descriptor instead of a byte array. @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static BitmapRef decode(BitmapHolder holder, JobContext jc, FileDescriptor fileDescriptor, BitmapFactory.Options options, BitmapPool pool) { if (pool == null) return decode(holder, jc, fileDescriptor, options); if (options == null) options = new BitmapFactory.Options(); if (options.inSampleSize < 1) options.inSampleSize = 1; options.inPreferredConfig = BitmapRef.getBitmapConfig(); BitmapRef ref = (options.inSampleSize == 1) ? findCachedBitmap(holder, jc, fileDescriptor, options, pool) : null; options.inBitmap = ref != null ? ref.get() : null; try { BitmapRef bitmap = decode(holder, jc, fileDescriptor, options); if (options.inBitmap != null && options.inBitmap != bitmap.get()) { pool.recycle(BitmapRef.newBitmap(holder, options.inBitmap)); options.inBitmap = null; } return bitmap; } catch (IllegalArgumentException e) { if (options.inBitmap == null) throw e; if (LOG.isWarnEnabled()) LOG.warn("decode fail with a given bitmap, try decode to a new bitmap"); pool.recycle(BitmapRef.newBitmap(holder, options.inBitmap)); options.inBitmap = null; return decode(holder, jc, fileDescriptor, options); } } private static BitmapRef findCachedBitmap(BitmapHolder holder, JobContext jc, byte[] data, int offset, int length, BitmapFactory.Options options, BitmapPool pool) { if (pool.isOneSize()) return pool.getBitmap(); decodeBounds(holder, jc, data, offset, length, options); return pool.getBitmap(options.outWidth, options.outHeight); } private static BitmapRef findCachedBitmap(BitmapHolder holder, JobContext jc, FileDescriptor fileDescriptor, BitmapFactory.Options options, BitmapPool pool) { if (pool.isOneSize()) return pool.getBitmap(); decodeBounds(holder, jc, fileDescriptor, options); return pool.getBitmap(options.outWidth, options.outHeight); } public static final int DEFAULT_JPEG_QUALITY = 90; public static final int UNCONSTRAINED = -1; /** * Compute the sample size as a function of minSideLength * and maxNumOfPixels. * minSideLength is used to specify that minimal width or height of a * bitmap. * maxNumOfPixels is used to specify the maximal size in pixels that is * tolerable in terms of memory usage. * * The function returns a sample size based on the constraints. * Both size and minSideLength can be passed in as UNCONSTRAINED, * which indicates no care of the corresponding constraint. * The functions prefers returning a sample size that * generates a smaller bitmap, unless minSideLength = UNCONSTRAINED. * * Also, the function rounds up the sample size to a power of 2 or multiple * of 8 because BitmapFactory only honors sample size this way. * For example, BitmapFactory downsamples an image by 2 even though the * request is 3. So we round up the sample size to avoid OOM. */ public static int computeSampleSize(int width, int height, int minSideLength, int maxNumOfPixels) { int initialSize = computeInitialSampleSize( width, height, minSideLength, maxNumOfPixels); return initialSize <= 8 ? Utils.nextPowerOf2(initialSize) : (initialSize + 7) / 8 * 8; } private static int computeInitialSampleSize(int w, int h, int minSideLength, int maxNumOfPixels) { if (maxNumOfPixels == UNCONSTRAINED && minSideLength == UNCONSTRAINED) return 1; int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 : (int) FloatMath.ceil(FloatMath.sqrt((float) (w * h) / maxNumOfPixels)); if (minSideLength == UNCONSTRAINED) { return lowerBound; } else { int sampleSize = Math.min(w / minSideLength, h / minSideLength); return Math.max(sampleSize, lowerBound); } } // This computes a sample size which makes the longer side at least // minSideLength long. If that's not possible, return 1. public static int computeSampleSizeLarger(int w, int h, int minSideLength) { int initialSize = Math.max(w / minSideLength, h / minSideLength); if (initialSize <= 1) return 1; return initialSize <= 8 ? Utils.prevPowerOf2(initialSize) : initialSize / 8 * 8; } // Find the min x that 1 / x >= scale public static int computeSampleSizeLarger(float scale) { int initialSize = (int) FloatMath.floor(1f / scale); if (initialSize <= 1) return 1; return initialSize <= 8 ? Utils.prevPowerOf2(initialSize) : initialSize / 8 * 8; } // Find the max x that 1 / x <= scale. public static int computeSampleSize(float scale) { Utils.assertTrue(scale > 0); int initialSize = Math.max(1, (int) FloatMath.ceil(1 / scale)); return initialSize <= 8 ? Utils.nextPowerOf2(initialSize) : (initialSize + 7) / 8 * 8; } public static BitmapRef resizeBitmapByScale(BitmapHolder holder, BitmapRef bitmap, float scale, boolean recycle) { int width = Math.round(bitmap.getWidth() * scale); int height = Math.round(bitmap.getHeight() * scale); if (width == bitmap.getWidth() && height == bitmap.getHeight()) return bitmap; BitmapRef target = BitmapRef.createBitmap(holder, width, height, getConfig(bitmap)); if (target == null) return bitmap; Canvas canvas = new Canvas(target.get()); canvas.scale(scale, scale); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); canvas.drawBitmap(bitmap.get(), 0, 0, paint); if (recycle) bitmap.recycle(); return target; } private static Bitmap.Config getConfig(BitmapRef bitmap) { Bitmap.Config config = bitmap.getConfig(); if (config == null) config = BitmapRef.getBitmapConfig(); return config; } public static BitmapRef resizeDownBySideLength(BitmapHolder holder, BitmapRef bitmap, int maxLength, boolean recycle) { int srcWidth = bitmap.getWidth(); int srcHeight = bitmap.getHeight(); float scale = Math.min((float) maxLength / srcWidth, (float) maxLength / srcHeight); if (scale >= 1.0f) return bitmap; return resizeBitmapByScale(holder, bitmap, scale, recycle); } public static BitmapRef resizeAndCropCenter(BitmapHolder holder, BitmapRef bitmap, int size, boolean recycle) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); if (w == size && h == size) return bitmap; // scale the image so that the shorter side equals to the target; // the longer side will be center-cropped. float scale = (float) size / Math.min(w, h); BitmapRef target = BitmapRef.createBitmap(holder, size, size, getConfig(bitmap)); if (target == null) return bitmap; int width = Math.round(scale * bitmap.getWidth()); int height = Math.round(scale * bitmap.getHeight()); Canvas canvas = new Canvas(target.get()); canvas.translate((size - width) / 2f, (size - height) / 2f); canvas.scale(scale, scale); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); canvas.drawBitmap(bitmap.get(), 0, 0, paint); if (recycle) bitmap.recycle(); return target; } public static BitmapRef createVideoThumbnail(BitmapHolder holder, String filePath) { // MediaMetadataRetriever is available on API Level 8 // but is hidden until API Level 10 Class<?> clazz = null; Object instance = null; try { clazz = Class.forName("android.media.MediaMetadataRetriever"); instance = clazz.newInstance(); Method method = clazz.getMethod("setDataSource", String.class); method.invoke(instance, filePath); // The method name changes between API Level 9 and 10. if (Build.VERSION.SDK_INT <= 9) { return BitmapRef.newBitmap(holder, clazz.getMethod("captureFrame").invoke(instance)); } else { byte[] data = (byte[]) clazz.getMethod("getEmbeddedPicture").invoke(instance); if (data != null) { BitmapRef bitmap = BitmapRef.decodeByteArray(holder, data, 0, data.length); if (bitmap != null) return bitmap; } return BitmapRef.newBitmap(holder, clazz.getMethod("getFrameAtTime").invoke(instance)); } } catch (IllegalArgumentException ex) { // Assume this is a corrupt video file } catch (RuntimeException ex) { // Assume this is a corrupt video file. } catch (Throwable e) { if (LOG.isWarnEnabled()) LOG.warn("createVideoThumbnail", e); } finally { try { if (instance != null) clazz.getMethod("release").invoke(instance); } catch (Throwable ignored) { } } return null; } public static byte[] compressToBytes(BitmapRef bitmap) { return compressToBytes(bitmap, DEFAULT_JPEG_QUALITY); } public static byte[] compressToBytes(BitmapRef bitmap, int quality) { ByteArrayOutputStream baos = new ByteArrayOutputStream(65536); bitmap.compress(CompressFormat.JPEG, quality, baos); return baos.toByteArray(); } }
PHP
UTF-8
243
3.015625
3
[]
no_license
<?php class Person{ public static $question=array(); public static think(){ sleep(5); return true; } public static answer(){ echo "success"; } } $ret=Person::think(); if($ret){ Person::answer(); }else{ echo "answer error"; } ?>
Java
UTF-8
6,641
1.75
2
[]
no_license
package com.aohuan.detail.mine; import java.util.ArrayList; import java.util.List; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.aohuan.base.BaseActiviry; import com.lidroid.xutils.view.annotation.ContentView; import com.lidroid.xutils.view.annotation.ViewInject; import com.lidroid.xutils.view.annotation.event.OnClick; import com.aohuan.babycomming.R; import com.aohuan.bean.MycollectBean; import com.aohuan.bean.MycollectBean.GoodsList2; import com.aohuan.detail.first.activity.GoodsDetailActivity; import com.aohuan.detail.first.activity.SelectGoodsActivity; import com.aohuan.detail.first.activity.TaoCanDetailActivity; import com.aohuan.utils.adapter.CommonAdapter; import com.aohuan.utils.adapter.ViewHolder; import com.aohuan.utils.http.EFaceType; import com.aohuan.utils.http.EFaceTypeZGQ; import com.aohuan.utils.http.GetDataAsync; import com.aohuan.utils.http.GetDataAsyncZGQ; import com.aohuan.utils.http.IUpdateUI; import com.aohuan.utils.propriety.LoginHelper; import com.aohuan.utils.request.RequestBaseMap; import com.aohuan.utils.request.RequestBaseMapZGQ; /** * 我的套餐收藏 * @author Administrator * */ @ContentView(R.layout.activity_mine_collection) public class MyCollectionActivity extends BaseActiviry{ @ViewInject(R.id.title) private TextView mTvTitle; @ViewInject(R.id.back) private ImageButton mImgBtnBack; @ViewInject(R.id.no_data) private LinearLayout mRlNoData; @ViewInject(R.id.mine_list) private GridView mGridView; private List<GoodsList2> mListString; private CommonAdapter<GoodsList2> mCommonAdapter; @Override protected void onCreate(Bundle arg0) { super.onCreate(arg0); mTvTitle.setText("我的收藏"); mListString = new ArrayList<GoodsList2>(); //doCommit(); getData(); } private void getData() { GetDataAsync gs=new GetDataAsync(MyCollectionActivity.this, new IUpdateUI() { @Override public void updata(Object allData) { if (allData !=null && allData instanceof MycollectBean) { MycollectBean bean=(MycollectBean) allData; if (bean.getCode()==0) { mListString=bean.getList(); doCommit(); } }else if (allData ==null) { Toast.makeText(MyCollectionActivity.this, "网络不给力" , Toast.LENGTH_SHORT).show(); } } }, false, RequestBaseMap.getCollect(LoginHelper.getUser(getApplicationContext()).getId())); gs.execute(EFaceType.URL_MY_COLLECT); } private void setAdapter(){ mCommonAdapter = new CommonAdapter<GoodsList2>(this, mListString, R.layout.item_mine_shou_cang) { public void convert(ViewHolder helper, final GoodsList2 item) { helper.setText(R.id.tv_content, item.getProduct()); helper.setImageByUrl(R.id.img_content, item.getImage(), MyCollectionActivity.this); helper.setText(R.id.tv_title, item.getTitle()); helper.setText(R.id.tv_price_num, item.getTeam_price()); helper.getView(R.id.tv_delete).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDelete(item.getId()); } }); // helper.getConvertView().setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // Intent intent = new Intent(MyCollectionActivity.this, GoodsDetailActivity.class); // intent.putExtra("goodsid", item.getId()); // startActivity(intent); // } // }); } }; mGridView.setAdapter(mCommonAdapter); mGridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Log.e("TAG", ""+mListString.get(arg2).getGroup_id()); if(mListString.get(arg2).getGroup_id().equals("22")){ Intent intent = new Intent(getApplicationContext(), GoodsDetailActivity.class); intent.putExtra("goodsid", mListString.get(arg2).getId()); startActivity(intent); }else{ Intent intent = new Intent(getApplicationContext(), TaoCanDetailActivity.class); intent.putExtra("team_id", mListString.get(arg2).getId()); startActivity(intent); } } }); } /** * 删除的Dialog */ public void showDelete(final String id){ final Dialog dialog = new Dialog(this); View view = LayoutInflater.from(this).inflate(R.layout.dialog_delete_order_layout, null); Button cencal = (Button) view.findViewById(R.id.btn_cencal); Button sure = (Button) view.findViewById(R.id.btn_sure); TextView tv = (TextView) view.findViewById(R.id.tv_delete); tv.setText("确认删除收藏吗?"); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(view); dialog.setCanceledOnTouchOutside(false);//点击空白不会消失 dialog.show(); cencal.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dialog.dismiss(); } }); sure.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub deleteDataCollect(LoginHelper.getUser(getApplicationContext()).getId(), id); getData(); dialog.dismiss(); } }); } private void deleteDataCollect(String userid, String team_id){ IUpdateUI ui = new IUpdateUI() { @Override public void updata(Object allData) { // TODO Auto-generated method stub // if(allData == null){ // Toast.makeText(MyCollectionActivity.this, // "网络不给力", Toast.LENGTH_SHORT).show(); // return ; // } } }; GetDataAsyncZGQ asyncZGQ = new GetDataAsyncZGQ(this, ui, true, RequestBaseMapZGQ.getGoodsCollect(userid, team_id)); asyncZGQ.execute(EFaceTypeZGQ.URL_SELCT_GOODS_COLLECT); } private void doCommit(){ if(mListString!=null && mListString.size()>0){ mRlNoData.setVisibility(View.GONE); mGridView.setVisibility(View.VISIBLE); setAdapter(); }else{ mRlNoData.setVisibility(View.VISIBLE); mGridView.setVisibility(View.GONE); } } @OnClick({ R.id.back, }) public void onRlClick(View v) { switch (v.getId()) { case R.id.back: finish(); break; default: break; } } }
Java
UTF-8
1,587
2.546875
3
[]
no_license
package com.example.routemap.domain; import java.util.Date; public class InfoMarker { private String type; private String description; private String level; private Date date; private String author; private double latitude; private double longitude; public InfoMarker() { } public InfoMarker(String type, String description, String level, Date date, String author) { this.type = type; this.description = description; this.level = level; this.date = date; this.author = author; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } }
Java
UTF-8
2,392
2.125
2
[]
no_license
package com.costar.model; import com.alibaba.fastjson.annotation.JSONField; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.sql.Timestamp; @Entity @Table(name = "sys_notice") @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator") public class SysNotice { private String id; private String title; private String content; private String url; private String sub; @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Timestamp createTime; private Integer deletemark; private Integer noticeType; private String createUsername; @Id @Column(name = "id") @GeneratedValue(generator = "uuid2") public String getId() { return id; } public void setId(String id) { this.id = id; } @Basic @Column(name = "title") public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Basic @Column(name = "content") public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Basic @Column(name = "url") public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Basic @Column(name = "sub") public String getSub() { return sub; } public void setSub(String sub) { this.sub = sub; } @Basic @Column(name = "create_time") public Timestamp getCreateTime() { return createTime; } public void setCreateTime(Timestamp createTime) { this.createTime = createTime; } @Basic @Column(name = "deletemark") public Integer getDeletemark() { return deletemark; } public void setDeletemark(Integer deletemark) { this.deletemark = deletemark; } @Basic @Column(name = "notice_type") public Integer getNoticeType() { return noticeType; } public void setNoticeType(Integer noticeType) { this.noticeType = noticeType; } @Basic @Column(name = "create_username") public String getCreateUsername() { return createUsername; } public void setCreateUsername(String createUsername) { this.createUsername = createUsername; } }
SQL
UTF-8
2,421
3.078125
3
[]
no_license
-- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 10.5.5-MariaDB - mariadb.org binary distribution -- Server OS: Win32 -- HeidiSQL Version: 11.0.0.5919 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!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' */; -- Dumping database structure for supervisor DROP DATABASE IF EXISTS `supervisor`; CREATE DATABASE IF NOT EXISTS `supervisor` /*!40100 DEFAULT CHARACTER SET latin1 */; USE `supervisor`; -- Dumping structure for table supervisor.host CREATE TABLE IF NOT EXISTS `host` ( `hostid` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, `ipaddress` varchar(50) DEFAULT NULL, `description` varchar(50) DEFAULT NULL, `lastping` int(11) DEFAULT NULL, `lastevent` int(11) DEFAULT NULL, PRIMARY KEY (`hostid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- Dumping structure for table event CREATE TABLE IF NOT EXISTS `event` ( `eventid` int(10) NOT NULL AUTO_INCREMENT, `hostid` int(10) NOT NULL DEFAULT '0', `localtime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `description` char(255) DEFAULT '', `type` tinyint(4) DEFAULT NULL, `group` int(11) NOT NULL DEFAULT '0', `utctime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`eventid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- Dumping structure for table props CREATE TABLE IF NOT EXISTS `props` ( `propid` int(10) NOT NULL AUTO_INCREMENT, `hostid` int(10) NOT NULL DEFAULT '0', `category` varchar(10) DEFAULT NULL, `name` varchar(30) DEFAULT NULL, `value` varchar(255) DEFAULT NULL, PRIMARY KEY (`propid`), UNIQUE KEY `idx` (`hostid`,`category`,`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `props` (`propid`, `hostid`, `category`, `name`, `value`) VALUES (1, 0, 'db', 'version', '1'); -- Data exporti -- Data exporting was unselected. /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
C#
UTF-8
4,322
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Text.Json; using Terminal.Gui; using StackExchange.Redis; namespace Redis_TUI { class Program { static List<string> listOfNames = new List<string>(); static List<string> secondList = new List<string>(); static ListView listView; static ListView rightListView; static TextView textView; static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost"); static void Main(string[] args) { Application.Init(); var top = Application.Top; // Creates the top-level window to show var winNodes = new Window("Nodes") { X = 0, Y = 1, // Leave one row for the toplevel menu // By using Dim.Fill(), it will automatically resize without manual intervention Width = top.Frame.Width / 5, Height = Dim.Fill() }; var winDetails = new Window("Details") { X = Pos.Right(winNodes), Y = Pos.AnchorEnd(top.Frame.Height / 5), // Leave one row for the toplevel menu // By using Dim.Fill(), it will automatically resize without manual intervention Width = Dim.Fill(), Height = top.Frame.Height / 5 }; var winValues = new Window("Values") { X = Pos.Right(winNodes), Y = 1, // Leave one row for the toplevel menu // By using Dim.Fill(), it will automatically resize without manual intervention Width = Dim.Fill(), Height = Dim.Fill() - (top.Frame.Height / 5) }; top.Add(winNodes); top.Add(winValues); top.Add(winDetails); // Creates a menubar, the item "New" has a help menu. var menu = new MenuBar(new MenuBarItem[] { new MenuBarItem ("_File", new MenuItem [] { //new MenuItem ("_New", "Creates new file", NewFile), //new MenuItem ("_Close", "", () => Close ()), //new MenuItem ("_Quit", "", () => { if (Quit ()) top.Running = false; }) }), new MenuBarItem ("_Edit", new MenuItem [] { new MenuItem ("_Copy", "", null), new MenuItem ("C_ut", "", null), new MenuItem ("_Paste", "", null) }) }); top.Add(menu); try { IServer server = redis.GetServer("localhost", 6379); foreach (var key in server.Keys()) { listOfNames.Add(key); } listView = new ListView(new Rect(0, 0, top.Frame.Width / 5, 200), listOfNames); listView.OpenSelectedItem += onItemClick; textView = new TextView() { X = 0 , Y = 0, Width = Dim.Fill(), Height = Dim.Fill() }; var labelNodes = new Label("Nodes: ") { X = 0, Y = 0 }; var labelValue = new Label("Value: ") { X = Pos.Right(listView), Y = 0 }; winNodes.Add(listView); winValues.Add(textView); } catch (Exception e) { MessageBox.ErrorQuery("Unable to connect to Redis", "Please check Redis is running", "Okay"); } Application.Run(); } static void onItemClick(ListViewItemEventArgs lviea) { IDatabase db = redis.GetDatabase(); //MessageBox.Query("Is this right", (string)db.StringGet((string)lviea.Value), "Yes", "no"); //listOfNames.Insert(lviea.Item + 1, "->TESTTST"); //listView.MoveDown(); //textView.Text = PrettyJson((string)db.StringGet((string)lviea.Value)); textView.Text = (string)db.StringGet((string)lviea.Value); } public static string PrettyJson(string unPrettyJson) { var options = new JsonSerializerOptions() { WriteIndented = true }; var jsonElement = JsonSerializer.Deserialize<JsonElement>(unPrettyJson); return JsonSerializer.Serialize(jsonElement, options); } } }
Python
UTF-8
136
3.21875
3
[]
no_license
number_of_boyfriend = 5 if number_of_boyfriend: print("Idihh.. dia playboy") print("Jumlah pacarnya ada", number_of_boyfriend)
JavaScript
UTF-8
384
2.546875
3
[]
no_license
import * as actionTypes from '../actionTypes'; const initialState = {}; const kudosReducer = (state=initialState, action) => { switch (action.type) { case actionTypes.FETCH_USER_SUCCESS: return { ...state, ...action.payload.kudos }; default: return state; } } export default kudosReducer;
Java
UTF-8
3,255
2.703125
3
[]
no_license
package Controller; import View.Apresentacao; import static java.lang.Thread.sleep; public class SimulacaoJogo { private String casa; private int ratingCasa; private int golosCasa; private String fora; private int ratingFora; private int golosFora; Apresentacao apresentacao; public SimulacaoJogo(String c, int rc, String f, int rf){ this.casa = c; this.ratingCasa = rc; this.golosCasa = 0; this.fora = f; this.ratingFora = rf; this.golosFora = 0; this.apresentacao = new Apresentacao(); } public void simula() throws InterruptedException { int total = ratingCasa + ratingFora; int tickCasa = 0; int tickFora = 0; double chance = 0; for(int tickAtual = 0; tickAtual < total; tickAtual++){ if(tickAtual == total/2){ apresentacao.printBreak(); }else if(tickAtual % 2 == 0){ if(tickAtual / 2 >= ratingCasa); else{ chance = Math.random(); if(chance <= 0.04){ golosCasa += 1; apresentacao.printGoloCasa(tickAtual*90/total,casa,golosCasa,fora,golosFora); } else if (chance > 0.04 && chance <= 0.045){ apresentacao.penalti(tickAtual*90/total,fora); sleep(2000); chance = Math.random(); if(chance >= 0.5){ golosCasa += 1; apresentacao.printGoloCasa(tickAtual*90/total,casa,golosCasa,fora,golosFora); } } else if (chance > 0.045 && chance <= 0.09){ apresentacao.prinCanto(tickAtual*90/total,casa); } } } else { if(tickAtual / 2 >= ratingFora); else{ chance = Math.random(); if(chance <= 0.04){ golosFora += 1; apresentacao.printGoloFora(tickAtual*90/total,casa,golosCasa,fora,golosFora); } else if (chance > 0.04 && chance <= 0.045){ apresentacao.penalti(tickAtual*90/total,fora); sleep(2000); chance = Math.random(); if(chance >= 0.5){ golosCasa += 1; apresentacao.printGoloFora(tickAtual*90/total,casa,golosCasa,fora,golosFora); } } else if (chance > 0.045 && chance <= 0.09){ apresentacao.prinCanto(tickAtual*90/total,fora); } } } if(tickCasa >= ratingCasa); if(tickFora >= ratingFora); sleep(200); } } public int getGolosCasa() { return golosCasa; } public void setGolosCasa(int golosCasa) { this.golosCasa = golosCasa; } public int getGolosFora() { return golosFora; } public void setGolosFora(int golosFora) { this.golosFora = golosFora; } }
Java
UTF-8
338
1.546875
2
[]
no_license
package backend.domain; import lombok.*; import java.io.Serializable; @NoArgsConstructor @AllArgsConstructor @Data @ToString @Builder public class AccuracyHelper implements Serializable { private String username; private Long method; private Long songId; private double[] e; private double[] x; }
C#
UTF-8
2,816
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using CommunicationLibrary; namespace BullChatPrototype { public enum Status { Offline = 0, Connecting = 1, Failed = 2, Connected = 3 } public class User { public String ConnectionId; public String Ip; public String Name; public Status Status; private bool incoming; private Client outgoing; public User(String ConnectionId, String ip) { // set status this.Status = Status.Connecting; // save id, server, ip this.ConnectionId = ConnectionId; this.Ip = ip; Console.WriteLine("Connecting to " + this.Ip + "..."); // create client this.outgoing = new Client(); bool connected = this.outgoing.connect(ip, 2345); // TODO: dynamic port if (!connected) { this.Status = Status.Failed; Console.WriteLine("Connection to " + this.Ip + " failed"); } else { Console.WriteLine("Connected! Initializing connection..."); this.outgoing.send("init", this.ConnectionId); } // check connection CheckConnection(); } public void ClientConnected() { this.incoming = true; CheckConnection(); } public void ClientDisconnected() { this.incoming = false; } public void CheckConnection() { if (incoming && outgoing != null) { Connected(); } } public void Connected() { this.Status = Status.Connected; SendName(); Console.WriteLine("Done! Connection to " + this.Ip + " initialized!"); } public void Received(String type, String message) { switch (type) { case "hello": this.Name = message; Console.WriteLine(this.Ip + " is " + this.Name); break; case "message": Console.WriteLine(this.Name + " => " + Chat.Name + ": " + message); break; } } public void Send(String message) { this.outgoing.send("message", message); } public void SendName() { this.outgoing.send("hello", Chat.Name); } public void SendContact(User user) { this.outgoing.send("contact", user.Ip); } } }
Python
UTF-8
584
3.65625
4
[]
no_license
# -*- coding: utf-8 -*- import math Cv=int(input('digite o numero de pontos do C:')) Ce=int(input('digite o numero de empates do C:')) Cs=int(input('digite o saldo de gols de C:')) Fv=int(input('digite o numero de pontos do F:')) Fe=int(input('digite o numero de empates do F:')) Fs=int(input('digite o saldo de gols de F:')) if Cv>Fv: print('FF') elif Fv>Cv: print('C') else: if Ce>Fe: print('C') elif Fe>Ce: print('F') else: if Cs>Fs: print('C') elif Fe>Ce: print('F') else: print('=')
Markdown
UTF-8
761
2.65625
3
[ "MIT" ]
permissive
--- layout: default title: Error - 00000 description: A description of the error with code 00000, and some trouble shooting steps. section: errors --- # {{ page.title }} {{ page.description }} ## What is the cause of this issue? This issue usually occurs when MDOQ is unable to connect to the MDOQ Connector on the instance/production site. This could be for a number of reasons, and isn't usually something to be worried about. ## Troubleshooting - Visit your instance, using the links from the detail page and confirm it can be accessed. Sometimes development on an instance can cause the frontend of magento to become inaccessible, meaning Mdoq is unable to talk to your instance. Resolving this issue should allow Mdoq to talk to your instance again.
Python
UTF-8
83
3.28125
3
[]
no_license
a=input("enter the number") mul=1 for i in range(1,a+1): mul=mul*i print mul
Markdown
UTF-8
1,114
3.0625
3
[]
no_license
# 传参 - 序 > 我们在开发脚本过程中,少不了会给执行的脚步传递参数 ,就好比我写一个文件复制的脚步,我需要动态传递我需要复制的文件路径和复制后存放的路径,要不然没用一次就改一次代码就太不人性化了。 - 实例 - 比我写了个脚本名为:006_shell_params.sh ```code shell #获取参数 echo "获取执行脚本名称:$0" echo "获取第一个参数:$1" echo "获取第二个参数:$2" echo "参数个数:$#" echo "全部参数:$*" ``` - 执行结果 ![参数结果](./img/shell_006_params.png) - 参数处理表 处理 | 说明 --- | --- $# | 参数个数 $* | 以字符串的方式输出所有参数 , "$*" -> "param0 param1 param2" $@ | 与$*相同,但是用 ***"*** 号括起来,是以数组形式输出 "$@" -> "param0" "param1" "param2" $! | 运行最后一个进程的ID $- | 显示Shell的当前选项 $? | 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。
C
UTF-8
1,283
2.84375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <sys/msg.h> #include <limits.h> #include <stdint.h> #include <errno.h> #define BUF_SIZE 512 //not support. //static _thread char buf[BUF_SIZE]; static char buf[BUF_SIZE]; char *giveAndGet(int number); void *threadFuc(void *arg); int main(int argc,char* argv[]) { pthread_t t; char *str; int s; int number=1; str=giveAndGet(3); s=pthread_create(&t,NULL,threadFuc,(void *)(intptr_t)number); if(s!=0){ printf("create error\n"); exit(1); } s=pthread_join(t,NULL); if(s!=0){ printf("join error\n"); exit(1); } printf("Main buf is [%s]\n",str); return 0; } char *giveAndGet(int number){ switch(number){ case 0: sprintf(buf,"you give me 0"); break; case 1: sprintf(buf,"you give me 1"); break; case 2: sprintf(buf,"you give me 2"); break; default: sprintf(buf,"I dont know"); break; } return buf; } void *threadFuc(void *arg){ int number=(intptr_t)arg; char *str=giveAndGet(number); printf("thread buf is [%s]\n",str); return NULL; }
Markdown
UTF-8
2,889
3
3
[]
no_license
## Goal A common 3D game uses to have models (3D also) created by designers/modellers on software like [3DS Max](http://www.autodesk.es/products/3ds-max/overview) or [Blender](https://www.blender.org/). Models are exported in known formats so can be read from game engines. One of those formats is [FBX](https://en.wikipedia.org/wiki/FBX), an standard within games industry. In the following paragraphs, you will learn to load an .fbx model and add it into an scene. ## Hands-on ### With Wave Visual Editor Create a new project with Wave Visual Editor. On the Asset Details panel, double click on Assets folder: ![](images/LoadModelFromFile/AssetsDetailPane.jpg) Right click on its empty space and select Import Asset. We will add [isis.fbx](https://github.com/WaveEngine/Samples/blob/master/Graphics3D/IsisTemple/Content/Assets/Models/isis.fbx) file, which is part of the [IsisTemple sample](https://github.com/WaveEngine/Samples/tree/master/Graphics3D/IsisTemple/Content/Assets/Models). Once Wave Visual Editor has loaded the model, simply drag and drop the item into the Viewport: ![](images/LoadModelFromFile/DragIsisModel.jpg) ### With Visual Studio/Xamarin Studio Open the project from Visual Studio or Xamarin Studio, and rebuild the solution just to update `WaveContent.cs` -a helper to easily reference the paths to the assets you have added in Wave Visual Editor. There are a few pieces -components actually- needed to handle an .fbx model (appart from those needed to place an entity in a 3D world): * [SkinnedModel](xref:WaveEngine.Components.Graphics3D.SkinnedModel): in charge of loading the .fbx file, also reads the animations such file has. * [SkinnedModelRenderer](xref:WaveEngine.Components.Graphics3D.SkinnedModelRenderer): makes the final render. * [Animation3D](xref:WaveEngine.Components.Animation.Animation3D): since our model is "skinned", it implies we want to handle its animations to trigger those in any moment of the game. This functionality is specifically covered [here](Play-an-Animated-FBX-Model.md). Modify your `Scene.CreateScene()` method in this way (notice how `isis.fbx` is referenced through `WaveContent`): ```C# protected override void CreateScene() { this.Load(WaveContent.Scenes.MyScene); var isis = new Entity() .AddComponent(new Transform3D()) .AddComponent(new MaterialsMap()) .AddComponent(new SkinnedModel(WaveContent.Assets.isis_fbx)) .AddComponent(new Animation3D()) .AddComponent(new SkinnedModelRenderer()); this.EntityManager.Add(isis); } ``` In the end, we are adding the same entity hierarchy Wave Visual Editor creates when we drag and drop the model to the scene: ![] (images/LoadModelFromFile/EntityDetails.jpg) ## Wrap-up This recipe has guided us through what is an FBX file and how it can be loaded into Wave Engine, both visually and through source code.
Java
UTF-8
582
1.976563
2
[]
no_license
package com.scuse.mapper; import com.scuse.entity.Candidate; import java.util.List; import org.springframework.stereotype.Repository; @Repository public interface CandidateMapper { int insert(Candidate record); int insertSelective(Candidate record); Candidate selectByToken(String token); Candidate selectByPhone(String phone); Candidate selectByMail(String mail); Candidate selectByIdNum(String idNum); Candidate selectById(int id); int getMaxID(); int updateByPrimaryKeySelective(Candidate candidate); List<Candidate> getAll(); }
PHP
UTF-8
795
2.609375
3
[ "MIT" ]
permissive
<?php namespace App\Models\Scrum; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; class Sprint_Model_Team_Model extends Model { protected $table = 'sprint_team'; protected $fillable = ['sprint_id', 'team_id','state', 'sprint_team_worked_hours', 'sprint_team_capacity']; // Funciones estaticas public static function getRecord($sprint,$team){ // Funcion que retorna el id de un registro de la tabla sprint_team // que coincida con un equipo en especifico y un sprint $id = DB::table('sprint_team AS st') ->select('st.id') ->where('st.sprint_id', '=', $sprint) ->where('st.team_id', '=', $team) ->first(); return $id; } }
PHP
UTF-8
610
2.796875
3
[]
no_license
<!DOCTYPE html> <html> <body> <?php $server = "localhost"; $user = "kguo"; $pwd = "17417174"; $db = "kguo_1"; $conn = new mysqli($server, $user, $pwd, $db); if($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql_select = "SELECT * FROM Video"; if($res = $conn->query($sql_select)) { while($row = $res->fetch_assoc()) { echo "Video ID: " . $row["id"] . " Title: " . $row["Title"] . " Channel_ID: " . $row["Channel_id"] . " Publish date: " . $row["Publish_date"] . " Views: " . $row["Views"] . "<br>"; } } mysqli_close($conn); ?> </body> </html>
Java
UTF-8
683
3.421875
3
[]
no_license
package JavaCore4.File; import java.io.File; public class FileDemo2 { public static void main(String[] args) { File dir = new File("G:\\Person"); dir.mkdir(); //directory will be created String dirlocation = dir.getAbsolutePath(); //get the directory path that was created System.out.println("Directory Path : "+dirlocation); System.out.println("Directory Name : "+dir.getName()); //get the directory name if (dir.delete()) { System.out.println(dir.getName()+" directory/folder has been deleted."); } } }
Python
UTF-8
1,228
3.09375
3
[]
no_license
import numpy as np class Q_Learner: def __init__(self, world, epsilon=0.4, alpha=0.1, gamma=1): self.world = world self.epsilon = epsilon self.alpha = alpha self.gamma = gamma self.q_matrix = dict() for x in range(world.height): for y in range(world.width): self.q_matrix[(x, y)] = {'up': 0, 'down': 0, 'left': 0, 'right': 0} def choose_direction(self, possible_directions): if np.random.uniform(0, 1) < self.epsilon: chosen_direction = possible_directions[np.random.randint(0, len(possible_directions))] else: q_vals = self.q_matrix[self.world.robotLoc] maxValue = max(q_vals.values()) chosen_direction = np.random.choice([k for k, v in q_vals.items() if v == maxValue]) return chosen_direction def learn(self, p_state, c_state, reward, direction): q_vals = self.q_matrix[c_state] maxValue = max(q_vals.values()) current_q = self.q_matrix[p_state][direction] self.q_matrix[p_state][direction] = (1 - self.alpha) * current_q + self.alpha * (reward + self.gamma * maxValue) def show_table(self): print(self.q_matrix)
C++
UTF-8
1,123
2.546875
3
[]
no_license
#include"ANN.h" using namespace ml; ANN::ANN() { ann = ANN_MLP::create(); } ANN::~ANN() { ; } void ANN::setLayerSize(Mat layerSize) { if(ann != NULL) { ann->setLayerSizes(layerSize); } return; } void ANN::setTrainMethod(ml::ANN_MLP::TrainingMethods trainMethod) { if(ann != NULL) { ann->setTrainMethod(trainMethod, 0.1, 0.1); } return; } void ANN::setActivationFunction(ml::ANN_MLP::ActivationFunctions activationFunction) { if(ann != NULL) { ann->setActivationFunction(activationFunction); } return; } void ANN::train(const Mat& trainData, ml::SampleTypes sampleType, Mat& response) { if(ann != NULL) { ann->train(trainData, sampleType, response); } } float ANN::predict(Mat& sampleMat, Mat& responseMat) { if(ann != NULL) { return ann->predict(sampleMat, responseMat); } return 0; } bool ANN::load(const String& filename) { ann = Algorithm::load<ANN_MLP>(filename); if(ann != NULL) { return true; } else { ann = ANN_MLP::create(); return false; } } void ANN::save(const String& filename) { ann->save(filename); } bool ANN::isTrained() { return ann->isTrained(); }
JavaScript
UTF-8
453
2.875
3
[]
no_license
// Mapbox API Key MAPBOX_API_KEY = "pk.eyJ1IjoibWVsbHVzYnJhbmRvbiIsImEiOiJja3FzcXQ0bG4ycWFrMm9tdmN3bmNxZHd3In0.zp0RMIIVSgMBMW_E-JycrQ"; // The endpoint used for fetching data from geocoding MAPBOX_ENPOINT = "https://api.mapbox.com/geocoding/v5/mapbox.places"; // Sets the API call to use postcodes for retrieving data from geocoding MAPBOX_PARAMS = `types=postcode&access_token=${MAPBOX_API_KEY}`; // Generates the full URL for the API call function generateApiCall(zipcode) { return `${MAPBOX_ENPOINT}/${zipcode}.json?${MAPBOX_PARAMS}`; }
C++
UTF-8
2,786
3.578125
4
[]
no_license
#include <iostream> using std::cin; using std::cout; using std::endl; class Vehicle { public: virtual double getCapacity()const { return capacity; } virtual double getExpense()const { return expense; } virtual double getNumPassengers()const { return numPassengers; } virtual double getMaxSpeed()const { return 500; //Testing if in one class doesn't exist this method } virtual double getHorsepower()const { return horsepower; } private: double capacity; double expense; //per 100km int numPassengers; double maxSpeed; int horsepower; }; class Car : public Vehicle { public: Car(double _capacity, double _expense, int _numPassengers, double _maxSpeed, int _horsepowers) :capacity(_capacity), expense(_expense), numPassengers(_numPassengers), maxSpeed(_maxSpeed), horsepowers(_horsepowers) {} double getCapacity()const { return capacity; } double getExpense()const { return expense; } double getNumPassengers()const { return numPassengers; } double getMaxSpeed()const { return maxSpeed; } double setNewMaxSpeed(double newSpeed) { return newSpeed; } double getHorsepower()const { return horsepowers; } /* void print()const { cout << "Type vehicle: Car" << endl; cout << "Expense per 100km: " << getExpense()<<"l" << endl; cout << "Total capacity: " << getCapacity() << "l" << endl; cout << "Maximum speed: " << getMaxSpeed() << "km/h" << endl; cout << "Maximum number of passengers: " << getNumPassengers() << endl; cout << "Horsepowers: " << getHorsepower() << endl; } */ private: double capacity; double expense; int numPassengers; double maxSpeed; int horsepowers; }; class Truck: public Vehicle { public: Truck(double _capacity, double _expense, int _numPassengers, double _maxSpeed, int _horsepowers) :capacity(_capacity), expense(_expense), numPassengers(_numPassengers), maxSpeed(_maxSpeed), horsepowers(_horsepowers) {} double getCapacity()const { return capacity; } double getExpense()const { return expense; } double getNumPassengers()const { return numPassengers; } //double getMaxSpeed()const //{ //return maxSpeed; //} double setNewMaxSpeed(double newSpeed) { return newSpeed; } double getHorsepower()const { return horsepowers; } private: double capacity; double expense; int numPassengers; double maxSpeed; int horsepowers; }; int main() { Car car(53.6, 12.09, 7, 250, 180); Truck truck(115.5, 40.06, 3, 180, 450); Vehicle *v1 = &car; Vehicle *v2 = &truck; Vehicle v3; cout << "NumPassenger in car: " << v1->getNumPassengers() << endl; cout << "Max Speed truck: " << v2->getMaxSpeed() << endl; cout << "Horsepower truck: " << v2->getHorsepower()<<endl; cout << "Max speed vehicle: " << v3.getMaxSpeed() << endl; return 0; }
Python
UTF-8
1,283
3.28125
3
[ "MIT" ]
permissive
import sys from copy import deepcopy from itertools import chain, product def parse_seats(instream): return [list(iter(l.strip())) for l in instream if l.strip()] def find_adjacent(r, c, seats): candidates = [(r + rd, c + cd) for (rd, cd) in product([-1, 0, 1], [-1, 0, 1]) if (rd, cd) != (0, 0)] return [seats[r][c] for (r, c) in candidates if (0 <= r < len(seats)) and (0 <= c < len(seats[r]))] def is_empty_and_isolated(seat, r, c, seats): return seat == 'L' and find_adjacent(r, c, seats).count('#') == 0 def is_occupied_and_surrounded(seat, r, c, seats): return seat == '#' and find_adjacent(r, c, seats).count('#') >= 4 def advance_seats(seats): new_seats = deepcopy(seats) for r, row in enumerate(seats): for c, seat in enumerate(row): if is_empty_and_isolated(seat, r, c, seats): new_seats[r][c] = '#' elif is_occupied_and_surrounded(seat, r, c, seats): new_seats[r][c] = 'L' return new_seats def main(): seats = parse_seats(sys.stdin) old_seats = [] while old_seats != seats: old_seats = seats seats = advance_seats(seats) print(list(chain.from_iterable(seats)).count('#')) if __name__ == '__main__': main()
Markdown
UTF-8
166,985
3.125
3
[]
no_license
[toc] # 5 SWIG 基础知识 This chapter describes the basic operation of SWIG, the structure of its input files, and how it handles standard ANSI C declarations. C++ support is described in the next chapter. However, C++ programmers should still read this chapter to understand the basics. Specific details about each target language are described in later chapters. > 本章介绍了 SWIG 的基本操作,输入文件的结构,以及它如何处理标准 ANSI C 声明。对 C++ 的支持将在下一章中介绍。但是,C++ 程序员仍应阅读本章以了解基础知识。有关每种目标语言的具体细节将在后面的章节中介绍。 ## 5.1 运行 SWIG To run SWIG, use the `swig` command with options and a filename like this: > 要运行 SWIG,请配合选项和文件名使用 `swig` 命令: ``` swig [ options ] filename ``` where `filename` is a SWIG interface file or a C/C++ header file. Below is a subset of `options` that can be used. Additional options are also defined for each target language. A full list can be obtained by typing `swig -help` or `swig *-<lang>* -help` for language `*<lang>*` specific options. > 其中 `filename` 是一个 SWIG 接口文件或一个 C/C++ 头文件。下面是 `options` 可选范围的子集。也为每一个目标语言定义额外的选项。完整的列表可以通过 `swig -help` 或 `swig -<lang> -help` 获得(`<lang>` 针对特定语言)。 ``` -allegrocl Generate ALLEGROCL wrappers -chicken Generate CHICKEN wrappers -clisp Generate CLISP wrappers -cffi Generate CFFI wrappers -csharp Generate C# wrappers -d Generate D wrappers -go Generate Go wrappers -guile Generate Guile wrappers -java Generate Java wrappers -javascript Generate Javascript wrappers -lua Generate Lua wrappers -modula3 Generate Modula 3 wrappers -mzscheme Generate Mzscheme wrappers -ocaml Generate Ocaml wrappers -octave Generate Octave wrappers -perl Generate Perl wrappers -php5 Generate PHP5 wrappers -php7 Generate PHP7 wrappers -pike Generate Pike wrappers -python Generate Python wrappers -r Generate R (aka GNU S) wrappers -ruby Generate Ruby wrappers -scilab Generate Scilab wrappers -sexp Generate Lisp S-Expressions wrappers -tcl Generate Tcl wrappers -uffi Generate Common Lisp / UFFI wrappers -xml Generate XML wrappers -c++ Enable C++ processing -cppext ext Change file extension of C++ generated files to ext (default is cxx, except for PHP5 which uses cpp) -Dsymbol Define a preprocessor symbol -Fmicrosoft Display error/warning messages in Microsoft format -Fstandard Display error/warning messages in commonly used format -help Display all options -Idir Add a directory to the file include path -lifile Include SWIG library file <ifile> -module name Set the name of the SWIG module -o outfile Set name of C/C++ output file to <outfile> -oh headfile Set name of C++ output header file for directors to <headfile> -outcurrentdir Set default output dir to current dir instead of input file's path -outdir dir Set language specific files output directory -pcreversion Display PCRE version information -swiglib Report location of SWIG library and exit -version Display SWIG version number ``` ### 5.1.1 输入格式 As input, SWIG expects a file containing ANSI C/C++ declarations and special SWIG directives. More often than not, this is a special SWIG interface file which is usually denoted with a special `.i` or `.swg` suffix. In certain cases, SWIG can be used directly on raw header files or source files. However, this is not the most typical case and there are several reasons why you might not want to do this (described later). The most common format of a SWIG interface is as follows: > SWIG 需要一个包含 ANSI C/C++ 声明和特殊 SWIG 指令的文件作为输入。通常,这是一个特殊的 SWIG 接口文件,用特殊的 `.i` 或 `.swg` 后缀表示。在某些情况下,SWIG 可以直接用于原始头文件或源文件。但是,这不是最典型的情况,并且有几个原因可能导致你不想这样做(稍后介绍)。 > > SWIG 接口最常见的格式如下: ``` %module mymodule %{ #include "myheader.h" %} // Now list ANSI C/C++ declarations int foo; int bar(int x); ... ``` The module name is supplied using the special `%module` directive. Modules are described further in the [Modules Introduction](http://www.swig.org/Doc3.0/Modules.html#Modules_introduction) section. Everything in the `%{ ... %}` block is simply copied verbatim to the resulting wrapper file created by SWIG. This section is almost always used to include header files and other declarations that are required to make the generated wrapper code compile. It is important to emphasize that just because you include a declaration in a SWIG input file, that declaration does *not* automatically appear in the generated wrapper code---therefore you need to make sure you include the proper header files in the `%{ ... %}` section. It should be noted that the text enclosed in `%{ ... %}` is not parsed or interpreted by SWIG. The `%{...%}` syntax and semantics in SWIG is analogous to that of the declarations section used in input files to parser generation tools such as yacc or bison. > 模块名由特定的 `%module` 指令提供。对模块的进一步讨论在[模块-引言](http://www.swig.org/Doc3.0/Modules.html#Modules_introduction)章节。 > > `%{...%}` 块中的所有内容都只会逐字复制到 SWIG 最终创建的包装器文件中。此部分几乎总是用于包含头文件和其他声明用于生成的包装器代码的编译。重点强调,因为你仅仅在 SWIG 输入文件中包含一个声明,该声明*不会*自动出现在生成的包装器代码中——因此你需要确保在 `%{...%}` 部分中包含正确的头文件。应该注意的是,SWIG 不解析或解释包含在 `%{...%}` 中的文本。SWIG 中的 `%{...%}` 语法和语义类似于解析器生成工具(如 yacc 或 bison)输入文件中的声明部分。 ### 5.1.2 SWIG 输出 The output of SWIG is a C/C++ file that contains all of the wrapper code needed to build an extension module. SWIG may generate some additional files depending on the target language. By default, an input file with the name `file.i` is transformed into a file `file_wrap.c` or `file_wrap.cxx` (depending on whether or not the `-c++` option has been used). The name of the output C/C++ file can be changed using the `-o` option. In certain cases, file suffixes are used by the compiler to determine the source language (C, C++, etc.). Therefore, you have to use the `-o` option to change the suffix of the SWIG-generated wrapper file if you want something different than the default. For example: > SWIG 的输出是一个 C/C++ 文件,其中包含构建扩展模块所需的所有包装器代码。SWIG 可能会根据目标语言生成一些其他文件。默认情况下,名为 `file.i` 的输入文件将转换为文件 `file_wrap.c` 或 `file_wrap.cxx`(取决于是否使用了 `-c++` 选项)。可以使用 `-o` 选项更改 C/C++ 输出文件的名称。在某些情况下,编译器使用文件后缀来确定源语言(C、C++ 等)。因此,如果需要不同于默认值的东西,则必须使用 `-o` 选项来更改 SWIG 生成的包装器文件的后缀。例如: ``` $ swig -c++ -python -o example_wrap.cpp example.i ``` The C/C++ output file created by SWIG often contains everything that is needed to construct an extension module for the target scripting language. SWIG is not a stub compiler nor is it usually necessary to edit the output file (and if you look at the output, you probably won't want to). To build the final extension module, the SWIG output file is compiled and linked with the rest of your C/C++ program to create a shared library. For many target languages SWIG will also generate proxy class files in the target language. The default output directory for these language specific files is the same directory as the generated C/C++ file. This can be modified using the `-outdir` option. For example: > SWIG 创建的 C/C++ 输出文件通常包含为目标脚本语言构建扩展模块所需的所有内容。SWIG 不是存根编译器(stub compiler),通常也不需要编辑输出文件(如果你看一看输出文件,你可能不会想要去编辑)。要构建最终的扩展模块,SWIG 输出文件将被编译并与其余的 C/C++ 程序链接以创建动态库。 > > 对于许多目标语言,SWIG 还将生成目标语言的代理类文件。这些特定于语言的文件的默认输出目录与生成的 C/C++ 文件是同一目录。这可以使用 `-outdir` 选项进行修改。例如: ``` $ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i ``` If the directories `cppfiles` and `pyfiles` exist, the following will be generated: > 如果目录 `cppfiles` 和 `pyfiles` 存在,将生成以下内容: ``` cppfiles/example_wrap.cpp pyfiles/example.py ``` If the `-outcurrentdir` option is used (without `-o`) then SWIG behaves like a typical C/C++ compiler and the default output directory is then the current directory. Without this option the default output directory is the path to the input file. If `-o` and `-outcurrentdir` are used together, `-outcurrentdir` is effectively ignored as the output directory for the language files is the same directory as the generated C/C++ file if not overridden with `-outdir`. > 如果使用 `-outcurrentdir` 选项(没有 `-o`),则 SWIG 的行为类似于典型的 C/C++ 编译器,默认输出目录则是当前目录。如果没有此选项,则默认输出目录是输入文件的路径。如果同时使用 `-o` 和 `-outcurrentdir`,`-outcurrentdir` 实际上会被忽略,因为语言文件的输出目录与生成的 C/C++ 文件是相同的目录,如果没有用 `-outdir` 覆盖的话。 ### 5.1.3 注释 C and C++ style comments may appear anywhere in interface files. In previous versions of SWIG, comments were used to generate documentation files. However, this feature is currently under repair and will reappear in a later SWIG release. > C 和 C++ 样式的注释可以出现在接口文件中的任何位置。在早期版本的 SWIG 中,注释用于生成文档文件。但是,此功能目前正在修复中,并将在稍后的 SWIG 版本中重新出现。 ### 5.1.4 C 预处理器 Like C, SWIG preprocesses all input files through an enhanced version of the C preprocessor. All standard preprocessor features are supported including file inclusion, conditional compilation and macros. However, `#include` statements are ignored unless the `-includeall` command line option has been supplied. The reason for disabling includes is that SWIG is sometimes used to process raw C header files. In this case, you usually only want the extension module to include functions in the supplied header file rather than everything that might be included by that header file (i.e., system headers, C library functions, etc.). It should also be noted that the SWIG preprocessor skips all text enclosed inside a `%{...%}` block. In addition, the preprocessor includes a number of macro handling enhancements that make it more powerful than the normal C preprocessor. These extensions are described in the "[Preprocessor](http://www.swig.org/Doc3.0/Preprocessor.html#Preprocessor)" chapter. > 与 C 一样,SWIG 通过 C 预处理器的增强版预处理所有输入文件。支持所有标准预处理器功能,包括文件包含、条件编译和宏。但是,除非提供了 `-includeall` 命令行选项,否则将忽略 `#include` 语句。禁用包括的原因是 SWIG 有时用于处理原始 C 头文件。在这种情况下,你通常只希望扩展模块包含所提供的头文件中的函数,而不是该头文件可能包含的所有内容(即系统头文件、C 库函数等)。 > > 还应注意,SWIG 预处理器会跳过括在 `%{...%}` 块内的所有文本。此外,预处理器还包括许多宏处理增强功能,使其比普通的 C 预处理器更强大。这些扩展在[预处理器](http://www.swig.org/Doc3.0/Preprocessor.html#Preprocessor)一章中描述。 ### 5.1.5 SWIG 指令 Most of SWIG's operation is controlled by special directives that are always preceded by a "`%`" to distinguish them from normal C declarations. These directives are used to give SWIG hints or to alter SWIG's parsing behavior in some manner. Since SWIG directives are not legal C syntax, it is generally not possible to include them in header files. However, SWIG directives can be included in C header files using conditional compilation like this: > SWIG 的大多数操作都是由特殊指令控制的,这些指令总是以 `%` 开头,以区别于普通的 C 声明。这些指令用于给 SWIG 提供提示或以某种方式更改 SWIG 的解析行为。 > > 由于 SWIG 指令不是合法的 C 语法,因此通常不可能将它们包含在头文件中。但是,SWIG 指令可以使用条件编译包含在 C 头文件中,如下所示: ```c /* header.h --- Some header file */ /* SWIG directives -- only seen if SWIG is running */ #ifdef SWIG %module foo #endif ``` `SWIG` is a special preprocessing symbol defined by SWIG when it is parsing an input file. > `SWIG` 是 SWIG 在解析输入文件时定义的特殊预处理符号。 ### 5.1.6 解析限制 Although SWIG can parse most C/C++ declarations, it does not provide a complete C/C++ parser implementation. Most of these limitations pertain to very complicated type declarations and certain advanced C++ features. Specifically, the following features are not currently supported: * Non-conventional type declarations. For example, SWIG does not support declarations such as the following (even though this is legal C): > 虽然 SWIG 可以解析大多数 C/C++ 声明,但它不提供完整的 C/C++ 解析器实现。大多数这些限制都与非常复杂的类型声明,以及某些高级 C++ 功能有关。具体而言,目前不支持以下功能: > > * 非传统类型声明。例如,SWIG 不支持以下声明(即使这是合法的 C): ```c /* Non-conventional placement of storage specifier (extern) */ const int extern Number; /* Extra declarator grouping */ Matrix (foo); // A global variable /* Extra declarator grouping in parameters */ void bar(Spam (Grok)(Doh)); ``` In practice, few (if any) C programmers actually write code like this since this style is never featured in programming books. However, if you're feeling particularly obfuscated, you can certainly break SWIG (although why would you want to?). * Running SWIG on C++ source files (the code in a .c, .cpp or .cxx file) is not recommended. The usual approach is to feed SWIG header files for parsing C++ definitions and declarations. The main reason is if SWIG parses a scoped definition or declaration (as is normal for C++ source files), it is ignored, unless a declaration for the symbol was parsed earlier. For example > 实际上,很少(如果有的话)有 C 程序员实际编写这样的代码,因为这种风格从未出现在编程书籍中。但是,如果你感到特别困惑,你就确定是在违反 SWIG(为什么非要这么做呢?)。 > > * 不建议在 C++ 源文件(`.c`、`.cpp` 或 `.cxx` 文件中的代码)上运行 SWIG。通常的方法是给 SWIG 提供头文件以解析 C++ 定义和声明。主要原因是如果 SWIG 解析范围定义或声明(对于 C++ 源文件来说是正常的),源文件将被忽略,除非先前解析了符号的声明。例如 ```c++ /* bar not wrapped unless foo has been defined and the declaration of bar within foo has already been parsed */ int foo::bar(int) { ... whatever ... } ``` * Certain advanced features of C++ such as nested classes are not yet fully supported. Please see the C++ [Nested classes](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_nested_classes) section for more information. In the event of a parsing error, conditional compilation can be used to skip offending code. For example: > * C++ 的某些高级功能(如嵌套类)尚未完全支持。有关更多信息,请参阅 C++ [嵌套类](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_nested_classes)部分。 > > 如果出现解析错误,可以使用条件编译来跳过非法代码。例如: ```c #ifndef SWIG ... some bad declarations ... #endif ``` Alternatively, you can just delete the offending code from the interface file. One of the reasons why SWIG does not provide a full C++ parser implementation is that it has been designed to work with incomplete specifications and to be very permissive in its handling of C/C++ datatypes (e.g., SWIG can generate interfaces even when there are missing class declarations or opaque datatypes). Unfortunately, this approach makes it extremely difficult to implement certain parts of a C/C++ parser as most compilers use type information to assist in the parsing of more complex declarations (for the truly curious, the primary complication in the implementation is that the SWIG parser does not utilize a separate *typedef-name* terminal symbol as described on p. 234 of K&R). > 或者,你可以从接口文件中删除有问题的代码。 > > SWIG 没有提供完整的 C++ 解析器实现的原因之一是它被设计为使用不完整的规范,并且在处理 C/C++ 数据类型时非常宽松(例如,即使有丢失的类声明或透明数据类型,SWIG 也可以生成接口)。不幸的是,这种方法使得实现 C/C++ 解析器的某些部分变得极其困难,因为大多数编译器使用类型信息来帮助解析更复杂的声明(深层原因是,实现中的主要复杂性是 SWIG 解析器不使用单独的 *typedef-name* 终止符,如 K&R 第 234 页所述)。 ## 5.2 包装简单的 C 声明 SWIG wraps simple C declarations by creating an interface that closely matches the way in which the declarations would be used in a C program. For example, consider the following interface file: > SWIG 通过创建一个接口文件来包装简单的 C 声明,与 C 程序中声明的使用方式非常地匹配。例如,请考虑以下接口文件: ``` %module example %inline %{ extern double sin(double x); extern int strcmp(const char *, const char *); extern int Foo; %} #define STATUS 50 #define VERSION "1.1" ``` In this file, there are two functions `sin()` and `strcmp()`, a global variable `Foo`, and two constants `STATUS` and `VERSION`. When SWIG creates an extension module, these declarations are accessible as scripting language functions, variables, and constants respectively. For example, in Tcl: > 在这个文件中,有两个函数 `sin()` 和 `strcmp()`,一个全局变量 `Foo`,以及两个常量 `STATUS` 和 `VERSION`。当 SWIG 创建扩展模块时,这些声明可以分别作为脚本语言的函数、变量和常量访问。例如,在 Tcl 中: ```tcl % sin 3 5.2335956 % strcmp Dave Mike -1 % puts $Foo 42 % puts $STATUS 50 % puts $VERSION 1.1 ``` Or in Python: > 或 Python 中: ```python >>> example.sin(3) 5.2335956 >>> example.strcmp('Dave', 'Mike') -1 >>> print example.cvar.Foo 42 >>> print example.STATUS 50 >>> print example.VERSION 1.1 ``` Whenever possible, SWIG creates an interface that closely matches the underlying C/C++ code. However, due to subtle differences between languages, run-time environments, and semantics, it is not always possible to do so. The next few sections describe various aspects of this mapping. > 只要有可能,SWIG 就会创建一个与底层 C/C++ 代码紧密匹配的接口。但是,由于语言、运行时环境和语义之间的细微差别,并不总是可以这样做。接下来的几节将介绍这种映射的各个方面。 ### 5.2.1 处理基本类型 In order to build an interface, SWIG has to convert C/C++ datatypes to equivalent types in the target language. Generally, scripting languages provide a more limited set of primitive types than C. Therefore, this conversion process involves a certain amount of type coercion. Most scripting languages provide a single integer type that is implemented using the `int` or `long` datatype in C. The following list shows all of the C datatypes that SWIG will convert to and from integers in the target language: > 为了构建接口,SWIG 必须将 C/C++ 数据类型转换为目标语言中的等效类型。通常,脚本语言提供比 C 更有限的一组原始类型。因此,此转换过程涉及一定量的类型强制。 > > 大多数脚本语言提供单个整数类型,使用 C 中的 `int` 或 `long` 数据类型实现。SWIG 将把下列表中显示的所有 C 数据类型转换为目标语言的整数: ``` int short long unsigned signed unsigned short unsigned long unsigned char signed char bool ``` When an integral value is converted from C, a cast is used to convert it to the representation in the target language. Thus, a 16 bit short in C may be promoted to a 32 bit integer. When integers are converted in the other direction, the value is cast back into the original C type. If the value is too large to fit, it is silently truncated. `unsigned char` and `signed char` are special cases that are handled as small 8-bit integers. Normally, the `char` datatype is mapped as a one-character ASCII string. The `bool` datatype is cast to and from an integer value of 0 and 1 unless the target language provides a special boolean type. Some care is required when working with large integer values. Most scripting languages use 32-bit integers so mapping a 64-bit long integer may lead to truncation errors. Similar problems may arise with 32 bit unsigned integers (which may appear as large negative numbers). As a rule of thumb, the `int` datatype and all variations of `char` and `short` datatypes are safe to use. For `unsigned int` and `long` datatypes, you will need to carefully check the correct operation of your program after it has been wrapped with SWIG. Although the SWIG parser supports the `long long` datatype, not all language modules support it. This is because `long long` usually exceeds the integer precision available in the target language. In certain modules such as Tcl and Perl5, `long long` integers are encoded as strings. This allows the full range of these numbers to be represented. However, it does not allow `long long` values to be used in arithmetic expressions. It should also be noted that although `long long` is part of the ISO C99 standard, it is not universally supported by all C compilers. Make sure you are using a compiler that supports `long long` before trying to use this type with SWIG. SWIG recognizes the following floating point types : > 当从 C 转换整数值时,使用强制转换将其转换为目标语言中的表示。因此,C 中的 16 位整数可以被提升为 32 位整数。当整数在另一个方向上转换时,该值将被转换回原始 C 类型。如果该值太大而无法匹配,则会被默默截断。 > > `unsigned char` 和 `signed char` 是特殊情况,以 8 位整数处理。通常,`char` 数据类型被映射为单字符 ASCII 字符串。 > > 除非目标语言提供特殊的布尔类型,否则 `bool` 数据类型将转换为 `0` 和 `1`。 > > 使用大整数值时需要注意一些事项。大多数脚本语言使用 32 位整数,因此映射 64 位整数可能会导致截断错误。32 位无符号整数可能会出现类似的问题(可能显示为大的负数)。根据经验,`int` 以及 `char` 和 `short` 的所有变体都可以安全使用。对于 `unsigned int` 和 `long`,在使用 SWIG 包装后,你需要仔细检查程序的正确性。 > > 虽然 SWIG 解析器支持 `long long` 数据类型,但并非所有语言模块都支持它。这是因为 `long long` 通常超过目标语言中可用的整数精度。在某些语言中,如 Tcl 和 Perl5,`long long` 整数被编码为字符串。这允许表示这些数字的全部范围。但是,它不允许在算术表达式中使用 `long long` 值。还应该注意的是,虽然 `long long` 是 ISO C99 标准的一部分,但并非所有 C 编译器普遍支持。在尝试将此类型与 SWIG 一起使用之前,请确保使用支持 `long long` 的编译器。 > > SWIG 识别以下浮点类型: ``` float double ``` Floating point numbers are mapped to and from the natural representation of floats in the target language. This is almost always a C `double`. The rarely used datatype of `long double` is not supported by SWIG. The `char` datatype is mapped into a NULL terminated ASCII string with a single character. When used in a scripting language it shows up as a tiny string containing the character value. When converting the value back into C, SWIG takes a character string from the scripting language and strips off the first character as the char value. Thus if the value "foo" is assigned to a `char` datatype, it gets the value `f'. The `char *` datatype is handled as a NULL-terminated ASCII string. SWIG maps this into a 8-bit character string in the target scripting language. SWIG converts character strings in the target language to NULL terminated strings before passing them into C/C++ . The default handling of these strings does not allow them to have embedded NULL bytes. Therefore, the `char *` datatype is not generally suitable for passing binary data. However, it is possible to change this behavior by defining a SWIG typemap. See the chapter on [Typemaps](http://www.swig.org/Doc3.0/Typemaps.html#Typemaps) for details about this. At this time, SWIG provides limited support for Unicode and wide-character strings (the C `wchar_t` type). Some languages provide typemaps for wchar_t, but bear in mind these might not be portable across different operating systems. This is a delicate topic that is poorly understood by many programmers and not implemented in a consistent manner across languages. For those scripting languages that provide Unicode support, Unicode strings are often available in an 8-bit representation such as UTF-8 that can be mapped to the `char *`type (in which case the SWIG interface will probably work). If the program you are wrapping uses Unicode, there is no guarantee that Unicode characters in the target language will use the same internal representation (e.g., UCS-2 vs. UCS-4). You may need to write some special conversion functions. > 浮点数映射到目标语言中浮点数的自然表示形式。这几乎总是一个 C `double`。SWIG 不支持很少使用的 `long double` 数据类型。 > > `char` 数据类型映射到带有 NULL 终止符的单字符 ASCII 字符串。在脚本语言中使用时,它显示为包含字符值的小字符串。将值转换回 C 时,SWIG 从脚本语言中获取一个字符串,并将第一个字符作为字符值剥离。因此,如果将值 `foo` 分配给 `char` 数据类型,则它将获得值 `f`。 > > `char *` 数据类型作为以 NULL 结尾的 ASCII 字符串处理。SWIG 将此映射为目标脚本语言中的 8 位字符串。SWIG 将目标语言中的字符串转换为 NULL 结尾的字符串,然后再将它们传递给 C/C++ 。这些字符串的默认处理不允许它们具有嵌入的 NULL 字节。因此,`char *` 数据类型通常不适合传递二进制数据。但是,可以通过定义 SWIG 类型映射来更改此行为。有关详细信息,请参阅[类型映射](http://www.swig.org/Doc3.0/Typemaps.html#Typemaps)一章。 > > 目前,SWIG 对 Unicode 和宽字符串(C `wchar_t` 类型)提供有限的支持。有些语言为 `wchar_t` 提供了类型映射,但请记住,这些语言可能无法在不同的操作系统中移植。这是一个微妙的主题,很多程序员都很难理解,而且没有以一致的方式跨语言实现。对于那些提供 Unicode 支持的脚本语言,Unicode 字符串通常以 8 位表示形式提供,例如 UTF-8,可以映射到 `char *` 类型(在这种情况下,SWIG 接口可能会起作用)。如果要包装的程序使用 Unicode,则无法保证目标语言中的 Unicode 字符将使用相同的内部表示(例如,UCS-2 与 UCS-4)。你可能需要编写一些特殊的转换函数。 ### 5.2.2 全局变量 Whenever possible, SWIG maps C/C++ global variables into scripting language variables. For example, > 只要有可能,SWIG 就会将 C/C++ 全局变量映射到脚本语言变量中。例如, ``` %module example double foo; ``` results in a scripting language variable like this: > 最终的脚本语言变量如下: ``` # Tcl set foo [3.5] ;# Set foo to 3.5 puts $foo ;# Print the value of foo # Python cvar.foo = 3.5 # Set foo to 3.5 print cvar.foo # Print value of foo # Perl $foo = 3.5; # Set foo to 3.5 print $foo, "\n"; # Print value of foo # Ruby Module.foo = 3.5 # Set foo to 3.5 print Module.foo, "\n" # Print value of foo ``` Whenever the scripting language variable is used, the underlying C global variable is accessed. Although SWIG makes every attempt to make global variables work like scripting language variables, it is not always possible to do so. For instance, in Python, all global variables must be accessed through a special variable object known as `cvar`(shown above). In Ruby, variables are accessed as attributes of the module. Other languages may convert variables to a pair of accessor functions. For example, the Java module generates a pair of functions `double get_foo()` and `set_foo(double val)` that are used to manipulate the value. Finally, if a global variable has been declared as `const`, it only supports read-only access. Note: this behavior is new to SWIG-1.3. Earlier versions of SWIG incorrectly handled `const` and created constants instead. > 每当使用脚本语言变量时,都会访问底层 C 全局变量。虽然 SWIG 尽一切努力使全局变量像脚本语言变量一样工作,但并不总是这样做。例如,在 Python 中,必须通过称为 `cvar` 的特殊变量对象(如上所示)访问所有全局变量。在 Ruby 中,变量作为模块的属性进行访问。其他语言可以将变量转换为一对存取函数。例如,Java 模块生成一对函数 `double get_foo()` 和 `set_foo(double val)` 用于操作该值。 > > 最后,如果全局变量已声明为 `const`,则它仅支持只读访问。注意:此行为是 SWIG-1.3 的新增功能。早期版本的 SWIG 错误地处理了 `const` 并改为创建了常量。 ### 5.2.3 常量 Constants can be created using `#define`, enumerations, or a special `%constant` directive. The following interface file shows a few valid constant declarations : > 可以使用 `#define`、枚举或特殊的 `%constant` 指令创建常量。以下接口文件显示了一些有效的常量声明: ``` #define I_CONST 5 // An integer constant #define PI 3.14159 // A Floating point constant #define S_CONST "hello world" // A string constant #define NEWLINE '\n' // Character constant enum boolean {NO=0, YES=1}; enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; %constant double BLAH = 42.37; #define PI_4 PI/4 #define FLAGS 0x04 | 0x08 | 0x40 ``` In `#define` declarations, the type of a constant is inferred by syntax. For example, a number with a decimal point is assumed to be floating point. In addition, SWIG must be able to fully resolve all of the symbols used in a `#define` in order for a constant to actually be created. This restriction is necessary because `#define` is also used to define preprocessor macros that are definitely not meant to be part of the scripting language interface. For example: > 在 `#define` 声明中,常量的类型由语法推断。例如,假设带小数点的数字是浮点数。此外,SWIG 必须能够完全解析 `#define` 中使用的所有符号,以便实际创建常量。这种限制是必要的,因为 `#define` 也用于定义预处理器宏,这些宏绝对不是脚本语言接口的一部分。例如: ``` #define EXTERN extern EXTERN void foo(); ``` In this case, you probably don't want to create a constant called `EXTERN`(what would the value be?). In general, SWIG will not create constants for macros unless the value can be completely determined by the preprocessor. For instance, in the above example, the declaration > 在这种情况下,你可能不希望创建一个名为 `EXTERN` 的常量(值是什么?)。通常,SWIG 不会为宏创建常量,除非该值可以由预处理器完全确定。例如,在上面的例子中,声明 ``` #define PI_4 PI/4 ``` defines a constant because `PI` was already defined as a constant and the value is known. However, for the same conservative reasons even a constant with a simple cast will be ignored, such as > 定义一个常量,因为 `PI` 已被定义为常量且值已知。但是,出于同样的保守原因,即使是简单强制转换的常量也会被忽略,例如 ``` #define F_CONST (double) 5 // A floating point constant with cast ``` The use of constant expressions is allowed, but SWIG does not evaluate them. Rather, it passes them through to the output file and lets the C compiler perform the final evaluation (SWIG does perform a limited form of type-checking however). For enumerations, it is critical that the original enum definition be included somewhere in the interface file (either in a header file or in the `%{ %}` block). SWIG only translates the enumeration into code needed to add the constants to a scripting language. It needs the original enumeration declaration in order to get the correct enum values as assigned by the C compiler. The `%constant` directive is used to more precisely create constants corresponding to different C datatypes. Although it is not usually needed for simple values, it is more useful when working with pointers and other more complex datatypes. Typically, `%constant` is only used when you want to add constants to the scripting language interface that are not defined in the original header file. > 允许使用常量表达式,但 SWIG 不会对它们进行求值。相反,它将它们传递给输出文件,并让 C 编译器执行最终求值(但 SWIG 确实执行了有限形式的类型检查)。 > > 对于枚举,将原始枚举定义包含在接口文件中的某个位置(在头文件或 `%{ %}` 块中)至关重要。SWIG 仅将枚举转换为向脚本语言添加常量所需的代码。它需要原始的枚举声明才能获得 C 编译器指定的正确枚举值。 > > `%constant` 指令用于更精确地创建与不同 C 数据类型对应的常量。虽然简单值通常不需要它,但在使用指针和其他更复杂的数据类型时更有用。通常,只有当你想要向脚本语言接口添加原始头文件中未定义的常量时才使用 `%constant`。 ### 5.2.4 一点关于 `const` 的文字 A common confusion with C programming is the semantic meaning of the `const` qualifier in declarations--especially when it is mixed with pointers and other type modifiers. In fact, previous versions of SWIG handled `const` incorrectly--a situation that SWIG-1.3.7 and newer releases have fixed. Starting with SWIG-1.3, all variable declarations, regardless of any use of `const`, are wrapped as global variables. If a declaration happens to be declared as `const`, it is wrapped as a read-only variable. To tell if a variable is `const` or not, you need to look at the right-most occurrence of the `const` qualifier (that appears before the variable name). If the right-most `const` occurs after all other type modifiers (such as pointers), then the variable is `const`. Otherwise, it is not. Here are some examples of `const` declarations. > C 编程的一个常见疑惑是声明中 `const` 限定符的语义含义——特别是当它与指针和其他类型修饰符混合时。实际上,早期版本的 SWIG 错误地处理了 `const`,这已在 SWIG-1.3.7 和更新版本修复。 > > 从 SWIG-1.3 开始,所有变量声明,无论怎样使用 `const`,都被包装为全局变量。如果声明恰好声明为 `const`,则它将被包装为只读变量。要判断一个变量是否为 `const`,你需要查看最右边出现的 `const` 限定符(出现在变量名之前)。如果最右边的 `const` 出现在所有其他类型修饰符(例如指针)之后,那么变量是 `const`。否则,事实并非如此。 > > 以下是 `const` 声明的一些示例。 ```c const char a; // A constant character char const b; // A constant character (the same) char *const c; // A constant pointer to a character const char *const d; // A constant pointer to a constant character ``` Here is an example of a declaration that is not `const`: > 不是 `const` 声明的一些示例: ```c const char *e; // A pointer to a constant character. The pointer // may be modified. ``` In this case, the pointer `e` can change---it's only the value being pointed to that is read-only. Please note that for const parameters or return types used in a function, SWIG pretty much ignores the fact that these are const, see the section on [const-correctness](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_const) for more information. **Compatibility Note:** One reason for changing SWIG to handle `const` declarations as read-only variables is that there are many situations where the value of a `const` variable might change. For example, a library might export a symbol as `const` in its public API to discourage modification, but still allow the value to change through some other kind of internal mechanism. Furthermore, programmers often overlook the fact that with a constant declaration like `char *const`, the underlying data being pointed to can be modified--it's only the pointer itself that is constant. In an embedded system, a `const`declaration might refer to a read-only memory address such as the location of a memory-mapped I/O device port (where the value changes, but writing to the port is not supported by the hardware). Rather than trying to build a bunch of special cases into the `const`qualifier, the new interpretation of `const` as "read-only" is simple and exactly matches the actual semantics of `const` in C/C++ . If you really want to create a constant as in older versions of SWIG, use the `%constant` directive instead. For example: > 在这种情况下,指针 `e` 可以改变——只是它指向的值是只读的。 > > 请注意,对于函数中使用的 `const` 参数或返回类型,SWIG 几乎忽略了这些是 `const` 的事实,请参阅 [`const` 正确性](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_const)部分了解更多信息。 > > **注意兼容性:**更改 SWIG 以将 `const` 声明作为只读变量处理的一个原因是,在很多情况下,`const` 变量的值可能会发生变化。例如,库可能会在其公共 API 中将符号导出为 `const` 以阻止修改,但仍允许通过其他类型的内部机制更改该值。此外,程序员经常忽略这样一个事实:使用像 `char *const` 这样的常量声明,可以修改指向的底层数据——它只是指针本身是常量。在嵌入式系统中,`const` 声明可能指的是只读存储器地址,例如内存映射 I/O 设备端口的位置(值发生变化,但硬件不支持写入端口)。不是试图在 `const` 修饰符中构建一堆特殊情况,而是将 `const` 作为“只读”的新解释很简单,并且与 C/C++ 中 `const` 的实际语义完全匹配。如果你真的想在旧版本的 SWIG 中创建一个常量,请改用 `%constant` 指令。例如: ``` %constant double PI = 3.14159; ``` or > 或 ``` #ifdef SWIG #define const %constant #endif const double foo = 3.4; const double bar = 23.4; const int spam = 42; #ifdef SWIG #undef const #endif ... ``` ### 5.2.5 `char *` 的注意事项 Before going any further, there is one bit of caution involving `char *` that must now be mentioned. When strings are passed from a scripting language to a C `char *`, the pointer usually points to string data stored inside the interpreter. It is almost always a really bad idea to modify this data. Furthermore, some languages may explicitly disallow it. For instance, in Python, strings are supposed to be immutable. If you violate this, you will probably receive a vast amount of wrath when you unleash your module on the world. The primary source of problems are functions that might modify string data in place. A classic example would be a function like this: > 在继续之前,必须提到一点 `char *` 的注意事项。当字符串从脚本语言传递到 C `char *` 时,指针通常指向存储在解释器中的字符串数据。修改这些数据几乎总是一个坏主意。此外,某些语言可能明确禁止它。例如,在 Python 中,字符串应该是不可变的。如果你违反了这一点,那么当你发布你的模块时,你可能会收到一大波愤怒的意见。 > > 问题的主要来源是可能会修改字符串数据的函数。一个典型的例子是这样的函数: ```c char *strcat(char *s, const char *t) ``` Although SWIG will certainly generate a wrapper for this, its behavior will be undefined. In fact, it will probably cause your application to crash with a segmentation fault or other memory related problem. This is because `s` refers to some internal data in the target language--data that you shouldn't be touching. The bottom line: don't rely on `char *` for anything other than read-only input values. However, it must be noted that you could change the behavior of SWIG using [typemaps](http://www.swig.org/Doc3.0/Typemaps.html#Typemaps). > 虽然 SWIG 肯定会为此生成一个包装器,但它的行为将是未定义的。实际上,它可能会导致应用程序崩溃,导致分段错误或其他与内存相关的问题。这是因为 `s` 指向的是目标语言中的一些内部数据——你不应该碰的数据。 > > 底线:除了只读输入值之外,不要依赖 `char *`。但是,必须注意,你可以使用[类型映射](http://www.swig.org/Doc3.0/Typemaps.html#Typemaps)更改 SWIG 的行为。 ## 5.3 指针与复杂对象 Most C programs manipulate arrays, structures, and other types of objects. This section discusses the handling of these datatypes. > 大多数 C 程序会操纵数组、结构体和其他类型的对象。本节讨论这些数据类型的处理。 ### 5.3.1 简单指针 Pointers to primitive C datatypes such as > SWIG 完全支持指向原始 C 数据类型的指针。 ```c int * double *** char ** ``` are fully supported by SWIG. Rather than trying to convert the data being pointed to into a scripting representation, SWIG simply encodes the pointer itself into a representation that contains the actual value of the pointer and a type-tag. Thus, the SWIG representation of the above pointers (in Tcl), might look like this: > SWIG 不试图将指向的数据转换为脚本表示,而是简单地将指针本身编码为包含指针实际值和类型标记的表示。因此,上述指针(在 Tcl 中)的 SWIG 表示可能如下所示: ```tcl _10081012_p_int _1008e124_ppp_double _f8ac_pp_char ``` A NULL pointer is represented by the string "NULL" or the value 0 encoded with type information. All pointers are treated as opaque objects by SWIG. Thus, a pointer may be returned by a function and passed around to other C functions as needed. For all practical purposes, the scripting language interface works in exactly the same way as you would use the pointer in a C program. The only difference is that there is no mechanism for dereferencing the pointer since this would require the target language to understand the memory layout of the underlying object. The scripting language representation of a pointer value should never be manipulated directly. Even though the values shown look like hexadecimal addresses, the numbers used may differ from the actual machine address (e.g., on little-endian machines, the digits may appear in reverse order). Furthermore, SWIG does not normally map pointers into high-level objects such as associative arrays or lists (for example, converting an `int *` into an list of integers). There are several reasons why SWIG does not do this: * There is not enough information in a C declaration to properly map pointers into higher level constructs. For example, an `int *` may indeed be an array of integers, but if it contains ten million elements, converting it into a list object is probably a bad idea. * The underlying semantics associated with a pointer is not known by SWIG. For instance, an `int *` might not be an array at all--perhaps it is an output value! * By handling all pointers in a consistent manner, the implementation of SWIG is greatly simplified and less prone to error. > NULL 指针由字符串 `NULL` 或用类型信息编码的值 `0` 表示。 > > SWIG 将所有指针视为不透明对象。因此,指针可以由函数返回并根据需要传递给其他 C 函数。出于所有实际目的,脚本语言接口的工作方式与在 C 程序中使用指针的方式完全相同。唯一的区别是没有解引用指针的机制,因为这需要目标语言来理解底层对象的内存布局。 > > 永远不要直接操作指针值的脚本语言表示。尽管所示的值看起来像十六进制地址,但所使用的数字可能与实际的机器地址不同(例如,在小端机器上,数字可能以相反的顺序出现)。此外,SWIG 通常不会将指针映射到高级对象,例如关联数组或列表(例如,将 `int *` 转换为整数列表)。SWIG 不这样做有几个原因: > > * C 声明中没有足够的信息来将指针正确映射到更高级别的结构。例如,`int *` 可能确实是一个整数数组,但如果它包含一千万个元素,将它转换为一个列表对象可能是一个坏主意。 > * SWIG 不知道与指针相关的基础语义。例如,`int *` 可能根本不是一个数组——也许它是一个输出值! > * 通过以一致的方式处理所有指针,SWIG 的实现大大简化并且不容易出错。 ### 5.3.2 运行时指针类型检查 By allowing pointers to be manipulated from a scripting language, extension modules effectively bypass compile-time type checking in the C/C++ compiler. To prevent errors, a type signature is encoded into all pointer values and is used to perform run-time type checking. This type-checking process is an integral part of SWIG and can not be disabled or modified without using typemaps (described in later chapters). Like C, `void *` matches any kind of pointer. Furthermore, `NULL` pointers can be passed to any function that expects to receive a pointer. Although this has the potential to cause a crash, `NULL` pointers are also sometimes used as sentinel values or to denote a missing/empty value. Therefore, SWIG leaves NULL pointer checking up to the application. > 通过允许从脚本语言操作指针,扩展模块有效地绕过了 C/C++ 编译器中的编译时类型检查。为了防止错误,类型签名被编码到所有指针值中,并用于执行运行时类型检查。此类型检查过程是 SWIG 的组成部分,不使用类型映射就无法禁用或修改(在后面的章节中有介绍)。 > > 像 C 一样,`void *` 匹配任何类型的指针。此外,NULL 指针可以传递给任何期望接受指针的函数。虽然这有可能导致崩溃,但 NULL 指针有时也用作标记值或表示缺失/空值。因此,SWIG 将 NULL 指针对应到应用程序。 ### 5.3.3 派生类型、结构体和类 For everything else (structs, classes, arrays, etc...) SWIG applies a very simple rule : **Everything else is a pointer** In other words, SWIG manipulates everything else by reference. This model makes sense because most C/C++ programs make heavy use of pointers and SWIG can use the type-checked pointer mechanism already present for handling pointers to basic datatypes. Although this probably sounds complicated, it's really quite simple. Suppose you have an interface file like this : > 对于其他一切(结构体、类、数组等),SWIG 应用了一个非常简单的规则: > > **其他一切皆是指针** > > 换句话说,SWIG 通过引用操纵其他所有内容。这个模型很有意义,因为大多数 C/C++ 程序都大量使用指针,SWIG 可以使用已经存在的指针类型检查机制来处理指向基本数据类型的指针。 > > 虽然这可能听起来很复杂,但它确实非常简单。假设你有一个这样的接口文件: ``` %module fileio FILE *fopen(char *, char *); int fclose(FILE *); unsigned fread(void *ptr, unsigned size, unsigned nobj, FILE *); unsigned fwrite(void *ptr, unsigned size, unsigned nobj, FILE *); void *malloc(int nbytes); void free(void *); ``` In this file, SWIG doesn't know what a `FILE` is, but since it's used as a pointer, so it doesn't really matter what it is. If you wrapped this module into Python, you can use the functions just like you expect : > 在这个文件中,SWIG 不知道 `FILE` 是什么,但由于它被用作指针,所以它并不重要。如果将此模块包装到 Python 中,则可以像预期的那样使用这些函数: ```python # Copy a file def filecopy(source, target): f1 = fopen(source, "r") f2 = fopen(target, "w") buffer = malloc(8192) nbytes = fread(buffer, 8192, 1, f1) while (nbytes > 0): fwrite(buffer, 8192, 1, f2) nbytes = fread(buffer, 8192, 1, f1) free(buffer) ``` In this case `f1`, `f2`, and `buffer` are all opaque objects containing C pointers. It doesn't matter what value they contain--our program works just fine without this knowledge. > 在这种情况下,`f1`、`f2` 和 `buffer` 都是包含 C 指针的不透明对象。它们包含什么值并不重要——我们的程序在没有这些知识的情况下工作得很好。 ### 5.3.4 未定义数据类型 When SWIG encounters an undeclared datatype, it automatically assumes that it is a structure or class. For example, suppose the following function appeared in a SWIG input file: > 当 SWIG 遇到未声明的数据类型时,它会自动假定它是结构体或类。例如,假设 SWIG 输入文件中出现以下函数: ```c void matrix_multiply(Matrix *a, Matrix *b, Matrix *c); ``` SWIG has no idea what a "`Matrix`" is. However, it is obviously a pointer to something so SWIG generates a wrapper using its generic pointer handling code. Unlike C or C++, SWIG does not actually care whether `Matrix` has been previously defined in the interface file or not. This allows SWIG to generate interfaces from only partial or limited information. In some cases, you may not care what a `Matrix` really is as long as you can pass an opaque reference to one around in the scripting language interface. An important detail to mention is that SWIG will gladly generate wrappers for an interface when there are unspecified type names. However, **all unspecified types are internally handled as pointers to structures or classes!** For example, consider the following declaration: > SWIG 不知道 `Matrix` 是什么。但是,它显然是指向某事物的指针,因此 SWIG 使用其通用指针处理代码生成包装器。 > > 与 C 或 C++ 不同,SWIG 实际上并不关心先前是否在接口文件中定义了 `Matrix`。这允许 SWIG 仅从部分或有限信息生成接口。在某些情况下,只要你可以在脚本语言接口中传递一个不透明的引用,你可能不关心 `Matrix` 是什么。 > > 需要注意的一个重要细节是,当存在未指定的类型名称时,SWIG 将很乐意为接口生成包装器。但是,**所有未指定的类型都在内部处理为指向结构体或类的指针!**例如,请考虑以下声明: ```c void foo(size_t num); ``` If `size_t` is undeclared, SWIG generates wrappers that expect to receive a type of `size_t *` (this mapping is described shortly). As a result, the scripting interface might behave strangely. For example: > 如果 `size_t` 未声明,SWIG 会生成期望接收 `size_t *` 类型的包装器(稍后将描述此映射)。因此,脚本接口可能会表现得很奇怪。例如: ``` foo(40); TypeError: expected a _p_size_t. ``` The only way to fix this problem is to make sure you properly declare type names using `typedef`. > 解决此问题的唯一方法是确保使用 `typedef` 正确声明类型名称。 ### 5.3.5 `typedef` Like C, `typedef` can be used to define new type names in SWIG. For example: > 与 C 一样,`typedef` 可用于在 SWIG 中定义新的类型名称。例如: ```c typedef unsigned int size_t; ``` `typedef` definitions appearing in a SWIG interface are not propagated to the generated wrapper code. Therefore, they either need to be defined in an included header file or placed in the declarations section like this: > 出现在 SWIG 接口中的 `typedef` 定义不会传播到生成的包装器代码。因此,它们需要在包含的头文件中定义,或者放在声明部分中,如下所示: ``` %{ /* Include in the generated wrapper file */ typedef unsigned int size_t; %} /* Tell SWIG about it */ typedef unsigned int size_t; ``` or > 或 ``` %inline %{ typedef unsigned int size_t; %} ``` In certain cases, you might be able to include other header files to collect type information. For example: > 在某些情况下,你可能能够包含其他头文件来收集类型信息。例如: ``` %module example %import "sys/types.h" ``` In this case, you might run SWIG as follows: > 这种情况下,你要如下运行 SWIG: ``` $ swig -I/usr/include -includeall example.i ``` It should be noted that your mileage will vary greatly here. System headers are notoriously complicated and may rely upon a variety of non-standard C coding extensions (e.g., such as special directives to GCC). Unless you exactly specify the right include directories and preprocessor symbols, this may not work correctly (you will have to experiment). SWIG tracks `typedef` declarations and uses this information for run-time type checking. For instance, if you use the above `typedef` and had the following function declaration: > 应该注意的是,你的里程在这里会有很大变化。系统头文件众所周知地复杂并且可能依赖于各种非标准 C 编码扩展(例如,诸如对 GCC 的特殊指令)。除非你确切地指定了正确的包含目录和预处理程序符号,否则这可能无法正常工作(你必须进行实验)。 > > SWIG 跟踪 `typedef` 声明并将此信息用于运行时类型检查。例如,如果你使用上面的 `typedef` 并具有以下函数声明: ```c void foo(unsigned int *ptr); ``` The corresponding wrapper function will accept arguments of type `unsigned int *` or `size_t *`. > 相应的包装函数将接受类型为 `unsigned int *` 或 `size_t *` 的参数。 ## 5.4 其他实操指南 So far, this chapter has presented almost everything you need to know to use SWIG for simple interfaces. However, some C programs use idioms that are somewhat more difficult to map to a scripting language interface. This section describes some of these issues. > 到目前为止,本章介绍了使用 SWIG 进行简单接口时需要了解的几乎所有内容。但是,一些 C 程序使用的惯用法更难以映射到脚本语言接口。本节介绍其中一些问题。 ### 5.4.1 通过值解析结构体 Sometimes a C function takes structure parameters that are passed by value. For example, consider the following function: > 有时,C 函数采用按值传递的结构体参数。例如,请考虑以下函数: ```c double dot_product(Vector a, Vector b); ``` To deal with this, SWIG transforms the function to use pointers by creating a wrapper equivalent to the following: > 为了解决这个问题,SWIG 通过创建一个等效于以下内容的包装器来转换函数以使用指针: ```c double wrap_dot_product(Vector *a, Vector *b) { Vector x = *a; Vector y = *b; return dot_product(x, y); } ``` In the target language, the `dot_product()` function now accepts pointers to Vectors instead of Vectors. For the most part, this transformation is transparent so you might not notice. > 在目标语言中,`dot_product()` 函数现在接受指向 `Vector` 的指针而不是 `Vector`。在大多数情况下,这种转变是透明的,因此你可能不会注意到。 ### 5.4.2 返回值 C functions that return structures or classes datatypes by value are more difficult to handle. Consider the following function: > 按值返回结构体或类数据类型的 C 函数更难处理。考虑以下函数: ```c Vector cross_product(Vector v1, Vector v2); ``` This function wants to return `Vector`, but SWIG only really supports pointers. As a result, SWIG creates a wrapper like this: > 这个函数想要返回 `Vector`,但 SWIG 只支持指针。因此,SWIG 创建了一个这样的包装器: ```c Vector *wrap_cross_product(Vector *v1, Vector *v2) { Vector x = *v1; Vector y = *v2; Vector *result; result = (Vector *) malloc(sizeof(Vector)); *(result) = cross(x, y); return result; } ``` or if SWIG was run with the `-c++` option: > 如果在 `-c++` 模式下运行 SWIG: ```c++ Vector *wrap_cross(Vector *v1, Vector *v2) { Vector x = *v1; Vector y = *v2; Vector *result = new Vector(cross(x, y)); // Uses default copy constructor return result; } ``` In both cases, SWIG allocates a new object and returns a reference to it. It is up to the user to delete the returned object when it is no longer in use. Clearly, this will leak memory if you are unaware of the implicit memory allocation and don't take steps to free the result. That said, it should be noted that some language modules can now automatically track newly created objects and reclaim memory for you. Consult the documentation for each language module for more details. It should also be noted that the handling of pass/return by value in C++ has some special cases. For example, the above code fragments don't work correctly if `Vector` doesn't define a default constructor. The section on SWIG and C++ has more information about this case. > 在这两种情况下,SWIG 都会分配一个新对象并返回对它的引用。用户在不再使用时删除返回的对象。显然,如果你不知道隐式内存分配并且不采取措施来释放结果,这将导致内存泄漏。也就是说,应该注意的是,某些语言模块现在可以自动跟踪新创建的对象并为你回收内存。有关更多详细信息,请参阅每个语言模块的文档。 > > 还应该注意的是,C++ 中按值传递/返回的处理有一些特殊情况。例如,如果 `Vector` 没有定义默认构造函数,则上面的代码片段无法正常工作。SWIG 和 C++ 的部分有关于此案例的更多信息。 ### 5.4.3 链接结构体变量 When global variables or class members involving structures are encountered, SWIG handles them as pointers. For example, a global variable like this > 当遇到涉及结构体的全局变量或类成员时,SWIG 将它们作为指针处理。例如,像这样的全局变量 ```c Vector unit_i; ``` gets mapped to an underlying pair of set/get functions like this : > 被映射到一对底层的 set/get 函数,如下所示: ```c Vector *unit_i_get() { return &unit_i; } void unit_i_set(Vector *value) { unit_i = *value; } ``` Again some caution is in order. A global variable created in this manner will show up as a pointer in the target scripting language. It would be an extremely bad idea to free or destroy such a pointer. Also, C++ classes must supply a properly defined copy constructor in order for assignment to work correctly. > 小心再三。以这种方式创建的全局变量将显示为目标脚本语言中的指针。释放或销毁这样的指针是一个非常糟糕的主意。此外,C++ 类必须提供正确定义的复制构造函数,以使赋值正常工作。 ### 5.4.4 链接到 `char *` When a global variable of type `char *` appears, SWIG uses `malloc()`or `new` to allocate memory for the new value. Specifically, if you have a variable like this > 当出现 `char *` 类型的全局变量时,SWIG 使用 `malloc()` 或 `new` 为新值分配内存。具体来说,如果你有这样的变量 ```c char *foo; ``` SWIG generates the following code: > SWIG 产生如下代码: ```c /* C mode */ void foo_set(char *value) { if (foo) free(foo); foo = (char *) malloc(strlen(value)+1); strcpy(foo, value); } /* C++ mode. When -c++ option is used */ void foo_set(char *value) { if (foo) delete [] foo; foo = new char[strlen(value)+1]; strcpy(foo, value); } ``` If this is not the behavior that you want, consider making the variable read-only using the `%immutable` directive. Alternatively, you might write a short assist-function to set the value exactly like you want. For example: > 如果这不是你想要的行为,请考虑使用 `%immutable` 指令将变量设置为只读。或者,你可以编写一个简短的辅助函数来完全按照你的意愿设置值。例如: ``` %inline %{ void set_foo(char *value) { strncpy(foo, value, 50); } %} ``` Note: If you write an assist function like this, you will have to call it as a function from the target scripting language (it does not work like a variable). For example, in Python you will have to write: > **注意:**如果你编写这样的辅助函数,则必须将其作为函数从目标脚本语言中调用(它不像变量那样工作)。例如,在 Python 中你必须写: ```python >>> set_foo("Hello World") ``` A common mistake with `char *` variables is to link to a variable declared like this: > `char *` 变量的一个常见错误是链接到这样声明的变量: ```c char *VERSION = "1.0"; ``` In this case, the variable will be readable, but any attempt to change the value results in a segmentation or general protection fault. This is due to the fact that SWIG is trying to release the old value using `free`or `delete` when the string literal value currently assigned to the variable wasn't allocated using `malloc()` or `new`. To fix this behavior, you can either mark the variable as read-only, write a typemap (as described in Chapter 6), or write a special set function as shown. Another alternative is to declare the variable as an array: > 在这种情况下,变量将是可读的,但任何更改值的尝试都会导致分段或一般保护错误。这是因为当使用 `malloc()` 或 `new` 分配当前分配给变量的字符串文字值时,SWIG 正试图使用 `free` 或 `delete` 释放旧值。要解决此问题,你可以将变量标记为只读,编写类型映射(如第 6 章所述),或者编写一个特殊的 set 函数。另一种方法是将变量声明为数组: ```c char VERSION[64] = "1.0"; ``` When variables of type `const char *` are declared, SWIG still generates functions for setting and getting the value. However, the default behavior does *not* release the previous contents (resulting in a possible memory leak). In fact, you may get a warning message such as this when wrapping such a variable: > 当声明类型为 `const char *` 的变量时,SWIG 仍会生成用于设置和获取值的函数。但是,默认行为*不*释放先前的内容(导致可能的内存泄漏)。实际上,在包装这样的变量时,你可能会收到一条警告消息: ``` example.i:20. Typemap warning. Setting const char * variable may leak memory ``` The reason for this behavior is that `const char *` variables are often used to point to string literals. For example: > 这种行为的原因是 `const char *` 变量通常用于指向字符串文字。例如: ```c const char *foo = "Hello World\n"; ``` Therefore, it's a really bad idea to call `free()` on such a pointer. On the other hand, it *is* legal to change the pointer to point to some other value. When setting a variable of this type, SWIG allocates a new string (using malloc or new) and changes the pointer to point to the new value. However, repeated modifications of the value will result in a memory leak since the old value is not released. > 因此,在这样的指针上调用 `free()` 是一个非常糟糕的主意。另一方面,将指针更改为指向某个其他值是合法的。设置此类型的变量时,SWIG 会分配一个新字符串(使用 `malloc` 或 `new`)并将指针更改为指向新值。但是,重复修改该值将导致内存泄漏,因为旧值未释放。 ### 5.4.5 数组 Arrays are fully supported by SWIG, but they are always handled as pointers instead of mapping them to a special array object or list in the target language. Thus, the following declarations : > SWIG 完全支持数组,但它们总是作为指针处理,而不是将它们映射到目标语言中的特殊数组对象或列表。因此,以下声明: ```c int foobar(int a[40]); void grok(char *argv[]); void transpose(double a[20][20]); ``` are processed as if they were really declared like this: > 的处理好像它们真的被声明为如下这样: ```c int foobar(int *a); void grok(char **argv); void transpose(double (*a)[20]); ``` Like C, SWIG does not perform array bounds checking. It is up to the user to make sure the pointer points to a suitably allocated region of memory. Multi-dimensional arrays are transformed into a pointer to an array of one less dimension. For example: > 与 C 一样,SWIG 不执行数组边界检查。用户可以确保指针指向适当分配的内存区域。 > > 多维数组被转换为指向较少维度的数组的指针。例如: ```c int [10]; // Maps to int * int [10][20]; // Maps to int (*)[20] int [10][20][30]; // Maps to int (*)[20][30] ``` It is important to note that in the C type system, a multidimensional array `a[][]` is **NOT** equivalent to a single pointer `*a` or a double pointer such as `**a`. Instead, a pointer to an array is used (as shown above) where the actual value of the pointer is the starting memory location of the array. The reader is strongly advised to dust off their C book and re-read the section on arrays before using them with SWIG. Array variables are supported, but are read-only by default. For example: > 值得注意的是,在 C 类型系统中,多维数组 `a[][]` 是不等价于单个指针 `*a` 或双指针如 `**a`。而是使用指向数组的指针(如上所示),其中指针的实际值是数组的起始内存位置。强烈建议读者在使用 SWIG 之前拿出尘封的 C 语言书,并重新阅读数组部分。 > > 支持数组变量,但默认情况下它们是只读的。例如: ```c int a[100][200]; ``` In this case, reading the variable 'a' returns a pointer of type `int (*)[200]` that points to the first element of the array `&a[0][0]`. Trying to modify 'a' results in an error. This is because SWIG does not know how to copy data from the target language into the array. To work around this limitation, you may want to write a few simple assist functions like this: > 在这种情况下,读取变量 `a` 会返回一个类型为 `int (*)[200]` 的指针,指向数组的第一个元素 `&a[0][0]`。试图修改 `a` 会导致错误。这是因为 SWIG 不知道如何将目标语言中的数据复制到数组中。要解决此限制,你可能需要编写一些简单的辅助函数,如下所示: ``` %inline %{ void a_set(int i, int j, int val) { a[i][j] = val; } int a_get(int i, int j) { return a[i][j]; } %} ``` To dynamically create arrays of various sizes and shapes, it may be useful to write some helper functions in your interface. For example: > 要动态创建各种大小和形状的数组,在接口中编写一些辅助函数可能很有用。例如: ``` // Some array helpers %inline %{ /* Create any sort of [size] array */ int *int_array(int size) { return (int *) malloc(size*sizeof(int)); } /* Create a two-dimension array [size][10] */ int (*int_array_10(int size))[10] { return (int (*)[10]) malloc(size*10*sizeof(int)); } %} ``` Arrays of `char` are handled as a special case by SWIG. In this case, strings in the target language can be stored in the array. For example, if you have a declaration like this, > `char` 数组由 SWIG 作为特例处理。在这种情况下,目标语言中的字符串可以存储在数组中。例如,如果你有这样的声明, ```c char pathname[256]; ``` SWIG generates functions for both getting and setting the value that are equivalent to the following code: > SWIG 生成用于获取和设置值的函数,这些函数等效于以下代码: ```c char *pathname_get() { return pathname; } void pathname_set(char *value) { strncpy(pathname, value, 256); } ``` In the target language, the value can be set like a normal variable. > 在目标语言中,可以将值设置为普通变量。 ### 5.4.6 创建只读变量 A read-only variable can be created by using the `%immutable` directive as shown : > 可以使用 `%immutable` 指令创建只读变量,如下所示: ``` // File : interface.i int a; // Can read/write %immutable; int b, c, d; // Read only variables %mutable; double x, y; // read/write ``` The `%immutable` directive enables read-only mode until it is explicitly disabled using the `%mutable` directive. As an alternative to turning read-only mode off and on like this, individual declarations can also be tagged as immutable. For example: > `%immutable` 指令启用只读模式,除非使用 `%mutable` 指令显式禁用它。作为这种关闭和打开只读模式的替代方法,单个声明也可以标记为不可变。例如: ``` %immutable x; // Make x read-only ... double x; // Read-only (from earlier %immutable directive) double y; // Read-write ... ``` The `%mutable` and `%immutable` directives are actually [%feature directives](http://www.swig.org/Doc3.0/Customization.html#Customization_features) defined like this: > `%mutable` 和 `%immutable` 实际上是如下定义的 [`%feature` 指令](http://www.swig.org/Doc3.0/Customization.html#Customization_features): ``` #define %immutable %feature("immutable") #define %mutable %feature("immutable", "") ``` If you wanted to make all wrapped variables read-only, barring one or two, it might be easier to take this approach: > 如果你想将所有包装变量设为只读,而不是一两个,否则采用这种方法可能更容易: ``` %immutable; // Make all variables read-only %feature("immutable", "0") x; // except, make x read/write ... double x; double y; double z; ... ``` Read-only variables are also created when declarations are declared as `const`. For example: > 当声明声明为 `const` 时也会创建只读变量。例如: ```c const int foo; /* Read only variable */ char * const version="1.0"; /* Read only variable */ ``` **Compatibility note:** Read-only access used to be controlled by a pair of directives `%readonly` and `%readwrite`. Although these directives still work, they generate a warning message. Simply change the directives to `%immutable;` and `%mutable;` to silence the warning. Don't forget the extra semicolon! > **注意兼容性:**只读访问过去由一对指令 `%readonly` 和 `%readwrite` 控制。尽管这些指令仍然有效,但它们会生成警告消息。只需将指令更改为 `%immutable;` 和 `%mutable;` 即可使警告静音。**不要忘记额外的分号!** ### 5.4.7 重命名与忽略声明 #### 5.4.7.1 特定标识符的简单重命名 Normally, the name of a C declaration is used when that declaration is wrapped into the target language. However, this may generate a conflict with a keyword or already existing function in the scripting language. To resolve a name conflict, you can use the `%rename`directive as shown : > 通常,当声明包装到目标语言中时,将使用 C 声明的名称。但是,这可能会与脚本语言中的关键字或已存在的函数产生冲突。要解决名称冲突,可以使用 `%rename` 指令,如下所示: ``` // interface.i %rename(my_print) print; extern void print(const char *); %rename(foo) a_really_long_and_annoying_name; extern int a_really_long_and_annoying_name; ``` SWIG still calls the correct C function, but in this case the function `print()` will really be called "`my_print()`" in the target language. The placement of the `%rename` directive is arbitrary as long as it appears before the declarations to be renamed. A common technique is to write code for wrapping a header file like this: > SWIG 仍然调用正确的 C 函数,但在这种情况下,函数 `print()` 将在目标语言中被称为 `my_print()`。 > > `%rename` 指令的放置是任意的,只要它出现在要重命名的声明之前。一种常见的技术是编写用于包装头文件的代码,如下所示: ``` // interface.i %rename(my_print) print; %rename(foo) a_really_long_and_annoying_name; %include "header.h" ``` `%rename` applies a renaming operation to all future occurrences of a name. The renaming applies to functions, variables, class and structure names, member functions, and member data. For example, if you had two-dozen C++ classes, all with a member function named `print' (which is a keyword in Python), you could rename them all to `output' by specifying : > `%rename` 对所有将来出现的名称应用重命名操作。重命名适用于函数、变量、类和结构体名称、成员函数和成员数据。例如,如果你有二十几个 C++ 类,都有一个名为 `print` 的成员函数(它是 Python 中的一个关键字),你可以通过指定它们将它们全部重命名为 `output`: ``` %rename(output) print; // Rename all 'print' functions to 'output' ``` SWIG does not normally perform any checks to see if the functions it wraps are already defined in the target scripting language. However, if you are careful about namespaces and your use of modules, you can usually avoid these problems. Closely related to `%rename` is the `%ignore` directive. `%ignore` instructs SWIG to ignore declarations that match a given identifier. For example: > SWIG 通常不执行任何检查以查看它包装的函数是否已在目标脚本语言中定义。但是,如果你对命名空间和模块的使用非常小心,通常可以避免这些问题。 > > 与 `%rename` 密切相关的是 `%ignore` 指令。`%ignore` 指示 SWIG 忽略与给定标识符匹配的声明。例如: ``` %ignore print; // Ignore all declarations named print %ignore MYMACRO; // Ignore a macro ... #define MYMACRO 123 void print(const char *); ... ``` Any function, variable etc which matches `%ignore` will not be wrapped and therefore will not be available from the target language. A common usage of `%ignore` is to selectively remove certain declarations from a header file without having to add conditional compilation to the header. However, it should be stressed that this only works for simple declarations. If you need to remove a whole section of problematic code, the SWIG preprocessor should be used instead. **Compatibility note:** Older versions of SWIG provided a special `%name`directive for renaming declarations. For example: > 任何与 `%ignore` 匹配的函数、变量等都不会被包装,因此无法在目标语言中使用。`%ignore` 的一个常见用法是有选择地从头文件中删除某些声明,而不必向头部添加条件编译。但是,应该强调的是,这仅适用于简单的声明。如果你需要删除整个有问题的代码段,则应使用 SWIG 预处理器。 > > **注意兼容性:**旧版本的 SWIG 为重命名声明提供了一个特殊的 `%name` 指令。例如: ``` %name(output) extern void print(const char *); ``` This directive is still supported, but it is deprecated and should probably be avoided. The `%rename` directive is more powerful and better supports wrapping of raw header file information. > 仍然支持该指令,但它已被弃用,应该避免使用。`%rename` 指令功能更强大、更好地支持包装原始头文件信息。 #### 5.4.7.2 高级重命名支持 While writing `%rename` for specific declarations is simple enough, sometimes the same renaming rule needs to be applied to many, maybe all, identifiers in the SWIG input. For example, it may be necessary to apply some transformation to all the names in the target language to better follow its naming conventions, like adding a specific prefix to all wrapped functions. Doing it individually for each function is impractical so SWIG supports applying a renaming rule to all declarations if the name of the identifier to be renamed is not specified: > 虽然为特定声明编写 `%rename` 很简单,但有时需要将相同的重命名规则应用于 SWIG 输入中的许多(可能是全部)标识符。例如,可能需要对目标语言中的所有名称应用某些转换,以便更好地遵循其命名约定,例如向所有包装器函数添加特定前缀。为每个函数单独执行操作是不切实际的,因此如果未指定要重命名的标识符的名称,SWIG 支持将重命名规则应用于所有声明: ``` %rename("myprefix_%s") ""; // print -> myprefix_print ``` This also shows that the argument of `%rename` doesn't have to be a literal string but can be a `printf()`-like format string. In the simplest form, `"%s"` is replaced with the name of the original declaration, as shown above. However this is not always enough and SWIG provides extensions to the usual format string syntax to allow applying a (SWIG-defined) function to the argument. For example, to wrap all C functions `do_something_long()` as more Java-like `doSomethingLong()` you can use the `"lowercamelcase"` extended format specifier like this: > 这也表明 `%rename` 的参数不必是文字字符串,但可以是 `printf()` 类型格式的字符串。在最简单的形式中,`%s` 被替换为原始声明的名称,如上所示。然而,这并不总是足够的,并且 SWIG 提供了对通常的格式字符串语法的扩展,以允许将(SWIG 定义的)函数应用于参数。例如,要将所有 C 函数 `do_something_long()` 包装为更像 Java 的 `doSomethingLong()`,你可以使用这样的 `lowercamelcase` 扩展格式说明符: ``` %rename("%(lowercamelcase)s") ""; // foo_bar -> fooBar; FooBar -> fooBar ``` Some functions can be parametrized, for example the `"strip"` one strips the provided prefix from its argument. The prefix is specified as part of the format string, following a colon after the function name: > 某些函数可以进行参数化,例如 `strip` 从其参数中剥离提供的前缀。在函数名称后跟冒号后,前缀被指定为格式字符串的一部分: ``` %rename("%(strip:[wx])s") ""; // wxHello -> Hello; FooBar -> FooBar ``` Below is the table summarizing all currently defined functions with an example of applying each one. Note that some of them have two names, a shorter one and a more descriptive one, but the two functions are otherwise equivalent: > 下面是总结所有当前定义的函数的表,其中包含应用每个函数的示例。请注意,其中一些名称有两个名称,一个较短的名称和一个更具描述性的名称,但这两个函数在其他方面是等效的: | Function | Returns | Example (in/out) | | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ---------- | | `uppercase` or `upper` | Upper case version of the string. | `Print` | `PRINT` | | `lowercase` or `lower` | Lower case version of the string. | `Print` | `print` | | `title` | String with first letter capitalized and the rest in lower case. | `print` | `Print` | | `firstuppercase` | String with the first letter capitalized and the rest unchanged. | `printIt` | `PrintIt` | | `firstlowercase` | String with the first letter in lower case and the rest unchanged. | `PrintIt` | `printIt` | | `camelcase` or `ctitle` | String with capitalized first letter and any letter following an underscore (which are removed in the process) and rest in lower case. | `print_it` | `PrintIt` | | `lowercamelcase` or `lctitle` | String with every letter following an underscore (which is removed in the process) capitalized and rest, including the first letter, in lower case. | `print_it` | `printIt` | | `undercase` or `utitle` | Lower case string with underscores inserted before every upper case letter in the original string and any number not at the end of string. Logically, this is the reverse of `camelcase`. | `PrintIt` | `print_it` | | `schemify` | String with all underscores replaced with dashes, resulting in more Lispers/Schemers-pleasing name. | `print_it` | `print-it` | | `strip:[prefix]` | String without the given prefix or the original string if it doesn't start with this prefix. Note that square brackets should be used literally, e.g. `%rename("strip:[wx]")` | `wxPrint` | `Print` | | `rstrip:[suffix]` | String without the given suffix or the original string if it doesn't end with this suffix. Note that square brackets should be used literally, e.g. `%rename("rstrip:[Cls]")` | `PrintCls` | `Print` | | `regex:/pattern/subst/` | String after (Perl-like) regex substitution operation. This function allows to apply arbitrary regular expressions to the identifier names. The *pattern* part is a regular expression in Perl syntax (as supported by the [Perl Compatible Regular Expressions (PCRE)](http://www.pcre.org/)) library and the *subst* string can contain back-references of the form `\N` where `N` is a digit from 0 to 9, or one of the following escape sequences: `\l`, `\L`, `\u`, `\U` or `\E`. The back-references are replaced with the contents of the corresponding capture group while the escape sequences perform the case conversion in the substitution string: `\l` and `\L` convert to the lower case, while `\u` and `\U`convert to the upper case. The difference between the elements of each pair is that `\l`and `\u` change the case of the next character only, while `\L` and `\U` do it for all the remaining characters or until `\E` is encountered. Finally please notice that backslashes need to be escaped in C strings, so in practice `"\\"` must be used in all these escape sequences. For example, to remove any alphabetic prefix before an underscore and capitalize the remaining part you could use the following directive:`%rename("regex:/(\\w+)_(.*)/\\u\\2/")` | `prefix_print` | `Print` | | `command:cmd` | Output of an external command `cmd` with the string passed to it as input. Notice that this function is extremely slow compared to all the other ones as it involves spawning a separate process and using it for many declarations is not recommended. The *cmd* is not enclosed in square brackets but must be terminated with a triple `'<'` sign, e.g. `%rename("command:tr -d aeiou <<<")`(nonsensical example removing all vowels) | `Print` | `Prnt` | The most general function of all of the above ones (not counting `command` which is even more powerful in principle but which should generally be avoided because of performance considerations) is the`regex` one. Here are some more examples of its use: > 所有上述功能中最常用的功能(不包括 `command`,原则上功能更强大,但由于性能方面的考虑通常应该避免这种功能)是 `regex`。以下是其使用的更多示例: ``` // Strip the wx prefix from all identifiers except those starting with wxEVT %rename("%(regex:/wx(?!EVT)(.*)/\\1/)s") ""; // wxSomeWidget -> SomeWidget // wxEVT_PAINT -> wxEVT_PAINT // Apply a rule for renaming the enum elements to avoid the common prefixes // which are redundant in C#/Java %rename("%(regex:/^([A-Z][a-z]+)+_(.*)/\\2/)s", %$isenumitem) ""; // Colour_Red -> Red // Remove all "Set/Get" prefixes. %rename("%(regex:/^(Set|Get)(.*)/\\2/)s") ""; // SetValue -> Value // GetValue -> Value ``` As before, everything that was said above about `%rename` also applies to `%ignore`. In fact, the latter is just a special case of the former and ignoring an identifier is the same as renaming it to the special`"$ignore"` value. So the following snippets > 和以前一样,关于 `%rename` 的上述内容也适用于 `%ignore`。事实上,后者只是前者的特例,忽略标识符与将其重命名为特殊的 `$ignore` 值相同。所以下面的片段 ``` %ignore print; ``` and > 以及 ``` %rename("$ignore") print; ``` are exactly equivalent and `%rename` can be used to selectively ignore multiple declarations using the previously described matching possibilities. > 完全等价,`%rename` 可用于使用前面描述的匹配可能性选择性地忽略多个声明。 #### 5.4.7.3 限制全局重命名规则 As explained in the previous sections, it is possible to either rename individual declarations or apply a rename rule to all of them at once. In practice, the latter is however rarely appropriate as there are always some exceptions to the general rules. To deal with them, the scope of an unnamed `%rename` can be limited using subsequent `match`parameters. They can be applied to any of the attributes associated by SWIG with the declarations appearing in its input. For example: > 如前面部分所述,可以重命名单个声明,也可以一次将重命名规则应用于所有声明。实际上,后者很少适用,因为一般规则总有一些例外。为了处理它们,可以使用后续的 `match` 参数来限制未命名的 `%rename` 的范围。它们可以应用于 SWIG 关联的任何属性,并在其输入中显示声明。例如: ``` %rename("foo", match$name="bar") ""; ``` can be used to achieve the same effect as the simpler > 可以用更简单的方式达到同样的效果 ``` %rename("foo") bar; ``` and so is not very interesting on its own. However `match` can also be applied to the declaration type, for example `match="class"` restricts the match to class declarations only (in C++) and `match="enumitem"`restricts it to the enum elements. SWIG also provides convenience macros for such match expressions, for example > 所以它本身并不是很有趣。但是 `match` 也可以应用于声明类型,例如 `match ="class"` 仅限于匹配类声明(在 C++ 中)和 `match ="enumitem"` 将它限制为枚举元素。SWIG 还为这种匹配表达式提供了便利的宏,例如 ``` %rename("%(title)s", %$isenumitem) ""; ``` will capitalize the names of all the enum elements but not change the case of the other declarations. Similarly, `%$isclass`, `%$isfunction`,`%$isconstructor`, `%$isunion`, `%$istemplate`, and `%$isvariable`can be used. Many other checks are possible and this documentation is not exhaustive, see the "%rename predicates" section in `swig.swg` for the full list of supported match expressions. In addition to literally matching some string with `match` you can also use `regexmatch` or `notregexmatch` to match a string against a regular expression. For example, to ignore all functions having "Old" as a suffix you could use > 将大写所有枚举元素的名称,但不改变其他声明的大小写。类似地,可以使用 `%$isclass`、`%$isfunction`、`%$isconstructor`、`%$isunion`、`%$istemplate` 和 `%$isvariable`。许多其他检查都是可能的,本文档并非详尽无遗,请参阅 `swig.swg` 中的 `%rename` 谓词部分,以获取支持的匹配表达式的完整列表。 > > 除了将一些字符串与 `match` 字面匹配之外,你还可以使用 `regexmatch` 或 `notregexmatch` 来匹配正则表达式的字符串。例如,要忽略所有具有 `Old` 作为后缀的函数,你可以使用 ``` %rename("$ignore", regexmatch$name="Old$") ""; ``` For simple cases like this, specifying the regular expression for the declaration name directly can be preferable and can also be done using `regextarget`: > 对于像这样的简单情况,直接指定声明名称的正则表达式是可取的,也可以使用 `regextarget` 来完成: ``` %rename("$ignore", regextarget=1) "Old$"; ``` Notice that the check is done only against the name of the declaration itself, if you need to match the full name of a C++ declaration you must use `fullname` attribute: > 请注意,仅对声明本身的名称进行检查,如果需要匹配 C++ 声明的全名,则必须使用 `fullname` 属性: ``` %rename("$ignore", regextarget=1, fullname=1) "NameSpace::ClassName::.*Old$"; ``` As for `notregexmatch`, it restricts the match only to the strings not matching the specified regular expression. So to rename all declarations to lower case except those consisting of capital letters only: > 对于 `notregexmatch`,它仅将匹配限制为与指定正则表达式不匹配的字符串。因此,除了仅包含大写字母的声明外,将所有声明重命名为小写: ``` %rename("$(lower)s", notregexmatch$name="^[A-Z]+$") ""; ``` Finally, variants of `%rename` and `%ignore` directives can be used to help wrap C++ overloaded functions and methods or C++ methods which use default arguments. This is described in the [Ambiguity resolution and renaming](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_ambiguity_resolution_renaming) section in the C++ chapter. > 最后,`%rename` 和 `%ignore` 指令的变体可用于帮助包装 C++ 重载函数和方法或使用默认参数的 C++ 方法。这在 C++ 章节的[消歧义和重命名](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_ambiguity_resolution_renaming)部分中进行了描述。 #### 5.4.7.4 包装一些符号而忽略其他 Using the techniques described above it is possible to ignore everything in a header and then selectively wrap a few chosen methods or classes. For example, consider a header, `myheader.h`which has many classes in it and just the one class called `Star` is wanted within this header, the following approach could be taken: > 使用上述技术,可以忽略头文件中的所有内容,然后有选择地包装一些选定的方法或类。例如,考虑一个头文件,`myheader.h`,其中包含许多类,并且在此头文件中只需要一个名为 `Star` 的类,可以采用以下方法: ``` %ignore ""; // Ignore everything // Unignore chosen class 'Star' %rename("%s") Star; // As the ignore everything will include the constructor, destructor, methods etc // in the class, these have to be explicitly unignored too: %rename("%s") Star::Star; %rename("%s") Star::~Star; %rename("%s") Star::shine; // named method %include "myheader.h" ``` Another approach which might be more suitable as it does not require naming all the methods in the chosen class is to begin by ignoring just the classes. This does not add an explicit ignore to any members of the class, so when the chosen class is unignored, all of its methods will be wrapped. > 有另一种可能更合适的方法(因为它不需要命名所选类中的所有方法),首先忽略类。这不会向类的任何成员添加显式忽略,因此当所选类被取消时,它的所有方法都将被包装。 ``` %rename($ignore, %$isclass) ""; // Only ignore all classes %rename("%s") Star; // Unignore 'Star' %include "myheader.h" ``` ### 5.4.8 默认/可选参数 SWIG supports default arguments in both C and C++ code. For example: > SWIG 支持 C 和 C++ 代码中的默认参数。例如: ```c int plot(double x, double y, int color=WHITE); ``` In this case, SWIG generates wrapper code where the default arguments are optional in the target language. For example, this function could be used in Tcl as follows : > 在这种情况下,SWIG 生成包装器代码,其中默认参数在目标语言中是可选的。例如,此函数可以在 Tcl 中使用,如下所示: ```tcl % plot -3.4 7.5 # Use default value % plot -3.4 7.5 10 # set color to 10 instead ``` Although the ANSI C standard does not allow default arguments, default arguments specified in a SWIG interface work with both C and C++. **Note:** There is a subtle semantic issue concerning the use of default arguments and the SWIG generated wrapper code. When default arguments are used in C code, the default values are emitted into the wrappers and the function is invoked with a full set of arguments. This is different to when wrapping C++ where an overloaded wrapper method is generated for each defaulted argument. Please refer to the section on [default arguments](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_default_args) in the C++ chapter for further details. > 尽管 ANSI C 标准不允许使用默认参数,但 SWIG 接口中指定的默认参数同时适用于 C 和 C++。 > > 关于使用默认参数和 SWIG 生成的包装器代码存在一个微妙的语义问题。当在 C 代码中使用默认参数时,默认值将发送到包装器中,并使用一组完整的参数调用该函数。这与包装 C++ 时的不同之处在于为每个默认参数生成重载的包装器方法。有关更多详细信息,请参阅 C++ 一章中有关[默认参数](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_default_args)的部分。 ### 5.4.9 函数指针与回调 Occasionally, a C library may include functions that expect to receive pointers to functions--possibly to serve as callbacks. SWIG provides full support for function pointers provided that the callback functions are defined in C and not in the target language. For example, consider a function like this: > 有时,C 库可能包含期望接受函数指针的函数——可能用作回调函数。SWIG 提供对函数指针的完全支持,前提是回调函数是用 C 语言定义的,而不是用目标语言定义的。例如,考虑这样的函数: ```c int binary_op(int a, int b, int (*op)(int, int)); ``` When you first wrap something like this into an extension module, you may find the function to be impossible to use. For instance, in Python: > 当你第一次将这样的东西包装到扩展模块中时,你可能会发现该功能无法使用。例如,在 Python 中: ```python >>> def add(x, y): ... return x+y ... >>> binary_op(3, 4, add) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: Type error. Expected _p_f_int_int__int >>> ``` The reason for this error is that SWIG doesn't know how to map a scripting language function into a C callback. However, existing C functions can be used as arguments provided you install them as constants. One way to do this is to use the `%constant` directive like this: > 出现此错误的原因是 SWIG 不知道如何将脚本语言函数映射到 C 回调中。但是,如果将现有 C 函数作为常量安装,则可以将它们用作参数。一种方法是使用 `%constant` 指令,如下所示: ``` /* Function with a callback */ int binary_op(int a, int b, int (*op)(int, int)); /* Some callback functions */ %constant int add(int, int); %constant int sub(int, int); %constant int mul(int, int); ``` In this case, `add`, `sub`, and `mul` become function pointer constants in the target scripting language. This allows you to use them as follows: > 在这种情况下,`add`、`sub` 和 `mul` 成为目标脚本语言中的函数指针常量。这允许你按如下方式使用它们: ```python >>> binary_op(3, 4, add) 7 >>> binary_op(3, 4, mul) 12 >>> ``` Unfortunately, by declaring the callback functions as constants, they are no longer accessible as functions. For example: > 不幸的是,通过将回调函数声明为常量,它们不再可以作为函数访问。例如: ```python >>> add(3, 4) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object is not callable: '_ff020efc_p_f_int_int__int' >>> ``` If you want to make a function available as both a callback function and a function, you can use the `%callback` and `%nocallback`directives like this: > 如果你想把一个函数作为回调函数和函数使用,你可以像这样使用 `%callback` 和 `%nocallback` 指令: ``` /* Function with a callback */ int binary_op(int a, int b, int (*op)(int, int)); /* Some callback functions */ %callback("%s_cb"); int add(int, int); int sub(int, int); int mul(int, int); %nocallback; ``` The argument to `%callback` is a printf-style format string that specifies the naming convention for the callback constants (`%s` gets replaced by the function name). The callback mode remains in effect until it is explicitly disabled using `%nocallback`. When you do this, the interface now works as follows: > `%callback` 的参数是一个 `printf` 样式的格式字符串,它指定了回调常量的命名约定(`%s` 被函数名替换)。回调模式保持有效,直到使用 `%nocallback` 显式禁用它。执行此操作时,接口现在的工作方式如下: ```python >>> binary_op(3, 4, add_cb) 7 >>> binary_op(3, 4, mul_cb) 12 >>> add(3, 4) 7 >>> mul(3, 4) 12 ``` Notice that when the function is used as a callback, special names such as `add_cb` are used instead. To call the function normally, just use the original function name such as `add()`. SWIG provides a number of extensions to standard C printf formatting that may be useful in this context. For instance, the following variation installs the callbacks as all upper case constants such as `ADD`, `SUB`, and `MUL`: > 请注意,当该函数用作回调时,将使用特殊名称,例如 `add_cb`。要正常调用函数,只需使用原始函数名称,例如 `add()`。 > > SWIG 为标准 C `printf` 格式提供了许多扩展,在这种情况下可能很有用。例如,以下变体将回调安装为所有大写常量,例如 `ADD`、`SUB` 和 `MUL`: ``` /* Some callback functions */ %callback("%(uppercase)s"); int add(int, int); int sub(int, int); int mul(int, int); %nocallback; ``` A format string of `"%(lowercase)s"` converts all characters to lower case. A string of `"%(title)s"` capitalizes the first character and converts the rest to lower case. And now, a final note about function pointer support. Although SWIG does not normally allow callback functions to be written in the target language, this can be accomplished with the use of typemaps and other advanced SWIG features. See the [Typemaps chapter](http://www.swig.org/Doc3.0/Typemaps.html#Typemaps) for more about typemaps and individual target language chapters for more on callbacks and the 'director' feature. > 格式字符串 `"%(lowercase)s"` 将所有字符转换为小写。一串 `"%(title)s"` 将第一个字符大写并将其余字符转换为小写字母。 > > 现在,关于函数指针支持的最后一点。尽管 SWIG 通常不允许以目标语言编写回调函数,但这可以通过使用类型映射和其他高级 SWIG 功能来实现。有关字典图和单个目标语言章节的更多信息,请参阅[类型映射章节](http://www.swig.org/Doc3.0/Typemaps.html#Typemaps),了解有关回调和导向器(director)功能的更多信息。 ## 5.5 结构体与共用体 This section describes the behavior of SWIG when processing ANSI C structures and union declarations. Extensions to handle C++ are described in the next section. If SWIG encounters the definition of a structure or union, it creates a set of accessor functions. Although SWIG does not need structure definitions to build an interface, providing definitions makes it possible to access structure members. The accessor functions generated by SWIG simply take a pointer to an object and allow access to an individual member. For example, the declaration : > 本节描述了处理 ANSI C 结构体和共用体声明时 SWIG 的行为。处理 C++ 的扩展将在下一节中介绍。 > > 如果 SWIG 遇到结构体和共用体的定义,它将创建一组访问器函数。虽然 SWIG 不需要结构体定义来构建接口,但提供定义可以使其访问结构体成员。SWIG 生成的访问器函数只需接受指向对象的指针,并允许访问单个成员。例如,声明: ```c struct Vector { double x, y, z; } ``` gets transformed into the following set of accessor functions : > 变为以下一组访问函数: ```c double Vector_x_get(struct Vector *obj) { return obj->x; } double Vector_y_get(struct Vector *obj) { return obj->y; } double Vector_z_get(struct Vector *obj) { return obj->z; } void Vector_x_set(struct Vector *obj, double value) { obj->x = value; } void Vector_y_set(struct Vector *obj, double value) { obj->y = value; } void Vector_z_set(struct Vector *obj, double value) { obj->z = value; } ``` In addition, SWIG creates default constructor and destructor functions if none are defined in the interface. For example: > 此外,如果接口中没有定义,SWIG 会创建默认构造函数和析构函数。例如: ```c struct Vector *new_Vector() { return (Vector *) calloc(1, sizeof(struct Vector)); } void delete_Vector(struct Vector *obj) { free(obj); } ``` Using these low-level accessor functions, an object can be minimally manipulated from the target language using code like this: > 使用这些低级访问器函数,可以使用以下代码从目标语言中对对象进行最低限度的操作: ```c v = new_Vector() Vector_x_set(v, 2) Vector_y_set(v, 10) Vector_z_set(v, -5) ... delete_Vector(v) ``` However, most of SWIG's language modules also provide a high-level interface that is more convenient. Keep reading. > 但是,SWIG 的大多数语言模块也提供了更方便的高级接口。继续阅读。 ### 5.5.1 `typedef` 与结构体 SWIG supports the following construct which is quite common in C programs : > SWIG 支持以下构造,这在 C 程序中很常见: ```c typedef struct { double x, y, z; } Vector; ``` When encountered, SWIG assumes that the name of the object is `Vector` and creates accessor functions like before. The only difference is that the use of `typedef` allows SWIG to drop the `struct` keyword on its generated code. For example: > 当遇到时,SWIG 假定对象的名称是 `Vector` 并创建像之前一样的访问器函数。唯一的区别是使用 `typedef` 允许 SWIG 在其生成的代码上删除 `struct` 关键字。例如: ```c double Vector_x_get(Vector *obj) { return obj->x; } ``` If two different names are used like this : > 如果两个不同的名字被如下使用: ```c typedef struct vector_struct { double x, y, z; } Vector; ``` the name `Vector` is used instead of `vector_struct` since this is more typical C programming style. If declarations defined later in the interface use the type `struct vector_struct`, SWIG knows that this is the same as `Vector` and it generates the appropriate type-checking code. > 使用名称 `Vector` 代替 `vector_struct`,因为这是更典型的 C 编程风格。如果稍后在接口中定义的声明使用类型 `struct vector_struct`,则 SWIG 知道它与 `Vector` 相同,并且它生成适当的类型检查代码。 ### 5.5.2 字符串与结构体 Structures involving character strings require some care. SWIG assumes that all members of type `char *` have been dynamically allocated using `malloc()` and that they are NULL-terminated ASCII strings. When such a member is modified, the previous contents will be released, and the new contents allocated. For example : > 涉及字符串的结构体需要一些小心。SWIG 假定 `char *` 类型的所有成员都是使用 `malloc()` 动态分配的,并且它们是以 NULL 结尾的 ASCII 字符串。修改此类成员后,将释放先前的内容,并分配新内容。例如 : ``` %module mymodule ... struct Foo { char *name; ... } ``` This results in the following accessor functions : > 这导致了如下的访问器函数: ```c char *Foo_name_get(Foo *obj) { return Foo->name; } char *Foo_name_set(Foo *obj, char *c) { if (obj->name) free(obj->name); obj->name = (char *) malloc(strlen(c)+1); strcpy(obj->name, c); return obj->name; } ``` If this behavior differs from what you need in your applications, the SWIG "memberin" typemap can be used to change it. See the typemaps chapter for further details. Note: If the `-c++` option is used, `new` and `delete` are used to perform memory allocation. > 如果此行为与你在应用程序中所需的行为不同,则可以使用 SWIG `memberin` 类型映射来更改它。有关更多详细信息,请参阅类型映射章节。 > > 注意:如果使用 `-c++` 选项,则使用 `new` 和 `delete` 来执行内存分配。 ### 5.5.3 数组成员 Arrays may appear as the members of structures, but they will be read-only. SWIG will write an accessor function that returns the pointer to the first element of the array, but will not write a function to change the contents of the array itself. When this situation is detected, SWIG may generate a warning message such as the following : > 数组可能显示为结构体的成员,但它们将是只读的。SWIG 将编写一个访问器函数,该函数返回指向数组第一个元素的指针,但不会编写一个函数来更改数组本身的内容。检测到这种情况时,SWIG 可能会生成一条警告消息,如下所示: ``` interface.i:116. Warning. Array member will be read-only ``` To eliminate the warning message, typemaps can be used, but this is discussed in a later chapter. In many cases, the warning message is harmless. > 要消除警告消息,可以使用类型映射,但这将在后面的章节中讨论。在许多情况下,警告消息是无害的。 ### 5.5.4 结构体数据成员 Occasionally, a structure will contain data members that are themselves structures. For example: > 有时,结构体将包含本身就是结构体的数据成员。例如: ```c typedef struct Foo { int x; } Foo; typedef struct Bar { int y; Foo f; /* struct member */ } Bar; ``` When a structure member is wrapped, it is handled as a pointer, unless the `%naturalvar` directive is used where it is handled more like a C++ reference (see [C++ Member data](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_member_data)). The accessors to the member variable as a pointer are effectively wrapped as follows: > 当一个结构体成员被包装时,它被作为指针处理,除非使用 `%naturalvar` 指令处理它更像 C++ 引用(参见 [C++ 成员数据](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_member_data))。作为指针的成员变量的访问器函数有效地被包装成如下形式: ```c Foo *Bar_f_get(Bar *b) { return &b->f; } void Bar_f_set(Bar *b, Foo *value) { b->f = *value; } ``` The reasons for this are somewhat subtle but have to do with the problem of modifying and accessing data inside the data member. For example, suppose you wanted to modify the value of `f.x` of a `Bar`object like this: > 其原因有些微妙,但与修改和访问数据成员内部数据的问题有关。例如,假设你想要修改 `Bar` 对象的 `f.x` 的值,如下所示: ```c Bar *b; b->f.x = 37; ``` Translating this assignment to function calls (as would be used inside the scripting language interface) results in the following code: > 将此赋值转换为函数调用(将在脚本语言接口中使用)会产生以下代码: ```c Bar *b; Foo_x_set(Bar_f_get(b), 37); ``` In this code, if the `Bar_f_get()` function were to return a `Foo` instead of a `Foo *`, then the resulting modification would be applied to a *copy*of `f` and not the data member `f` itself. Clearly that's not what you want! It should be noted that this transformation to pointers only occurs if SWIG knows that a data member is a structure or class. For instance, if you had a structure like this, > 在这段代码中,如果 `Bar_f_get()` 函数返回一个 `Foo` 而不是 `Foo *`,那么得到的修改将应用于 `f` 的副本而不是数据成员 `f` 本身。显然,这不是你想要的! > > 应该注意,只有当 SWIG 知道数据成员是结构体或类时,才会发生对指针的转换。例如,如果你有这样的结构, ```c struct Foo { WORD w; }; ``` and nothing was known about `WORD`, then SWIG will generate more normal accessor functions like this: > 并且对 `WORD` 一无所知,那么 SWIG 将生成更多正常的访问器函数,如下所示: ```c WORD Foo_w_get(Foo *f) { return f->w; } void Foo_w_set(FOO *f, WORD value) { f->w = value; } ``` **Compatibility Note:** SWIG-1.3.11 and earlier releases transformed all non-primitive member datatypes to pointers. Starting in SWIG-1.3.12, this transformation *only* occurs if a datatype is known to be a structure, class, or union. This is unlikely to break existing code. However, if you need to tell SWIG that an undeclared datatype is really a struct, simply use a forward struct declaration such as `"struct Foo;"`. > **注意兼容性:**SWIG-1.3.11 及更早版本将所有非原始成员数据类型转换为指针。从 SWIG-1.3.12 开始,如果已知数据类型是结构体、类或共用体则仅发生此转换。这不太可能破坏现有代码。但是,如果你需要告诉 SWIG 一个未声明的数据类型实际上是一个结构体,只需使用一个正向结构体声明,如 `struct Foo;`。 ### 5.5.5 C 构造函数和析构函数 When wrapping structures, it is generally useful to have a mechanism for creating and destroying objects. If you don't do anything, SWIG will automatically generate functions for creating and destroying objects using `malloc()` and `free()`. Note: the use of `malloc()` only applies when SWIG is used on C code (i.e., when the `-c++` option is *not*supplied on the command line). C++ is handled differently. If you don't want SWIG to generate default constructors for your interfaces, you can use the `%nodefaultctor` directive or the `-nodefaultctor` command line option. For example: > 在包装结构体时,通常有一种用于创建和销毁对象的机制。如果你什么都不做,SWIG 会自动生成使用 `malloc()` 和 `free()` 创建和销毁对象的函数。注意:使用 `malloc()` 仅适用于在 C 代码上使用 SWIG(即,在命令行上*不*提供 `-c++` 选项)。C++ 的处理方式不同。 > > 如果你不希望 SWIG 为你的接口生成默认构造函数,则可以使用 `%nodefaultctor` 指令或 `-nodefaultctor` 命令行选项。例如: ``` swig -nodefaultctor example.i ``` or > 或 ``` %module foo ... %nodefaultctor; // Don't create default constructors ... declarations ... %clearnodefaultctor; // Re-enable default constructors ``` If you need more precise control, `%nodefaultctor` can selectively target individual structure definitions. For example: > 如果你需要更精确的控制,`%nodefaultctor` 可以选择性地定位单个结构体定义。例如: ``` %nodefaultctor Foo; // No default constructor for Foo ... struct Foo { // No default constructor generated. }; struct Bar { // Default constructor generated. }; ``` Since ignoring the implicit or default destructors most of the time produces memory leaks, SWIG will always try to generate them. If needed, however, you can selectively disable the generation of the default/implicit destructor by using `%nodefaultdtor` > 由于忽略隐式或默认析构函数大部分时间都会产生内存泄漏,因此 SWIG 将始终尝试生成它们。但是,如果需要,可以使用 `%nodefaultdtor` 选择性地禁用默认/隐式析构函数的生成 ``` %nodefaultdtor Foo; // No default/implicit destructor for Foo ... struct Foo { // No default destructor is generated. }; struct Bar { // Default destructor generated. }; ``` **Compatibility note:** Prior to SWIG-1.3.7, SWIG did not generate default constructors or destructors unless you explicitly turned them on using `-make_default`. However, it appears that most users want to have constructor and destructor functions so it has now been enabled as the default behavior. **Note:** There are also the `-nodefault` option and `%nodefault`directive, which disable both the default or implicit destructor generation. This could lead to memory leaks across the target languages, and it is highly recommended you don't use them. > **注意兼容性:**在 SWIG-1.3.7 之前,SWIG 不会生成默认构造函数或析构函数,除非你使用 `-make_default` 明确打开它们。但是,似乎大多数用户都希望拥有构造函数和析构函数,因此现在已将其作为默认行为启用。 > > **注意:**还有 `-nodefault` 选项和 `%nodefault` 指令,它们禁用默认或隐式析构函数生成。这可能会导致目标语言内存泄漏,强烈建议你不要使用它们。 ### 5.5.6 向 C 结构体添加成员函数 Most languages provide a mechanism for creating classes and supporting object oriented programming. From a C standpoint, object oriented programming really just boils down to the process of attaching functions to structures. These functions normally operate on an instance of the structure (or object). Although there is a natural mapping of C++ to such a scheme, there is no direct mechanism for utilizing it with C code. However, SWIG provides a special `%extend`directive that makes it possible to attach methods to C structures for purposes of building an object oriented interface. Suppose you have a C header file with the following declaration : > 大多数语言都提供了一种创建类和支持面向对象编程的机制。从 C 的角度来看,面向对象编程实际上归结为将函数附加到结构体的过程。这些函数通常在结构体(或对象)的实例上运行。虽然 C++ 有这样一种自然的映射方式,但是没有直接的机制可以将它与 C 代码一起使用。但是,SWIG 提供了一个特殊的 `%extend` 指令,可以将方法附加到 C 结构体以构建面向对象的接口。假设你有一个带有以下声明的 C 头文件: ```c /* file : vector.h */ ... typedef struct Vector { double x, y, z; } Vector; ``` You can make a `Vector` look a lot like a class by writing a SWIG interface like this: > 你可以通过编写如下所示的 SWIG 接口使 `Vector` 看起来很像一个类: ``` // file : vector.i %module mymodule %{ #include "vector.h" %} %include "vector.h" // Just grab original C header file %extend Vector { // Attach these functions to struct Vector Vector(double x, double y, double z) { Vector *v; v = (Vector *) malloc(sizeof(Vector)); v->x = x; v->y = y; v->z = z; return v; } ~Vector() { free($self); } double magnitude() { return sqrt($self->x*$self->x+$self->y*$self->y+$self->z*$self->z); } void print() { printf("Vector [%g, %g, %g]\n", $self->x, $self->y, $self->z); } }; ``` Note the usage of the `$self` special variable. Its usage is identical to a C++ 'this' pointer and should be used whenever access to the struct instance is required. Also note that C++ constructor and destructor syntax has been used to simulate a constructor and destructor, even for C code. There is one subtle difference to a normal C++ constructor implementation though and that is although the constructor declaration is as per a normal C++ constructor, the newly constructed object must be returned **as if** the constructor declaration had a return value, a `Vector *` in this case. Now, when used with proxy classes in Python, you can do things like this : > 注意 `$self` 特殊变量的用法。它的用法与 C++ `this` 指针相同,只要需要访问结构体实例,就应该使用它。另请注意,C++ 构造函数和析构函数语法已用于模拟构造函数和析构函数,即使对于 C 代码也是如此。虽然正常的 C++ 构造函数实现有一个细微的区别,虽然构造函数声明是按照普通的 C++ 构造函数,但是必须返回新构造的对象,**好像**构造函数声明有一个返回值,在这种情况下是 `Vector *`。 > > 现在,当与 Python 中的代理类一起使用时,你可以执行以下操作: ```python >>> v = Vector(3, 4, 0) # Create a new vector >>> print v.magnitude() # Print magnitude 5.0 >>> v.print() # Print it out [ 3, 4, 0 ] >>> del v # Destroy it ``` The `%extend` directive can also be used inside the definition of the Vector structure. For example: > `%extend` 指令也可以在 `Vector` 结构体的定义中使用。例如: ``` // file : vector.i %module mymodule %{ #include "vector.h" %} typedef struct Vector { double x, y, z; %extend { Vector(double x, double y, double z) { ... } ~Vector() { ... } ... } } Vector; ``` Note that `%extend` can be used to access externally written functions provided they follow the naming convention used in this example : > 请注意,`%extend` 可用于访问外部编写的函数,前提是它们遵循此示例中使用的命名约定: ``` /* File : vector.c */ /* Vector methods */ #include "vector.h" Vector *new_Vector(double x, double y, double z) { Vector *v; v = (Vector *) malloc(sizeof(Vector)); v->x = x; v->y = y; v->z = z; return v; } void delete_Vector(Vector *v) { free(v); } double Vector_magnitude(Vector *v) { return sqrt(v->x*v->x+v->y*v->y+v->z*v->z); } // File : vector.i // Interface file %module mymodule %{ #include "vector.h" %} typedef struct Vector { double x, y, z; %extend { Vector(int, int, int); // This calls new_Vector() ~Vector(); // This calls delete_Vector() double magnitude(); // This will call Vector_magnitude() ... } } Vector; ``` The name used for `%extend` should be the name of the struct and not the name of any `typedef` to the struct. For example: > `%extend` 用的名字和结构体的名字相同,而非结构体的 `typedef`。例如: ``` typedef struct Integer { int value; } Int; %extend Integer { ... } /* Correct name */ %extend Int { ... } /* Incorrect name */ struct Float { float value; }; typedef struct Float FloatValue; %extend Float { ... } /* Correct name */ %extend FloatValue { ... } /* Incorrect name */ ``` There is one exception to this rule and that is when the struct is anonymously named such as: > 有一个例外,就是当结构体是匿名的时候,例如: ``` typedef struct { double value; } Double; %extend Double { ... } /* Okay */ ``` A little known feature of the `%extend` directive is that it can also be used to add synthesized attributes or to modify the behavior of existing data attributes. For example, suppose you wanted to make `magnitude` a read-only attribute of `Vector` instead of a method. To do this, you might write some code like this: > `%extend` 指令的一个鲜为人知的功能是它还可以用于添加合成属性或修改现有数据属性的行为。例如,假设你想要 `magnitude` 是 `Vector` 的只读属性而不是方法。为此,你可以编写如下代码: ``` // Add a new attribute to Vector %extend Vector { const double magnitude; } // Now supply the implementation of the Vector_magnitude_get function %{ const double Vector_magnitude_get(Vector *v) { return (const double) sqrt(v->x*v->x+v->y*v->y+v->z*v->z); } %} ``` Now, for all practical purposes, `magnitude` will appear like an attribute of the object. A similar technique can also be used to work with data members that you want to process. For example, consider this interface: > 现在,出于所有实际目的,`magnitude` 将看起来像对象的属性。 > > 类似的技术也可用于处理你要处理的数据成员。例如,考虑这个接口: ```c typedef struct Person { char name[50]; ... } Person; ``` Say you wanted to ensure `name` was always upper case, you can rewrite the interface as follows to ensure this occurs whenever a name is read or written to: > 假设你想确保 `name` 总是大写,你可以按如下方式重写接口,以确保每当读取或写入名称时都会发生这种情况: ``` typedef struct Person { %extend { char name[50]; } ... } Person; %{ #include <string.h> #include <ctype.h> void make_upper(char *name) { char *c; for (c = name; *c; ++c) *c = (char)toupper((int)*c); } /* Specific implementation of set/get functions forcing capitalization */ char *Person_name_get(Person *p) { make_upper(p->name); return p->name; } void Person_name_set(Person *p, char *val) { strncpy(p->name, val, 50); make_upper(p->name); } %} ``` Finally, it should be stressed that even though `%extend` can be used to add new data members, these new members can not require the allocation of additional storage in the object (e.g., their values must be entirely synthesized from existing attributes of the structure or obtained elsewhere). **Compatibility note:** The `%extend` directive is a new name for the `%addmethods` directive. Since `%addmethods` could be used to extend a structure with more than just methods, a more suitable directive name has been chosen. > 最后,应该强调的是,即使 `%extend` 可以用于添加新的数据成员,这些新成员也不需要在对象中分配额外的存储(例如,它们的值必须完全从现有结构体的属性合成或在别处获得)。 > > **注意兼容性:**`%extend` 指令是 `%addmethods` 指令的新名称。由于 `%addmethods` 可以用于扩展具有多个方法的结构,因此选择了更合适的指令名称。 ### 5.5.7 嵌套结构体 Occasionally, a C program will involve structures like this : > 有时候,C 程序会涉及这样的结构体: ```c typedef struct Object { int objtype; union { int ivalue; double dvalue; char *strvalue; void *ptrvalue; } intRep; } Object; ``` When SWIG encounters this, it performs a structure splitting operation that transforms the declaration into the equivalent of the following: > 当 SWIG 遇到此问题时,它会执行结构体拆分操作,将声明转换为以下等效项: ```c typedef union { int ivalue; double dvalue; char *strvalue; void *ptrvalue; } Object_intRep; typedef struct Object { int objType; Object_intRep intRep; } Object; ``` SWIG will then create an `Object_intRep` structure for use inside the interface file. Accessor functions will be created for both structures. In this case, functions like this would be created : > 然后,SWIG 将创建一个 `Object_intRep` 结构,以便在接口文件中使用。将为两个结构创建访问器功能。在这种情况下,将创建这样的函数: ```c Object_intRep *Object_intRep_get(Object *o) { return (Object_intRep *) &o->intRep; } int Object_intRep_ivalue_get(Object_intRep *o) { return o->ivalue; } int Object_intRep_ivalue_set(Object_intRep *o, int value) { return (o->ivalue = value); } double Object_intRep_dvalue_get(Object_intRep *o) { return o->dvalue; } //... etc ... ``` Although this process is a little hairy, it works like you would expect in the target scripting language--especially when proxy classes are used. For instance, in Perl: > 虽然这个过程有点惊险,但它的工作方式与目标脚本语言中的预期相同——尤其是在使用代理类时。例如,在 Perl 中: ```perl # Perl5 script for accessing nested member $o = CreateObject(); # Create an object somehow $o->{intRep}->{ivalue} = 7 # Change value of o.intRep.ivalue ``` If you have a lot of nested structure declarations, it is advisable to double-check them after running SWIG. Although, there is a good chance that they will work, you may have to modify the interface file in certain cases. Finally, note that nesting is handled differently in C++ mode, see [Nested classes](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_nested_classes). > 如果你有很多嵌套结构体声明,建议在运行 SWIG 后仔细检查它们。虽然它们很可能会起作用,但在某些情况下可能需要修改接口文件。 > > 最后,C++ 模式下嵌套的处理方式不同,详见[嵌套类](http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_nested_classes)。 ### 5.5.8 其他关于包装结构体的事项 SWIG doesn't care if the declaration of a structure in a `.i` file exactly matches that used in the underlying C code (except in the case of nested structures). For this reason, there are no problems omitting problematic members or simply omitting the structure definition altogether. If you are happy passing pointers around, this can be done without ever giving SWIG a structure definition. Starting with SWIG 1.3, a number of improvements have been made to SWIG's code generator. Specifically, even though structure access has been described in terms of high-level accessor functions such as this, > SWIG 不关心 `.i` 文件中的结构体声明是否与底层 C 代码中使用的结构体完全匹配(嵌套结构体除外)。出于这个原因,省略有问题的成员或完全省略结构体定义是没有问题的。如果你很高兴传递指针,这可以在不给 SWIG 一个结构体定义的情况下完成。 > > 从 SWIG 1.3 开始,对 SWIG 的代码生成器进行了许多改进。具体来说,即使已经根据诸如此类的高级访问器函数描述了结构体访问, ```c double Vector_x_get(Vector *v) { return v->x; } ``` most of the generated code is actually inlined directly into wrapper functions. Therefore, no function `Vector_x_get()` actually exists in the generated wrapper file. For example, when creating a Tcl module, the following function is generated instead: > 大多数生成的代码实际上直接内联到包装器函数中。因此,生成的包装器文件中实际上不存在函数 `Vector_x_get()`。例如,在创建 Tcl 模块时,会生成以下函数: ```c static int _wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct Vector *arg1 ; double result ; if (SWIG_GetArgs(interp, objc, objv, "p:Vector_x_get self ", &arg0, SWIGTYPE_p_Vector) == TCL_ERROR) return TCL_ERROR; result = (double ) (arg1->x); Tcl_SetObjResult(interp, Tcl_NewDoubleObj((double) result)); return TCL_OK; } ``` The only exception to this rule are methods defined with `%extend`. In this case, the added code is contained in a separate function. Finally, it is important to note that most language modules may choose to build a more advanced interface. Although you may never use the low-level interface described here, most of SWIG's language modules use it in some way or another. > 此规则的唯一例外是使用 `%extend` 定义的方法。在这种情况下,添加的代码包含在单独的函数中。 > > 最后,需要注意的是,大多数语言模块可能会选择构建更高级的接口。虽然你可能永远不会使用此处描述的低级接口,但 SWIG 的大多数语言模块都会以某种方式使用它。 ## 5.6 代码插入 Sometimes it is necessary to insert special code into the resulting wrapper file generated by SWIG. For example, you may want to include additional C code to perform initialization or other operations. There are four common ways to insert code, but it's useful to know how the output of SWIG is structured first. > 有时需要在 SWIG 生成的结果包装器文件中插入特殊代码。例如,你可能希望包含其他 C 代码以执行初始化或其他操作。插入代码有四种常用方法,但首先了解如何构造 SWIG 的输出很有用。 ### 5.6.1 SWIG 的输出 When SWIG creates its output C/C++ file, it is broken up into five sections corresponding to runtime code, headers, wrapper functions, and module initialization code (in that order). * **Begin section**. A placeholder for users to put code at the beginning of the C/C++ wrapper file. This is most often used to define preprocessor macros that are used in later sections. * **Runtime code**. This code is internal to SWIG and is used to include type-checking and other support functions that are used by the rest of the module. * **Header section**. This is user-defined support code that has been included by the `%{ ... %}` directive. Usually this consists of header files and other helper functions. * **Wrapper code**. These are the wrappers generated automatically by SWIG. * **Module initialization**. The function generated by SWIG to initialize the module upon loading. > 当 SWIG 创建其输出 C/C++ 文件时,它将分为五个部分,分别对应于运行时代码、头文件、包装器函数和模块初始化代码(按此顺序)。 > > * **开始部分** > > 用户的占位符,用于将代码放在 C/C++ 包装器文件的开头。这通常用于定义后续部分中使用的预处理器宏。 > > * **运行时代码** > > 此代码是 SWIG 的内部代码,用于包含类型检查和其他模块使用的支持函数。 > > * **头文件部分** > > 这是用户定义的支持代码,已由 `%{...%}` 指令包含。通常这包括头文件和其他辅助函数。 > > * **包装器函数** > > 这些是 SWIG 自动生成的包装器。 > > * **模块初始化** > > SWIG 生成的函数,用于在加载时初始化模块。 ### 5.6.2 代码插入块 The `%insert` directive enables inserting blocks of code into a given section of the generated code. It can be used in one of two ways: > `%insert` 指令允许将代码块插入生成代码的给定部分。它可以使用以下两种方式之一: ``` %insert("section") "filename" %insert("section") %{ ... %} ``` The first will dump the contents of the file in the given `filename` into the named `section`. The second inserts the code between the braces into the named `section`. For example, the following adds code into the runtime section: > 第一种将把给定 `filename` 中文件的内容转储到命名的 `section` 中。第二种将大括号之间的代码插入到命名的 `section` 中。例如,以下内容将代码添加到运行时部分: ``` %insert("runtime") %{ ... code in runtime section ... %} ``` There are the 5 sections, however, some target languages add in additional sections and some of these result in code being generated into a target language file instead of the C/C++ wrapper file. These are documented when available in the target language chapters. Macros named after the code sections are available as additional directives and these macro directives are normally used instead of `%insert`. For example, `%runtime` is used instead of `%insert("runtime")`. The valid sections and order of the sections in the generated C/C++ wrapper file is as shown: > 有 5 个部分,但是,一些目标语言在附加部分中添加,其中一些导致代码生成到目标语言文件而不是 C/C++ 包装器文件。目标语言章节中提供了这些内容。以代码段命名的宏可用作附加指令,并且通常使用这些宏指令而不是 `%insert`。例如,使用 `%runtime` 而不是 `%insert("runtime")`。生成的 C/C++ 包装器文件中的有效部分和部分的顺序如下所示: ``` %begin %{ ... code in begin section ... %} %runtime %{ ... code in runtime section ... %} %header %{ ... code in header section ... %} %wrapper %{ ... code in wrapper section ... %} %init %{ ... code in init section ... %} ``` The bare `%{ ... %}` directive is a shortcut that is the same as `%header %{ ... %}`. The `%begin` section is effectively empty as it just contains the SWIG banner by default. This section is provided as a way for users to insert code at the top of the wrapper file before any other code is generated. Everything in a code insertion block is copied verbatim into the output file and is not parsed by SWIG. Most SWIG input files have at least one such block to include header files and support C code. Additional code blocks may be placed anywhere in a SWIG file as needed. > 简单的 `%{...%}` 指令是一个与 `%header%{...%}` 相同的快捷方式。 > > `%begin` 部分实际上是空的,因为它默认只包含 SWIG 标签。提供此部分是为了让用户在生成任何其他代码之前在包装器文件的顶部插入代码。代码插入块中的所有内容都会逐字复制到输出文件中,并且不会被 SWIG 解析。大多数 SWIG 输入文件至少有一个这样的块,包括头文件和支持 C 代码。根据需要,可以将附加代码块放置在 SWIG 文件中的任何位置。 ``` %module mymodule %{ #include "my_header.h" %} ... Declare functions here %{ void some_extra_function() { ... } %} ``` A common use for code blocks is to write "helper" functions. These are functions that are used specifically for the purpose of building an interface, but which are generally not visible to the normal C program. For example : > 代码块的一个常见用途是编写“辅助”函数。这些函数专门用于构建接口,但通常对普通 C 程序不可见。例如 : ``` %{ /* Create a new vector */ static Vector *new_Vector() { return (Vector *) malloc(sizeof(Vector)); } %} // Now wrap it Vector *new_Vector(); ``` ### 5.6.3 内联代码块 Since the process of writing helper functions is fairly common, there is a special inlined form of code block that is used as follows : > 由于编写辅助函数的过程相当普遍,因此有一种特殊的内联形式的代码块,其使用方法如下: ``` %inline %{ /* Create a new vector */ Vector *new_Vector() { return (Vector *) malloc(sizeof(Vector)); } %} ``` The `%inline` directive inserts all of the code that follows verbatim into the header portion of an interface file. The code is then parsed by both the SWIG preprocessor and parser. Thus, the above example creates a new command `new_Vector` using only one declaration. Since the code inside an `%inline %{ ... %}` block is given to both the C compiler and SWIG, it is illegal to include any SWIG directives inside a `%{ ... %}` block. > `%inline` 指令将逐字输入的所有代码插入到接口文件的头文件部分中。然后由 SWIG 预处理器和解析器解析代码。因此,上面的示例仅使用一个声明创建一个新命令 `new_Vector`。由于 `%inline%{...%}` 块内的代码被赋予 C 编译器和 SWIG,因此在 `%{...%}` 块中包含任何 SWIG 指令是非法的。 ### 5.6.4 初始化块 When code is included in the `%init` section, it is copied directly into the module initialization function. For example, if you needed to perform some extra initialization on module loading, you could write this: > 当代码包含在 `%init` 部分中时,它会直接复制到模块初始化函数中。例如,如果你需要在模块加载时执行一些额外的初始化,你可以这样写: ``` %init %{ init_variables(); %} ``` ## 5.7 一个构建接口的策略 This section describes the general approach for building interfaces with SWIG. The specifics related to a particular scripting language are found in later chapters. > 本节介绍使用 SWIG 构建接口的一般方法。与特定脚本语言相关的细节可在后面的章节中找到。 ### 5.7.1 为 SWIG 准备 C 程序 SWIG doesn't require modifications to your C code, but if you feed it a collection of raw C header files or source code, the results might not be what you expect---in fact, they might be awful. Here's a series of steps you can follow to make an interface for a C program : * Identify the functions that you want to wrap. It's probably not necessary to access every single function of a C program--thus, a little forethought can dramatically simplify the resulting scripting language interface. C header files are a particularly good source for finding things to wrap. * Create a new interface file to describe the scripting language interface to your program. * Copy the appropriate declarations into the interface file or use SWIG's `%include` directive to process an entire C source/header file. * Make sure everything in the interface file uses ANSI C/C++ syntax. * Make sure all necessary ``typedef`' declarations and type-information is available in the interface file. In particular, ensure that the type information is specified in the correct order as required by a C/C++ compiler. Most importantly, define a type before it is used! A C compiler will tell you if the full type information is not available if it is needed, whereas SWIG will usually not warn or error out as it is designed to work without full type information. However, if type information is not specified correctly, the wrappers can be sub-optimal and even result in uncompilable C/C++ code. * If your program has a main() function, you may need to rename it (read on). * Run SWIG and compile. Although this may sound complicated, the process turns out to be fairly easy once you get the hang of it. In the process of building an interface, SWIG may encounter syntax errors or other problems. The best way to deal with this is to simply copy the offending code into a separate interface file and edit it. However, the SWIG developers have worked very hard to improve the SWIG parser--you should report parsing errors to the [swig-devel mailing list](http://www.swig.org/mail.html) or to the [SWIG bug tracker](http://www.swig.org/bugs.html). > SWIG 不需要修改你的 C 代码,但如果你提供原始 C 头文件或源代码的集合,结果可能不是你所期望的——实际上,它们可能很糟糕。以下是为 C 程序创建接口时可以遵循的一系列步骤: > > * 确定要包装的函数。可能没有必要访问 C 程序的每个单独的函数——因此,一点预先的考虑可以大大简化最终的脚本语言接口。查找要包装的东西的话,C 头文件是特别好的源头。 > * 创建一个新的接口文件来描述程序的脚本语言接口。 > * 将适当的声明复制到接口文件中,或使用 SWIG 的 `%include` 指令处理整个 C 源/头文件。 > * 确保接口文件中的所有内容都使用 ANSI C/C++ 语法。 > * 确保接口文件中提供了所有必需的 `typedef` 声明和类型信息。特别是,确保按照 C/C++ 编译器的要求以正确的顺序指定类型信息。最重要的是,在使用之前定义一个类型!如果需要,C 编译器将告诉你完整类型信息是否不可用,而 SWIG 通常不会发出警告或错误,因为它设计为在没有完整类型信息的情况下工作。但是,如果未正确指定类型信息,则包装器可能是次优的,甚至会导致无法编译的 C/C++ 代码。 > * 如果你的程序具有 `main()` 函数,则可能需要重命名(只读)。 > * 运行 SWIG 并编译。 > > 虽然这可能听起来很复杂,但是一旦掌握了它,这个过程就相当容易了。 > > 在构建接口的过程中,SWIG 可能会遇到语法错误或其他问题。处理此问题的最佳方法是将有问题的代码复制到单独的接口文件中并进行编辑。但是,SWIG 开发人员非常努力地改进 SWIG 解析器——你应该将解析错误报告给 [swig-devel 邮件列表](http://www.swig.org/mail.html)或 [SWIG bug tracker](http://www.swig.org/bugs.html)。 ### 5.7.2 SWIG 接口文件 The preferred method of using SWIG is to generate a separate interface file. Suppose you have the following C header file : > 使用 SWIG 的首选方法是生成单独的接口文件。假设你有以下 C 头文件: ```c /* File : header.h */ #include <stdio.h> #include <math.h> extern int foo(double); extern double bar(int, int); extern void dump(FILE *f); ``` A typical SWIG interface file for this header file would look like the following : > 此头文件的典型 SWIG 接口文件如下所示: ``` /* File : interface.i */ %module mymodule %{ #include "header.h" %} extern int foo(double); extern double bar(int, int); extern void dump(FILE *f); ``` Of course, in this case, our header file is pretty simple so we could use a simpler approach and use an interface file like this: > 当然,在这种情况下,我们的头文件非常简单,所以我们可以使用更简单的方法并使用这样的接口文件: ``` /* File : interface.i */ %module mymodule %{ #include "header.h" %} %include "header.h" ``` The main advantage of this approach is minimal maintenance of an interface file for when the header file changes in the future. In more complex projects, an interface file containing numerous `%include` and `#include` statements like this is one of the most common approaches to interface file design due to lower maintenance overhead. > 这种方法的主要优点是,当头文件将来发生变化时,接口文件的维护很少。在更复杂的项目中,包含许多 `%include` 和 `#include` 语句的接口文件是最常见的接口文件设计方法之一,因为维护成本较低。 ### 5.7.3 为什么使用单独的接口文件? Although SWIG can parse many header files, it is more common to write a special `.i` file defining the interface to a package. There are several reasons why you might want to do this: * It is rarely necessary to access every single function in a large package. Many C functions might have little or no use in a scripted environment. Therefore, why wrap them? * Separate interface files provide an opportunity to provide more precise rules about how an interface is to be constructed. * Interface files can provide more structure and organization. * SWIG can't parse certain definitions that appear in header files. Having a separate file allows you to eliminate or work around these problems. * Interface files provide a more precise definition of what the interface is. Users wanting to extend the system can go to the interface file and immediately see what is available without having to dig it out of header files. > 虽然 SWIG 可以解析许多头文件,但更常见的是编写一个特殊的 `.i` 文件来定义包的接口。你希望这样做的可能原因有以下几种: > > * 很少需要访问大型包中的每个函数。许多 C 函数可能在脚本环境中很少或没有用处。因此,为什么要包装它们? > * 单独的接口文件提供了一个机会,可以提供有关如何构造接口的更精确的规则。 > * 接口文件可以提供更多的结构和组织。 > * SWIG 无法解析头文件中出现的某些定义。拥有单独的文件可以消除或解决这些问题。 > * 接口文件提供了更精确的接口定义。想要扩展系统的用户可以转到接口文件,并立即查看可用的内容,而无需将其从头文件中删除。 ### 5.7.4 获得正确的头文件 Sometimes, it is necessary to use certain header files in order for the code generated by SWIG to compile properly. Make sure you include certain header files by using a `%{ %}` block like this: > 有时,必须使用某些头文件才能使 SWIG 生成的代码正确编译。确保使用 `%{ %}` 块包含某些头文件,如下所示: ``` %module graphics %{ #include <GL/gl.h> #include <GL/glu.h> %} // Put the rest of the declarations here ... ``` ### 5.7.5 怎么处理 `main()` If your program defines a `main()` function, you may need to get rid of it or rename it in order to use a scripting language. Most scripting languages define their own `main()` procedure that is called instead. `main()` also makes no sense when working with dynamic loading. There are a few approaches to solving the `main()` conflict: * Get rid of `main()` entirely. * Rename `main()` to something else. You can do this by compiling your C program with an option like `-Dmain=oldmain`. * Use conditional compilation to only include `main()` when not using a scripting language. Getting rid of `main()` may cause potential initialization problems of a program. To handle this problem, you may consider writing a special function called `program_init()` that initializes your program upon startup. This function could then be called either from the scripting language as the first operation, or when the SWIG generated module is loaded. As a general note, many C programs only use the `main()` function to parse command line options and to set parameters. However, by using a scripting language, you are probably trying to create a program that is more interactive. In many cases, the old `main()` program can be completely replaced by a Perl, Python, or Tcl script. **Note:** In some cases, you might be inclined to create a scripting language wrapper for `main()`. If you do this, the compilation will probably work and your module might even load correctly. The only trouble is that when you call your `main()` wrapper, you will find that it actually invokes the `main()` of the scripting language interpreter itself! This behavior is a side effect of the symbol binding mechanism used in the dynamic linker. The bottom line: don't do this. > 如果你的程序定义了一个 `main()` 函数,你可能需要删除它或重命名它以使用脚本语言。大多数脚本语言都定义了自己调用的 `main()` 程序。使用动态加载时,`main()` 也没有意义。解决 `main()` 冲突有几种方法: > > * 完全摆脱 `main()`。 > * 将 `main()` 重命名为其他内容。你可以通过使用 `-Dmain = oldmain` 等选项编译 C 程序来完成此操作。 > * 在不使用脚本语言时,使用条件编译仅包含 `main()`。 > > 摆脱 `main()` 可能会导致程序潜在的初始化问题。要处理这个问题,你可以考虑编写一个名为 `program_init()` 的特殊函数,它在启动时初始化你的程序。然后可以从脚本语言中调用此函数作为第一个操作,或者在加载 SWIG 生成的模块时调用此函数。 > > 总的来说,许多 C 程序只使用 `main()` 函数来解析命令行选项和设置参数。但是,通过使用脚本语言,你可能正在尝试创建更具交互性的程序。在许多情况下,旧的 `main()` 程序可以完全被 Perl、Python 或 Tcl 脚本替换。 > > **注意:**在某些情况下,你可能倾向于为 `main()` 创建脚本语言包装器。如果你这样做,编译可能会工作,你的模块甚至可能正确加载。唯一的麻烦是当你调用你的 `main()` 包装器时,你会发现它实际上调用了脚本语言解释器本身的 `main()`!此行为是动态链接器中使用的符号绑定机制的副作用。底线:不要这样做。
Java
UTF-8
7,779
2.09375
2
[]
no_license
package com.myproject.controller; import com.myproject.exception.UserException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.apache.commons.mail.*; import com.myproject.dao.RegisteredUserDAO; import com.myproject.dao.RequestDAO; import com.myproject.dao.UserDAO; import com.myproject.pojo.MillionsEveryday; import com.myproject.pojo.Payment; import com.myproject.pojo.RegisteredUser; import com.myproject.pojo.Request; import com.myproject.pojo.User; import com.myproject.validator.UserValidation; @Controller @RequestMapping("/user/*") public class UserController { @Autowired @Qualifier("userDao") RegisteredUserDAO userDao; @Autowired @Qualifier("uDao") UserDAO uDao; @Autowired @Qualifier("requestDao") RequestDAO requestDao; @Autowired @Qualifier("registeredUserValidator") UserValidation validator; @InitBinder("registeredUserValidator") private void initBinder(WebDataBinder binder) { binder.setValidator(validator); } @RequestMapping(value = "user/login", method = RequestMethod.GET) protected String userLogin(HttpServletRequest request) throws Exception { return "login"; } @RequestMapping(value = "user/home", method = RequestMethod.GET) protected String home(HttpServletRequest request) throws Exception { return "requestReply"; } @RequestMapping(value = "user/book", method = RequestMethod.POST) protected String book(HttpServletRequest request) throws Exception { HttpSession session = request.getSession(true); int noBooks = Integer.parseInt(request.getParameter("noBooks")); session.setAttribute("noBooks",noBooks); return "disp"; } @RequestMapping(value = "user/login", method = RequestMethod.POST) protected ModelAndView requestReply(HttpServletRequest request) throws Exception { List<Request> requests = requestDao.list(); ModelAndView mv=new ModelAndView("requestReply"); Map<String,String> status = new LinkedHashMap<String,String>(); status.put("approve", "approve"); status.put("reject", "reject"); mv.addObject("status", status); mv.addObject("requests",requests); mv.addObject("reqobj",new Request()); return mv; //return new ModelAndView("requestReply", "reqobj", new Request()); } @RequestMapping(value = "user/admin", method = RequestMethod.POST) protected ModelAndView adminMenu(HttpServletRequest request) throws Exception { HttpSession session = (HttpSession) request.getSession(); User u=null; try { System.out.print("loginUser"); u = uDao.get(request.getParameter("username"), request.getParameter("password")); if(u == null){ System.out.println("UserName/Password does not exist"); session.setAttribute("errorMessage", "UserName/Password does not exist"); return new ModelAndView("error"); } session.setAttribute("user", u); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); session.setAttribute("errorMessage", "error while login"); return new ModelAndView("error"); } if(u.getRole().equals("retailer")||u.getRole().equals("reguser")){ return new ModelAndView("home"); } else{ List<Request> requests = requestDao.list(); ModelAndView mv=new ModelAndView("requestReply"); Map<String,String> status = new LinkedHashMap<String,String>(); status.put("approve", "approve"); status.put("reject", "reject"); mv.addObject("status", status); mv.addObject("requests",requests); mv.addObject("reqobj",new Request()); return mv; } //return new ModelAndView("requestReply", "reqobj", new Request()); } @RequestMapping(value = "user/register.htm", method = RequestMethod.GET) protected ModelAndView registerNewUser(HttpServletRequest request) throws Exception { //validator.validate(user, result); return new ModelAndView("userRegister", "user", new RegisteredUser()); } @RequestMapping(value = "user/h", method = RequestMethod.GET) protected ModelAndView h(HttpServletRequest request) throws Exception { //validator.validate(user, result); return new ModelAndView("login"); } @RequestMapping(value = "user/win", method = RequestMethod.POST) protected ModelAndView play(HttpServletRequest request, @ModelAttribute("payment") Payment pa, BindingResult result) throws Exception { //validator.validate(user, result); String eDate=request.getParameter("expiryDate"); HttpSession session = (HttpSession) request.getSession(); User u= (User)session.getAttribute("user"); pa.setAmount(1); Payment p= userDao.pay(pa,eDate,u.getUserID()); //List <Payment> pl=userDao.getPay(u.getUserID()); return new ModelAndView("play", "millions", new MillionsEveryday()); } @RequestMapping(value = "user/second", method = RequestMethod.POST) protected ModelAndView play(HttpServletRequest request) throws Exception { return new ModelAndView("play", "millions", new MillionsEveryday()); } @RequestMapping(value = "user/logout", method = RequestMethod.POST) protected ModelAndView logout(HttpServletRequest request) throws Exception { return new ModelAndView("home"); } @RequestMapping(value = "user/retReq", method = RequestMethod.GET) protected ModelAndView retailerReq(HttpServletRequest request) throws Exception { List<Request> requests = requestDao.list(); ModelAndView mv=new ModelAndView("requestReply"); Map<String,String> status = new LinkedHashMap<String,String>(); status.put("approve", "approve"); status.put("reject", "reject"); mv.addObject("status", status); mv.addObject("requests",requests); mv.addObject("reqobj",new Request()); return mv; //return new ModelAndView("play", "millions", new MillionsEveryday()); } @RequestMapping(value = "/user/register", method = RequestMethod.POST) protected ModelAndView completeRegistration(HttpServletRequest request, @ModelAttribute("user") RegisteredUser user, BindingResult result) throws Exception { //UserValidation validator= new UserValidation(); validator.validate(user, result); if (result.hasErrors()) { return new ModelAndView("userRegister", "user", user); } System.out.print("registerNewUser"); //RegisteredUserDAO userDao=new RegisteredUserDAO(); RegisteredUser u = userDao.register(user); //System.out.println("Exception: " + e.getMessage()); //return new ModelAndView("error", "errorMessage", "error while login"); Email email = new SimpleEmail(); email.setHostName("smtp.googlemail.com"); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator("eljoba91@gmail.com", "Ronaldo@7")); email.setSSLOnConnect(true); email.setFrom("eljoba91@gmail.com"); email.setSubject("Registration"); email.setMsg("CONGRATULATIONS..You have successfully registered and on your way to becoming a millionaire :-)"); email.addTo(u.getEmail()); email.send(); return new ModelAndView("login", "user", user); } }
Java
UTF-8
621
2.0625
2
[]
no_license
package com.kingdee.constants; /** * Response code for Json result * * @author code */ public abstract class AbstractRespCode { public static final String OK = "0"; public static final String FAILED = "-1"; /** * 图形验证码不匹配 */ public static final String CAPTCHA_MISMATCH = "-2"; /** * 手机验证码错误 */ public static final String PHONE_VC_WRONG = "-3"; /** * 身份证与名称不匹配 */ public static final String IDCODE_MISMATCH = "-4"; /** * Token错误 */ public static final String TOKEN_MISMATCH = "403"; }
Java
UTF-8
1,728
3.65625
4
[]
no_license
package src; /** * La classe CelluleEtatMort représente l'état d'une cellule morte. * Implémente l'interface CelluleEtat * @see CelluleEtat * * @author Mathilde MOTTAY */ public class CelluleEtatMort implements CelluleEtat { // Instance unique de l'état mort d'une cellule private static CelluleEtatMort instanceUniqueCelluleEtatMort = null; /** * Retourne l'unique instance de l'état mort d'une cellule (Design Pattern Singleton) * @return L'unique instance de l'état mort d'une cellule */ public static CelluleEtatMort getInstance(){ if(instanceUniqueCelluleEtatMort == null){ instanceUniqueCelluleEtatMort = new CelluleEtatMort(); } return instanceUniqueCelluleEtatMort; } /** * Retourne l'unique instance de l'état vivant d'une cellule * @return L'unique instance de l'état vivant d'une cellule */ @Override public CelluleEtat vit(){ return CelluleEtatVivant.getInstance(); } /** * Retourne l'état (déjà mort) de la cellule * @return Etat mort de la cellule */ @Override public CelluleEtat meurt(){ return this; } /** * Retourne false puisque la cellule est à l'état morte. */ @Override public boolean estVivante(){ return false; } /** * Accepte que le visiteur passé en paramètre visite la cellule passée en paramètre * @param visiteur Un visiteur * @param cellule Une cellule */ @Override public void accepte(Visiteur visiteur, Cellule cellule){ visiteur.visiteCelluleMorte(cellule); } }
Java
UTF-8
2,057
2.375
2
[]
no_license
package asadyian.zahra.digitallibrary.service; import asadyian.zahra.digitallibrary.controller.model.ItemOption; import asadyian.zahra.digitallibrary.controller.model.attachmenttype.AttachmentTypeRequest; import asadyian.zahra.digitallibrary.controller.model.attachmenttype.AttachmentTypeResponse; import asadyian.zahra.digitallibrary.domain.entities.AttachmentTypeEntity; import asadyian.zahra.digitallibrary.domain.repository.AttachmentTypeRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class AttachmentTypeService { private final AttachmentTypeRepository repository; @Transactional public AttachmentTypeResponse saveOrUpdate(AttachmentTypeRequest request) { AttachmentTypeEntity result = repository.save(request.convert2AttachmentType()); return AttachmentTypeEntity.convert2response(result); } @Transactional public void removeById(Long id) { repository.deleteById(id); } @Transactional(readOnly = true) public AttachmentTypeResponse loadById(Long id) { return repository.findById(id).map(AttachmentTypeEntity::convert2response) .orElseThrow(() -> new RuntimeException("can not find entity")); } @Transactional(readOnly = true) public List<AttachmentTypeResponse> fetchAll() { return repository.findAll().stream().map(AttachmentTypeEntity::convert2response).collect(Collectors.toList()); } @Transactional(readOnly = true) public List<ItemOption> searchByTitle(String title) { if (title == null || title.isEmpty()) { return repository.findAll().stream().map((a) -> new ItemOption(a.getId(), a.getTitle())).collect(Collectors.toList()); } return repository.findAllByTitle(title).stream().map((a) -> new ItemOption(a.getId(), a.getTitle())).collect(Collectors.toList()); } }
JavaScript
UTF-8
6,248
2.703125
3
[]
no_license
const now = new Date().getMonth(); console.log(now); let monthes = document.querySelectorAll('.monthes li'), years = document.querySelectorAll('.years li '); let currentMonthSpan = document.querySelector('.current-month'); let currentFilterData = { month: now, year: new Date().getFullYear(), }; let aviableMonthes = new Set(); let aviableYears = new Set(); each(document.querySelectorAll('.slider img'), (img) => { aviableMonthes.add(+img.dataset.month); aviableYears.add(+img.dataset.year); }); // for (let i = 0; i <= now; i++) { // monthes[i].classList.add('active'); // if (i === now) { // monthes[i].classList.add('current'); // currentMonthSpan.innerHTML = monthes[i].innerHTML + ' ' + new Date().getFullYear(); // } // } each(monthes, (month) => { if (!aviableMonthes.has(+month.dataset.value)) { month.classList.remove('active'); } else { month.classList.add('active'); } }) each(years, (year) => { if (!aviableYears.has(+year.dataset.value)) { year.remove(); } }) each(years, (el) => { if (+el.innerHTML === new Date().getFullYear()) el.classList.add('current'); el.classList.add('active'); el.addEventListener('click', function(evt) { each(years, el => el.classList.remove('current')); el.classList.add('current'); changeFilterDate(); }); }) monthes.forEach(month => { month.addEventListener('click', function(evt) { each(monthes, (el) => { el.classList.remove('current') }); month.classList.add('current'); changeFilterDate() // currentMonthSpan.innerHTML = month.innerHTML + ' ' + new Date().getUTCFullYear(); }); }) each(document.querySelectorAll('.select-box'), (el) => { el.addEventListener('click', function(evt) { console.log(this.dataset.name); changeFilterDate(this.dataset.name); }); }) function changeFilterDate(name) { let month = document.querySelector('.monthes .current'); let year = document.querySelector('.years .current'); if (document.documentElement.clientWidth < 576) { if (name.match(/year/)) { currentFilterData.year = +document.querySelector(`.${name} input:checked`).value; } else if (name.match(/month/)) { currentFilterData.month = +document.querySelector(`.${name} input:checked`).value; } // currentFilterData.year = document.querySelector('.years input[name^="years"]:checked').value; } else { currentFilterData.month = +month.dataset.value; currentFilterData.year = +year.dataset.value; smoothTextChange(currentMonthSpan.innerHTML, month.innerHTML + ' ' + year.innerHTML, currentMonthSpan, true) } filterSlides($('.slider'), currentFilterData); } function filterSlides(slider, data) { slider.slick('slickUnfilter'); if (data.month < 10) data.month = '0' + data.month; slider.slick('slickFilter', `[data-month=${data.month}][data-year=${data.year}]`); console.log(slider); } /* beautify preserve:start */ @@include('../libs/slick/slick.min.js') /* beautify preserve:end */ $('.slider').on('init', (e, t) => { // console.log(e, t); $('.slider-counter .all').html(t.slideCount); // console.log(t.listHeight); // document.querySelector('.slider').style.minHeight = getComputedStyle(document.querySelector('.build-progress-wrapper')).height; document.querySelector('.slider').style.minHeight = '150px'; }) $('.slider').on('afterChange', (e, t, f) => { // console.log(e); // console.log(t); // console.log(f); $('.slider-counter .current').html(f + 1); }); $('.slider').on('reInit', (init, init1) => { $('.slider-counter .all').html(init1.slideCount); if (init1.slideCount === 0) { changePseudoProperties('.slider', 'transform:scaleY(1) !important;', 'after'); document.querySelector(`.slider-counter`).style.opacity = '0'; } else { changePseudoProperties('.slider', 'transform:scaleY(0) !important;', 'after'); document.querySelector(`.slider-counter`).style.opacity = '1'; } //console.log(init1.slideCount); }); var buildSlider = $('.slider').slick({ prevArrow: '.arrow-prev', nextArrow: '.arrow-next', }); /*functions */ function each(array, func) { array.forEach(el => { func(el); }) } function smoothTextChange(startText, finishText, elem, firstStart) { if (firstStart) elem.style.minHeight = getComputedStyle(elem).height; if (firstStart) elem.style.minWidth = getComputedStyle(elem).width; // finishText = putFinishTextInSpan(finishText); function timeoutChange(text, element) { if (text.length === 0) { element.innerHTML = finishText; // fillText(finishText) return; } element.innerHTML = text; setTimeout(() => { timeoutChange(text.slice(0, text.length - 1), elem); }, 50); function fillText(toFill) { element.innerHTML = toFill; if (toFill.length === 0) return; setTimeout(() => { fillText(toFill.substring(0, toFill.length - 1)); }, 50); } } function putFinishTextInSpan(finishText1) { finishText1 = finishText1.split('').map((el, i) => `<span style="animation-delay:${i/10}s" class="fadeIn">${el}</span>`); return finishText1.toString().replace(/,/g, ''); } timeoutChange(startText, elem); }; function changePseudoProperties(container, cssText, pseudoType) { let containerSelector = ''; if (pseudoType === undefined) { console.warn(`Pseudo element is not defined, ${changePseudoProperties.name} is stopping`); return; } if (typeof container === 'string') { containerSelector = container; container = document.querySelector(container); } else { containerSelector = `.${container.classList[0]}`; } if (container.querySelector('style')) container.querySelector('style').remove(); let style = document.createElement('style'); style.innerHTML = ` ${containerSelector}:${pseudoType}{ ${cssText} } `; container.append(style); }
Java
GB18030
1,004
2.609375
3
[]
no_license
package com.czd.shopping.pojo; /** * @author MyEclipse Persistence Tools * pojoǺڿʹɹ * ɹ * bean */ public class Category { private Integer cid; private String ctype; private Boolean chot; private Integer aid; public Category() { super(); } public Category(String ctype, Boolean chot, Integer aid) { super(); this.ctype = ctype; this.chot = chot; this.aid = aid; } public Integer getCid() { return cid; } public void setCid(Integer cid) { this.cid = cid; } public String getCtype() { return ctype; } public void setCtype(String ctype) { this.ctype = ctype; } public Boolean getChot() { return chot; } public void setChot(Boolean chot) { this.chot = chot; } public Integer getAid() { return aid; } public void setAid(Integer aid) { this.aid = aid; } public String toString(){ return "[" + cid + "," + chot + "," + ctype + "]"; } }
C
UTF-8
1,506
2.53125
3
[]
no_license
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct kevent {int flags; scalar_t__ ident; scalar_t__ filter; scalar_t__ fflags; scalar_t__ data; scalar_t__ udata; scalar_t__* ext; } ; /* Variables and functions */ int EV_ADD ; int /*<<< orphan*/ abort () ; int /*<<< orphan*/ free (char*) ; char* kevent_to_str (struct kevent*) ; int /*<<< orphan*/ printf (char*,char*,char*) ; void kevent_cmp(struct kevent *k1, struct kevent *k2) { char *kev1_str; char *kev2_str; /* XXX- Workaround for inconsistent implementation of kevent(2) */ #ifdef __FreeBSD__ if (k1->flags & EV_ADD) k2->flags |= EV_ADD; #endif if (k1->ident != k2->ident || k1->filter != k2->filter || k1->flags != k2->flags || k1->fflags != k2->fflags || k1->data != k2->data || k1->udata != k2->udata || k1->ext[0] != k2->ext[0] || k1->ext[1] != k2->ext[1] || k1->ext[0] != k2->ext[2] || k1->ext[0] != k2->ext[3]) { kev1_str = kevent_to_str(k1); kev2_str = kevent_to_str(k2); printf("kevent_cmp: mismatch:\n %s !=\n %s\n", kev1_str, kev2_str); free(kev1_str); free(kev2_str); abort(); } }
Python
UTF-8
142
3.890625
4
[]
no_license
def factorial(x): s = 1 if x == 0: return s for i in range(1, x + 1): s = s * i return s print(factorial(20))
Java
UTF-8
9,191
2.546875
3
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2012-2020 Snowflake Computing Inc. All rights reserved. */ package net.snowflake.client.jdbc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import net.snowflake.client.core.SFSession; import org.apache.commons.text.StringEscapeUtils; import org.junit.Test; /** This is the unit tests for ResultJsonParserV2 */ public class ResultJsonParserV2Test { @Test public void simpleTest() throws SnowflakeSQLException { SFSession session = null; String simple = "[\"1\", \"1.01\"]," + "[null, null]," + "[\"2\", \"0.13\"]," + "[\"\", \"\"]," + "[\"\\\"escape\\\"\", \"\\\"escape\\\"\"]," + "[\"\\u2605\", \"\\u263A\\u263A\"]," + "[\"\\ud841\\udf0e\", \"\\ud841\\udf31\\ud841\\udf79\"]," + "[\"{\\\"date\\\" : \\\"2017-04-28\\\",\\\"dealership\\\" : \\\"Tindel Toyota\\\"}\", \"[1,2,3,4,5]\"]"; byte[] data = simple.getBytes(StandardCharsets.UTF_8); JsonResultChunk chunk = new JsonResultChunk("", 8, 2, data.length, session); ResultJsonParserV2 jp = new ResultJsonParserV2(); jp.startParsing(chunk, session); ByteBuffer byteBuffer = ByteBuffer.wrap(data); jp.continueParsing(byteBuffer, session); byte[] remaining = new byte[byteBuffer.remaining()]; byteBuffer.get(remaining); jp.endParsing(ByteBuffer.wrap(remaining), session); assertEquals("1", chunk.getCell(0, 0).toString()); assertEquals("1.01", chunk.getCell(0, 1).toString()); assertNull(chunk.getCell(1, 0)); assertNull(chunk.getCell(1, 1)); assertEquals("2", chunk.getCell(2, 0).toString()); assertEquals("0.13", chunk.getCell(2, 1).toString()); assertEquals("", chunk.getCell(3, 0).toString()); assertEquals("", chunk.getCell(3, 1).toString()); assertEquals("\"escape\"", chunk.getCell(4, 0).toString()); assertEquals("\"escape\"", chunk.getCell(4, 1).toString()); assertEquals("★", chunk.getCell(5, 0).toString()); assertEquals("☺☺", chunk.getCell(5, 1).toString()); assertEquals("𠜎", chunk.getCell(6, 0).toString()); assertEquals("𠜱𠝹", chunk.getCell(6, 1).toString()); assertEquals( "{\"date\" : \"2017-04-28\",\"dealership\" : \"Tindel Toyota\"}", chunk.getCell(7, 0).toString()); assertEquals("[1,2,3,4,5]", chunk.getCell(7, 1).toString()); } @Test public void simpleStreamingTest() throws SnowflakeSQLException { SFSession session = null; String simple = "[\"1\", \"1.01\"]," + "[null, null]," + "[\"2\", \"0.13\"]," + "[\"\", \"\"]," + "[\"\\\"escape\\\"\", \"\\\"escape\\\"\"]," + "[\"☺☺\", \"☺☺☺\"], " + "[\"\\ud841\\udf0e\", \"\\ud841\\udf31\\ud841\\udf79\"]," + "[\"{\\\"date\\\" : \\\"2017-04-28\\\",\\\"dealership\\\" : \\\"Tindel Toyota\\\"}\", \"[1,2,3,4,5]\"]"; byte[] data = simple.getBytes(StandardCharsets.UTF_8); JsonResultChunk chunk = new JsonResultChunk("", 8, 2, data.length, session); ResultJsonParserV2 jp = new ResultJsonParserV2(); jp.startParsing(chunk, session); int len = 15; ByteBuffer byteBuffer = null; for (int i = 0; i < data.length; i += len) { if (i + len < data.length) { byteBuffer = ByteBuffer.wrap(data, i, len); jp.continueParsing(byteBuffer, session); } else { byteBuffer = ByteBuffer.wrap(data, i, data.length - i); jp.continueParsing(byteBuffer, session); } } byte[] remaining = new byte[byteBuffer.remaining()]; byteBuffer.get(remaining); jp.endParsing(ByteBuffer.wrap(remaining), session); assertEquals("1", chunk.getCell(0, 0).toString()); assertEquals("1.01", chunk.getCell(0, 1).toString()); assertNull(chunk.getCell(1, 0)); assertNull(chunk.getCell(1, 1)); assertEquals("2", chunk.getCell(2, 0).toString()); assertEquals("0.13", chunk.getCell(2, 1).toString()); assertEquals("", chunk.getCell(3, 0).toString()); assertEquals("", chunk.getCell(3, 1).toString()); assertEquals("\"escape\"", chunk.getCell(4, 0).toString()); assertEquals("\"escape\"", chunk.getCell(4, 1).toString()); assertEquals("☺☺", chunk.getCell(5, 0).toString()); assertEquals("☺☺☺", chunk.getCell(5, 1).toString()); assertEquals("𠜎", chunk.getCell(6, 0).toString()); assertEquals("𠜱𠝹", chunk.getCell(6, 1).toString()); assertEquals( "{\"date\" : \"2017-04-28\",\"dealership\" : \"Tindel Toyota\"}", chunk.getCell(7, 0).toString()); assertEquals("[1,2,3,4,5]", chunk.getCell(7, 1).toString()); } /** * Test the largest column size 16 MB * * @throws SnowflakeSQLException Will be thrown if parsing fails */ @Test public void LargestColumnTest() throws SnowflakeSQLException { SFSession session = null; StringBuilder sb = new StringBuilder(); StringBuilder a = new StringBuilder(); for (int i = 0; i < 16 * 1024 * 1024; i++) { a.append("a"); } StringBuilder b = new StringBuilder(); for (int i = 0; i < 16 * 1024 * 1024; i++) { b.append("b"); } StringBuilder c = new StringBuilder(); for (int i = 0; i < 16 * 1024 * 1024; i++) { c.append("c"); } StringBuilder s = new StringBuilder(); for (int i = 0; i < 16 * 1024 * 1024 - 5; i += 6) { s.append("\\u263A"); } sb.append("[\"") .append(a) .append("\",\"") .append(b) .append("\"],[\"") .append(c) .append("\",\"") .append(s) .append("\"]"); byte[] data = sb.toString().getBytes(StandardCharsets.UTF_8); JsonResultChunk chunk = new JsonResultChunk("", 2, 2, data.length, session); ResultJsonParserV2 jp = new ResultJsonParserV2(); jp.startParsing(chunk, session); ByteBuffer byteBuffer = ByteBuffer.wrap(data); jp.continueParsing(byteBuffer, session); byte[] remaining = new byte[byteBuffer.remaining()]; byteBuffer.get(remaining); jp.endParsing(ByteBuffer.wrap(remaining), session); assertEquals(a.toString(), chunk.getCell(0, 0).toString()); assertEquals(b.toString(), chunk.getCell(0, 1).toString()); assertEquals(c.toString(), chunk.getCell(1, 0).toString()); assertEquals(StringEscapeUtils.unescapeJava(s.toString()), chunk.getCell(1, 1).toString()); } // SNOW-802910: Test to cover edge case '\u0000\u0000' where null could be dropped. @Test public void testAsciiSequential() throws SnowflakeSQLException { SFSession session = null; String ascii = "[\"\\u0000\\u0000\\u0000\"]"; byte[] data = ascii.getBytes(StandardCharsets.UTF_8); JsonResultChunk chunk = new JsonResultChunk("", 1, 1, data.length, session); ResultJsonParserV2 jp = new ResultJsonParserV2(); jp.startParsing(chunk, session); // parse the first null ByteBuffer byteBuffer = ByteBuffer.wrap(data, 0, 14); jp.continueParsing(byteBuffer, session); // parse the rest of the string byteBuffer = ByteBuffer.wrap(data, 9, 13); jp.continueParsing(byteBuffer, session); byteBuffer = ByteBuffer.wrap(data, 15, 7); jp.continueParsing(byteBuffer, session); // finish parsing byte[] remaining = new byte[byteBuffer.remaining()]; byteBuffer.get(remaining); jp.endParsing(ByteBuffer.wrap(remaining), session); // check null is not dropped assertEquals("00 00 00 ", stringToHex(chunk.getCell(0, 0).toString())); } // SNOW-802910: Test to cover edge case '\u0003ä\u0000' where null could be dropped. @Test public void testAsciiCharacter() throws SnowflakeSQLException { SFSession session = null; String ascii = "[\"\\u0003ä\\u0000\"]"; byte[] data = ascii.getBytes(StandardCharsets.UTF_8); JsonResultChunk chunk = new JsonResultChunk("", 1, 1, data.length, session); ResultJsonParserV2 jp = new ResultJsonParserV2(); jp.startParsing(chunk, session); // parse ETX and UTF-8 character ByteBuffer byteBuffer = ByteBuffer.wrap(data, 0, data.length); jp.continueParsing(byteBuffer, session); int position = byteBuffer.position(); // try to parse null byteBuffer = ByteBuffer.wrap(data, position, data.length - position); jp.continueParsing(byteBuffer, session); byte[] remaining = new byte[byteBuffer.remaining()]; byteBuffer.get(remaining); jp.endParsing(ByteBuffer.wrap(remaining), session); // Ã00 is returned assertEquals("03 C3 A4 00 ", stringToHex(chunk.getCell(0, 0).toString())); } public static String stringToHex(String input) { byte[] byteArray = input.getBytes(StandardCharsets.UTF_8); StringBuilder sb = new StringBuilder(); char[] hexBytes = new char[2]; for (int i = 0; i < byteArray.length; i++) { hexBytes[0] = Character.forDigit((byteArray[i] >> 4) & 0xF, 16); hexBytes[1] = Character.forDigit((byteArray[i] & 0xF), 16); sb.append(hexBytes); sb.append(" "); // Space every two characters to make it easier to read visually } return sb.toString().toUpperCase(); } }
JavaScript
UTF-8
11,308
2.5625
3
[ "Apache-2.0" ]
permissive
const util = require('util'); const assert = require('assert'); const ui = require('cliui'); const cli_table = require('cli-table3'); // colors array: [dark, med, light] const colors_red = ['\x1B[2;31m', '\x1B[1;31m', '\x1B[1;91m']; const colors_blue = ['\x1B[2;34m', '\x1B[1;34m', '\x1B[38;5;104m']; const colors_yellow = ['\x1B[33m', '\x1B[1;93m', '\x1B[38;5;228m']; const colors_gray = ['\x1B[2;37m', '\x1B[37m']; const colors_green = ['\x1B[32m', '\x1B[92m']; // default color const colors = colors_blue; // highlight color const highlight = '\x1B[1;38;5;105m'; // 125 // error color const error_color = '\x1B[1;38;5;124m'; // success task checked. const task_ok = '\x1B[0m\x1B[36m ✓ \x1B[0m'; const task_warn = '\x1B[33m ⚠ \x1B[0m'; const task_error = '\x1B[31m ✕ \x1B[0m'; const hideCursor = '\x1B[?25l'; const showCursor = '\x1B[?25h'; const clearLine = '\x1B[2K'; const saveCursor = '\x1B7'; const restoreCursor = '\x1B8'; const normalColor = '\x1B[0m'; const boldText = '\x1B[1m'; const italicText = '\x1B[3m'; function getDateDiff(date /*: Date */) { const seconds = Math.floor((new Date() - date) / 1000); let interval = Math.floor(seconds / 31536000); if (interval > 1) { return `${interval} years ago`; } if (interval === 1) { return `${interval} year ago`; } interval = Math.floor(seconds / 2592000); if (interval > 1) { return `${interval} months ago`; } if (interval === 1) { return `${interval} month ago`; } interval = Math.floor(seconds / 86400); if (interval > 1) { return `${interval} days ago`; } if (interval === 1) { return `${interval} day ago`; } interval = Math.floor(seconds / 3600); if (interval > 1) { return `${interval} hours ago`; } if (interval === 1) { return `${interval} hour ago`; } interval = Math.floor(seconds / 60); return `${interval} minutes ago`; } /** * Format markdown-style tags surrounding text in a string to ASCII color tags * \*\*blue\*\* ~~yellow~~ !!red!! ##gray## ^^green^^ * @param {string} strs String to format */ function markdown(strs) { if (process.env.AKA_NO_COLORS) { return strs.replace(/(\*\*\*)(.+)(\*\*\*)/g, '$2') .replace(/(\*\*)(.+)(\*\*)/g, '$2') .replace(/(\*)(.+)(\*)/g, '$2') .replace(/(~~~)([^~]+)(~~~)/g, '$2') .replace(/(~~)([^~]+)(~~)/g, '$2') .replace(/(!!)([^!]+)(!!)/g, '$2') .replace(/(###)([^#]+)(###)/g, '$2') .replace(/(##)([^#]+)(##)/g, '$2') .replace(/(\^\^\^)([^^]+)(\^\^\^)/g, '$2') .replace(/(\^\^)([^^]+)(\^\^)/g, '$2'); } return strs.replace(/(\*\*\*)(.+)(\*\*\*)/g, `${colors[1]}$2${normalColor}`) .replace(/(\*\*)(.+)(\*\*)/g, `${colors[2]}$2${normalColor}`) .replace(/(\*)(.+)(\*)/g, `${colors[0]}$2${normalColor}`) .replace(/(~~~)([^~]+)(~~~)/g, `${colors_yellow[1]}$2${normalColor}`) .replace(/(~~)([^~]+)(~~)/g, `${colors_yellow[0]}$2${normalColor}`) .replace(/(!!)([^!]+)(!!)/g, `${colors_red[1]}$2${normalColor}`) .replace(/(###)([^#]+)(###)/g, `${colors_gray[0]}$2${normalColor}`) .replace(/(##)([^#]+)(##)/g, `${colors_gray[1]}$2${normalColor}`) .replace(/(\^\^\^)([^^]+)(\^\^\^)/g, `${colors_green[0]}$2${normalColor}`) .replace(/(\^\^)([^^]+)(\^\^)/g, `${colors_green[1]}$2${normalColor}`); } function task(text) { assert.ok(text, 'A task name must be provided!'); text = markdown(text); const loading_text = ['\u28fe', '\u28fd', '\u28fb', '\u28bf', '\u287f', '\u28df', '\u28ef', '\u28f7']; let i = 0; let interval = null; const start = function start() { process.stdout.write(`${hideCursor + text} ... `); interval = setInterval(() => { process.stdout.write(`\b${highlight}${loading_text[i % loading_text.length]}\x1B[0m`); i++; }, 100); }; const end = function end(result) { if (interval) { clearInterval(interval); } process.stdout.write(`\b${normalColor}${showCursor}`); if (result.toLowerCase() === 'ok') { process.stdout.write(`${task_ok}\n`); } else if (result.toLowerCase() === 'warn' || result.toLowerCase() === 'warning') { process.stdout.write(`${task_warn}\n`); } else if (result.toLowerCase() === 'error' || result.toLowerCase() === 'err') { process.stdout.write(`${task_error}\n`); } else { process.stdout.write('\n'); } }; return { start, end }; } function loading(text) { text = text || 'Loading'; text = markdown(text); // const loading_text_moons = ['🌕', '🌖', '🌗', '🌘', '🌑', '🌒', '🌓', '🌔']; // const loading_text_clocks = ['🕐', '🕑', '🕒', '🕓', '🕔', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕛']; const loading_text_binary = ['\u28fe', '\u28fd', '\u28fb', '\u28bf', '\u287f', '\u28df', '\u28ef', '\u28f7']; const loading_text = loading_text_binary; let i = 0; let interval = null; const start = function start() { process.stdout.write(`${saveCursor + hideCursor + text} ... `); interval = setInterval(() => { process.stdout.write(`\b${highlight}${loading_text[i % loading_text.length]}\x1B[0m`); i++; }, 75); }; const end = function end() { if (interval) { clearInterval(interval); process.stdout.write(clearLine + normalColor + showCursor + restoreCursor); } }; return { start, end }; } function error(obj, onLogin) { if (process.env.DEBUG && obj && obj.message && obj.stack) { console.log(obj.message); console.log(obj.stack); } if (obj && obj.code && obj.code === 401 && !onLogin) { process.stderr.write(` ${error_color}▸${normalColor} You do not appear to be logged in, use "aka auth:login" and try again.\n${normalColor}`); } else if (obj.code && obj.body) { try { const msg = JSON.parse(obj.body.toString()); if (msg.message) { console.error(`☠ ${error_color}Error ${obj.code}${normalColor}${msg.message ? (`, ${msg.message}`) : obj.body.toString()}`); } else if (msg.error_description && msg.error) { console.error(`☠ ${error_color}Error ${normalColor}${msg.error_description} (${msg.error})`); } else { console.error(`☠ ${error_color}Error ${normalColor}`, obj.body); } } catch (e) { const msg = obj.body.toString(); console.error(`☠ ${error_color}Error ${normalColor}`, obj.code, msg && msg !== '' ? msg.replace(/\n/, '\n ') : 'The specified item was not found. Did you forget to provide an app name, or other parameter?'); } } else if (obj.message) { console.error(`☠ ${obj.message}`); } else { console.error(`☠ ${obj}`); } } function fromKeyedArrayToTable(data) { const out = []; Object.keys(data).forEach((key) => { data[key].forEach((item, i) => { out[i] = out[i] || {}; out[i][key] = item; }); }); return out; } function table(obj, options) { if (obj.length === 0) { console.log('No data found.'); return; } const keys = Object.keys(obj[0]); const t = new cli_table({ head: keys, style: { head: ['bold', 'blue'] }, ...options }); // eslint-disable-line obj.forEach((o) => { const d = []; keys.forEach((k) => { if (o[k] && typeof (o[k]) === 'object') { o[k] = Object.keys(o[k]).map((z) => `${z}=${o[k][z] ? o[k][z].toString() : null}`).join(', '); } d.push(o[k] ? o[k].toString() : ''); }); t.push(d); }); console.log(t.toString()); } function vtable(obj, sort) { const dis = ui({ width: process.stdout.columns }); const keys = sort ? Object.keys(obj).sort() : Object.keys(obj); let max_width = 35; keys.forEach((d) => { if (obj[d] && typeof (obj[d]) === 'object') { const subkeys = sort ? Object.keys(obj[d]).sort() : Object.keys(obj[d]); obj[d] = subkeys.map((z) => { if (obj[d][z] && typeof (obj[d][z]) !== 'string') { return Object.keys(obj[d][z]).map((y) => (`${y}=${obj[d][z][y].toString()}`)).join(', '); } return `${z}=${obj[d][z] ? obj[d][z].toString() : ''}`; }).join(', '); } max_width = d.length > max_width ? d.length : max_width; }); keys.forEach((d) => { dis.div( { text: colors[2] + d + normalColor, width: max_width + 2, padding: [0, 1, 0, 1] }, { text: obj[d], padding: [0, 1, 0, 1] }, ); }); console.log(dis.toString()); } function shell(obj) { Object.keys(obj).forEach((d) => { console.log(`${d}="${obj[d]}"`); }); } function header(text) { console.log(`${highlight}➟➟➟ ${normalColor}${text}`); } function hidden(prompt, callback) { const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const stdin = process.openStdin(); let i = 0; const data_track = function data_track(char) { char += ''; switch (char) { case '\n': case '\r': case '\u0004': stdin.pause(); break; default: process.stdout.write(`\x1B[2K\x1B[200D${prompt}[${(i % 2 === 1) ? '=-' : '-='}]`); i++; break; } }; process.stdin.on('data', data_track); rl.question(prompt, (value) => { rl.history = rl.history.slice(1); process.stdin.removeListener('data', data_track); rl.close(); callback(value); }); } function print(err, obj, sort) { if (err) { return error(err); } if (Array.isArray(obj)) { return table(obj); } if (obj.name && obj.id) { console.log(markdown(`###===### ^^^${obj.name} (${obj.id})^^^`)); } return vtable(obj, sort); } function format_objects(formatter, not_found, err, data) { if (data && data.length > 0) { data = data.map(formatter).map(markdown); console.log(data.join('\n')); } else if (data && data.length === 0) { console.log(not_found); } else { error(err); } } function question(prompt, cb) { const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); return new Promise((resolve) => { rl.question(prompt, (answer) => { rl.close(); if (cb) { cb(answer); } resolve(answer); }); }); } question[util.promisify.custom] = (prompt) => new Promise((resolve) => { question(prompt, (answer) => resolve(answer)); }); function input(cb) { const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question('> ', (answer) => { rl.close(); cb(answer); }); } function confirm(strs, cb) { console.log(markdown(strs)); input(cb); } function soft_error(strs) { console.log(markdown(` !!▸!! ${strs}`)); } function update_statement(current, latest) { return markdown(`~~Update available! Run 'aka update' to update.~~ \n!!${current}!! -> ^^${latest}^^`); } function bold(s) { return boldText + s + normalColor; } function italic(s) { return italicText + s + normalColor; } module.exports = { question, hidden, soft_error, confirm, input, loading, task, error, table, vtable, shell, color: colors[2], nocolor: normalColor, highlight, header, fromKeyedArrayToTable, print, markdown, friendly_date: getDateDiff, format_objects, update_statement, bold, italic, };
Python
UTF-8
2,676
2.796875
3
[]
no_license
import ast import csv matrix = [[0]*28 for x in range(2000,2017)] porcentagem = [[0]*28 for x in range(2000,2017)] for ano in range(2000,2017): dados = open('Resultado/CerradoMT'+str(ano)+'.txt').readlines() linha = dados[-1].replace('\n','') linha = linha[linha.index('{'):linha.index('}')+1] dic = ast.literal_eval(linha) a = ano - 2000 matrix[a][0] = ano porcentagem[a][0] = ano soma = 0 for k,v in dic.iteritems(): if(k!=0): soma = soma + v for k,v in dic.iteritems(): if(k!=0): matrix[a][int(k)] = v porcentagem[a][int(k)] = (v*100.0)/soma with open("pixels.csv", "wb") as f: writer = csv.writer(f,delimiter=';') writer.writerow(['ano',1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]) writer.writerows(matrix) with open("porcentagem.csv", "wb") as f: writer = csv.writer(f,delimiter=';') writer.writerow(['ano',1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]) writer.writerows(porcentagem) def gerar(titulo): matrixReservas = [[0]*28 for x in range(2000,2017)] porcentagemReservas = [[0]*28 for x in range(2000,2017)] porcentagemReservasRelacaoCerrado = [[0]*28 for x in range(2000,2017)] for ano in range(2000,2017): dados = open('Resultado/Cerrado'+titulo+'MT'+str(ano)+'.txt').readlines() linha = dados[-1].replace('\n','') linha = linha[linha.index('{'):linha.index('}')+1] dic = ast.literal_eval(linha) a = ano - 2000 matrixReservas[a][0] = ano porcentagemReservas[a][0] = ano porcentagemReservasRelacaoCerrado[a][0] = ano soma = 0 for k,v in dic.iteritems(): if(k!=0): soma = soma + v for k,v in dic.iteritems(): if(k!=0): matrixReservas[a][int(k)] = v porcentagemReservas[a][int(k)] = (v*100.0)/soma print(a,k,matrix[a][int(k)],v) porcentagemReservasRelacaoCerrado[a][int(k)] = v/float(matrix[a][int(k)])*100.0 with open("pixels"+titulo+".csv", "wb") as f: writer = csv.writer(f,delimiter=';') writer.writerow(['ano',1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]) writer.writerows(matrixReservas) with open("porcentagem"+titulo+".csv", "wb") as f: writer = csv.writer(f,delimiter=';') writer.writerow(['ano',1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]) writer.writerows(porcentagemReservas) with open("porcentagem"+titulo+"RelacaoCerrado.csv", "wb") as f: writer = csv.writer(f,delimiter=';') writer.writerow(['ano',1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]) writer.writerows(porcentagemReservasRelacaoCerrado) gerar('Reservas') gerar('TerraIndigena') gerar('UnidadeConservacao')
Python
UTF-8
289
3.6875
4
[]
no_license
def stringPermutations(s): if len(s) == 0: return [] if len(s) == 1: return [s] output = [] for i in range(len(s)): start = s[i] remainderStr = s[:i] + s[i + 1:] for p in stringPermutations(remainderStr): output.append([start] + p) return output
C++
UTF-8
1,512
3.171875
3
[]
no_license
#include <iostream> #include <vector> #include <stack> #include <queue> #include <string> #include <algorithm> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if(pHead1 && pHead2) { ListNode *p, *ret, *p1cur=pHead1, *p2cur=pHead2; /* decide root node */ if(p1cur->val < p2cur->val) { p = ret = p1cur; p1cur = p1cur->next; } else { p = ret = p2cur; p2cur = p2cur->next; } /* start merge proc */ while(p1cur && p2cur) { if(p1cur->val < p2cur->val) { p = p->next = p1cur; p1cur = p1cur->next; } else { p = p->next = p2cur; p2cur = p2cur->next; } } while(p1cur) { p = p->next = p1cur; p1cur = p1cur->next; } while(p2cur) { p = p->next = p2cur; p2cur = p2cur->next; } return ret; } else if(pHead1) return pHead1; else if(pHead2) return pHead2; else return NULL; } int main(void) { const int _a1[] = {1,3,5}; ListNode *pHead1 = new ListNode(_a1[0]); ListNode *p = pHead1; for(int i=1; i<3; ++i) { p->next = new ListNode(_a1[i]); p = p->next; } const int _a2[] = {2,4,6}; ListNode *pHead2 = new ListNode(_a2[0]); p = pHead2; for(int i=1; i<3; ++i) { p->next = new ListNode(_a2[i]); p = p->next; } p = Merge(pHead1, pHead2); while(p) { cout << p->val; p = p->next; } cout << endl; return 0; }
C
UTF-8
5,945
3.140625
3
[ "MIT" ]
permissive
// // Created by Shaotien Lee on 2020/9/13. // #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "kdTree.h" #include "pointFunctions.h" #include "dictFunctions.h" /* get x coordinate from input */ double getX(char* buffer) { double x = 0; char* xStr = NULL; int i = 0; while(i < strlen(buffer)) { if (buffer[i] != ' ') { i++; continue; } xStr = cutString(buffer, 0, i); break; } if (xStr != NULL) { x = strtod(xStr, NULL); } free(xStr); return x; } /* get y coordinate from input */ double getY(char* buffer) { double y = 0; char* yStr = NULL; int i = 0; int j = 0; while (buffer[i] != ' ') { i++; } j = i + 1; while (buffer[j] != ' ') { j++; } yStr = cutString(buffer, i + 1, j); if (yStr != NULL) { y = strtod(yStr, NULL); } free(yStr); return y; } /* get range from input */ double getRange(char* buffer) { double range = 0; char* rangeStr = NULL; int start = 0; //start from the number after the space int size = 0; while (buffer[start] != ' ') { start++; } start++; while (buffer[start] != ' ') { start++; } start++; size = strlen(buffer) - start; // number of chars in Y part rangeStr = (char*) calloc(size + 1, sizeof(char)); for(int i = 0; i < size; i++) { rangeStr[i] = buffer[start++]; } rangeStr[size] = '\0'; range = strtod(rangeStr, NULL); free(rangeStr); return range; } /* calc distance between two tree nodes */ double distanceCalc(treeNode_ptr p_node, treeNode_ptr p_target) { double answer = sqrt(pow(p_node->nodeX - p_target->nodeX, 2) + pow(p_node->nodeY - p_target->nodeY ,2)); return answer; } /* used to count compares */ void countCompare(int *compareCounter) { *compareCounter = *compareCounter + 1; } void displayFound(FILE *outfile, treeNode_ptr p_result, treeNode_ptr p_target, double range) { treeNode_ptr p = p_result; while(p != NULL) { fprintf(outfile,"%.9g %.9g %.9g --> ", p_target->nodeX, p_target->nodeY, range); fprintf(outfile, "Census year: %d || ", p -> censusYear); fprintf(outfile, "Block ID: %d || ", p -> blockId); fprintf(outfile, "Property ID: %d || ", p -> propertyId); fprintf(outfile, "Base property ID: %d || ", p -> basePropertyId); fprintf(outfile, "CLUE small area: %s || ", p -> clueSmallArea); fprintf(outfile, "Trading Name: %s || ", p -> name); fprintf(outfile, "Industry (ANZSIC4) code: %d || ", p -> industryCode); fprintf(outfile, "Industry (ANZSIC4) description: %s || ", p -> industryDescription); fprintf(outfile, "x coordinate: %.5f || ", p -> xCoordinate); fprintf(outfile, "y coordinate: %.5f || ", p -> yCoordinate); fprintf(outfile, "Location: %s || \n", p -> location); p = p->next; } } /* find nearest point, p_best will point to it */ void findInRange(FILE *outfile, treeNode_ptr p_root, treeNode_ptr p_target, treeNode_ptr* p_close, double range, int *compareCounter, int *isFound) { double d, dMQ; if (p_root == NULL) return; countCompare(compareCounter); d = distanceCalc(p_root, p_target); if(p_root->dimension == 'x') { dMQ = p_root->nodeX - p_target->nodeX; } else if (p_root->dimension == 'y') { dMQ = p_root->nodeY - p_target->nodeY; } if (*p_close == NULL) { *p_close = p_root; } /* if the point is in range */ if (*p_close != NULL && d < range) { *p_close = p_root; displayFound(outfile, *p_close, p_target, range); *isFound = 1; } if (dMQ > 0) { findInRange(outfile, p_root->left, p_target, p_close, range, compareCounter, isFound); } else { findInRange(outfile, p_root->right, p_target, p_close, range, compareCounter, isFound); } /* do we need to check the other side? */ if (pow(dMQ, 2) >= pow(range, 2)) return; /* check the other side */ if (dMQ > 0) { findInRange(outfile, p_root->right, p_target, p_close, range, compareCounter, isFound); } else { findInRange(outfile, p_root->left, p_target, p_close, range, compareCounter, isFound); } } void searchRange(treeNode_ptr root, FILE *outfile) { const char quitCommand[] = "quit!"; char* whatToFind = NULL; size_t whatToFindNumber = 0; double targetX = 0; double targetY = 0; double range = 0; treeNode_ptr p_root = NULL; treeNode_ptr p_target = NULL; treeNode_ptr p_close = NULL; double bestD; int compareCounter; int isFound; while(1) { fflush(stdin); if (getline(&whatToFind, &whatToFindNumber, stdin) == EOF) { /* detect ending of stdin if users use < operator in bash */ break; } trimLastEnter(whatToFind); /* trim '\n' at the end of the string */ if (!strcmp(quitCommand, whatToFind)) { break; } targetX = getX(whatToFind); targetY = getY(whatToFind); range = getRange(whatToFind); free(whatToFind); whatToFind = NULL; isFound = 0; p_root = root; p_target = (treeNode_ptr) calloc(1, sizeof(treeNode_t)); p_target->nodeX = targetX; p_target->nodeY = targetY; compareCounter = 0; findInRange(outfile, p_root, p_target, &p_close, range, &compareCounter, &isFound); if(!isFound) { fprintf(outfile, "%.9g %.9g %.9g --> NOTFOUND\n", p_target->nodeX, p_target->nodeY, range); } printf("%.9g %.9g %.9g --> %d\n", targetX, targetY, compareCounter); free(p_target); } free(whatToFind); }
Java
UTF-8
3,239
2.765625
3
[]
no_license
package com.yuki.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; import java.util.Enumeration; /* * @title HttpServletRequest学习测试 * * 1. 请求参数相关 - getParameterNames、getParameter(单选框、输入框)tParameterValues(获取多选框)、getHeader() * 2. 客户端相关 - method(请求方式)、protocol(协议)、add(ip地址)、host(域名)、port(端口)、uri、queryStr * 3. 服务端相关 - serverAddr(服务器ip)、serverPort(服务器端口)、serverPath(servlet路径) * 4. 转发相关 - setAttribute、getRequestDispatcher、forward() * 5. 获取其他对象 - getServletConfig(initParam)、getServletContext(app对象)、getSession、getCookies() * */ @WebServlet(urlPatterns = "/simple",initParams = { @WebInitParam(name = "servletConfig",value = "this is servlet init params") }) public class SimpleServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // ServletConfig 测试initParams System.out.println(this.getServletConfig().getInitParameter("servletConfig")); // 1. getParamter()/getParamterNames()/getParamterValues() System.out.println("--------------getParam()、getParams()、getParamVals()---------------------"); Enumeration<String> iterator = req.getParameterNames(); while (iterator.hasMoreElements()) { System.out.println(iterator.nextElement()); } System.out.println(req.getParameter("name")); String[] hobbies = req.getParameterValues("hobby"); System.out.println(hobbies); // 2. uri相关 - System.out.println("--------------method、protocol、addr、host、port、uri、queryStr---------------------"); System.out.println(req.getMethod()); // 请求方式GEt-POST System.out.println(req.getProtocol()); // 协议 System.out.println(req.getRemoteAddr()); // ip System.out.println(req.getRemoteHost()); // ip域名 System.out.println(req.getRemotePort()); // port System.out.println(req.getRequestURI()); // uri System.out.println(req.getQueryString()); // queryString // 3. 服务器相关信息-- sserverName、serverPort、servletPath System.out.println(req.getServerName()); // localhost System.out.println(req.getServletPath()); // simple System.out.println(req.getServerPort()); // 8080 // 4. 设置属性 setAttribute和 getRequestDispatcher和forward - 重定向 // 5 获取其他对象 - initParams、session、cookies、applicationContext String cp = getServletConfig().getInitParameter("servletConfig"); Cookie[] cookies = req.getCookies(); for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].getName()); System.out.println(cookies[i].getValue()); } HttpSession session = req.getSession(true); ServletContext servletContext = req.getServletContext(); } }
Python
UTF-8
2,360
2.703125
3
[ "Apache-2.0" ]
permissive
import json import sqlite3 import random import string def get(dic): connection = sqlite3.connect('database.db') cursor = connection.cursor() result = cursor.execute('select * from ' + dic['table'] + ' where id == ?', [dic['id']]) items = [] for row in result: item = dict(zip([d[0] for d in cursor.description], row)) items.append(item) connection.close() return items def add(dic): connection = sqlite3.connect('database.db') cursor = connection.cursor() table = dic.pop('table') values = prepare_values(dic.values()) keys = ', '.join(dic.keys()) print('insert into ' + table + ' (' + keys + ') values (' + values + ')') cursor.execute('insert into ' + table + ' (' + keys + ') values (' + values + ')') connection.commit() connection.close() return None def delete(dic): connection = sqlite3.connect('database.db') cursor = connection.cursor() cursor.execute('delete from ' + dic['table'] + ' where id == ?', [dic['id']]) connection.commit() return None def list(dic): connection = sqlite3.connect('database.db') cursor = connection.cursor() result = cursor.execute('select * from ' + dic['table']) items = [] for row in result: item = dict(zip([d[0] for d in cursor.description], row)) items.append(item) connection.close() return items def generate_id(dic): rand = '' for i in range(10): rand = rand + random.choice(string.ascii_letters) connection = sqlite3.connect('database.db') cursor = connection.cursor() cursor.execute('select * from ' + dic['table'] + ' where id = ?', [rand]) if cursor.rowcount == -1: connection.close() return rand else: connection.close() return generate_id(dic) def generate_token(dic): rand = '' for i in range(20): rand = rand + random.choice(string.ascii_letters) connection = sqlite3.connect('database.db') cursor = connection.cursor() cursor.execute('select * from ' + dic['table'] + ' where token = ?', [rand]) if cursor.rowcount == -1: connection.close() return rand else: connection.close() return generate_token(dic) def prepare_values(vals): if vals == None or len(vals) == 0: return None result = '' for v in vals: if result == '': result = '\'' + str(v) + '\'' else: result = result + ', ' + '\'' + str(v) + '\'' return result
JavaScript
UTF-8
8,982
2.6875
3
[ "MIT" ]
permissive
const fs = require('fs'); const schemas = require('./schemas.js')(); const sfoHeaderSchema = schemas.create('SFOHeader', [{ name: "magic", type: "raw", size: 4 },{ name: "version", type: "raw", size: 4 }, { name: "keyTableOffset", type: "int32" }, { name: "dataTableOffset", type: "int32" }, { name: "entryCount", type: "int32" }]); const indexTableEntrySchema = schemas.create('IndexTableEntry', [{ name: "keyOffset", type: "uint16" }, { name: "paramFormat", type: "uint16" }, { name: "paramLength", type: "uint32" }, { name: "paramMaxLength", type: "uint32" }, { name: "dataOffset", type: "uint32" }]); const paramTypes = { "ACCOUNT_ID": "uint64", "SAVEDATA_BLOCKS": "uint64", }; module.exports = function() { const sfoEditor = {}; let sfoData = {}; sfoEditor.load = function(sfoFilePath) { const sfoBuffer = fs.readFileSync(sfoFilePath); return sfoEditor.loadFromBuffer(sfoBuffer); }; sfoEditor.show = function() { console.log(sfoData); }; sfoEditor.loadFromBuffer = function(sfoBuffer) { sfoData = {}; const sfoHeader = sfoHeaderSchema.fromBuffer(sfoBuffer); sfoData.header = sfoHeader; const sfoIndex = []; const entries = new Map; sfoData.index = sfoIndex; sfoData.entries = entries; sfoData.entryIndexMapping = {}; let indexTableOffset = sfoHeaderSchema.size; for (let i = 0; i < sfoHeader.entryCount; i++) { const offset = indexTableOffset + (i * indexTableEntrySchema.size); const indexEntry = indexTableEntrySchema.fromBuffer(sfoBuffer, offset); sfoIndex.push(indexEntry); const keyOffset = sfoHeader.keyTableOffset + indexEntry.keyOffset; const dataOffset = sfoHeader.dataTableOffset + indexEntry.dataOffset; const key = schemas.readEntryFromBuffer({ type: "utf8", }, sfoBuffer, keyOffset, Number.MAX_VALUE); sfoData.entryIndexMapping[key] = i; let value = undefined; if (indexEntry.paramFormat === 0x4) { value = schemas.readEntryFromBuffer({ type: paramTypes[key] || "raw", }, sfoBuffer, dataOffset, dataOffset + indexEntry.paramLength); } else if (indexEntry.paramFormat === 0x204) { value = schemas.readEntryFromBuffer({ type: "utf8", }, sfoBuffer, dataOffset, dataOffset + indexEntry.paramMaxLength); } else if (indexEntry.paramFormat === 0x404) { value = schemas.readEntryFromBuffer({ type: "uint32", }, sfoBuffer, dataOffset, dataOffset + indexEntry.paramMaxLength); } entries.set(key, value); } } sfoEditor.editEntry = function(key, value) { const entryIndex = sfoData.entryIndexMapping[key]; if (entryIndex == null) { throw Error(`No entry for ${key}`); } const index = sfoData.index[entryIndex]; let indexType; if (index.paramFormat === 0x4) { indexType = paramTypes[key] || "raw"; } else if (index.paramFormat === 0x204) { indexType = "utf8"; } else if (index.paramFormat === 0x404) { indexType = "uint32"; } if (indexType === "uint32") { if (isNaN(value)) { throw Error(`[${key}] value must be a number!`); } if (typeof value === "bigint") { throw Error(`[${key}] value can not be a bigint!`); } if (value < 0 || 0xFFFFFFFF < value) { throw Error(`[${key}] Value must be at least 0 and at most 4294967295!`); } } else if (indexType === "utf8") { if (typeof value !== "string") { throw Error(`[${key}] value must be a string!`); } const maxStringLength = index.paramMaxLength - 1; if (value.length > maxStringLength) { throw Error(`[${key}] string length must be at most ${maxStringLength}`); } } else if (indexType === "uint64") { if (!isNaN(value)) { value = BigInt(value); } if (typeof value !== "bigint") { throw Error(`[${key}] value must be a bigint!`); } const maxValue = 2n**64n; if (value < 0n || maxValue < value) { throw Error(`[${key}] value must be at least 0 and at most ${maxValue.toString()}!`); } } else if (indexType === "raw") { if (!Array.isArray(value)) { throw Error(`[${key}] value must be an array!`); } if (value.length !== index.paramMaxLength) { throw Error(`[${key}] value must have ${index.paramMaxLength} elements!`); } let isCorrectType = true; for (const item of value) { if (typeof item !== "number") { isCorrectType = false; break; } if (item < 0 || 255 < item) { isCorrectType = false; break; } } if (!isCorrectType) { throw Error(`[${key}] all elements must be a number that is at least 0 and at most 255!`); } } sfoData.entries.set(key, value); if (indexType === 'utf8') { index.paramLength = value.length + 1; } } function alignByFour(value) { if (value%4) { return value + (4 - (value%4)); } return value; } sfoEditor.export = function() { const offsets = {}; offsets.header = 0; const headerSize = 0x14; let size = headerSize; offsets.indexTable = size; const indexTableEntrySize = 0x10; const entryCount = sfoData.header.entryCount; size += indexTableEntrySize * entryCount; offsets.keyTable = size; let keyTableSize = Array.from(sfoData.entries.keys()) .reduce((size, key) => size + (key.length + 1), 0); keyTableSize = alignByFour(keyTableSize); size += keyTableSize; offsets.dataTable = size; const dataTableSize = sfoData.index.reduce((size, index) => size + index.paramMaxLength, 0); size += dataTableSize; const buffer = Buffer.alloc(size); // update these just in case they changed sfoData.header.keyTableOffset = offsets.keyTable; sfoData.header.dataTableOffset = offsets.dataTable; sfoHeaderSchema.toBuffer(sfoData.header, buffer); // sort alphabetically const entryKeys = Array.from(sfoData.entries.keys()).sort(); let indexOffset = offsets.indexTable; let keyOffset = 0; let dataOffset = 0; for (let i = 0; i < entryKeys.length; i++) { const entryKey = entryKeys[i]; const entryValue = sfoData.entries.get(entryKey); const entrySFOIndex = sfoData.entryIndexMapping[entryKey]; const sfoIndex = sfoData.index[entrySFOIndex]; // relative to the base sfoIndex.keyOffset = keyOffset; sfoIndex.dataOffset = dataOffset; // write index to buffer indexTableEntrySchema.toBuffer(sfoIndex, buffer, indexOffset); // write key to buffer schemas.writeEntryToBuffer({ type: "utf8", }, entryKey, buffer, offsets.keyTable + keyOffset); // write value to buffer if (sfoIndex.paramFormat === 0x4) { const entryObj = { type: paramTypes[entryKey] || "raw", }; if (entryObj.type === 'raw') { entryObj.size = entryValue.length; } schemas.writeEntryToBuffer(entryObj, entryValue, buffer, offsets.dataTable + dataOffset); } else if (sfoIndex.paramFormat === 0x204) { schemas.writeEntryToBuffer({ type: "utf8", }, entryValue, buffer, offsets.dataTable + dataOffset); } else if (sfoIndex.paramFormat === 0x404) { schemas.writeEntryToBuffer({ type: "uint32", }, entryValue, buffer, offsets.dataTable + dataOffset); } keyOffset += entryKey.length + 1; dataOffset += sfoIndex.paramMaxLength; indexOffset += indexTableEntrySize; } return buffer; } // keyTable = 212 // dataTable = 348 return sfoEditor; }
Python
UTF-8
3,855
2.9375
3
[]
no_license
""" Capstone Project. Code for testing basics. Author: David Mutchler, based on work by Dave Fisher and others. READ and RUN this module but ** DO NOT MODIFY IT. ** Fall term, 2018-2019. """ # Austin module import rosebotics_new as rb import time import ev3dev.ev3 as ev3 def main(): """ Runs tests. """ run_tests() def run_tests(): """ Runs various tests. """ print('starting test') # run_test_drive_system() print('test done') #run_test_touch_sensor() #run_test_color_sensor() drive_system = rb.DriveSystem() drive_system.go_straight_inches(12) drive_system.go_straight_inches(-12) drive_system.spin_in_place_degrees(720) drive_system.turn_degrees(70) def run_test_drive_system(): """ Tests the drive_system of the Snatch3rRobot. """ robot = rb.Snatch3rRobot() print() print("Testing the drive_system of the robot.") print("Move at (20, 50) - that is, veer left slowly") robot.drive_system.start_moving(20, 50) time.sleep(2) robot.drive_system.stop_moving() print("Left/right wheel positions:", robot.drive_system.left_wheel.get_degrees_spun(), robot.drive_system.right_wheel.get_degrees_spun()) time.sleep(1) print() print("Spin clockwise at half speed for 2.5 seconds") robot.drive_system.move_for_seconds(2.5, 50, -50) print("Left/right wheel positions:", robot.drive_system.left_wheel.get_degrees_spun(), robot.drive_system.right_wheel.get_degrees_spun()) robot.drive_system.left_wheel.reset_degrees_spun() robot.drive_system.right_wheel.reset_degrees_spun(2000) time.sleep(1) print() print("Move forward at full speed for 1.5 seconds, coast to stop") robot.drive_system.start_moving() time.sleep(1.5) robot.drive_system.stop_moving(rb.StopAction.COAST) print("Left/right wheel positions:", robot.drive_system.left_wheel.get_degrees_spun(), robot.drive_system.right_wheel.get_degrees_spun()) def run_test_touch_sensor(): """ Tests the touch_sensor of the Snatch3rRobot. """ robot = rb.Snatch3rRobot() print() print("Testing the touch_sensor of the robot.") print("Repeatedly press and release the touch sensor.") print("Press Control-C when you are ready to stop testing.") time.sleep(1) count = 1 while True: print("{:4}.".format(count), "Touch sensor value is: ", robot.touch_sensor.get_value()) time.sleep(0.5) count = count + 1 def run_test_color_sensor(): """ Tests the color_sensor of the Snatch3rRobot. """ robot = rb.Snatch3rRobot() print() print("Testing the color_sensor of the robot.") print("Repeatedly move the robot to different surfaces.") print("Press Control-C when you are ready to stop testing.") time.sleep(1) count = 1 while True: print("{:4}.".format(count), "Color sensor value/color/intensity is: ", "{:3} {:3} {:3}".format(robot.color_sensor.get_value()[0], robot.color_sensor.get_value()[1], robot.color_sensor.get_value()[2]), "{:4}".format(robot.color_sensor.get_color()), "{:4}".format(robot.color_sensor.get_reflected_intensity())) time.sleep(0.5) count = count + 1 def beep_if_blob(): cam = rb.Snatch3rRobot() print('plz work') count = 0 while 1 == 1: blob = cam_boi.camera.get_biggest_blob() print(blob) size = blob.get_area() print(size) count =+ 1 print (size) if size >= 60: print('it worked?') ev3.Sound.beep().wait(1) break else: print("eh",count) print('yah?!!!!') main()
Markdown
UTF-8
5,315
3.265625
3
[ "MIT" ]
permissive
--- layout: page title: Loading Fonts parent: cpp_manual next: input --- TrueType and OpenType fonts can be loaded into RmlUi by the application. RmlUi has no default font, so at least one font must be loaded before text can be rendered. To load a font, call one of the `Rml::LoadFontFace()` functions. The simplest of these takes a file name and optional fallback and weight parameters: ```cpp // Adds a new font face to the font engine. The face's family, style and weight will be determined from the face itself. // @param[in] file_name The file to load the face from. // @param[in] fallback_face True to use this font face for unknown characters in other font faces. // @param[in] weight The weight to load when the font face contains multiple weights, otherwise the weight to register the font as. By // default it loads all found font weights. // @return True if the face was loaded successfully, false otherwise. bool LoadFontFace(const String& file_name, bool fallback_face = false, Style::FontWeight weight = Style::FontWeight::Auto); ``` This function will load the font file specified (opening it through the file interface). The font's family (the string you specify the font with using the `font-family`{:.prop} RCSS property), the style (normal or italic) and by default the weight are all fetched from the font file itself. RmlUi will generate the font data for specific sizes of the font as required by the application. Note that if you are loading a .ttc, only the first font will be registered. If enabled, the `fallback_face` option will make the given font face be used for any unknown characters in other fonts. This is useful for example to provide a single font face for emojis, and another one providing characters for e.g. cyrillic or greek. Then these fonts will be used whenever characters encountered are not located in the fonts specified by the document. Multiple fallback faces can be used, and they will be prioritized in the order they were loaded. When the `weight` parameter is `Auto`{:.value} the weight is automatically retrieved from the font. Further, if the font contains multiple weight variations then all of them are loaded. Any other value of `weight` is either used to override the registered weight, or when there are multiple weights in the face, choose which weight variation to load. Overriding the default `weight` parameter can be done by one of `Rml::Style::FontWeight::Normal`{:.value}, `Bold`{:.value}, or any numeric value \[1,1000\] by casting, for example `(Rml::Style::FontWeight)850`{:.value}. If you need to load a font face from memory, and override the family name, style or weight of the font, use the more complex `LoadFontFace()`: ```cpp // Adds a new font face from memory to the font engine. The face's family, style and weight is given by the parameters. // @param[in] data A pointer to the data. // @param[in] data_size Size of the data in bytes. // @param[in] family The family to register the font as. // @param[in] style The style to register the font as. // @param[in] weight The weight to load when the font face contains multiple weights, otherwise the weight to register the font as. By // default it loads all found font weights. // @param[in] fallback_face True to use this font face for unknown characters in other font faces. // @return True if the face was loaded successfully, false otherwise. // @lifetime The pointed to 'data' must remain available until after the call to Rml::Shutdown. static bool LoadFontFace(const byte* data, int data_size, const String& family, Style::FontStyle style, Style::FontWeight weight = Style::FontWeight::Auto, bool fallback_face = false); ``` - When the provided `family` is empty, the font family and style is automatically retrieved from the font. - `style` is one of `Rml::Style::FontStyle::Normal`{:.value} or `Italic`{:.value}. - The `weight` and `fallback_face` parameters work exactly like in the above function. The italic and bold versions of a font are selected with the `font-weight`{:.prop} and `font-style`{:.prop} RCSS properties. In the following example, the font file at `data/trilobyte.ttf`{:.path} is loaded and registered with RmlUi with the family name, style and weight settings specified in the file itself. ```cpp Rml::LoadFontFace("data/trilobyte.ttf"); ``` In this example, the font file is loaded from memory with overrides for the name, style and weight. ```cpp std::vector<unsigned char> trilobyte_b = MyAssetLoader("data/trilobyte_b.ttf"); Rml::LoadFontFace(trilobyte_b.data(), trilobyte_b.size(), "Trilobyte", Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Bold); /* ... */ // Note that the data must stay alive until after the call to Rml::Shutdown. Rml::Shutdown(); trilobyte_b.clear(); ``` These fonts would be specified in RCSS with the following rules (assuming 'trilobyte.ttf' registers a font of the family 'Trilobyte'): ```css body { font-family: Trilobyte; } strong { font-weight: bold; } ``` If you are unsure about the font-family name of a loaded font file, take a look at the log output as that will list the names of all loaded fonts.
JavaScript
UTF-8
802
3.5
4
[]
no_license
const calculation = (leftSet, rightSet, acc) => { [...leftSet].forEach(left => { [...rightSet].forEach(right => { acc.add(left + right); acc.add(left - right); acc.add(left * right); if (right !== 0) acc.add(Math.floor(left / right)) }) }) } const solution = (N, number) => { const accumulate = new Array(9).fill(0).map(v => new Set()); for (let i = 1; i <= 8; i++) { const init = '1'.repeat(i) * N; accumulate[i].add(init); } for (let i = 1; i <= 8; i++) { for (let j = 1; j < i; j++) { const leftSet = accumulate[j]; const rightSet = accumulate[i - j]; calculation(leftSet, rightSet, accumulate[i]); } if (accumulate[i].has(number)) { return i; } } return -1; } console.log(solution(5, 12));
C++
UTF-8
26,923
2.515625
3
[]
no_license
#include "StdAfx.h" #include "OrderBook.h" const std::string OrderBook::logName = "OrderBook"; OrderBook::OrderBook(Stock* stock, TraderManager* traderManager, bool perfAnalytics) { _threshold = 0.01; _stock = stock; _ruleManager = new RuleManager(); _traderManager = traderManager; _openPrice = stock->getLastPrice(); _lastPrice = _openPrice; _time = 0; _prices.push_back(PastPrice(_lastPrice, _time)); _performanceAnalytics = perfAnalytics; if (_performanceAnalytics) { _timer = new WallTimer(); _matchTime = 0; _traderProcTime = 0; std::string temp = "Time,Price,Bid,Call,Spread,BuyOrderCount,SellOrderCount,TradesCount,MatchTime,OclProcTime,TraderProcTime"; //std::cout << temp << std::endl; Logger::GetInstance()->Data(temp); } else { _timer = NULL; _matchTime = NULL; _traderProcTime = NULL; std::string temp = "Time,Price,Bid,Call,Spread,NumberBuyOrder,NumberSellOrder,NumberTrades,MinPrice,AvePrice,MaxPrice"; //std::cout << temp << std::endl; Logger::GetInstance()->Data(temp); } _buyMarketOrders = 0; _buyLimitOrders = 0; _sellMarketOrders = 0; _sellLimitOrders = 0; _buyVolume = 0; _sellVolume = 0; try { _traderManager->Init(); } catch (...) { std::stringstream temp1; temp1 << "Failed in OrderBook():_traderManager->Init() - " << __FILE__ << " (" << __LINE__ << ")"; std::string temp = Utils::MergeException(temp1.str(), Utils::ResurrectException()); Logger::GetInstance()->Error(logName, temp); std::cerr << temp << std::endl; std::getchar(); exit(-1); } } OrderBook::OrderBook(Stock* stock, TraderManager* traderManager, double openPrice, bool perfAnalytics) { _threshold = 0.01; _stock = stock; _ruleManager = new RuleManager(); _traderManager = traderManager; _openPrice = openPrice; _lastPrice = stock->getLastPrice(); _time = 0; _prices.push_back(PastPrice(_lastPrice, _time)); _performanceAnalytics = perfAnalytics; if (_performanceAnalytics) { _timer = new WallTimer(); _matchTime = 0; _traderProcTime = 0; std::string temp = "Time,Price,Bid,Call,Spread,BuyOrderCount,SellOrderCount,TradesCount,MatchTime,OclProcTime,TraderProcTime"; //std::cout << temp << std::endl; Logger::GetInstance()->Data(temp); } else { _timer = NULL; _matchTime = NULL; _traderProcTime = NULL; std::string temp = "Time,Price,Bid,Call,Spread,NumberBuyOrder,NumberSellOrder,NumberTrades"; //std::cout << temp << std::endl; Logger::GetInstance()->Data(temp); } _buyMarketOrders = 0; _buyLimitOrders = 0; _sellMarketOrders = 0; _sellLimitOrders = 0; _buyVolume = 0; _sellVolume = 0; try { _traderManager->Init(); } catch (...) { std::stringstream temp1; temp1 << "Failed in OrderBook():_traderManager->Init() - " << __FILE__ << " (" << __LINE__ << ")"; std::string temp = Utils::MergeException(temp1.str(), Utils::ResurrectException()); Logger::GetInstance()->Error(logName, temp); throw new std::exception(temp.c_str()); } } OrderBook::~OrderBook(void) { if (_performanceAnalytics) { delete _timer; } delete _ruleManager; } Order* OrderBook::getOrderPtr(Order order) { Logger::GetInstance()->Debug(logName, Utils::Merge("Getting Pointer for order:", order.toString())); std::list<Order>::iterator it; if (order.isBuy()) { for (it = _buyOrders.begin(); it != _buyOrders.end(); it++) { if (it->equals(&order)) { Logger::GetInstance()->Debug(logName, "DONE"); return &*it; } } } else { for (it = _sellOrders.begin(); it != _sellOrders.end(); it++) { if (it->equals(&order)) { Logger::GetInstance()->Debug(logName, "DONE"); return &*it; } } } Logger::GetInstance()->Debug(logName, "DONE"); return NULL; } Order* OrderBook::getOrderPtr(int id) { Logger::GetInstance()->Debug(logName, Utils::Merge("Getting Pointer for order id:", Utils::ItoS(id))); std::list<Order>::iterator it; //First search buy orders for (it = _buyOrders.begin(); it != _buyOrders.end(); it++) { if (it->getOrderNumber() == id) { Logger::GetInstance()->Debug(logName, "DONE"); return &*it; } } //If not found search sell orders for (it = _sellOrders.begin(); it != _sellOrders.end(); it++) { if (it->getOrderNumber() == id) { Logger::GetInstance()->Debug(logName, "DONE"); return &*it; } } //if nothing is found Logger::GetInstance()->Debug(logName, "DONE"); return NULL; } Order OrderBook::GetOrder(int id) { Logger::GetInstance()->Debug(logName, Utils::Merge("Getting Pointer for order id:", Utils::ItoS(id))); std::list<Order>::iterator it; //First search buy orders for (it = _buyOrders.begin(); it != _buyOrders.end(); it++) { if (it->getOrderNumber() == id) { Logger::GetInstance()->Debug(logName, "DONE"); return *it; } } //If not found search sell orders for (it = _sellOrders.begin(); it != _sellOrders.end(); it++) { if (it->getOrderNumber() == id) { Logger::GetInstance()->Debug(logName, "DONE"); return *it; } } //if nothing is found Logger::GetInstance()->Debug(logName, "DONE"); throw new std::exception(Utils::Merge("No order found with id:", Utils::ItoS(id)).c_str()); } Trade* OrderBook::getTradePtr(Trade trade) { Logger::GetInstance()->Debug(logName, Utils::Merge("Getting Pointer for trade:", trade.toString())); std::vector<Trade>::iterator it; for (it = _trades.begin(); it != _trades.end(); it++) { if (it->equals(&trade)) { Logger::GetInstance()->Debug(logName, "DONE"); return &*it; } } Logger::GetInstance()->Debug(logName, "DONE"); return NULL; } void OrderBook::notifyTraders(Trade* trade) { Logger::GetInstance()->Debug(logName, "Notifying Traders of trade"); _traderManager->notify(trade); Logger::GetInstance()->Debug(logName, "DONE"); } void OrderBook::print() { std::stringstream stream; stream << "==============================\n"; stream << "---------------" << this->getTime() << "---------------\n"; std::list<Order>::iterator it; for (it = _buyOrders.begin(); it != _buyOrders.end(); it++) { stream << it->toString() << "\n"; } stream << "\n"; for (it = _sellOrders.begin(); it != _sellOrders.end(); it++) { stream << it->toString() << "\n"; } stream << "------------Trades------------\n"; for (int i = 0; i < _trades.size(); i++) { stream << _trades.at(i).toString() << "\n"; } std::cout << stream.str() << std::endl; } void OrderBook::printPrice() { std::cout << _lastPrice << std::endl; } void OrderBook::printTrades() { std::stringstream stream; stream << "------------Trades------------\n"; for (int i = 0; i < _trades.size(); i++) { stream << _trades.at(i).toString() << "\n"; } std::cout << stream.str() << std::endl; } void OrderBook::printBrief() { std::stringstream stream; if (_performanceAnalytics) { /*char T[512]; sprintf_s(T, "%d,%.2f,%d,%d,%d,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f\t\t", _time, this->getLastPrice().price, this->getBuyOrders().size(), this->getSellOrders().size(), _trades.size(), _matchTime, GetAveMatchTime(), GetMaxMatchTime(), _traderProcTime, GetAveTraderProcTime(), GetMaxTraderProcTime(), _traderManager->getProcessTime(), GetAveOclProcTime(), GetMaxOclProcTime()); stream << T << "\r";*/ char T[512]; sprintf_s(T, "%d,%.2f,%.2f,%.2f,%.2f,%d,%d,%d,%.3f,%.3f,%.3f", _time, this->getLastPrice().price, this->GetBid(), this->GetCall(), this->GetSpread(), this->getBuyOrders().size(), this->getSellOrders().size(), _trades.size(), _matchTime, _traderProcTime, _traderManager->getProcessTime()); /*sprintf_s(T, "%d,%.2f,%d,%d,%d,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f\t\t", _time, this->getLastPrice().price, this->getBuyOrders().size(), this->getSellOrders().size(), _trades.size(), _matchTime, 1.0f, 1.0f, _traderProcTime, 1.0f, 1.0f, _traderManager->getProcessTime(), 1.0f, 1.0f);*/ stream << T << "\r"; } else { char T[128]; sprintf_s(T, "%d,%.2f,%d,%d,%d\t\t", _time, this->getLastPrice().price, this->getBuyOrders().size(), this->getSellOrders().size(), _trades.size()); stream << T << "\r"; } std::cout << stream.str(); std::ofstream output; } void OrderBook::registerTrader(Trader* trader) { Logger::GetInstance()->Debug(logName, "Registering Trader"); _traderManager->addTrader(trader); Logger::GetInstance()->Debug(logName, "DONE"); } void OrderBook::unRegisterTrader(Trader* trader) { Logger::GetInstance()->Debug(logName, "Unregistering Trader"); _traderManager->removeTrader(trader); Logger::GetInstance()->Debug(logName, "DONE"); } void OrderBook::processTraders() { Logger::GetInstance()->Debug(logName, "Processing Traders"); if (_performanceAnalytics) _timer->Start(); try { _traderManager->process(this); } catch (...) { std::stringstream temp1; temp1 << "Failed in processTraders:_traderManager->process() - " << __FILE__ << " (" << __LINE__ << ")"; std::string temp = Utils::MergeException(temp1.str(), Utils::ResurrectException()); Logger::GetInstance()->Error(logName, temp); std::cerr << temp << std::endl; std::getchar(); exit(-1); } if (_performanceAnalytics) _traderProcTime = _timer->GetCounter(); Logger::GetInstance()->Debug(logName, "DONE"); } void OrderBook::addRule(IRule* rule) { Logger::GetInstance()->Info(logName, Utils::Merge("Adding rule:", rule->ToString())); _ruleManager->addRule(rule); } void OrderBook::removeRule(IRule* rule) { Logger::GetInstance()->Info(logName, Utils::Merge("Removing rule:", rule->ToString())); _ruleManager->removeRule(rule); } void OrderBook::submitOrder(Order order) { Logger::GetInstance()->Debug(logName, Utils::Merge("Submitting order to queue. Order:", order.toString())); queue.enqueue(OrderRequest(order, true)); } void OrderBook::deSubmitOrder(int orderId) { Logger::GetInstance()->Debug(logName, Utils::Merge("Submitting cancel request to queue for order id:", Utils::ItoS(orderId))); queue.enqueue(OrderRequest(GetOrder(orderId), false)); } void OrderBook::addOrder(Order order) { Logger::GetInstance()->Order(order.toStringCSV()); Logger::GetInstance()->Debug(logName, "Adding order to appropriate order list"); if (order.isBuy()) { _buyOrders.push_back(order); Logger::GetInstance()->Info(logName, Utils::Merge("Added buy order:", order.toString())); Logger::GetInstance()->Debug(logName, "Sorting Buy orders"); _buyOrders.sort(Order::compareBuys); Logger::GetInstance()->Debug(logName, "DONE"); if (order.isMarket()) { _buyMarketOrders++; Logger::GetInstance()->Info(logName, Utils::Merge("Number of Buy Market Orders:", Utils::ItoS(_buyMarketOrders))); } else if (order.isLimit()) { _buyLimitOrders++; Logger::GetInstance()->Info(logName, Utils::Merge("Number of Buy Limit Orders:", Utils::ItoS(_buyLimitOrders))); } _buyVolume += order.getSize(); Logger::GetInstance()->Info(logName, Utils::Merge("Total Buy Volume on the book:", Utils::ItoS(_buyVolume))); } else { _sellOrders.push_back(order); Logger::GetInstance()->Info(logName, Utils::Merge("Added sell order:", order.toString())); Logger::GetInstance()->Debug(logName, "Sorting Sell orders"); _sellOrders.sort(Order::compareSells); Logger::GetInstance()->Debug(logName, "DONE"); if (order.isMarket()) { _sellMarketOrders++; Logger::GetInstance()->Info(logName, Utils::Merge("Number of Sell Market Orders:", Utils::ItoS(_sellMarketOrders))); } else if(order.isLimit()) { _sellLimitOrders++; Logger::GetInstance()->Info(logName, Utils::Merge("Number of Sell Limit Orders:", Utils::ItoS(_sellLimitOrders))); } _sellVolume += order.getSize(); Logger::GetInstance()->Info(logName, Utils::Merge("Total Sell Volume on the book:", Utils::ItoS(_sellVolume))); } Logger::GetInstance()->Debug(logName, "DONE"); } void OrderBook::removeOrder(Order order) { Logger::GetInstance()->Debug(logName, "Removing order to appropriate order list"); if (order.isBuy()) { _buyOrders.remove(order); Logger::GetInstance()->Info(logName, Utils::Merge("Removed buy order:", order.toString())); Logger::GetInstance()->Debug(logName, "Sorting Buy orders"); _buyOrders.sort(Order::compareBuys); Logger::GetInstance()->Debug(logName, "DONE"); if (order.isMarket()) { _buyMarketOrders--; Logger::GetInstance()->Info(logName, Utils::Merge("Number of Buy Market Orders:", Utils::ItoS(_buyMarketOrders))); } else if (order.isLimit()) { _buyLimitOrders--; Logger::GetInstance()->Info(logName, Utils::Merge("Number of Buy Limit Orders:", Utils::ItoS(_buyLimitOrders))); } _buyVolume -= order.getSize(); Logger::GetInstance()->Info(logName, Utils::Merge("Total Buy Volume on the book:", Utils::ItoS(_buyVolume))); } else { _sellOrders.remove(order); Logger::GetInstance()->Info(logName, Utils::Merge("Removed sell order:", order.toString())); Logger::GetInstance()->Debug(logName, "Sorting Sell orders"); _sellOrders.sort(Order::compareSells); Logger::GetInstance()->Debug(logName, "DONE"); if (order.isMarket()) { _sellMarketOrders--; Logger::GetInstance()->Info(logName, Utils::Merge("Number of Sell Market Orders:", Utils::ItoS(_sellMarketOrders))); } else if (order.isLimit()) { _sellLimitOrders--; Logger::GetInstance()->Info(logName, Utils::Merge("Number of Sell Limit Orders:", Utils::ItoS(_sellLimitOrders))); } _sellVolume -= order.getSize(); Logger::GetInstance()->Info(logName, Utils::Merge("Total Sell Volume on the book:", Utils::ItoS(_sellVolume))); } Logger::GetInstance()->Debug(logName, "DONE"); } void OrderBook::updateOrderSize(Order*& order, int size) { Logger::GetInstance()->Debug(logName, Utils::Merge(Utils::Merge("Updating order size to:", Utils::ItoS(size)), order->toString())); if (size <= 0) { this->removeOrder(*order); //if (order->isBuy()) // _buyOrders.remove(*order); //else // _sellOrders.remove(*order); order = NULL; } else { if (order->isBuy()) _buyVolume -= (order->getSize() - size); else if (order->isSell()) _sellVolume -= (order->getSize() - size); order->setSize(size); } Logger::GetInstance()->Debug(logName, "DONE"); } void OrderBook::matchOrders() { Logger::GetInstance()->Debug(logName, "Matching Orders"); if (_performanceAnalytics) _timer->Start(); if (!queue.isEmpty()) { OrderRequest request = queue.dequeue(); Logger::GetInstance()->Info(logName, Utils::Merge("Dequeued request:", request.ToString())); Logger::GetInstance()->Debug(logName, "Processing Request"); if (request.isInsert()) { try { this->addOrder(request.getOrder()); _ruleManager->applyRules(this, getOrderPtr(request.getOrder())); } catch (...) { std::stringstream temp1; temp1 << "Failed in matchOrders:addOrder/applyRules - " << __FILE__ << " (" << __LINE__ << ")"; std::string temp = Utils::MergeException(temp1.str(), Utils::ResurrectException()); Logger::GetInstance()->Error(logName, temp); std::cerr << temp << std::endl; std::getchar(); exit(-1); } } else { Order tempOrder = request.getOrder(); this->removeOrder(tempOrder); try { _ruleManager->applyRules(this, &tempOrder); } catch (...) { std::stringstream temp1; temp1 << "Failed in matchOrders:applyRules - " << __FILE__ << " (" << __LINE__ << ")"; std::string temp = Utils::MergeException(temp1.str(), Utils::ResurrectException()); Logger::GetInstance()->Error(logName, temp); std::cerr << temp << std::endl; std::getchar(); exit(-1); } } Logger::GetInstance()->Debug(logName, "DONE"); } if (_performanceAnalytics) _matchTime = _timer->GetCounter(); } void OrderBook::publishTrade(Trade trade) { Logger::GetInstance()->Info(logName, Utils::Merge("Publishing trade:", trade.toString())); _stock->setLastPrice(trade.getPrice()); Logger::GetInstance()->Info(logName, Utils::Merge("Last Trade Price:", Utils::DtoS(_stock->getLastPrice()))); Logger::GetInstance()->Trade(trade.toStringCSV()); //_tradesCount++; _trades.push_back(trade); Trade* tradePtr = getTradePtr(trade); Logger::GetInstance()->Debug(logName, "Notifying Traders"); this->notifyTraders(tradePtr); //this->notifyTraders(&trade); Logger::GetInstance()->Debug(logName, "DONE"); } RuleManager* OrderBook::getRuleManager() { return _ruleManager; } void OrderBook::setRuleManager(RuleManager* ruleManager) { _ruleManager = ruleManager; } std::list<Order> OrderBook::getBuyOrders() { return _buyOrders; } std::list<Order> OrderBook::getSellOrders() { return _sellOrders; } int OrderBook::getNumBuyOrders() { return _buyOrders.size(); } int OrderBook::getNumSellOrders() { return _sellOrders.size(); } void OrderBook::setLastPrice(double price) { if (price > 500 || price < 20) std::cout << "error"; _lastPrice = price; Logger::GetInstance()->Info(logName, Utils::Merge("Set last Price: $", Utils::DtoS(_lastPrice))); /*char temp[16]; sprintf_s(temp, "%.2f", price); std::string temp2(temp);*/ } PastPrice OrderBook::getLastPrice() { return PastPrice(_lastPrice, _time); } std::vector<PastPrice> OrderBook::getLastPrices() { return _prices; } std::vector<PastPrice> OrderBook::getLastPricesN(int N) { if (N > _prices.size()) throw new std::exception("Range is larger than length of past prices data"); std::vector<PastPrice> result; for (int i = (_prices.size() - 1); i < (_prices.size() - (N+1)); i--) { result.push_back(PastPrice(_prices.at(i).price, _prices.at(i).time)); } return result; } PastPrice* OrderBook::getLastPricesPArray() { /*PastPrice* pPrices = new PastPrice[_prices.size()-1]; for (int i=0; i < _prices.size(); i++) { pPrices[i].price = _prices[i].price; pPrices[i].time = _prices[i].time; } return pPrices;*/ /*if (_prices.size() > 4000) { std::vector<PastPrice> temp; for (int i=_prices.size()-4001; i < _prices.size(); i++) { temp.push_back(_prices[i]); } return &temp[0]; } else {*/ return &_prices[0]; } PastPrice* OrderBook::getLastPricesPArrayN(int N) { /*if (N > _prices.size()) throw new std::exception("Range is larger than length of past prices data"); PastPrice* pPrices = new PastPrice[N]; for (int i= (_prices.size()-1-N); i < _prices.size(); i++) { pPrices[i].price = _prices[i].price; pPrices[i].time = _prices[i].time; } return pPrices; */ return &_prices[0]; } int OrderBook::GetMarketBuyCount() { return _buyMarketOrders; } int OrderBook::GetMarketSellCount() { return _sellMarketOrders; } int OrderBook::GetLimitBuyCount() { return _buyLimitOrders; } int OrderBook::GetLimitSellCount() { return _sellLimitOrders; } void OrderBook::setTime(int time) { _time = time; } int OrderBook::getTime() { return _time; } void OrderBook::update() { std::stringstream stream; if (_performanceAnalytics) { _matchTimes.push_back(_matchTime); _traderProcTimes.push_back(_traderProcTime); _oclProcTimes.push_back(_traderManager->getProcessTime()); _tradesSize = sizeof(_trades) + sizeof(Trade)*_trades.capacity(); _ordersSize = (sizeof(_buyOrders) + sizeof(Order)*_buyOrders.size()) + (sizeof(_sellOrders) + sizeof(Order)*_sellOrders.size()); char T[512]; /*sprintf_s(T, "%d,%.2f,%d,%d,%d,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f", _time, this->getLastPrice().price, this->getBuyOrders().size(), this->getSellOrders().size(), _trades.size(), _matchTime, GetAveMatchTime(), GetMaxMatchTime(), _traderProcTime, GetAveTraderProcTime(), GetMaxTraderProcTime(), _traderManager->getProcessTime(), GetAveOclProcTime(), GetMaxOclProcTime());*/ sprintf_s(T, "%d,%.2f,%.2f,%.2f,%.2f,%d,%d,%d,%.3f,%.3f,%.3f", _time, this->getLastPrice().price, this->GetBid(), this->GetCall(), this->GetSpread(), this->getBuyOrders().size(), this->getSellOrders().size(), _trades.size(), _matchTime, _traderProcTime, _traderManager->getProcessTime()); stream << T; Logger::GetInstance()->Data(stream.str()); Logger::GetInstance()->Prices(this->getLastPrice().price); Logger::GetInstance()->BuyOrders(this->getBuyOrders().size()); Logger::GetInstance()->SellOrders(this->getSellOrders().size()); } else { char T[128]; sprintf_s(T, "%d,%.2f,%d,%d,%d", _time, this->getLastPrice().price, this->getBuyOrders().size(), this->getSellOrders().size(), _trades.size()); stream << T; Logger::GetInstance()->Data(stream.str()); } //if the price has changed store the change and time if (this->getLastPrice().price != _prices.back().price) { if (_prices.size() > 4000) { for (int i=0; i < _prices.size()-1; i++) { _prices[i] = _prices[i+1]; } _prices[4000] = PastPrice(this->getLastPrice().price, _time); } else { _prices.push_back(PastPrice(this->getLastPrice().price, _time)); } } _allPrices.push_back(this->getLastPrice().price); _spreads.push_back(this->GetSpread()); if (_time > 0) _pastReturns.push_back(_allPrices.back() - _allPrices[_allPrices.size()-2]); _time++; Logger::GetInstance()->SetTime(_time, true); _traderManager->notify(_time); } Stock* OrderBook::getStock() { return _stock; } void OrderBook::enablePerfAnalytics() { if (!_performanceAnalytics) { _performanceAnalytics = true; _timer = new WallTimer(); } } void OrderBook::disablePerfAnalytics() { if (_performanceAnalytics) { _performanceAnalytics = false; if (_timer != NULL) delete _timer; _timer = NULL; } } bool OrderBook::BuyContainsMarket() { return this->GetBuyMarketCount() > 0; } bool OrderBook::BuyContainsLimit() { return this->GetBuyLimitCount() > 0; } bool OrderBook::SellContainsMarket() { return this->GetSellMarketCount() > 0; } bool OrderBook::SellContainsLimit() { return this->GetSellLimitCount() > 0; } int OrderBook::GetBuyMarketCount() { return _buyMarketOrders; } int OrderBook::GetBuyLimitCount() { return _buyLimitOrders; } int OrderBook::GetSellMarketCount() { return _sellMarketOrders; } int OrderBook::GetSellLimitCount() { return _sellLimitOrders; } int OrderBook::getBuyVolume() { int count = 0; for (auto it = _buyOrders.begin(); it != _buyOrders.end(); it++) { count += it->getSize(); } return count; //return _buyVolume; } int OrderBook::getSellVolume() { int count = 0; for (auto it = _sellOrders.begin(); it != _sellOrders.end(); it++) { count += it->getSize(); } return count; //return _sellVolume; } TraderManager* OrderBook::GetTraderManager() { return _traderManager; } double OrderBook::GetAveMatchTime() { return Utils::Mean(_matchTimes); } double OrderBook::GetMaxMatchTime() { return Utils::Max(_matchTimes); } double OrderBook::GetAveTraderProcTime() { return Utils::Mean(_traderProcTimes); } double OrderBook::GetMaxTraderProcTime() { return Utils::Max(_traderProcTimes); } double OrderBook::GetAveOclProcTime() { return Utils::Mean(_oclProcTimes); } double OrderBook::GetMaxOclProcTime() { return Utils::Max(_oclProcTimes); } size_t OrderBook::GetBookSize() { size_t result = 0; result += sizeof(OrderBook); result += _traderManager->SizeOf(); result += sizeof(Trade)*_trades.capacity(); result += sizeof(Order)*(_buyOrders.size() + _sellOrders.size()); result += _prices.size()*sizeof(PastPrice) + sizeof(std::vector<double>); result += _allPrices.size()*sizeof(double) + sizeof(std::vector<double>); result += _pastReturns.size()*sizeof(double) + sizeof(std::vector<double>); return result; } double OrderBook::GetBid() { double bid = -DBL_MAX; bool set = false; for (auto it = _buyOrders.begin(); it != _buyOrders.end(); it++) { if (it->isLimit()) { bid = max(bid, it->getPrice()); set = true; } } if (!set) { bid = this->getLastPrice().price; } return bid; } double OrderBook::GetCall() { double call = DBL_MAX; bool set = false; for (auto it = _sellOrders.begin(); it != _sellOrders.end(); it++) { if (it->isLimit()) { call = min(call, it->getPrice()); set = true; } } if (!set) { call = this->getLastPrice().price; } return call; } double OrderBook::GetSpread() { return this->GetCall() - this->GetBid(); } double OrderBook::GetMinPrice() { return Utils::Min(_allPrices); } double OrderBook::GetAvePrice() { return Utils::Mean(_allPrices); } double OrderBook::GetMaxPrice() { return Utils::Max(_allPrices); } double OrderBook::GetTradesPerSecond() { return _trades.size()/((double)_time/1000); } double OrderBook::GetMinReturns1ms() { return Utils::Min(_pastReturns); } double OrderBook::GetAveReturns1ms() { return Utils::Mean(_pastReturns); } double OrderBook::GetMaxReturns1ms() { return Utils::Max(_pastReturns); } double OrderBook::GetMinReturns1s() { std::vector<double> tempReturns; for (int i=1000; i < _allPrices.size(); i++) tempReturns.push_back(_allPrices[i]-_allPrices[i-1000]); return Utils::Min(tempReturns); } double OrderBook::GetAveReturns1s() { std::vector<double> tempReturns; for (int i=1000; i < _allPrices.size(); i++) tempReturns.push_back(_allPrices[i]-_allPrices[i-1000]); return Utils::Mean(tempReturns); } double OrderBook::GetMaxReturns1s() { std::vector<double> tempReturns; for (int i=1000; i < _allPrices.size(); i++) tempReturns.push_back(_allPrices[i]-_allPrices[i-1000]); return Utils::Max(tempReturns); } double OrderBook::GetReturn1m() { return _allPrices[59999] - _openPrice; } double OrderBook::GetMinRTProfit() { return _traderManager->GetMinRTProfit(); } double OrderBook::GetAveRTProfit() { return _traderManager->GetAveRTProfit(); } double OrderBook::GetMaxRTProfit() { return _traderManager->GetMaxRTProfit(); } double OrderBook::GetMinLRTProfit() { return _traderManager->GetMinLRTProfit(); } double OrderBook::GetAveLRTProfit() { return _traderManager->GetAveLRTProfit(); } double OrderBook::GetMaxLRTProfit() { return _traderManager->GetMaxLRTProfit(); } double OrderBook::GetMinPTProfit() { return _traderManager->GetMinPTProfit(); } double OrderBook::GetAvePTProfit() { return _traderManager->GetAvePTProfit(); } double OrderBook::GetMaxPTProfit() { return _traderManager->GetMaxPTProfit(); } double OrderBook::GetMinMTProfit() { return _traderManager->GetMinMTProfit(); } double OrderBook::GetAveMTProfit() { return _traderManager->GetAveMTProfit(); } double OrderBook::GetMaxMTProfit() { return _traderManager->GetMaxMTProfit(); } double OrderBook::GetAveProfit() { return _traderManager->GetAveProfit(); } double OrderBook::GetVolatilityPerMin() { std::vector<double> temp; temp.resize(_allPrices.size()); tbb::parallel_for(tbb::blocked_range<int>(1, _allPrices.size()-1), TBBlog(_allPrices, temp)); double vol = Utils::Stdev(temp); vol *= std::sqrt(60000.0f); return vol; } double OrderBook::GetAveSpread() { return Utils::Mean(_spreads); } int OrderBook::GetMinTraderProcessT() { return _traderManager->GetMinTraderProcessT(); } int OrderBook::GetAveTraderProcessT() { return _traderManager->GetAveTraderProcessT(); } int OrderBook::GetMaxTraderProcessT() { return _traderManager->GetMaxTraderProcessT(); }
Java
UTF-8
2,865
2.3125
2
[]
no_license
package org.cargo.controller; import org.apache.log4j.Logger; import org.cargo.bean.Page; import org.cargo.bean.transportation.Transportation; import org.cargo.exception.DaoException; import org.cargo.properties.MappingProperties; import org.cargo.service.TransportationService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GetUserTransportationsPageCommand implements Command{ private static final Logger LOGGER = Logger.getLogger(GetUserTransportationsPageCommand.class); private static String userTransportationsPage; private static String errorPage; private static TransportationService transpService = TransportationService.getInstance(); public GetUserTransportationsPageCommand() { LOGGER.debug("Initializing GetUserTransportationsPageCommand"); MappingProperties properties = MappingProperties.getInstance(); userTransportationsPage = properties.getProperty("userTransportationsPage"); errorPage = properties.getProperty("errorPage"); } @Override public String execute(HttpServletRequest request, HttpServletResponse response) { LOGGER.debug("Executing send user transportations list page command"); // Map<String, String> pageParams = validatePageRequest(request.getParameter("p"), // request.getParameter("s"), request.getParameter("sortDirection"), // request.getParameter("sortBy")); // // Integer pageNo = Integer.parseInt(pageParams.getOrDefault("p", "1")); // Integer pageSize = Integer.parseInt(pageParams.getOrDefault("s", "10")); // String sortDirection = pageParams.getOrDefault("sortDirection", "ASC"); // String sortBy = pageParams.getOrDefault("sortBy", "id"); Integer pageNo = Integer.parseInt(request.getParameter("p")); Integer pageSize = Integer.parseInt(request.getParameter("s")); String sortDirection = request.getParameter("sortDirection"); String sortBy = request.getParameter("sortBy"); try { Page<Transportation> page = transpService.findTransportationsByUser( request.getSession().getAttribute("user"), pageNo, pageSize, sortDirection, sortBy); request.getSession().setAttribute("sortDirection", sortDirection); request.getSession().setAttribute("sortBy", sortBy); request.getSession().setAttribute("currentPage", pageNo); request.getSession().setAttribute("userOrders", page); request.getSession().setAttribute("reverseSortDirection", sortDirection.equals("asc") ? "desc" : "asc"); return userTransportationsPage; } catch (DaoException e) { request.getSession().setAttribute("errorMessage", e.getMessage()); return errorPage; } } }
Java
UTF-8
2,719
2.484375
2
[]
no_license
package com.glenwood.kernai.ui.abstraction; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import com.glenwood.customExceptions.EntityInstantiationError; import com.glenwood.kernai.data.abstractions.BaseEntity; import com.glenwood.kernai.data.abstractions.IEntityRepository; public class BaseEntityMasterDetailListEditPresenter<T extends BaseEntity, P extends BaseEntity> implements IEntityMasterDetailListEditPresenter<T, P> { protected IEntityRepository<T> repository; protected IEntityMasterDetailListEditView<T, P> view; protected IMasterDetailViewModel<T, P> model; private Class<T> clazz; private String entityTypeName; public BaseEntityMasterDetailListEditPresenter(IEntityMasterDetailListEditView<T, P> view, IMasterDetailViewModel<T, P> model, Class entityClass, String entityTypeName) { super(); this.view = view; this.model = model; this.clazz = entityClass; this.entityTypeName = entityTypeName; } @Override public void loadModels(P parent) { this.model.setParent(parent); } @Override public void addModel() { Constructor[] ctors = this.clazz.getDeclaredConstructors(); Constructor ctor = null; for (int i = 0; i < ctors.length; i++) { ctor = ctors[i]; if (ctor.getGenericParameterTypes().length > 0) break; } try { this.model.setCurrentItem((T)ctor.newInstance(this.model.getParent())); this.model.setDirty(true); this.model.getCurrentItem().addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { modelChanged(); } }); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); throw new EntityInstantiationError(); } this.view.afterAdd(); } @Override public void deleteModel() { this.model.getItems().remove(this.model.getCurrentItem()); this.repository.delete(model.getCurrentItem()); this.model.setCurrentItem(null); this.model.setDirty(false); this.view.refreshView(); } @Override public void saveModel() { this.repository.save(this.model.getCurrentItem()); } @Override public void loadModel(T entity) { model.setCurrentItem(entity); model.setDirty(false); this.model.getCurrentItem().addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { modelChanged(); } }); this.view.refreshView(); this.view.afterSelection(); } @Override public void modelChanged() { this.model.setDirty(true); } }
JavaScript
UTF-8
915
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "CC0-1.0" ]
permissive
const path = require('path') const fs = require('fs') const electron = require('electron') const userDataPath = (electron.app || electron.remote.app) .getPath('userData') function getAllTemplatesFiles() { if (!fs.existsSync(`${userDataPath}/templates`)) createTemplateDirectory() return fs .readdirSync(`${userDataPath}/templates`) .filter(fileName => /\.(json)/.test(fileName)) } function createTemplateDirectory() { fs.mkdirSync(`${userDataPath}/templates`) } function getLoadTemplateObj() { const templates = getAllTemplatesFiles() console.log(templates) const obj = templates.map((filePath) => { let content = require(`${userDataPath}/templates/${filePath}`) content.mockup.path = `${userDataPath}/templates/${content.mockup.path}` return content }) return { 'yourMockups': obj } } module.exports = { getAllTemplatesFiles, userDataPath, getLoadTemplateObj, }
Swift
UTF-8
2,522
2.8125
3
[]
no_license
import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var toDos: [String] = [] @IBOutlet weak var uiTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() uiTableView.delegate = self uiTableView.dataSource = self uiTableView.rowHeight = 50 } // func numberOfSections(in tableView: UITableView) -> Int { // return 1 // } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return toDos.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoCell", for: indexPath) as! TableViewCell cell.toDoLable?.text = toDos[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! TableViewCell if cell.isChecked == false { cell.checkMarkImage.image = UIImage(systemName: "checkmark.circle") cell.isChecked = true } else { cell.checkMarkImage.image = nil cell.isChecked = false } } @IBAction func addButton(_ sender: UIButton) { let addToDoAlert = UIAlertController(title: "Add To Do", message: "Add a new todo!", preferredStyle: .alert) addToDoAlert.addTextField() let addToDoAction = UIAlertAction(title: "Add", style: .default) { (action) in let newTodo = addToDoAlert.textFields![0] if newTodo.text != "" { self.toDos.append(newTodo.text!) self.uiTableView.reloadData() } } let cancelAction = UIAlertAction(title: "Cancel", style: .default) addToDoAlert.addAction(addToDoAction) addToDoAlert.addAction(cancelAction) present(addToDoAlert, animated: true, completion: nil) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { toDos.remove(at: indexPath.row) uiTableView.reloadData() } } }
JavaScript
UTF-8
325
3.59375
4
[]
no_license
// 哈希函数 function hashFunc(str, max) { let hashCode = 0 for (let i = 0; i < str.length; i++) { hashCode = 37 * hashCode + str.charCodeAt(i) } return hashCode % max } console.log(hashFunc('abc', 7)) console.log(hashFunc('mma', 7)) console.log(hashFunc('ddd', 7)) console.log(hashFunc('eee', 7))
Markdown
UTF-8
3,617
2.953125
3
[]
no_license
# Midterm Presentation By Pelle Jacobs, June 26th, 2017 Promoted by prof. Jochen De Weerdt and supervised by Vytautas Karalevicius --- # Small revision of focus point - instead of focusing on decentralized data storage with blockchain systems - more interesting 'how concept of replacing a previously thought indispensable, central entity with technology, can be applied to data storage, resulting in distributed data storage' This allows to broaden the focus from only 'blockchain' applications, to also include 'vanilla' public key cryptography which in itself is already a strong force in replacing a middleman. Although maybe not a huge difference, it gives me a the opportunity to have a different mental approach to the subject --- # Table of contents 1. Prior research: defining the major concepts 2. Aim of the research: how can the idea to replace the middle man by technology be applied when dealing with distributed databases? 3. Actual proposals on how to actually merge the idea of distributed data storage --- ## Prior research: defining the major concepts 3 main concepts to discuss: - public key encryption - blockchain: - the definition of a blockchain (as defined by Antonopoulos), the workings of a minimal blockchain, the characteristics of a blockchain (eg. consensus and availability) - properties of a blockchain: the differences between blockchain: consensus mechanisms (POW and POS), access to data (private and public), power to accept transactions (permissioned and unpermissioned) - examples of blockchains - distributed databases: + difference between the terms distributed, decentralized and centralized and advantages and trade offs of using a distributed databases compared to a fully centralised database or decentralized database + examples of distributed networks and databases and how they achieve consensus (git, torrent, non-persistent p2p networks) --- ## Aim of the research: Collaborative databases can face several specific challenges such as consensus issues and consistency / integrity issues. The characteristics of a blockchain could solve these issues. Applying the main idea to collaborative databases: there are two approaches - can this idea be applied to actually storing the data: what would this mean? What would the consequences / resulting situation be? what would the advantages be? what are some possible applications if this would be possible? - can this idea be applied to enable interaction between databases, either to achieve consensus between versions of the same database, or in the interactions between different databases --- ## Proposals: store data onto the blockchain Storing data onto the blockchain: - Not feasible: storing data directly onto a blockchain, eg. onto the Bitcoin blockchain: performances issues mostly because of limited space - Storing actual data onto Ethereum: as Ethereum allows anything, storing data is also possible - Using an alt chain that manages distributed data storage eg. Siacoin Coordinating consensus between databases: - Timestamping a collaborative database onto the bitcoin blockchain - Applied example: putting a will onto a blockchain: starting from a simple document that is signed with a private key all the way to an Ethereum program that actually publishes the document once deceased. --- ## Sources - Published literature: Antonopoulos - Published articles: Baran on Distributed Networks, Bitfury group on public and private blockchains and proof of work vs proof of stake - White papers: Bitcoin, Ethereum, Siacoin, Ripple, Interledger, Dash, InstantTX - FAQs and Wikis: Ethereum wiki, Ripple Dev Center,
Java
UTF-8
4,599
3.96875
4
[]
no_license
package array; /** * @author :DengSiYuan * @date :2019/10/15 20:53 * @desc : 8.字符串转换整数 * 【题目】 * 请你来实现一个 atoi 函数,使其能将字符串转换成整数。首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 * 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空 * 字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。 * 该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。 * * 【注意】 * 假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。 * 在任何情况下,若函数不能进行有效的转换时,请返回 0。 * 【说明】 * 假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231,231 − 1]。 * 如果数值超过这个范围,请返回  INT_MAX (231 − 1) 或 INT_MIN (−231) 。 * 【示例】 * 示例 1: * 输入: "42" * 输出: 42 * 示例 2: * 输入: " -42" * 输出: -42 * 解释: 第一个非空白字符为 '-', 它是一个负号。我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。 * 示例 3: * 输入: "4193 with words" * 输出: 4193 * 解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。 * 示例 4: * 输入: "words and 987" * 输出: 0 * 解释: 第一个非空字符是 'w', 但它不是数字或正、负号。因此无法执行有效的转换。 * 示例 5: * 输入: "-91283472332" * 输出: -2147483648 * 解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 因此返回 INT_MIN (−231) 。 */ public class StringToIntegerAtoi { /** * 【想法】 * 1、判断字符串是否为空/长度是否为0 * 2、去除头部空白字符,并对索引进行++维护 * 3、判断第一个非空字符是否是要求内的字符,若遇到'+'、'-',对index进行++维护,若为'-',则进行负数标记 * 4、从index的位置开始遍历字符数组,不断进行结果*10+取余的操作,若数值大于最大或最小,直接返回最大或最小 * @param str * @return * @throws RuntimeException */ public int myAtoi(String str) throws RuntimeException { if (str == null || str.length() == 0){ return 0; } char[] a = new char[]{'-','+','0','1','2','3','4','5','6','7','8','9'}; char[] chars = str.toCharArray(); long result = 0; boolean status = false; boolean isNegative = false; int length = chars.length; int index = 0; for (char c : chars) { if (c == ' '){ index++; }else { break; } } if (index >= length){ return 0; } for (char c : a) { if (chars[index] == c){ if (chars[index] == '-'){ isNegative = true; index++; }else if (chars[index] == '+'){ index++; } status = true; break; } } if (!status){ return 0; }else { while (index < length && chars[index] >= '0' && chars[index] <= '9'){ result = result * 10 + chars[index] - '0'; if (isNegative && -result <= Integer.MIN_VALUE){ return Integer.MIN_VALUE; } if (!isNegative && result >= Integer.MAX_VALUE){ return Integer.MAX_VALUE; } index++; } } if (isNegative){ return (int) -result; }else { return (int) result; } } public static void main(String[] args) { StringToIntegerAtoi atoi = new StringToIntegerAtoi(); String str = "+1"; int result = atoi.myAtoi(str); System.out.println(result); } }
Java
UTF-8
2,368
2.515625
3
[]
no_license
package com.lvdi.ruitianxia_cus.util; import java.io.File; import java.io.IOException; import com.ab.util.AbLogUtil; import android.graphics.Bitmap; import android.graphics.Matrix; import android.media.ExifInterface; import android.text.TextUtils; /** * * 类的详细描述: * * @author XuBiao * @version 1.0.1 * @time 2015年12月5日 下午3:15:01 */ public class BitmapRotateUtil { /** * TAG */ private static final String TAG = BitmapRotateUtil.class.getSimpleName(); // 定义静态的角度 public interface Inter_angle { public String ANGLE_ZERO = "0"; public String ANGLE_CIRCLE = "360"; public String ANGLE_NULL = "null"; } /** * 处理Bitmap旋转 * * @param bitmap * Bitmap对象 * @param angle * 角度 */ public static Bitmap matrixBitmapByAngle(Bitmap bitmap, String angle) { if (bitmap == null) { return null; } if (!TextUtils.isEmpty(angle) && !angle.equals(Inter_angle.ANGLE_ZERO) && !angle.equals(Inter_angle.ANGLE_CIRCLE) && !angle.equals(Inter_angle.ANGLE_NULL)) { // Matrix对Bitmap进行旋转处理 Matrix matrix = new Matrix(); int width = bitmap.getWidth(); int height = bitmap.getHeight(); matrix.setRotate(Float.parseFloat(angle)); bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); } return bitmap; } /** * 上传完成后 删除本地图片 * * @param path * 图片的本地路径 */ public void deleteBitmap(String path) { if (TextUtils.isEmpty(path)) { return; } File file = new File(path); if (file.exists()) { file.delete(); } } /** * 根据图片的本地路径获取它的旋转角度 * * @param path * 本地路径 * @return */ public static int readPictureDegree(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } }
C
UTF-8
2,287
2.828125
3
[]
no_license
#ifndef _MAN_COM_TRANSPORT_H_ #define _MAN_COM_TRANSPORT_H_ // START WINDOWS VERSION #include <windows.h> typedef UINT16 uint16_t; // END WINDOWS VERSION typedef enum { MAN_COM_STREAM_TRANSPORT_TCP = 0, MAN_COM_STREAM_TRANSPORT_MIPIO = 1, MAN_COM_STREAM_TRANSPORT_PIPE = 2, } ManComTransport; typedef struct { int placeholder; } ManComTransportDefinition; typedef struct { ManComTransport type; union { struct { int addressFamily; uint16_t port; } tcp; } data; } ManComTransportConfig; typedef struct _ManComTransportConfigNode ManComTransportConfigNode; struct _ManComTransportConfigNode { ManComTransportConfigNode* next; ManComTransportConfig config; }; /* TCP TRANSPORT A Transport needs to define a function to parse configuration and a structure to hold that configuration at runtime. Channel Definition Address Family AF_INET or AF_INET6 or (Some other C define) IP Address 0.0.0.0? 127.0.0.1? Port The transport configuration parse function should operate on something like a json or xml data structure (think about ASON too). Example Configuration: config.ljson (lenient json) ------------------------------------------- // No need for global '{' '}' // Map Keys do not need a ':' seperator Channels [ { ChannelName Http Transports [ Tcp AF_INET 0.0.0.0 80 ] ------------------------------------------- config.xml ------------------------------------------- <Channels> <Channel Name="Http"> <Transport Type="Tcp"> <AddressFamily>AF_INET</AddressFamily> <Port>80</Port> </Transport> </Channel> </Channels> ------------------------------------------- transports.config ------------------------------------------- Transport Tcp Type Stream ChannelConfig uint16 Port optional string Address optional string AddressFamily Transport Mipio Type ? ChannelConfig ?? ------------------------------------------- channels.config ------------------------------------------- Channel Http Transport Tcp AddressFamily=AF_INET Port=80 ------------------------------------------- */ #endif
Markdown
UTF-8
1,502
2.890625
3
[ "MIT" ]
permissive
# Frogger Arcade Game ## Table of Contents * [Install](#install) * [Instructions](#instructions) * [Contributing](#contributing) * [License](#license) * [Improvements](#improvements) ## Install ``` Ensure you have moved to a location in your directory where you want to copy the project via, "cd": $ Git Clone https://github.com/huschkaa/arcade-game ``` ## Game Instructions This game is a play off the classic frogger game with a human player and pesky cockroaches as your enemy! ###### Game Objective Move your player from the safe zone (grass) through enemy territory without colliding with any cockroaches. ###### How to Win If you successfully make it across to the water you will score a point and win that round against the cockroaches! If you fail to make it across you will receive a cockroach collision. ## Contributing This was a project for my Udacity Front End Development project. So a big shout out to them for helping in the development of this game. I highly recommend the program and if you are interested for more details, check out [Udacity](https://www.udacity.com/course/front-end-web-developer-nanodegree--nd001). ## License Memory Game is Copyright © 2017 Andrew Huschka. It is free software, and may be redistributed under the terms specified in the [License](License.txt) file. ## Improvements If you have any recommendations on improvements please send them through a git fork and I will review the changes. Based off the change I will let you know if it has been merged.
Java
UTF-8
302
2.40625
2
[]
no_license
package DesignPattern.SingletonPrototype; /*����ʽ������*/ public class JackSingleton { private static final JackSingleton jackSingleton = new JackSingleton(); private JackSingleton() { } public synchronized static JackSingleton getInstance() { return jackSingleton; } }
Python
UTF-8
8,301
3.1875
3
[]
no_license
import numpy as np from matplotlib import pyplot as plt import math class BlockingSystem(): def __init__(self, n, serviceTimes): self.n = n self.availUnits = [True] * n self.queueTime = [0] * n self.rejectedCustomers = 0 self.serviceTimes = serviceTimes self.customerCount = 0 def updateQueues(self, time): for i in range(self.n): if not (self.availUnits[i]): if time > self.queueTime[i]: self.availUnits[i] = True def customerArrival(self, time): self.updateQueues(time) foundQueue = False qCount = 0 while qCount < self.n and not (foundQueue): if self.availUnits[qCount]: self.availUnits[qCount] = False self.queueTime[qCount] = time + self.serviceTimes[self.customerCount] foundQueue = True qCount += 1 if not (foundQueue): self.rejectedCustomers += 1 self.customerCount += 1 return foundQueue def getNrRejected(self): return self.rejectedCustomers def print_statistics(mean, lower, upper): for i in range(len(mean)): print('{0:.0f} & {1:.4f} & {2:.4f} & {3:.4f}'.format(i, lower[i] / 100, mean[i] / 100, upper[i] / 100)) if __name__ == '__main__': simNR = 10000 nrQueues = 10 nrTrials = 10 ## exponential # Mean service time = 8 => beta = 8 in exponential # mean arrival time = 1 => lambda = 1 in poisson means = [] upperConf = [] lowerConf = [] k = 1 while k <= nrQueues: nrBlocked = [] for t in range(nrTrials): current_time = 0 arrivalProcess = np.random.exponential(1, simNR) serviceTimes = np.random.exponential(8, simNR) myBS = BlockingSystem(k, serviceTimes) for i in range(simNR): current_time += arrivalProcess[i] myBS.customerArrival(current_time) nrBlocked.append(myBS.getNrRejected()) meanBlocked = np.mean(nrBlocked) varBlocked = np.var(nrBlocked) means.append(meanBlocked) upperConf.append(meanBlocked + np.sqrt(varBlocked) / np.sqrt(nrTrials) * 1.96) lowerConf.append(meanBlocked - np.sqrt(varBlocked) / np.sqrt(nrTrials) * 1.96) k += 1 means = np.asarray(means) upperConf = np.asarray(upperConf) lowerConf = np.asarray(lowerConf) t = np.linspace(1, nrQueues, nrQueues) fig, ax = plt.subplots(1, 1) ax.plot(t, means / simNR * 100) ax.plot(t, upperConf / simNR * 100, '--', c='r') ax.plot(t, lowerConf / simNR * 100, '--', c='r') plt.show() print('Exponential-Poisson') print_statistics(means, lowerConf, upperConf) ##calculating theoretical values arriv_int = 1 service_time = 8 A = arriv_int * service_time n = 10 denominator = 0 for i in range(n + 1): denominator += A ** i / (math.factorial(i)) print(denominator) B = (A ** n / math.factorial(n)) / denominator print('B: ' + str(B)) ### erlang ##choosing k=1 and theta=1 to get a mean of 1 # means = [] # upperConf = [] # lowerConf = [] # k=1 # while k<=nrQueues: # nrBlocked = [] # for t in range(nrTrials): # current_time = 0 # arrivalProcess = np.random.gamma(1,1,simNR) # serviceTimes = np.random.exponential(1,simNR) # myBS = BlockingSystem(k,serviceTimes) # for i in range(simNR): # current_time += arrivalProcess[i] # myBS.customerArrival(current_time) # nrBlocked.append(myBS.getNrRejected()) # meanBlocked = np.mean(nrBlocked) # varBlocked = np.var(nrBlocked) # means.append(meanBlocked) # upperConf.append(meanBlocked+np.sqrt(varBlocked)/np.sqrt(nrTrials)*1.96) # lowerConf.append(meanBlocked-np.sqrt(varBlocked)/np.sqrt(nrTrials)*1.96) # k+=1 # means = np.asarray(means) # upperConf = np.asarray(upperConf) # lowerConf = np.asarray(lowerConf) # t = np.linspace(1,nrQueues,nrQueues) ##fig,ax = plt.subplots(1,1) ##ax.plot(t,means/simNR*100) ##ax.plot(t,upperConf/simNR*100,'--',c='r') ##ax.plot(t,lowerConf/simNR*100,'--',c='r') ##plt.show() ## hyper exponential # choosing k=1 and theta=1 to get a mean of 1 # p = [0.8,0.2] # lambd = [0.8333,5] # means = [] # upperConf = [] # lowerConf = [] # k=1 # while k<=nrQueues: # nrBlocked = [] # for t in range(nrTrials): # current_time = 0 # arrivalProcess1 = np.random.exponential(lambd[0],int(p[0]*simNR)) # arrivalProcess2 = np.random.exponential(lambd[1],int(p[1]*simNR)) # arrivalProcess = np.append(arrivalProcess1,arrivalProcess2) # np.random.shuffle(arrivalProcess) # serviceTimes = np.random.exponential(1,simNR) # myBS = BlockingSystem(k,serviceTimes) # for i in range(simNR): # current_time += arrivalProcess[i] # myBS.customerArrival(current_time) # nrBlocked.append(myBS.getNrRejected()) # meanBlocked = np.mean(nrBlocked) # varBlocked = np.var(nrBlocked) # means.append(meanBlocked) # upperConf.append(meanBlocked+np.sqrt(varBlocked)/np.sqrt(nrTrials)*1.96) # lowerConf.append(meanBlocked-np.sqrt(varBlocked)/np.sqrt(nrTrials)*1.96) # k+=1 # means = np.asarray(means) # upperConf = np.asarray(upperConf) # lowerConf = np.asarray(lowerConf) # t = np.linspace(1,nrQueues,nrQueues) # fig,ax = plt.subplots(1,1) # ax.plot(t,means/simNR*100) # ax.plot(t,upperConf/simNR*100,'--',c='r') # ax.plot(t,lowerConf/simNR*100,'--',c='r') # plt.show() ## constant service time # serviceTime = 20 # means = [] # upperConf = [] # lowerConf = [] # k=1 # while k<=nrQueues: # nrBlocked = [] # for t in range(nrTrials): # current_time = 0 # arrivalProcess = np.random.poisson(1,simNR) # serviceTimes = np.ones((simNR,1))*serviceTime # myBS = BlockingSystem(k,serviceTimes) # for i in range(simNR): # current_time += arrivalProcess[i] # myBS.customerArrival(current_time) # nrBlocked.append(myBS.getNrRejected()) # meanBlocked = np.mean(nrBlocked) # varBlocked = np.var(nrBlocked) # means.append(meanBlocked) # upperConf.append(meanBlocked+np.sqrt(varBlocked)/np.sqrt(nrTrials)*1.96) # lowerConf.append(meanBlocked-np.sqrt(varBlocked)/np.sqrt(nrTrials)*1.96) # k+=1 # means = np.asarray(means) # upperConf = np.asarray(upperConf) # lowerConf = np.asarray(lowerConf) # t = np.linspace(1,nrQueues,nrQueues) # fig,ax = plt.subplots(1,1) # ax.plot(t,means/simNR*100) # ax.plot(t,upperConf/simNR*100,'--',c='r') # ax.plot(t,lowerConf/simNR*100,'--',c='r') # plt.show() ## Pareto service time # serviceTime = 20 # means = [] # upperConf = [] # lowerConf = [] # k=1 # while k<=nrQueues: # nrBlocked = [] # for t in range(nrTrials): # current_time = 0 # arrivalProcess = np.random.poisson(1,simNR) # serviceTimes = np.random.pareto(2.05,simNR) # myBS = BlockingSystem(k,serviceTimes) # for i in range(simNR): # current_time += arrivalProcess[i] # myBS.customerArrival(current_time) # nrBlocked.append(myBS.getNrRejected()) # meanBlocked = np.mean(nrBlocked) # varBlocked = np.var(nrBlocked) # means.append(meanBlocked) # upperConf.append(meanBlocked+np.sqrt(varBlocked)/np.sqrt(nrTrials)*1.96) # lowerConf.append(meanBlocked-np.sqrt(varBlocked)/np.sqrt(nrTrials)*1.96) # k+=1 # means = np.asarray(means) # upperConf = np.asarray(upperConf) # lowerConf = np.asarray(lowerConf) # t = np.linspace(1,nrQueues,nrQueues) # fig,ax = plt.subplots(1,1) # ax.plot(t,means/simNR*100) # ax.plot(t,upperConf/simNR*100,'--',c='r') # ax.plot(t,lowerConf/simNR*100,'--',c='r') # plt.show()
Markdown
UTF-8
1,011
3.609375
4
[]
no_license
--- author: djaigo title: 单调栈 categories: - data_structure date: 2023-07-28 15:22:58 tags: --- 单调栈(monotone-stack)是指栈内元素(栈底到栈顶)都是(严格)单调递增或者单调递减的。 如果有新的元素入栈,栈调整过程中 *会将所有破坏单调性的栈顶元素出栈,并且出栈的元素不会再次入栈* 。由于每个元素只有一次入栈和出栈的操作,所以 *单调栈的维护时间复杂度是O(n)* 。 单调栈性质: 1\. 单调栈里的元素具有单调性。 2\. 递增(减)栈中可以找到元素左右两侧比自身小(大)的第一个元素。 我们主要使用第二条性质,该性质主要体现在栈调整过程中,下面以递增栈为例(假设所有元素都是唯一),当新元素入栈。 + 对于出栈元素来说:找到右侧第一个比自身小的元素。 + 对于新元素来说:等待所有破坏递增顺序的元素出栈后,找到左侧第一个比自身小的元素。
Java
UTF-8
4,558
2.859375
3
[]
no_license
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static Reader sc = new Reader(); static int mod = (int)(1e9+7),MAX=(int)(2e6+10); public static void main(String[] args) throws IOException{ int n = sc.nextInt(); int m = sc.nextInt(); int q = sc.nextInt(); long[][] dp = new long[n+1][n+1]; for(int i=1;i<=n;++i){ Arrays.fill(dp[i],Long.MAX_VALUE/10); dp[i][i] = 0; } for(int i=0;i<m;++i){ int u = sc.nextInt(); int v = sc.nextInt(); long w = Math.min(dp[u][v] , sc.nextLong()); dp[u][v] = dp[v][u] = w; } for(int k=1;k<=n;++k){ for(int i=1;i<=n;++i){ for(int j=1;j<=n;++j) dp[i][j] = Math.min(dp[i][j],dp[i][k] + dp[k][j]); } } while (q-->0){ int u = sc.nextInt(); int v = sc.nextInt(); if(dp[u][v] == Long.MAX_VALUE/10) out.println(-1+" "); else out.println(dp[u][v]+" "); } out.close(); } }
Java
UTF-8
3,165
3.15625
3
[]
no_license
package model; 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 bo.Aluno; import jdbc.ConnectionFactory; public class AlunoDAO { public void create(Aluno aluno) { //Insert sql no banco Connection banco = ConnectionFactory.getConnection(); PreparedStatement stmt = null; //Tentar inserção no banco try { String sql = "insert into aluno(matricula,nome,cidade) values (?,?,?)"; stmt = banco.prepareStatement(sql); //popula a query com os parametros stmt.setString(1,aluno.getMatricula()); stmt.setString(2, aluno.getNome()); stmt.setString(3, aluno.getCidade()); stmt.executeUpdate(); System.out.println("Aluno incluido com sucesso!"); } catch (SQLException e) { System.out.println("Erro ao incluir aluno!"); } finally { ConnectionFactory.closeConnection(banco, stmt); } } public List<Aluno> read(){ List<Aluno> listaAlunos = new ArrayList<Aluno>(); Connection banco = ConnectionFactory.getConnection(); PreparedStatement stmt = null; ResultSet rs = null; String sql = "select matricula,nome,cidade from aluno"; try { stmt = banco.prepareStatement(sql); rs = stmt.executeQuery(); //Enquanto houver registro, fica no loop while (rs.next()) { Aluno aluno = new Aluno(); aluno.setMatricula(rs.getString("matricula")); aluno.setNome(rs.getString("nome")); aluno.setCidade(rs.getString("cidade")); listaAlunos.add(aluno); } } catch(SQLException e) { System.out.println("Erro ao tentar ler aluno!"); } finally { ConnectionFactory.closeConnection(banco,stmt); } return listaAlunos; } public void update(Aluno aluno) { Connection banco = ConnectionFactory.getConnection(); PreparedStatement stmt = null; try { String sql = "update aluno set nome = ?, cidade = ? where matricula = ?"; stmt = banco.prepareStatement(sql); stmt.setString(1, aluno.getNome()); stmt.setString(2, aluno.getCidade()); stmt.setString(3, aluno.getMatricula()); stmt.executeUpdate(); System.out.println("Dados do aluno alterado com sucesso!"); } catch(SQLException e) { System.out.println("Erro ao tentar alterar dados do aluno!"); } finally { ConnectionFactory.closeConnection(banco, stmt); } } public void delete(Aluno aluno) { Connection banco = ConnectionFactory.getConnection(); PreparedStatement stmt = null; try { String sql = "delete from aluno where matricula = ?"; stmt = banco.prepareStatement(sql); stmt.setString(1, aluno.getMatricula()); stmt.executeUpdate(); System.out.println("Aluno excluido com sucesso!"); } catch(SQLException e) { System.out.println("Erro ao tentar excluir o aluno!"); } finally { ConnectionFactory.closeConnection(banco, stmt); } } }
Java
UTF-8
431
3
3
[ "MIT" ]
permissive
import java.io.*; //用字节流复制D盘aaa到E盘xxx public class APP02 { public static void main(String[] args) throws IOException { FileInputStream fir=new FileInputStream("D:\\aaa.txt"); FileOutputStream fow=new FileOutputStream("E:\\xxx.txt"); int a=0; while ((a=fir.read())!=-1){ fow.write(a);//一边读一边写 } fir.close(); fow.close(); } }
JavaScript
UTF-8
876
3.5625
4
[ "Apache-2.0" ]
permissive
const array = ['y', 'z', 'e', 'p', 't', 'g', 'm', 'k'] /** * Mets en forme les nombres: 75000 > 75k * @param { number } num * @returns { string } */ const form = function (num) { if (typeof num !== 'number') throw TypeError('Invalid argument') let [value, y] = [num, 0] for (let i = 24; i > 0; i = i - 3) { if (value >= 10 ** i) return ((value / 10 ** i).toFixed(1).toString().includes('.0') ? (value / 10 ** i).toFixed(0) : (value / 10 ** i).toFixed(1)) + array[y] else y++ } return value.toString() } /** * Version proto * @returns { string } */ Number.prototype.form = function () { let [value, y] = [this, 0] for (let i = 24; i > 0; i = i - 3) { if (value >= 10 ** i) return ((value / 10 ** i).toFixed(1).toString().includes('.0') ? (value / 10 ** i).toFixed(0) : (value / 10 ** i).toFixed(1)) + array[y] else y++ } return value.toString() }
Java
UTF-8
677
2
2
[]
no_license
package com.assocaition.management.module.statistical.service.serviceimpl; import com.assocaition.management.module.statistical.dao.StatisticalMapper; import com.assocaition.management.module.statistical.service.StatisticalService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author Duanjianhui * @date 2021-05-27 4:08 下午 * @describe */ @Service public class StatisticalServiceImpl implements StatisticalService { @Autowired StatisticalMapper statisticalMapper; @Override public int countDownlocal(String assID) { return statisticalMapper.countDownlocal(assID); } }
Java
UTF-8
1,107
4.125
4
[]
no_license
package xceptionsInJava; public class UnCheckedExceptions { /* UnChecked Exception :-> Are the Exceptions that are not checked at Compile time but are checked at Run Time. This means, even your program is throwing an Unchecked Exception and even it is not handled by user, it won't give a compilation error. Mostly, it is due to the incorrect data provided to the program. All Unchecked Exception are direct subclass of 'RuntimeException' Below are the examples of Unchecked Exception :-> NullPointerException , IllegalArgumentException Arithmetic Exception = E.g. When deviding a number by '0'; ArrayIndexOutOfBoundsException = E.g. When Array element at 8th position is accessed from an Array having Size of only 4 elements. */ public static void main(String[] args) { int num =0; int num1 = 10; int res = num1/num; // Deviding num1 i.e. 10 by num i.e. 0 => 10/0 = infinite System.out.println(res); /* Since, we are deviding an integer by 0, it will give Runtime Unchecked Exception called "Arithmetic Exception" */ } }
Java
UTF-8
746
1.78125
2
[]
no_license
package com.lichto.modtest.reference; /** * Created by Noah Lichtenstein on 6/19/2016. */ public final class Names { public static final class Blocks { public static final String FLAG = "flag"; } public static final class Items { public static final String LEAF = "leaf"; } public static final class NBT { public static final String UUID_MOST_SIG = "UUIDMostSig"; public static final String UUID_LEAST_SIG = "UUIDLeastSig"; } public static final class Keys { public static final String CATEGORY = "keys.modtest.category"; public static final String CHARGE = "keys.modtest.charge"; public static final String RELEASE = "keys.modtest.release"; } }
C
WINDOWS-1252
1,105
3.234375
3
[]
no_license
# include <stdio.h> # include <stdlib.h> # include <string.h> int main () { char number1[1000] = "\0"; char number2[1000] = "\0"; int num1[1000] = {0}; int num2[1000] = {0}; int num3[1000] = {0}; int length1 = 0, length2 = 0, length = 0; int i = 0, j = 0; //for (i=0;i<1000;i++) printf("num1 = %d num2 = %d\n",num1[i],num2[i]); printf("Please input two number:\n"); scanf("%s %s", number1, number2); length1 = strlen(number1); length2 = strlen(number2); for (i=0;i<length1;i++) num1[i] = number1[length1-i-1] - '0'; for (i=0;i<length2;i++) num2[i] = number2[length2-i-1] - '0'; length = length1 < length2 ? length2 : length1; //printf("length = %d, length1 = %d, length2 = %d\n", length, length1, length2);//䡿 for (i=0;i<length;i++) num3[i] = num1[i] + num2[i]; for (i=0;i<length;i++) { if (num3[i]>=10) { num3[i+1] += 1; num3[i] = num3[i] % 10; } } printf("The result is :\n"); if (num3[length]==0) i = length - 1; else i = length; for (;i>=0;i--) printf("%d", num3[i]); system("pause"); return 0; }
C#
UTF-8
843
2.6875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerAttack : MonoBehaviour { Camera _camera; void Start() { _camera = Camera.main; } // Update is called once per frame void Update() { if(Input.GetMouseButtonUp(0)) { Attack(); } } private void Attack() { int characterLayer = LayerMask.NameToLayer("Character"); Ray ray = _camera.ScreenPointToRay(Input.mousePosition); RaycastHit hit; Debug.DrawRay(ray.origin, ray.direction, Color.red, 3f); if(Physics.Raycast(ray, out hit, float.MaxValue, 1 << characterLayer)) { Debug.Log(hit.transform.gameObject); FindObjectOfType<Bulet>().Shooting(hit.point); } } }
C
UTF-8
2,983
3.890625
4
[]
no_license
/* * tokenizer.c * Written by Zack Colello and Anna Genke */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "tokenizer.h" char *indexPointer; //to be used to track where tokens are in the second argument. /* * * TKCreate creates a new TokenizerT object for a given set of separator * * characters (given as a string) and a token stream (given as a string). * * * * TKCreate should copy the two arguments so that it is not dependent on * * them staying immutable after returning. (In the future, this may change * * to increase efficiency.) * * * * If the function succeeds, it returns a non-NULL TokenizerT. * * Else it returns NULL. * * * * You need to fill in this function as part of your implementation. * */ TokenizerT *TKCreate(char *ts) { TokenizerT *temptok; int StringSize = strlen(ts); temptok = malloc(sizeof(TokenizerT)); temptok->input = (char*) malloc(StringSize +1); strcpy(temptok->input, ts); return temptok; } /* * * TKDestroy destroys a TokenizerT object. It should free all dynamically * * allocated memory that is part of the object being destroyed. * * * * You need to fill in this function as part of your implementation. * */ void TKDestroy(TokenizerT *tk) { free(tk); tk = NULL; } /* * * TKGetNextToken returns the next token from the token stream as a * * character string. Space for the returned token should be dynamically * * allocated. The caller is responsible for freeing the space once it is * * no longer needed. * * * * If the function succeeds, it returns a C string (delimited by '\0') * * containing the token. Else it returns 0. * * * * You need to fill in this function as part of your implementation. * */ char *TKGetNextToken(TokenizerT *tk) { int i, b, BBIndex; BBIndex = 0; char c; char* BigBuffer; //to be used for returning tokens BigBuffer = (char*) malloc(1000); for(i = 0; i<(strlen(indexPointer)+1); i++){ c = (indexPointer[i]); b = isDelimiter(c, tk); if(c == '\0'){ BigBuffer[BBIndex] = '\0'; indexPointer = '\0'; return BigBuffer; } if(b == 0){ //not delimiter, add to BigBuffer BigBuffer[BBIndex]=c; BBIndex++; }else{ //is delimiter, return now indexPointer = &tk->input[i+1]; tk->input = indexPointer; BigBuffer[BBIndex] = '\0'; return BigBuffer; } } return 0; } /* Function isDelimiter is used by main to check if a character in the second argument is a delimiter. * isDelimiter uses tokenizer's delimiters value to compare a character with those delimiter values. * It returns 1 if the character is in the delimiter string, and 0 otherwise. * */ int isDelimiter(char c, TokenizerT *tokenizer){ if(!isalnum(c)){ return 1; } return 0; //character c was not found to be a delimiter. Return 0 for false }
C++
UTF-8
1,496
3.828125
4
[]
no_license
/******************************************************************************/ /* * Question: #109 Convert Sorted List to Binary Search Tree * Given a singly linked list where elements are sorted in ascending order, convert it to a heigh balanced BST. */ /*****************************************************************************/ #include <iostream> #include "../Leetcode/BST.h" #include "../Leetcode/ListNode.h" // solution 1 - every time find the middle point and make it root // then recursively build left tree and right tree. // But this time complexity is O(nlogn) // solution 2 - build the tree from bottom-up // every time we need to make head point to the next and build the tree inorder // time complexity is O(n) TreeNode * buildTreeFromList(ListNode *& list, int start, int end) { if (start > end) return NULL; int mid = start + (end - start) / 2; TreeNode * leftTree = buildTreeFromList(list, start, mid - 1); TreeNode * node = new TreeNode(list->val); node->left = leftTree; list = list->next; node->right = buildTreeFromList(list, mid + 1, end); return node; } TreeNode* sortedListToBST(ListNode * head) { int length = listLength(head); return buildTreeFromList(head, 0, length-1); } /* int main(int argc, char ** argv) { int input[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // size is 5 int n = 10; ListNode * head = generateList(input, n); TreeNode * root = sortedListToBST(head); printPretty(root, 1, 0, cout); cout << "Hi this is LC 109" << endl; } */
C#
UTF-8
1,566
3.8125
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CrackingCodingInterviews { /* * Implemen t a method t o perform basi c string compression using the counts * of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. * I f the "compressed" string would no t become smaller than the original string, * your method should return the original string. */ class P1_5 { public string CompressString(string input){ char letter = input[1]; int count = 0; string result = string.Empty; for (int i = 0; i < input.Length; i++) { if (letter == input[i]) count++; else { result = result + letter + count; letter = input[i]; count = 1; } } result = result + letter + count; if (result.Length > input.Length) result = input; return result; } //static void Main(string[] args) //{ // P1_5 cs = new P1_5(); // string input = "aabcccccaaa"; // string compressed = cs.CompressString(input); // Console.WriteLine(compressed); // input = "aabbcc"; // compressed = cs.CompressString(input); // Console.WriteLine(compressed); // Console.ReadKey(); //} } }