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
Java
UTF-8
1,208
3.203125
3
[]
no_license
package Citizens; import Citizens.Model.Animal; import com.opencsv.CSVReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class AnimalReader { private String fileLocation = "C:\\Users\\Użytkownik\\Desktop\\source\\Zadania dodatkowe\\CitizenApp\\src\\main\\resources\\animal.csv"; public List<Animal> readAnimalListFromCSV () { List <Animal> animals = new ArrayList<>(); try (CSVReader reader = new CSVReader(new FileReader(fileLocation), ',')) { String [] nextLine; while ((nextLine = reader.readNext()) != null) { Animal.Builder builder = new Animal.Builder(); builder.id(Integer.parseInt(nextLine[0])); builder.name(nextLine[1]); builder.type(nextLine[2]); Animal animal = builder.build(); animals.add(animal); } } catch (FileNotFoundException e) { System.out.println("File Not Found!"); } catch (IOException e) { System.out.println("IO Exception!"); } return animals; } }
C
UTF-8
464
3.625
4
[]
no_license
#include<stdio.h> void strong_number() { int num,i,p,r,sum=0,save_num; printf("\n Enter a number"); scanf("%d",&num); save_num=num; while(num) { i=1,p=1; r=num%10; while(i<=r) { p=p*i; i++; } //while sum=sum+p; num=num/10; } //while if(sum==save_num) printf("%d is a Strong number", save_num); else printf("%d is not a Strong number", save_num); }
C++
UTF-8
7,639
2.859375
3
[]
no_license
#include "PPintrin.h" #include <stdlib.h> #include <math.h> // implementation of absSerial(), but it is vectorized using PP intrinsics void absVector(float *values, float *output, int N) { __pp_vec_float x; __pp_vec_float result; __pp_vec_float zero = _pp_vset_float(0.f); __pp_mask maskAll, maskIsNegative, maskIsNotNegative; // Note: Take a careful look at this loop indexing. This example // code is not guaranteed to work when (N % VECTOR_WIDTH) != 0. // Why is that the case? for (int i = 0; i < N; i += VECTOR_WIDTH) { // All ones maskAll = _pp_init_ones(); // All zeros maskIsNegative = _pp_init_ones(0); // Load vector of values from contiguous memory addresses _pp_vload_float(x, values + i, maskAll); // x = values[i]; // Set mask according to predicate _pp_vlt_float(maskIsNegative, x, zero, maskAll); // if (x < 0) { // Execute instruction using mask ("if" clause) _pp_vsub_float(result, zero, x, maskIsNegative); // output[i] = -x; // Inverse maskIsNegative to generate "else" mask maskIsNotNegative = _pp_mask_not(maskIsNegative); // } else { // Execute instruction ("else" clause) _pp_vload_float(result, values + i, maskIsNotNegative); // output[i] = x; } // Write results back to memory _pp_vstore_float(output + i, result, maskAll); } } void clampedExpVector(float *values, int *exponents, float *output, int N) { // // PP STUDENTS TODO: Implement your vectorized version of // clampedExpSerial() here. // // Your solution should work for any value of // N and VECTOR_WIDTH, not just when VECTOR_WIDTH divides N // __pp_vec_float x; __pp_vec_int y; __pp_vec_float result; __pp_vec_int count; __pp_vec_int zero = _pp_vset_int(0); //float onefloat = 1.f; int zeroint = 1; //float limitfloat = 9.999999f; __pp_vec_int one = _pp_vset_int(1); __pp_vec_float limit = _pp_vset_float(9.999999f); __pp_mask maskAll, maskexpiszero, maskexpisnotzero, maskcountnotzero, maskresultoutrange, maskand; float * limitfloat; limitfloat = (float *)malloc(VECTOR_WIDTH*sizeof(float)); for (int i = 0; i<VECTOR_WIDTH; i++) { limitfloat[i] = 9.999999f; } float *onefloat; onefloat = (float *)malloc(VECTOR_WIDTH*sizeof(float)); for (int i = 0; i<VECTOR_WIDTH; i++) { onefloat[i] = 1.f; } int a = N/VECTOR_WIDTH; int b = N%VECTOR_WIDTH; float * limitfloat_out; limitfloat_out = (float *)malloc(b*sizeof(float)); for (int i = 0; i<b; i++) { limitfloat_out[i] = 9.999999f; } float *onefloat_out; onefloat_out = (float *)malloc(b*sizeof(float)); for (int i = 0; i<b; i++) { onefloat_out[i] = 1.f; } for (int i = 0; i < N; i += VECTOR_WIDTH) { if (i == a*VECTOR_WIDTH) { maskAll = _pp_init_ones(b); maskexpiszero = _pp_init_ones(0); maskcountnotzero = _pp_init_ones(0); maskresultoutrange = _pp_init_ones(0); maskand = _pp_init_ones(b); _pp_vload_float(x, values + i, maskAll); // float x = values[i]; _pp_vload_int(y, exponents + i, maskAll); // int y = exponents[i]; _pp_veq_int(maskexpiszero, y, zero, maskAll); // if (y == 0) _pp_vload_float(result, onefloat_out, maskexpiszero); // output[i] = 1.f; maskexpisnotzero = _pp_mask_not(maskexpiszero); // else maskexpisnotzero = _pp_mask_and(maskexpisnotzero,maskand); _pp_vload_float(result, values + i, maskexpisnotzero); // float result = x; _pp_vsub_int(count, y, one, maskexpisnotzero); // int count = y - 1; _pp_vgt_int(maskcountnotzero ,count ,zero ,maskexpisnotzero); int numgtzero = _pp_cntbits(maskcountnotzero); while (numgtzero > 0) { _pp_vmult_float(result, result, x, maskcountnotzero); //result *= x; _pp_vsub_int(count, count, one, maskcountnotzero); // count--; _pp_vgt_int(maskcountnotzero ,count ,zero ,maskexpisnotzero); numgtzero = _pp_cntbits(maskcountnotzero); } _pp_vgt_float(maskresultoutrange,result, limit, maskexpisnotzero);// if (result > 9.999999f) _pp_vload_float(result, limitfloat_out, maskresultoutrange);// result = 9.999999f; _pp_vstore_float(output + i, result, maskAll);// output[i] = result; //free(limitfloat); //free(onefloat); } else{ maskAll = _pp_init_ones(); maskexpiszero = _pp_init_ones(0); maskcountnotzero = _pp_init_ones(0); maskresultoutrange = _pp_init_ones(0); _pp_vload_float(x, values + i, maskAll); // float x = values[i]; _pp_vload_int(y, exponents + i, maskAll); // int y = exponents[i]; _pp_veq_int(maskexpiszero, y, zero, maskAll); // if (y == 0) _pp_vload_float(result, onefloat, maskexpiszero); // output[i] = 1.f; maskexpisnotzero = _pp_mask_not(maskexpiszero); // else _pp_vload_float(result, values + i, maskexpisnotzero); // float result = x; _pp_vsub_int(count, y, one, maskexpisnotzero); // int count = y - 1; _pp_vgt_int(maskcountnotzero ,count ,zero ,maskexpisnotzero); int numgtzero = _pp_cntbits(maskcountnotzero); while (numgtzero > 0) { _pp_vmult_float(result, result, x, maskcountnotzero); //result *= x; _pp_vsub_int(count, count, one, maskcountnotzero); // count--; _pp_vgt_int(maskcountnotzero ,count ,zero ,maskexpisnotzero); numgtzero = _pp_cntbits(maskcountnotzero); } _pp_vgt_float(maskresultoutrange,result, limit, maskexpisnotzero);// if (result > 9.999999f) _pp_vload_float(result, limitfloat, maskresultoutrange);// result = 9.999999f; _pp_vstore_float(output + i, result, maskAll);// output[i] = result; //free(limitfloat); //free(onefloat); } } } // returns the sum of all elements in values // You can assume N is a multiple of VECTOR_WIDTH // You can assume VECTOR_WIDTH is a power of 2 float arraySumVector(float *values, int N) { // // PP STUDENTS TODO: Implement your vectorized version of arraySumSerial here // //float finalsum[VECTOR_WIDTH] = {0.f}; float *finalsum; finalsum = (float *)malloc(VECTOR_WIDTH*sizeof(float)); __pp_vec_float x = _pp_vset_float(0.f); __pp_vec_float sum = _pp_vset_float(0.f);// float sum = 0; __pp_mask arrmaskAll; //float aaa = 0; for (int i = 0; i < N; i += VECTOR_WIDTH) { arrmaskAll = _pp_init_ones(); _pp_vload_float(x ,values + i, arrmaskAll); // x = values[i]; _pp_vadd_float(sum ,sum ,x , arrmaskAll); // sum += values[i]; } int times = log(VECTOR_WIDTH)/log(2); for (int i = 0; i < times ; i++ ) { _pp_hadd_float(sum ,sum); _pp_interleave_float(sum ,sum); } /*_pp_hadd_float(sum ,sum); _pp_interleave_float(sum ,sum); _pp_hadd_float(sum ,sum);*/ _pp_vstore_float(finalsum, sum, arrmaskAll); return finalsum[0]; }
Markdown
UTF-8
5,732
3.6875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
## Objectives 1. Understand the concept of AR Lifecycle methods 2. Use `before_save`, `before_create`, and `before_validation` 3. Understand when to use `before_validation` vs. `before_save` ## Callbacks Now that you are integrating ActiveRecord into Rails, we must first have a quick discussion about how developers can control the "lifecycle" of our object. This means that it can be nice to inject our code every time ActiveRecord does something to our model. There are a ton of different places we can inject our code. In this reading we are going to discuss the most common ones. Before we begin, some quick terminology. Everything we cover here is called "Active Record Lifecycle Callbacks". Many people just call them callbacks. It's a bit shorter. Take a look at the blog app that is included. It's pretty simple. We have a `Post` model and a few views. The `Post` `belongs_to` an `Author`. Also in the `Post` model you'll notice a validation to make sure that post titles are in title case. Title case means every word starts with a capital letter. While this validation is great, there is a method provided by Rails called `#titlecase` that will do this for us. I still want this validation, but let's make it so that just automatically before we save the record it runs `#titlecase`. What a convenience we are providing to our users! We are going to use our first callback, `before_save`. We use this similar to how you use `has_many` or `validates`. They are at the top of your model files. First let's write our method to actually run the `#titlecase` method. ```ruby # post.rb def make_title_case self.title = self.title.titlecase end ``` Ok, now we want to run this whenever someone tries to save to the database. This is where the `before_save` comes: ```ruby class Post < ActiveRecord::Base belongs_to :author validate :is_title_case # New Code!! before_save :make_title_case private def is_title_case if title.split.any?{|w|w[0].upcase != w[0]} errors.add(:title, "Title must be in title case") end end def make_title_case self.title = self.title.titlecase end end ``` This shouldn't look too alien! Pretty much whenever you persist to the database (so `#save` and `#create`) this code will get run. Let's open up the console (`rails c`) and test it out: ```ruby p = Post.create(title: "testing") # (0.1ms) begin transaction # (0.1ms) rollback transaction # => #<Post id: nil, title: "testing", description: nil, created_at: nil, updated_at: nil, post_status: nil, author_id: nil> ``` Wait! There was no `INSERT` SQL command issued. In fact, we see the `rollback transaction` line. That means that it didn't actually save to the database. If we do `p.valid?` right now it will return `false`. That's not right. We automatically title case things. The validation should pass! Then after reading much documentation, it turns out that the `before_save` is called **after** validation occurs. So Rails goes `is valid?` "Nope! Stop!", and never makes it to `before_save`. Let's change our callback to the `before_validation` callback. This one happens **before** validation. That means that first our `before_validation` code works, which title cases the title, *then* the validation runs, which passes! Here is the final code: ```ruby class Post < ActiveRecord::Base belongs_to :author validate :is_title_case # New Code!! before_validation :make_title_case private def is_title_case if title.split.any?{|w|w[0].upcase != w[0]} errors.add(:title, "Title must be in title case") end end def make_title_case self.title = self.title.titlecase end end ``` Here is a rule of thumb: **Whenever you are modifying an attribute of the model, use `before_validation`. If you are doing some other action, then use `before_save`.** ### Before Save Now let's do something that belongs in the `before_save`. We use `before_save` for actions that need to occur that aren't modifying the model itself. For example, whenever you save to the database, let's send an email to the Author alerting them that the post was just saved! This is a perfect `before_save` action. It doesn't modify the model so there is no validation weirdness, and we don't want to email the user if the Post is invalid. That would be just mean! So if you had some method called `email_author_about_post` you would modify your `Post` model to look like this: ```ruby class Post < ActiveRecord::Base belongs_to :author validate :is_title_case before_validation :make_title_case # New Code!! before_save :email_author_about_post private def is_title_case if title.split.any?{|w|w[0].upcase != w[0]} errors.add(:title, "Title must be in title case") end end def make_title_case self.title = self.title.titlecase end end ``` ### Before Create Before you move on, let's cover one last callback that is super useful. This one is called `before_create`. `before_create` is very close to `before_save` with one major difference: it only gets called when a model is created for the first time. This means not every time the object is persisted, just when it is **new**. For more information on all of the callbacks available to you, check out [this amazing rails guide](http://guides.rubyonrails.org/active_record_callbacks.html). <p data-visibility='hidden'>View <a href='https://learn.co/lessons/activerecord-lifecycle-reading'>ActiveRecord Lifecycle Methods</a> on Learn.co and start learning to code for free.</p> <p class='util--hide'>View <a href='https://learn.co/lessons/activerecord-lifecycle-reading'>ActiveRecord Lifecycle Methods</a> on Learn.co and start learning to code for free.</p>
Java
UTF-8
1,878
2.46875
2
[]
no_license
package Control; import Model.InfoConfig; import NewGUI.Preferences; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author dodan_000 */ public class Database { public static String url = ""; public static String user = ""; public static String pass = ""; public static Connection conn = null; public static Statement stm = null; static private void setProperties(){ InfoConfig ifConfig = new InfoConfig(); ifConfig.getConfig(); url = ifConfig.url_db; user = ifConfig.user_name_db; pass = ifConfig.pass_word_db; } static public void setState(){ setProperties(); try { conn = DriverManager.getConnection(url, user, pass); stm = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); } catch (SQLException ex) { int n = JOptionPane.showConfirmDialog(null, "Giá trị kết nối đến Database không đúng!, Bạn cần phải thiết lập lại giá trị kết nối?", "Error Connection", JOptionPane.YES_NO_OPTION); if(n== JOptionPane.OK_OPTION){ Preferences preferences = new Preferences(); preferences.setVisible(true); } else{ } //Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } } }
C++
UTF-8
837
3.546875
4
[]
no_license
#include <Servo.h> Servo myservo; // create an object called myservo using the Servo library int pos = 0; // declare a variable for storing the position of the servo arm void setup() { myservo.attach(9); // attach the object myservo to the servo on pin 9 } void loop() { for(pos = 0; pos < 180; pos += 1) // go from 0° to 180° { // one step at a time myservo.write(pos); // go to the position stored in 'pos' delay(15); // wait 15ms for the servo to move to position } for(pos = 180; pos>=1; pos-=1) /// go from 180° to 0° { myservo.write(pos); // go to the position stored in 'pos' delay(15); // wait 15ms for the servo to move to position } }
Java
UTF-8
1,425
2.484375
2
[]
no_license
package com.example.bootstrap; import com.example.domain.Product; import com.example.repositories.ProductRepository; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component public class ProductLoader implements ApplicationListener<ContextRefreshedEvent> { private ProductRepository productRepository; private Logger log = Logger.getLogger(ProductLoader.class); @Autowired public void setProductRepository(ProductRepository productRepository) { this.productRepository = productRepository; } @Override public void onApplicationEvent(ContextRefreshedEvent event) { Product shirt = new Product(); shirt.setNombre("Angel JPA"); shirt.setPaterno("Paterno JPA"); shirt.setMaterno("Materno JPA"); shirt.setEdad(122); productRepository.save(shirt); log.info("Saved PersistenceJPAExample - id: " + shirt.getEdad()); Product mug = new Product(); shirt.setNombre("Angel 2 JPA"); shirt.setPaterno("Paterno 2 JPA"); shirt.setMaterno("Materno 2 JPA"); shirt.setEdad(123); productRepository.save(mug); log.info("Saved Mug - id:" + mug.getEdad()); } }
Java
UTF-8
11,305
2.109375
2
[]
no_license
package com.audio.libary.app; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.preference.PreferenceManager; import com.audio.libary.encoders.Factory; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; public class Storage extends com.github.axet.androidlibrary.app.Storage { public static String TAG = Storage.class.getSimpleName(); public static final String RECORDINGS = "recordings"; public static final String RAW = "raw"; public static final String TMP_REC = "recording.data"; public static final String TMP_ENC = "encoding.data"; public static final SimpleDateFormat SIMPLE = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss", Locale.US); public static final SimpleDateFormat ISO8601 = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US); public static List<Node> scan(Context context, Uri uri, final String[] ee) { return list(context, uri, new NodeFilter() { @Override public boolean accept(Node n) { for (String e : ee) { if (n.size > 0 && n.name.toLowerCase().endsWith("." + e)) return true; } return false; } }); } public static long average(Context context, long free) { // get average recording miliseconds based on compression format final SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(context); int rate = Integer.parseInt(shared.getString(MainApplication.PREFERENCE_RATE, "")); String ext = shared.getString(MainApplication.PREFERENCE_ENCODING, ""); int m = Sound.getChannels(context); long perSec = Factory.getEncoderRate(ext, rate) * m; return free / perSec * 1000; } public static File getLocalDataDir(Context context) { return new File(context.getApplicationInfo().dataDir); } public static File getFilesDir(Context context, String type) { File raw = new File(context.getFilesDir(), type); if (!raw.exists() && !raw.mkdirs() && !raw.exists()) throw new RuntimeException("no files permissions"); return raw; } public static class RecordingStats { public int duration; public long size; public long last; public RecordingStats() { } public RecordingStats(RecordingStats fs) { this.duration = fs.duration; this.size = fs.size; this.last = fs.last; } public RecordingStats(String json) { try { JSONObject j = new JSONObject(json); duration = j.getInt("duration"); size = j.getLong("size"); last = j.getLong("last"); } catch (JSONException e) { throw new RuntimeException(e); } } public JSONObject save() { try { JSONObject o = new JSONObject(); o.put("duration", duration); o.put("size", size); o.put("last", last); return o; } catch (JSONException e) { throw new RuntimeException(e); } } } public static class RecordingUri extends RecordingStats { public Uri uri; public String name; public RecordingUri(Context context, Uri f, RecordingStats fs) { super(fs); uri = f; name = Storage.getNameNoExt(context, uri); } } public Storage(Context context) { super(context); } public boolean isLocalStorageEmpty() { File[] ff = getLocalStorage().listFiles(); if (ff == null) return true; return ff.length == 0; } public boolean isExternalStoragePermitted() { return permitted(context, PERMISSIONS_RW); } public boolean recordingPending() { File tmp = getTempRecording(); return tmp.exists() && tmp.length() > 0; } public File getLocalInternal() { return new File(context.getFilesDir(), RECORDINGS); } public File getLocalExternal() { return context.getExternalFilesDir(RECORDINGS); } public Uri getStoragePath() { SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(context); String path = shared.getString(MainApplication.PREFERENCE_STORAGE, ""); return getStoragePath(path); } public boolean isLocalStorage(File f) { if (super.isLocalStorage(f)) return true; File a = context.getFilesDir(); if (f.getPath().startsWith(a.getPath())) return true; a = context.getExternalFilesDir(""); if (a != null && f.getPath().startsWith(a.getPath())) return true; if (Build.VERSION.SDK_INT >= 19) { File[] aa = context.getExternalFilesDirs(""); if (aa != null) { for (File b : aa) { if (f.getPath().startsWith(b.getPath())) return true; } } } return false; } @Override public void migrateLocalStorage() { migrateLocalStorage(new File(context.getApplicationInfo().dataDir, RECORDINGS)); // old recordings folder migrateLocalStorage(new File(context.getApplicationInfo().dataDir)); // old recordings folder migrateLocalStorage(context.getFilesDir()); // old recordings folder migrateLocalStorage(context.getExternalFilesDir("")); // old recordings folder migrateLocalStorage(getLocalInternal()); migrateLocalStorage(getLocalExternal()); } public void migrateLocalStorage(File l) { if (l == null) return; if (!canWrite(l)) return; Uri path = getStoragePath(); String s = path.getScheme(); if (s.equals(ContentResolver.SCHEME_FILE)) { File p = getFile(path); if (!canWrite(p)) return; if (l.equals(p)) // same storage path return; } Uri u = Uri.fromFile(l); if (u.equals(path)) // same storage path return; File[] ff = l.listFiles(); if (ff == null) return; for (File f : ff) { if (f.isFile()) // skip directories (we didn't create one) migrate(f, path); } } public Uri migrate(File f, Uri t) { Uri u = com.github.axet.androidlibrary.app.Storage.migrate(context, f, t); if (u == null) return null; MainApplication.setStar(context, u, MainApplication.getStar(context, Uri.fromFile(f))); // copy star to migrated file return u; } public Uri rename(Uri f, String t) { Uri u = com.github.axet.androidlibrary.app.Storage.rename(context, f, t); if (u == null) return null; MainApplication.setStar(context, u, MainApplication.getStar(context, f)); // copy star to renamed name return u; } public Uri getNewFile() { SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(context); String ext = shared.getString(MainApplication.PREFERENCE_ENCODING, ""); Uri parent = getStoragePath(); String s = parent.getScheme(); if (s.equals(ContentResolver.SCHEME_FILE)) { File p = getFile(parent); if (!p.exists() && !p.mkdirs()) throw new RuntimeException("Unable to create: " + parent); } return getNextFile(context, parent, SIMPLE.format(new Date()), ext); } public File getTempRecording() { File internalOld = new File(getLocalDataDir(context), "recorind.data"); if (internalOld.exists()) return internalOld; internalOld = new File(getLocalDataDir(context), TMP_REC); if (internalOld.exists()) return internalOld; internalOld = new File(context.getCacheDir(), TMP_REC); // cache/ dir auto cleared by OS if space is low if (internalOld.exists()) return internalOld; internalOld = context.getExternalCacheDir(); if (internalOld != null) { internalOld = new File(internalOld.getParentFile(), TMP_REC); if (internalOld.exists()) return internalOld; } File internal = new File(getFilesDir(context, RAW), TMP_REC); if (internal.exists()) return internal; // Starting in KITKAT, no permissions are required to read or write to the returned path; // it's always accessible to the calling app. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { if (!permitted(context, PERMISSIONS_RW)) return internal; } File c = context.getExternalFilesDir(RAW); if (c == null) // some old phones <15API with disabled sdcard return null return internal; File external = new File(c, TMP_REC); if (external.exists()) // external already been used as tmp storage, keep using it return external; try { long freeI = getFree(internal); long freeE = getFree(external); if (freeI > freeE) return internal; else return external; } catch (RuntimeException e) { // samsung devices unable to determine external folders return internal; } } public File getTempEncoding() { File internalOld = new File(context.getCacheDir(), TMP_ENC); if (internalOld.exists()) return internalOld; internalOld = context.getExternalCacheDir(); if (internalOld != null) { internalOld = new File(internalOld, TMP_ENC); if (internalOld.exists()) return internalOld; } File internal = new File(getFilesDir(context, RAW), TMP_ENC); if (internal.exists()) return internal; // Starting in KITKAT, no permissions are required to read or write to the returned path; // it's always accessible to the calling app. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { if (!permitted(context, PERMISSIONS_RW)) return internal; } File c = context.getExternalFilesDir(RAW); if (c == null) // some old phones <15API with disabled sdcard return null return internal; File external = new File(c, TMP_ENC); if (external.exists()) return external; try { long freeI = getFree(internal); long freeE = getFree(external); if (freeI > freeE) return internal; else return external; } catch (RuntimeException e) { // samsung devices unable to determine external folders return internal; } } }
Markdown
UTF-8
10,024
2.65625
3
[ "MIT" ]
permissive
[上一章](https://github.com/xiaominghe2014/spider_book/blob/master/book/知北游/第82章.md)&nbsp;&nbsp;&nbsp;&nbsp;[下一章](https://github.com/xiaominghe2014/spider_book/blob/master/book/知北游/第84章.md)&nbsp;&nbsp;&nbsp;&nbsp;[返回目录](https://github.com/xiaominghe2014/spider_book/blob/master/book/知北游/README.md) <br /> 第五册 第三章(上)让我欢喜让我忧<br />     鞭炮声震耳欲聋,我骑着长翅膀的白马,穿着大红袍,在海面上飞驰。海上突然浮出了一座五光十色的宫殿,海姬、甘柠真和鸠丹媚就站在宫殿门口,个个穿着鲜艳的红色吉服,三个美女齐齐撩起了霞盖头,对我笑。边上有好多妖怪吵吵嚷嚷:“新郎官到啦,快拜天地!”,“快拜天地,快进洞房!”     我傻乎乎地看着她们,然后宫殿开始慢慢下沉,妖怪们的声音越来越急:“新郎快点下马拜天地,来不及啦!”     “再不拜来不及啦!”     “来不及啦!”     难道我就是新郎?三个美女要一起嫁给我?我又惊又喜,想跳下马,谁料到屁股牢牢地粘在了马背上,动也动不了,急得我满头大汗。     宫殿慢慢沉入了大海,三个美女也一起消失了。而胯下的白马猛地一声嘶吼,居然变成了一头黑色的野猪,把我掀翻,然后梦就突然醒了。     睁开眼,天还没有亮,我迷迷糊糊地爬起来,想起刚才做的梦,脸上一阵发烧,既觉得荒唐,又有种说不出的窃喜。涛声如梦,不远处的河畔,甘柠真和公子樱并肩而立,喃喃细语。星桂花金灿灿地零星飘落,映得他们的背影一闪一烁。     日他***,这两个人居然还没睡,一直闲聊到现在!不知为什么,我觉得胸口一闷,像是被一柄大锤重敲了一下。看看四周,海姬在我身后十多米处,闭目伫立。斜对面,雷猛呈“大”字躺在地上,呼呼大睡,呼噜声像打雷一样。     我悄悄起身,蹑手蹑脚地走向河边。想偷听甘柠真和公子樱在说些什么。离他们几米远,我悄悄趴下,以公子樱的法力,要是我靠得太近,一定会被他发现的。     运起顺风耳秘道术,我的心怦怦乱跳。     “柠真,你和这位林飞朋友是如何认识的?”我听到公子樱在问。***,背后打探老子底细,不是好汉。     甘柠真稍一犹豫,道:“这涉及到多年前的一场秘密赌誓。请掌门师叔恕我不能说出。不过,林飞他,他是个好人。虽然他看上去有点吊儿郎当,但其实不是这样地。”     公子樱默然了一会,低声道:“小时候,无论我问你什么,你都会告诉我的。掌门师叔。唉,你过去总是叫我樱哥哥。”     “在我心里,你还是我的樱哥哥啊,教我弹琴,教我赋诗,还陪我一起玩过家家的游戏。同门的师兄弟都说你像我的亲哥哥一样。只是我现在不是小女孩了。你又贵为掌门,我当然不能像过去那样随便了。”     公子樱不说话了。低下头,淡白的星光下,他紫色的长发仿佛沾上了一层薄霜,艳丽得近乎忧伤。公子樱轻轻拨弦,琵琶声像寂寞的白露,点点滴滴滚落。     我撇撇嘴,日他***,半夜在美女面前弹琵琶,摆明了卖弄风骚嘛。     “青梅涩涩。绣马哒哒。既见昔人,云胡不喜。”和着声,甘真曼声浅唱,侧头看着公子樱:“师叔弹地是你过去编的青梅竹马曲吧,我还记得呢。既见昔人,云胡不喜。掌门师叔,难道你见到我不高兴吗?”     公子樱凝视着水中甘柠真的倒影,笑了笑,笑容中有淡淡的惘然:“怎么会呢?柠真,明日我打算回碧落赋了。魔主和罗生天互通款曲一事非同小可。我必须和清虚天其它门派商议对策。你——和我一起回去吗?”     甘柠真摇摇头:“我恐怕得和林飞、海姬在一起。”     我心里立刻舒服多了,转念又想。林飞你算什么,就算甘柠真和你在一起,也是恪于和龙蝶的誓约。想到这里,心里一阵失落。     公子樱不说话了,过了一会又道:“碧落赋的师兄弟们都很想念你。你已经很久没回去了,难道,你还在想当年的?师兄失踪后,碧落赋地掌门原本该由你继任的。”     “不要再说了。”甘真忽然寒声道,脸上露出凛然的神色。两个人都沉默了,过了片刻,甘柠真道:“掌门师叔,最近有没有谱写什么新曲子?你很久没有教我弹琴了。”     公子樱微微一笑,坐下,怀抱琵琶,五指轻扬,清婉的乐声随风飘落在河面上,犹如雨打芭蕉,淅淅沥沥。     天色越来越亮,河面染上一层玫瑰色的曙光,晨风吹开了一圈圈涟漪。甘真托着腮,坐在公子樱身旁,静静地听着     也沐浴了柔和的玫瑰色。望着他们地背影,我心里不知是什么滋味,     “喂,你小子在做什么?”背后冷不防传来一声低喝,回头一看,雷猛瞪圆了豹眼,凶神恶煞般盯着我,眼角还有黄白色的眼屎。     我忍不住一慌,随即义正词严地道:“你偷偷摸摸站在我身后干吗?偷窥啊?”     雷猛气得七窍生烟,一把揪住我地衣领,压低了声音:“是你小子在偷窥吧?告诉你,你小子还在穿尿布的时候,掌门就开始照顾小姐了,你别想动什么歪主意。”     我心虚地推开雷猛:“什么歪主意?老子听不懂你的话。”伸了个懒腰,大叫:“天亮喽,起床喽!”     &lt;.得这么早啊?啧啧,大清早弹琴,真是风雅。”     甘柠真淡淡地道:“我们没睡。”     海姬遥遥走来,冲我眨眨眼:“你们没睡,有人也没睡好。”     我脸一红,指着雷猛道:“这位雷护法年纪大了,估计是他没睡好。”     甘柠真走到我身边,冷然道:“以后再敢偷听我说话,小心你的耳朵。”     我窘迫地扭过头,顾左右而言它。甘柠真嘴角露出一丝笑意,这时,雷猛突然指着远处,叫起来:“那个妖怪又来了!”     云大郎一袭黑袍,低着头,沿河岸径直走来。海姬冷笑:“他来干什么?难道昨天输得不服气,今天又来找麻烦?”     在一棵星桂树下,云大郎站住。我沉吟道:“应该不会,否则他早带上一干妖怪了。”迟疑了一下,大步向他走去,海姬和甘柠真不放心,也跟了上来。     “林飞兄果然还没走。”云大郎平静地道。     我笑嘻嘻地道:“云兄有何贵干啊?难不成想请我喝早茶?”     “我来,是郑重谢过林兄昨日手下留情,饶我性命。”云大郎弯腰对我长长一揖,又道:“林兄,我能否和你单独说几句话?”     海姬微微摇头,我想了想,道:“云兄不是龌龊小人,你们走开吧。他不会暗算我的。”     云大郎的手微微一抖,等到海姬、甘柠真走远,涩声道:“林兄就这么相信我吗?”     我心中暗笑,你又打不过老子,怕你作甚?嘴里道:“咱们英雄相惜嘛。”眼角瞄准了他手上的黑包袱,一旦不对劲,立刻念出千千咒结。     云大郎颤声道:“林兄真是我的知己!这次前来,是想告诉你一个消息。魔刹天的鸠蝎妖是否是你地好友?半月前,她在魔刹天被魔主座下的四大妖王之一——夜流冰抓获,现已关押在魔刹天的葬花渊。”     我大惊失色,难怪见不到鸠丹媚,原来是被魔主的手下逮到了!云大郎苦笑一声:“我原本不该泄漏此事。可昨晚我辗转反侧,想起你的饶命之恩,无以为报。所以宁愿被魔主责罚,也要告诉你。”     “云兄!”我这下倒是真的感动了。云大郎真是君子啊,不折不扣的妖怪君子。我却对他没半点诚意,想到这里,我满怀愧疚。     “我该走了。林兄,如果你去魔刹天救鸠蝎妖,一定要小心。负责看押鸠丹媚的是夜流冰,他成名多年,妖力远在我之上。至于魔主倒是不必担心,魔主最近可能不会回魔刹天。”云大郎道,语气充满了诚恳。     我心头一热,没想到他这么够朋友,连忙问道:“葬花渊具体在什么位置?有多少机关陷阱?夜流冰又是什么妖怪?”     云大郎没有回答,我知道他为难,也不好意思再问了。望着云大郎离去的身影,我突然叫道:“云兄,你到底为什么投靠魔主?我觉得楚度不是好人啊!”     云大郎停下脚步,沉默了片刻,转过身,缓缓地抬起头,遮住脸的长发向两边散开。朝阳耀眼,在黝黑地衣领上面,我只看见一团浓密的白云,没有脸,没有五官,什么都没有。     “我是个云气凝化地妖怪,天生就没有脸。我多么想和你们一样,能拥有一张脸。”云大郎声音低沉:“传说在自在天,能实现所有的梦想。如果找到自在天,也许,我就会有一张脸了。”     垂下头,他捧着包袱,渐渐远去,声音隐隐地传来:“我相信,沙罗铁树选中的魔主,一定能带领我们找到自在天。” <br /> [上一章](https://github.com/xiaominghe2014/spider_book/blob/master/book/知北游/第82章.md)&nbsp;&nbsp;&nbsp;&nbsp;[下一章](https://github.com/xiaominghe2014/spider_book/blob/master/book/知北游/第84章.md)&nbsp;&nbsp;&nbsp;&nbsp;[返回目录](https://github.com/xiaominghe2014/spider_book/blob/master/book/知北游/README.md)
JavaScript
UTF-8
434
2.859375
3
[]
no_license
function loadspinner() { var element = document.querySelector(".main"); const container = document.createElement("div"); const tag = document.createElement("div"); container.classList.add("loader-container"); tag.classList.add("loader"); element.appendChild(container); container.appendChild(tag); } function stopspinner() { const tag = document.querySelector(".loader-container"); tag.remove(); }
Java
UTF-8
891
3.53125
4
[]
no_license
package com.sda.patterns.creational.factory; import com.sda.patterns.creational.factory.factory.RoadLogistics; import com.sda.patterns.creational.factory.factory.SeaLogistics; import java.util.Scanner; public class DemoFactoryPattern { public static void main(String[] args) { // create the right factory based on an input (truck or ship) Scanner input = new Scanner(System.in); System.out.println("Insert type of transport (truck/ship): "); String transport = input.nextLine(); if (transport.equals("truck")) { RoadLogistics factory = new RoadLogistics(); factory.planDelivery(); factory.createTransport(); } else if (transport.equals("ship")) { SeaLogistics factory = new SeaLogistics(); factory.planDelivery(); factory.createTransport(); } } }
Rust
UTF-8
2,230
2.515625
3
[ "Apache-2.0" ]
permissive
use super::{MessageQueue, MessageQueueConfig, ReplicationEvent}; use log::{error, info}; use std::{ process, sync::{mpsc, Arc}, }; use tokio::{runtime::Handle, sync::oneshot}; use utils::messaging_system::publisher::CommonPublisher; pub async fn replicate_db_events( config: MessageQueueConfig, recv: mpsc::Receiver<ReplicationEvent>, tokio_runtime: Handle, mut kill_signal: oneshot::Receiver<()>, ) { let producer = match &config.queue { MessageQueue::Kafka(kafka) => CommonPublisher::new_kafka(&kafka.brokers).await, MessageQueue::Amqp(amqp) => CommonPublisher::new_amqp(&amqp.connection_string).await, } .unwrap_or_else(|_e| { error!("Fatal error, synchronization channel cannot be created."); process::abort(); }); let producer = Arc::new(producer); loop { let event = recv.recv().unwrap_or_else(|_e| { error!("Fatal error, synchronization channel closed."); process::abort(); }); if kill_signal.try_recv().is_ok() { info!("Master replication disabled"); return; }; tokio_runtime.enter(|| { send_messages_to_kafka(producer.clone(), config.topic_or_exchange.clone(), event) }); } } fn send_messages_to_kafka( producer: Arc<CommonPublisher>, topic_or_exchange: String, event: ReplicationEvent, ) { let key = match &event { ReplicationEvent::AddSchema { id, .. } => id, ReplicationEvent::AddSchemaVersion { id, .. } => id, ReplicationEvent::AddViewToSchema { schema_id, .. } => schema_id, ReplicationEvent::UpdateSchemaMetadata { id, .. } => id, ReplicationEvent::UpdateView { id, .. } => id, }; let serialized = serde_json::to_string(&event).unwrap(); let serialized_key = key.to_string(); tokio::spawn(async move { let delivery_status = producer.publish_message( &topic_or_exchange, &serialized_key, serialized.as_bytes().to_vec(), ); if delivery_status.await.is_err() { error!("Fatal error, delivery status for message not received."); process::abort(); } }); }
TypeScript
UTF-8
2,838
2.625
3
[]
no_license
//----------------------------------------------------------------------------- // src/models/__tests__/user.dao.tes.ts //----------------------------------------------------------------------------- import '../../config/config' import { ObjectId } from 'bson' import MongoDAO from '../../config/mongodb-dao' import UserDAO, { IUser } from '../user.dao' describe(`UserDAO`, () => { let mongoClient: MongoDAO let users: IUser[] = [ { _id: new ObjectId(), email: "marv@bills.com", password: "secret123", }, { _id: new ObjectId(), email: "bruce@bills.com", password: "sackmaster", }, { _id: new ObjectId(), email: "thurmon@bills.com", password: "password123", } ] /** * Connect to MongoDB before running tests */ beforeAll( async () => { mongoClient = new MongoDAO() await mongoClient.connect() }) /** * Remove the data from the test DB and Close the MongoDB connection * after running the tests. */ afterAll( async () => { await mongoClient.conn(`users`).deleteMany({}) mongoClient.close() }) describe(`CRUD Operations`, () => { beforeEach( async () => { const docs = await mongoClient.conn(`users`).insertMany(users) }) afterEach( async () => { await mongoClient.conn(`users`).deleteMany({}) }) /////////////////////////////////////////////////////////////////////////// // TODO: 04/27/2021 // // NEED TO ADD THE FOLLOWING TEST CASES: // 1.) CANNOT ADD USER W/ DUPLICATE EMAIL ADDRESS // 2.) EMAIL AND PASSWORD ARE NON-BLANK FIELDS // 3.) A VALID EMAIL ADDRESS IS REQUIRED /////////////////////////////////////////////////////////////////////////// describe(`Create User`, () => { it(`Creates a user`, async () => { let user: IUser = { email: `andre@bills.com`, password: `number83`, } const result = await UserDAO.create(user) expect(result).toMatchObject(user) // Verify user is written to DB let conn = mongoClient.conn(`users`) let endUser = await conn.find({email: user.email}).toArray() expect(endUser.length).toBe(1) expect(endUser[0]).toMatchObject(user) }) }) describe(`Find User by Email`, () => { it(`Returns a user`, async () => { const email = users[0].email const result = await UserDAO.findByEmail(email) expect(result._id).toEqual(users[0]._id) expect(result.email).toBe(users[0].email) }) it(`Returns null if the user's email is not found`, async () => { const unknownEmail = `unknown@email.com` const result = await UserDAO.findByEmail(unknownEmail) expect(result).toBeNull() }) }) }) })
Java
UTF-8
1,052
1.984375
2
[]
no_license
package TAL.Repository; import TAL.model.Locataire; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.ArrayList; public interface RequetesLocataire extends JpaRepository<Locataire, Integer> { @Query(value="Select * from locataire where pseudo=:pseudo" , nativeQuery=true) ArrayList<Locataire> testepseudo(@Param("pseudo") String pseudo); @Query(value="Select * from locataire where email=:e" , nativeQuery=true) ArrayList<Locataire> testeemail(@Param("e") String email); @Query(value="Select * from locataire where email=:e" , nativeQuery=true) ArrayList<Locataire> getLocataireByEmail(@Param("e") String email); @Query(value="Select * from locataire where etat='bloqué';" , nativeQuery=true) ArrayList<Locataire> locataireBloqué(); @Query(value="Select * from locataire where id_locataire=:id;" , nativeQuery=true) Locataire getLocataire(@Param("id") int id); }
C++
UTF-8
1,525
2.734375
3
[]
no_license
// LCD, KEYPAD, SERVO SMART SAFE WITH RASPBERRY PI CAM #include <LiquidCrystal.h> //include LCD library (standard library) #include <Servo.h> #include <Keypad.h> Servo ServoMotor; char* password = "1234"; // change the password here, just pick any 3 numbers int position = 0; const byte ROWS = 4; const byte COLS = 3; char keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'} }; byte rowPins [ROWS] = {7, 6, 5, 4}; //pins of the keypad byte colPins [COLS] = {3, 2, 1}; LiquidCrystal lcd (A0, A1, A2, A3, A4, A5); // pins of the LCD. (RS, E, D4, D5, D6, D7) Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); int RedpinLock = 9; int GreenpinUnlock = 8; void setup() { pinMode(RedpinLock, OUTPUT); pinMode(GreenpinUnlock, OUTPUT); lcd.begin(16, 2); ServoMotor.attach(10); LockedPosition(true); } void loop() { char key = keypad.getKey(); lcd.setCursor(0, 0); lcd.print("Enter Password"); if (key == '*' || key == '#'){ position = 0; LockedPosition(true); } if (key == password[position]){ position ++; } if (position == 4){ LockedPosition(false); lcd.clear(); lcd.setCursor(0, 0); lcd.print("Password Correct!"); } delay(100); } void LockedPosition(int locked) { if (locked){ digitalWrite(RedpinLock, HIGH); digitalWrite(GreenpinUnlock, LOW); ServoMotor.write(11); } else{ digitalWrite(RedpinLock, LOW); digitalWrite(GreenpinUnlock, HIGH); ServoMotor.write(90); } }
Java
UTF-8
1,601
2.5
2
[ "Apache-2.0" ]
permissive
package com.mogade.java.tests.unit; import com.mogade.java.protocol.Response; import com.mogade.java.protocol.SaveScoreResponse; import org.junit.Test; import static junit.framework.Assert.*; public class TestResponse { @Test public void testOkResponse() { Response response = new SaveScoreResponse(null, null, null); assertNull(response.getInfo()); assertTrue(response.isOk()); assertFalse(response.isUnavailable()); assertFalse(response.isError()); assertNull(response.getStatus()); } @Test public void testOkResponseWithInfo() { String msg = "great username"; Response response = new SaveScoreResponse(msg, null, null); assertEquals(msg, response.getInfo()); assertTrue(response.isOk()); assertFalse(response.isUnavailable()); assertFalse(response.isError()); } @Test public void testUnavailableResponse() { String msg = "down for maintenance"; Response response = new SaveScoreResponse(null, msg, null); assertNull(response.getInfo()); assertFalse(response.isOk()); assertTrue(response.isUnavailable()); assertFalse(response.isError()); assertEquals(msg, response.getStatus()); } @Test public void testErrorResponse() { String msg = "error occured"; Response response = new SaveScoreResponse(null, null, msg); assertNull(response.getInfo()); assertFalse(response.isOk()); assertFalse(response.isUnavailable()); assertTrue(response.isError()); assertEquals(msg, response.getStatus()); } }
Python
UTF-8
917
2.703125
3
[]
no_license
import numpy as np #Imp PARAMS : maxsentence_length=sentence_length embedding_dim=100 max_num_words=50000 hiddendim=128 word_index = tokenizer.word_index glove_dir = 'path/Glove Embeddings/glove.6B.100d.txt' embeddings_index = {} f = open('/path/Glove Embeddings/glove.6B.100d.txt') for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefs f.close() print('Found %s word vectors.' % len(embeddings_index)) print(word_index) embedding_dim = 100 max_words = 50000 # OR -> LEN(WORDINDEX) + 1 embedding_matrix = np.zeros((max_words, embedding_dim)) for word, i in word_index.items(): if i < max_words: embedding_vector = embeddings_index.get(word) if embedding_vector is not None: # words not found in embedding index will be all-zeros. embedding_matrix[i] = embedding_vector
Java
UTF-8
21,064
2.296875
2
[ "Apache-2.0" ]
permissive
package org.struts.action.TravelManagement.TravelReports; import org.apache.commons.collections.map.LinkedMap; import org.paradyne.bean.TravelManagement.TravelReports.TrvlMainSchdlrReport; import org.paradyne.model.TravelManagement.TravelReports.TrvlMainSchdlrReportModel; import org.struts.lib.ParaActionSupport; /** * @author krishna date: 23-APRIL-2010 * */ public class TrvlMainSchdlrReportAction extends ParaActionSupport { static org.apache.log4j.Logger logger = org.apache.log4j.Logger .getLogger(TrvlMainSchdlrReportAction.class); TrvlMainSchdlrReport mainSchdlr; public void prepare_local() throws Exception { mainSchdlr = new TrvlMainSchdlrReport(); mainSchdlr.setMenuCode(957); } public void prepare_withLoginProfileDetails() throws Exception { TrvlMainSchdlrReportModel model = new TrvlMainSchdlrReportModel(); model.initiate(context, session); LinkedMap hMap = model.getTravelTypes(); mainSchdlr.setTrvlTypeMap(hMap); model.terminate(); } public Object getModel() { return mainSchdlr; } /** * @return the mainSchdlr */ public TrvlMainSchdlrReport getMainSchdlr() { return mainSchdlr; } /** * @param mainSchdlr the mainSchdlr to set */ public void setMainSchdlr(TrvlMainSchdlrReport mainSchdlr) { this.mainSchdlr = mainSchdlr; } /** * Search employee details * * @return String(f9 page) * @throws Exception */ public String f9ApprvrAction() throws Exception { /** * BUILD COMPLETE QUERY (ALONG WITH PARAMETERS) WHICH GIVES THE DESIRED * OUTPUT */ String query = "SELECT NVL(HRMS_EMP_OFFC.EMP_FNAME||' '||HRMS_EMP_OFFC.EMP_MNAME||' '||HRMS_EMP_OFFC.EMP_LNAME,' ') AS NAME," + " EMP_TOKEN,EMP_ID FROM HRMS_EMP_OFFC " + " LEFT JOIN HRMS_TITLE ON HRMS_TITLE.TITLE_CODE = HRMS_EMP_OFFC.EMP_TITLE_CODE"; query += getprofileQuery(mainSchdlr); query +=" AND EMP_STATUS='S'"; query += " ORDER BY HRMS_EMP_OFFC.EMP_ID"; /** * SET THE HEADER NAMES OF TABLE WHICH IS DISPLAYED IN POP-UP WINDOW. * */ String[] headers = { getMessage("tms.approver") }; String[] headerWidth = { "100" }; /** * -SET THE FIELDNAMES INTO WHICH THE VALUES ARE BEING POPULATED AFTER A * ROW IS SELECTED. -USEFULL IN CASES WHERE SUBMIT FLAG IS 'false' * -PARENT FORM WILL SHOW THE VALUES IN THE FILDS CORRSPONDING TO COLUMN * INDEX. NOTE: LENGHT OF COLUMN INDEX MUST BE SAME AS THE LENGTH OF * FIELDNAMES */ String[] fieldNames = { "apprvrName", "apprvrToken", "apprvrCode" }; /** * SET THE COLUMN INDEX E.G. SUPPOSE THE POP-UP SHOWS 4 COLUMNS, BUT ON * CLICKING A ROW ONLY SECOND AND FORTH COLUMN VALUES NEED TO BE SHOWN * IN THE PARENT WINDOW FIELDS THEN THE COLUMN INDEX CAN BE {1,3} * * NOTE: COLUMN NUMBERS STARTS WITH 0 * */ int[] columnIndex = { 0, 1, 2 }; /** * WHEN SET TO 'true' WILL SUBMIT THE FORM * */ String submitFlag = "false"; /** * IF THE 'submitFlag' IS 'true' , THE FORM WILL SUBMIT AND CALL * FOLLOWING METHOD IN THE ACTION * NAMING CONVENSTION: <NAME OF * ACTION>_<METHOD TO CALL>.action */ String submitToMethod = ""; /** * CALL THIS METHOD AFTER ALL PARAMETERS ARE DEFINED * */ setF9Window(query, headers, headerWidth, fieldNames, columnIndex, submitFlag, submitToMethod); return "f9page"; } /** * Search employee details * * @return String(f9 page) * @throws Exception */ public String f9SubSchdlrAction() throws Exception { /** * BUILD COMPLETE QUERY (ALONG WITH PARAMETERS) WHICH GIVES THE DESIRED * OUTPUT */ String query = "SELECT NVL(HRMS_EMP_OFFC.EMP_FNAME||' '||HRMS_EMP_OFFC.EMP_MNAME||' '||HRMS_EMP_OFFC.EMP_LNAME,' ') AS NAME," + " EMP_TOKEN,EMP_ID FROM HRMS_EMP_OFFC " + " LEFT JOIN HRMS_TITLE ON HRMS_TITLE.TITLE_CODE = HRMS_EMP_OFFC.EMP_TITLE_CODE"; query += getprofileQuery(mainSchdlr); query +=" AND EMP_STATUS='S'"; query += " ORDER BY HRMS_EMP_OFFC.EMP_ID"; /** * SET THE HEADER NAMES OF TABLE WHICH IS DISPLAYED IN POP-UP WINDOW. * */ String[] headers = { getMessage("tms.subSchdlr") }; String[] headerWidth = { "100" }; /** * -SET THE FIELDNAMES INTO WHICH THE VALUES ARE BEING POPULATED AFTER A * ROW IS SELECTED. -USEFULL IN CASES WHERE SUBMIT FLAG IS 'false' * -PARENT FORM WILL SHOW THE VALUES IN THE FILDS CORRSPONDING TO COLUMN * INDEX. NOTE: LENGHT OF COLUMN INDEX MUST BE SAME AS THE LENGTH OF * FIELDNAMES */ String[] fieldNames = { "subSchdlrName", "subSchdlrToken", "subSchdlrCode" }; /** * SET THE COLUMN INDEX E.G. SUPPOSE THE POP-UP SHOWS 4 COLUMNS, BUT ON * CLICKING A ROW ONLY SECOND AND FORTH COLUMN VALUES NEED TO BE SHOWN * IN THE PARENT WINDOW FIELDS THEN THE COLUMN INDEX CAN BE {1,3} * * NOTE: COLUMN NUMBERS STARTS WITH 0 * */ int[] columnIndex = { 0, 1, 2 }; /** * WHEN SET TO 'true' WILL SUBMIT THE FORM * */ String submitFlag = "false"; /** * IF THE 'submitFlag' IS 'true' , THE FORM WILL SUBMIT AND CALL * FOLLOWING METHOD IN THE ACTION * NAMING CONVENSTION: <NAME OF * ACTION>_<METHOD TO CALL>.action */ String submitToMethod = ""; /** * CALL THIS METHOD AFTER ALL PARAMETERS ARE DEFINED * */ setF9Window(query, headers, headerWidth, fieldNames, columnIndex, submitFlag, submitToMethod); return "f9page"; } /** * Search cadre details * * @return String(f9 page) * @throws Exception */ public String f9cadretaction() throws Exception { /** * BUILD COMPLETE QUERY (ALONG WITH PARAMETERS) WHICH GIVES THE DESIRED * OUTPUT */ String query = "SELECT DISTINCT NVL(CADRE_NAME,' '), CADRE_ID FROM HRMS_CADRE " + " ORDER BY CADRE_ID "; /** * SET THE HEADER NAMES OF TABLE WHICH IS DISPLAYED IN POP-UP WINDOW. * */ String[] headers = { getMessage("grade") }; String[] headerWidth = { "100" }; /** * -SET THE FIELDNAMES INTO WHICH THE VALUES ARE BEING POPULATED AFTER A * ROW IS SELECTED. -USEFULL IN CASES WHERE SUBMIT FLAG IS 'false' * -PARENT FORM WILL SHOW THE VALUES IN THE FILDS CORRSPONDING TO COLUMN * INDEX. NOTE: LENGHT OF COLUMN INDEX MUST BE SAME AS THE LENGTH OF * FIELDNAMES */ String[] fieldNames = { "gradeName", "gradeId" }; /** * SET THE COLUMN INDEX E.G. SUPPOSE THE POP-UP SHOWS 4 COLUMNS, BUT ON * CLICKING A ROW ONLY SECOND AND FORTH COLUMN VALUES NEED TO BE SHOWN * IN THE PARENT WINDOW FIELDS THEN THE COLUMN INDEX CAN BE {1,3} * * NOTE: COLUMN NUMBERS STARTS WITH 0 * */ int[] columnIndex = { 0, 1 }; /** * WHEN SET TO 'true' WILL SUBMIT THE FORM * */ String submitFlag = "false"; /** * IF THE 'submitFlag' IS 'true' , THE FORM WILL SUBMIT AND CALL * FOLLOWING METHOD IN THE ACTION * NAMING CONVENSTION: <NAME OF * ACTION>_<METHOD TO CALL>.action */ String submitToMethod = ""; /** * CALL THIS METHOD AFTER ALL PARAMETERS ARE DEFINED * */ setF9Window(query, headers, headerWidth, fieldNames, columnIndex, submitFlag, submitToMethod); return "f9page"; } /** * Search branch details * * @return String(f9 page) * @throws Exception */ public String f9centeraction() throws Exception { /** * BUILD COMPLETE QUERY (ALONG WITH PARAMETERS) WHICH GIVES THE DESIRED * OUTPUT */ String query = " SELECT NVL(CENTER_NAME,' '),CENTER_ID FROM HRMS_CENTER " /* * + " ,DEPT_NAME,DIV_NAME LEFT JOIN HRMS_DEPT * ON(HRMS_DEPT.DEPT_ID=HRMS_CENTER.CENTER_DEPT_ID)" + " LEFT * JOIN HRMS_DIVISION * ON(HRMS_DIVISION.DIV_ID=HRMS_DEPT.DEPT_DIV_CODE) " */ + " ORDER BY CENTER_ID "; /** * SET THE HEADER NAMES OF TABLE WHICH IS DISPLAYED IN POP-UP WINDOW. * */ String[] headers = { getMessage("branch") }; String[] headerWidth = { "100" }; /** * -SET THE FIELDNAMES INTO WHICH THE VALUES ARE BEING POPULATED AFTER A * ROW IS SELECTED. -USEFULL IN CASES WHERE SUBMIT FLAG IS 'false' * -PARENT FORM WILL SHOW THE VALUES IN THE FILDS CORRSPONDING TO COLUMN * INDEX. NOTE: LENGHT OF COLUMN INDEX MUST BE SAME AS THE LENGTH OF * FIELDNAMES */ String[] fieldNames = { "branchName", "brnchCode" }; /** * SET THE COLUMN INDEX E.G. SUPPOSE THE POP-UP SHOWS 4 COLUMNS, BUT ON * CLICKING A ROW ONLY SECOND AND FORTH COLUMN VALUES NEED TO BE SHOWN * IN THE PARENT WINDOW FIELDS THEN THE COLUMN INDEX CAN BE {1,3} * * NOTE: COLUMN NUMBERS STARTS WITH 0 * */ int[] columnIndex = { 0, 1 }; /** * WHEN SET TO 'true' WILL SUBMIT THE FORM * */ String submitFlag = "false"; /** * IF THE 'submitFlag' IS 'true' , THE FORM WILL SUBMIT AND CALL * FOLLOWING METHOD IN THE ACTION * NAMING CONVENSTION: <NAME OF * ACTION>_<METHOD TO CALL>.action */ String submitToMethod = ""; /** * CALL THIS METHOD AFTER ALL PARAMETERS ARE DEFINED * */ setF9Window(query, headers, headerWidth, fieldNames, columnIndex, submitFlag, submitToMethod); return "f9page"; } /** * Search department details * * @return String(f9 page) * @throws Exception */ public String f9deptaction() throws Exception { /** * BUILD COMPLETE QUERY (ALONG WITH PARAMETERS) WHICH GIVES THE DESIRED * OUTPUT */ String query = "SELECT DISTINCT NVL(DEPT_NAME,' '), DEPT_ID FROM HRMS_DEPT " + " ORDER BY DEPT_ID "; /** * SET THE HEADER NAMES OF TABLE WHICH IS DISPLAYED IN POP-UP WINDOW. * */ String[] headers = { getMessage("department") }; String[] headerWidth = { "100" }; /** * -SET THE FIELDNAMES INTO WHICH THE VALUES ARE BEING POPULATED AFTER A * ROW IS SELECTED. -USEFULL IN CASES WHERE SUBMIT FLAG IS 'false' * -PARENT FORM WILL SHOW THE VALUES IN THE FILDS CORRSPONDING TO COLUMN * INDEX. NOTE: LENGHT OF COLUMN INDEX MUST BE SAME AS THE LENGTH OF * FIELDNAMES */ String[] fieldNames = { "deptName", "deptCode" }; /** * SET THE COLUMN INDEX E.G. SUPPOSE THE POP-UP SHOWS 4 COLUMNS, BUT ON * CLICKING A ROW ONLY SECOND AND FORTH COLUMN VALUES NEED TO BE SHOWN * IN THE PARENT WINDOW FIELDS THEN THE COLUMN INDEX CAN BE {1,3} * * NOTE: COLUMN NUMBERS STARTS WITH 0 * */ int[] columnIndex = { 0, 1 }; /** * WHEN SET TO 'true' WILL SUBMIT THE FORM * */ String submitFlag = "false"; /** * IF THE 'submitFlag' IS 'true' , THE FORM WILL SUBMIT AND CALL * FOLLOWING METHOD IN THE ACTION * NAMING CONVENSTION: <NAME OF * ACTION>_<METHOD TO CALL>.action */ String submitToMethod = ""; /** * CALL THIS METHOD AFTER ALL PARAMETERS ARE DEFINED * */ setF9Window(query, headers, headerWidth, fieldNames, columnIndex, submitFlag, submitToMethod); return "f9page"; } /** * * @return * @throws Exception */ public String saveReport() throws Exception { TrvlMainSchdlrReportModel model = new TrvlMainSchdlrReportModel(); model.initiate(context, session); model.deleteSavedReport(mainSchdlr); boolean result = model.saveReportCriteria(mainSchdlr); if (result) addActionMessage(getMessage("save")); else addActionMessage(getMessage("duplicate")); model.terminate(); return SUCCESS; } public String searchSavedReport() throws Exception { /** * BUILD COMPLETE QUERY (ALONG WITH PARAMETERS) WHICH GIVES THE DESIRED * OUTPUT */ /* * String query = " SELECT REPORT_CRITERIA, NVL(REPORT_TITLE,' '), * REPORT_ID FROM HRMS_MISREPORT_HDR " + " ORDER BY REPORT_ID "; */ String query = " SELECT REPORT_CRITERIA, NVL(REPORT_TITLE,' '), REPORT_ID FROM HRMS_MISREPORT_HDR " + " WHERE REPORT_TYPE = 'TravelMainScheduler' ORDER BY REPORT_ID "; /** * SET THE HEADER NAMES OF TABLE WHICH IS DISPLAYED IN POP-UP WINDOW. * */ String[] headers = { getMessage("report.criteria"), getMessage("report.title") }; String[] headerWidth = { "50", "50" }; /** * -SET THE FIELDNAMES INTO WHICH THE VALUES ARE BEING POPULATED AFTER A * ROW IS SELECTED. -USEFULL IN CASES WHERE SUBMIT FLAG IS 'false' * -PARENT FORM WILL SHOW THE VALUES IN THE FILDS CORRSPONDING TO COLUMN * INDEX. NOTE: LENGHT OF COLUMN INDEX MUST BE SAME AS THE LENGTH OF * FIELDNAMES */ String[] fieldNames = { "settingName", "reportTitle", "reportId" }; /** * SET THE COLUMN INDEX E.G. SUPPOSE THE POP-UP SHOWS 4 COLUMNS, BUT ON * CLICKING A ROW ONLY SECOND AND FORTH COLUMN VALUES NEED TO BE SHOWN * IN THE PARENT WINDOW FIELDS THEN THE COLUMN INDEX CAN BE {1,3} * * NOTE: COLUMN NUMBERS STARTS WITH 0 * */ int[] columnIndex = { 0, 1, 2 }; /** * WHEN SET TO 'true' WILL SUBMIT THE FORM * */ String submitFlag = "true"; /** * IF THE 'submitFlag' IS 'true' , THE FORM WILL SUBMIT AND CALL * FOLLOWING METHOD IN THE ACTION * NAMING CONVENSTION: <NAME OF * ACTION>_<METHOD TO CALL>.action */ String submitToMethod = "TravelMainSchdlrReport_setDetails.action"; /** * CALL THIS METHOD AFTER ALL PARAMETERS ARE DEFINED * */ setF9Window(query, headers, headerWidth, fieldNames, columnIndex, submitFlag, submitToMethod); return "f9page"; } /** * Generate report in PDF/XLS or DOC * * @return * @throws Exception */ public String report() throws Exception { try { TrvlMainSchdlrReportModel model = new TrvlMainSchdlrReportModel(); model.initiate(context, session); mainSchdlr.setBackFlag(""); String[] labelNames = { getMessage("tms.empid"), getMessage("tms.travelType"), getMessage("branch"), getMessage("tms.trvlStrtDate"), getMessage("tms.subSchdlr"), getMessage("grade"), getMessage("tms.trvlEndDate"), getMessage("tms.applcntName"), getMessage("tms.trvlPurpose"), getMessage("tms.trvlAssigntDate"), getMessage("tms.approver"), getMessage("tms.trvlStatus"), getMessage("tms.trvlBookingDate"), getMessage("tms.trvlInitrName") }; model.getReport(mainSchdlr, response, labelNames, request); model.terminate(); } catch (Exception e) { logger.error("Exception in viewOnScreen() method : " + e); } return null; } public String reset() throws Exception { try { mainSchdlr.setApplDateSelect(""); mainSchdlr.setApplDateFrm(""); mainSchdlr.setApplDateTo(""); mainSchdlr.setApplStatus(""); mainSchdlr.setApprvrToken(""); mainSchdlr.setApprvrCode(""); mainSchdlr.setApprvrName(""); mainSchdlr.setSubSchdlrToken(""); mainSchdlr.setSubSchdlrCode(""); mainSchdlr.setSubSchdlrName(""); mainSchdlr.setApplFor(""); mainSchdlr.setTravelCheckVal(""); mainSchdlr.setTravelCheck(""); mainSchdlr.setHidTravelSelf(""); mainSchdlr.setTrvlSelf(""); mainSchdlr.setHidTravelComp(""); mainSchdlr.setAccomCheck(""); mainSchdlr.setTrvlSelf(""); mainSchdlr.setTrvlComp(""); mainSchdlr.setAccomCheckVal(""); mainSchdlr.setHidAccomSelf(""); mainSchdlr.setAccomSelf(""); mainSchdlr.setHidAccomComp(""); mainSchdlr.setLocalCheckVal(""); mainSchdlr.setLocalCheck(""); mainSchdlr.setHidLocalSelf(""); mainSchdlr.setLocalSelf(""); mainSchdlr.setHidLocalComp(""); mainSchdlr.setLocalComp(""); // column definitions mainSchdlr.setEmpIdFlag(""); mainSchdlr.setTravelIdFlag(""); mainSchdlr.setTrvlTypeFlag(""); mainSchdlr.setBranchFlag(""); mainSchdlr.setTravelStrtDateFlag(""); mainSchdlr.setSubSchdlrFlag(""); mainSchdlr.setGradeFlag(""); mainSchdlr.setTravelEndDateFlag(""); mainSchdlr.setApplcntNameFlag(""); mainSchdlr.setTrvlPurposeFlag(""); mainSchdlr.setTravelAssignDateFlag(""); mainSchdlr.setApprvrFlag(""); mainSchdlr.setTrvlStatusFlag(""); mainSchdlr.setTrvlBkngDateFlag(""); mainSchdlr.setTrvlInitrNameFlag(""); // advance filters mainSchdlr.setAssignDateSelect(""); mainSchdlr.setTADfromDate(""); mainSchdlr.setTADToDate(""); mainSchdlr.setTrvlStrtDateSelect(""); mainSchdlr.setTSDfromDate(""); mainSchdlr.setTSDToDate(""); mainSchdlr.setTrvlBookingDateSelect(""); mainSchdlr.setTBDfromDate(""); mainSchdlr.setTBDToDate(""); mainSchdlr.setSchCycleSelect(""); mainSchdlr.setSchCycleFrom(""); mainSchdlr.setSchCycleTo(""); mainSchdlr.setTrvlType(""); mainSchdlr.setGradeId(""); mainSchdlr.setGradeName(""); mainSchdlr.setBrnchCode(""); mainSchdlr.setBranchName(""); mainSchdlr.setDeptCode(""); mainSchdlr.setDeptName(""); mainSchdlr.setSortBy(""); mainSchdlr.setSortByAsc("checked"); mainSchdlr.setSortByDsc(""); mainSchdlr.setSortByOrder(""); mainSchdlr.setThenBy1(""); mainSchdlr.setThenByOrder1Asc("checked"); mainSchdlr.setThenByOrder1Dsc(""); mainSchdlr.setThenByOrder1(""); mainSchdlr.setThenBy2(""); mainSchdlr.setThenByOrder2Asc("checked"); mainSchdlr.setThenByOrder2(""); mainSchdlr.setThenByOrder2Dsc(""); mainSchdlr.setHiddenSortBy(""); mainSchdlr.setHiddenThenBy1(""); mainSchdlr.setHiddenThenBy2(""); mainSchdlr.setHiddenColumns(""); mainSchdlr.setHidReportView("checked"); mainSchdlr.setHidReportRadio(""); mainSchdlr.setReportType(""); mainSchdlr.setMyPage(""); mainSchdlr.setShow(""); mainSchdlr.setSettingName(""); mainSchdlr.setReportTitle(""); mainSchdlr.setReportId(""); mainSchdlr.setBackFlag(""); } catch (Exception e) { e.printStackTrace(); } return "success"; } public String setDetails() throws Exception { TrvlMainSchdlrReportModel model = new TrvlMainSchdlrReportModel(); model.initiate(context, session); model.setDetailOnScreen(mainSchdlr); model.terminate(); if (mainSchdlr.getSortByOrder().trim().equals("D")) mainSchdlr.setSortByDsc("checked"); if (mainSchdlr.getSortByOrder().trim().equals("A")) mainSchdlr.setSortByAsc("checked"); if (mainSchdlr.getThenByOrder1().trim().equals("D")) mainSchdlr.setThenByOrder1Dsc("checked"); if (mainSchdlr.getThenByOrder1().trim().equals("A")) mainSchdlr.setThenByOrder1Asc("checked"); if (mainSchdlr.getThenByOrder2().trim().equals("D")) mainSchdlr.setThenByOrder2Dsc("checked"); if (mainSchdlr.getThenByOrder2().trim().equals("A")) mainSchdlr.setThenByOrder2Asc("checked"); return SUCCESS; } /** * Display the report on screen * * @return String */ public String viewOnScreen() { mainSchdlr.setBackFlag(""); try { TrvlMainSchdlrReportModel model = new TrvlMainSchdlrReportModel(); model.initiate(context, session); // PASSING LABEL NAMES String[] labelNames = { getMessage("tms.empid"), getMessage("tms.travelType"), getMessage("branch"), getMessage("tms.trvlStrtDate"), getMessage("tms.subSchdlr"), getMessage("grade"), getMessage("tms.trvlEndDate"), getMessage("tms.applcntName"), getMessage("tms.trvlPurpose"), getMessage("tms.trvlAssigntDate"), getMessage("tms.approver"), getMessage("tms.trvlStatus"), getMessage("tms.trvlBookingDate"), getMessage("tms.trvlInitrName") }; // CALL TO MODEL model.callViewScreen(mainSchdlr, request, labelNames); model.terminate(); } catch (Exception e) { logger.error("Exception in viewOnScreen() method : " + e); } return "viewOnScreen"; } /** * Called on Back button in view screen * * @return String returns to the mis filter page */ public String callBack() { TrvlMainSchdlrReportModel model = new TrvlMainSchdlrReportModel(); model.initiate(context, session); try { prepare_withLoginProfileDetails(); } catch (Exception e) { e.printStackTrace(); }// end of try-catch block model.terminate(); mainSchdlr.setBackFlag("true"); logger.info("getSortByOrder..." + mainSchdlr.getSortByOrder()); if (mainSchdlr.getSortByOrder().trim().equals("D")) mainSchdlr.setSortByDsc("checked"); if (mainSchdlr.getSortByOrder().trim().equals("A")) mainSchdlr.setSortByAsc("checked"); if (mainSchdlr.getThenByOrder1().trim().equals("D")) mainSchdlr.setThenByOrder1Dsc("checked"); if (mainSchdlr.getThenByOrder1().trim().equals("A")) mainSchdlr.setThenByOrder1Asc("checked"); if (mainSchdlr.getThenByOrder2().trim().equals("D")) mainSchdlr.setThenByOrder2Dsc("checked"); if (mainSchdlr.getThenByOrder2().trim().equals("A")) mainSchdlr.setThenByOrder2Asc("checked"); mainSchdlr.setHiddenSortBy(mainSchdlr.getSortBy()); mainSchdlr.setHiddenThenBy1(mainSchdlr.getThenBy1()); mainSchdlr.setHiddenThenBy2(mainSchdlr.getThenBy2()); return SUCCESS; } }
JavaScript
UTF-8
2,196
2.546875
3
[]
no_license
import { React, useState } from 'react' import { connect } from "react-redux"; import { updateCity, fetchTemperature } from '../redux/temperature/t-act' const Popup = ({ updateCity, fetchTemperature }) => { const [cityName, setCityName] = useState(''); const onSubmit = () => { updateCity(cityName) fetchTemperature(); } const handleChange = event => { console.log('sdhfaksdfhbksd', event.target.value, cityName) setCityName(event.target.value); } return ( <> <button type="button" className="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop"> Enter City Name </button> <div className="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabIndex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div className="modal-dialog modal-dialog-centered"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="staticBackdropLabel">City Name</h5> <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div className="modal-body"> <input placeholder="type city here" value={cityName} onChange={handleChange} autoFocus={true} /> </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" className="btn btn-primary" data-bs-dismiss="modal" onClick={onSubmit}>Submit</button> </div> </div> </div> </div> </> ) } const mapDispatchToProps = dispatch => { return { updateCity: city => dispatch(updateCity(city)), fetchTemperature: () => dispatch(fetchTemperature()) } } export default connect( null, mapDispatchToProps )(Popup)
Markdown
UTF-8
37
3.671875
4
[]
no_license
# laravel-simple-restfull-api-sanctum
Markdown
UTF-8
6,118
2.515625
3
[]
no_license
SpringBootTemplate ================== # 简介 随着框架使用的不断的更新,后面使用SpringBoot会多,这边准备构建一个SpringBoot项目使用的模版。 所谓模版,和之前一样,就是一个最简单的项目,包含所有最简单的空实现。 <br/> <br/> ## 模版目的 - 1、不熟悉SpringBoot项目的人,在学习了SpringBoot的基础部分之后,能根据这个模版快速上手 - 2、开发团队的项目结构和使用装备的统一,包括目录结构,使用的一些组件上面的统一 - 3、不想重复造轮子,每次新建一个项目很麻烦 <br/> <br/> ## 目录说明 - `src/main/java/` 存放java代码,其中SpringBootTemplateApplication为SpringBoot启动类 - `src/main/resources/` application.yml 全局配置文件 application-data.yml 数据源相关配置文件 application-mvc.yml 页面mvc相关配置文件 application-config.yml 需要引入的一些全局配置 application-dev.yml 开发环境配置 application-prod.yml 生产环境配置 - `src/main/resources/static` 存放各种静态资源文件,如css,js,image等 - `src/main/resources/templates` 存放使用的页面文件,各种html等 - `src/main/resources/mapper` 存放mybatis的sql语句xml文件 <br/> <br/> ## 数据结构 > 表结构定义写法如下 ````sql SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user_tab -- ---------------------------- DROP TABLE IF EXISTS `user_tab`; CREATE TABLE `user_tab` ( `id` int(11) NOT NULL AUTO_INCREMENT, `val` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; SET FOREIGN_KEY_CHECKS = 1; ```` ## 注意事项 1. _项目启动前本机需要启动redis,否则会出现ERRROR_ 2. _测试地址为http://127.0.0.1:8080/test,测试方法全部在UserController中_ <br/> <br/> ## RedisUtil > 新Redis操作工具类,暴露如下操作方法 | 方法名 | 入参 | 出参 | | ------------- | ----------------------------------------- | ------- | | setExpireTime | String key, long timeout | boolean | | delete | String key | void | | hasKey | String key | boolean | | set | String key, Object value | void | | set | String key, Object value, Long expireTime | void | | get | String key | Object | <br/> <br/> ## CacheConfig简单缓存 1、启动类上需要加@EnableCaching注解 2、在需要执行缓存的类上面写上缓存前缀名称 @CacheConfig(cacheNames="user") 3、在查询方法上使用@Cacheable(key = "'list'")配置键的名称 4、在修改方法上使用@CachePut(key = "'list'")配置键的名称 http://127.0.0.1:8080/cache/user/list http://127.0.0.1:8080/cache/user/add http://127.0.0.1:8080/cache/user/delete <br/> <br/> ## FileHandleUtil > 文件上传工具类,上传到与jar包同级的static目录下,开发环境和服务器环境均可 ---------- 方法:upload 入参: inputStream 文件流 path 文件路径,如:image/ filename 文件名,如:test.jpg 出参: 最后文件存放路径为:static/upload/image/test.jpg 文件访问路径为:http://127.0.0.1:8080/upload/image/test.jpg 该方法返回值为:/upload/image/test.jpg ----------- 方法:delete 入参: path: 文件路径,是upload方法返回的路径如:/upload/image/test.jpg ---------- 关联配置: ```` spring: # 静态资源路径 resources: static-locations: classpath:static/,file:static/ ```` <br/> <br/> ## Dockerfile使用步骤 1、使用gradle的bootRepackage进行打包 2、Dockerfile目录下使用命令:docker build -t springboot:v1.0 . 3、启动本地redis,并修改application-dev.yml中redis的IP地址为宿主机的IP地址如:192.168.1.111,mysql的IP地址同理 4、使用命令:docker run --name springbootTemplate -d -p 8080:8080 springboot:v1.0 5、直接访问测试地址即可 ### 注意事项 - `Dockerfile`中的`APP_NAME`对应`jar.baseName-jar.version` - `Dockerfile`中的`APP_PORT`&`EXPOSE`根据项目情况填写 <br/> <br/> ## 快速启动和停止应用的脚本 app.sh脚本为快速启动应用和关闭应用的脚本,使用方法如下: 首先,将你需要发布的jar包,和含有上述内容的脚本app.sh,上传至linux服务器,**注意两者必须处于同一目录**,并给与app.sh相应执行权限,chmod 777 app.sh 然后就可以执行脚本,命令如下 | 命令 | 作用 | | :-: | :-: | | ./app.sh start | 启动应用 | | ./app.sh stop | 关闭应用 | | ./app.sh restart | 重启应用 | | ./app.sh status | 查看应用状态 | 脚本中可以修改的地方: nohup java -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -Xms512M -Xmx4G -jar $appName > /dev/null 2>&1 & 这是最终jar的启动命令,在这里你需要对gc、Xms、Xmx等针对你机器的实际情况修改,还可以添加你所需要的启动参数等。 for i in {5..1} 这里是设置restart的时候等待的时间,因为有的项目在5秒之内可能没有办法正常停止,所以可以调整为10秒,保证应用确实正常停止后再启动 - 脚本至更新1.0.1 1. 启动停止优化 ./app.sh start 默认会启动当前目录下最后放入的jar包,stop同理 2. 启动停止参数优化 ./app.sh start springBootTemplate-0.0.1-SNAPSHOT.jar后面可以跟上项目名称,启动或停止指定的项目 3. 重启指令优化,方便重新发布服务 ./app.sh restart如果当前目录下有两个jar包,会停止前一个放入的jar并备份,然后启动最新放入的jar 如:当前目录情况为 app1.jar 放入文件夹时间为12:00 app2.jar 放入文件夹时间为13:00 app.sh 执行重启指令后,先停止app1.jar,然后备份app1.jar,然后启动app2.jar
Java
UTF-8
1,512
1.804688
2
[]
no_license
package com.ilikezhibo.ggzb.userinfo.myfav; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.FragmentManager; import com.ilikezhibo.ggzb.BaseFragmentActivity; import com.ilikezhibo.ggzb.R; public class MyFavProjectActivity extends BaseFragmentActivity { private MyFavProjectFragment map; private FragmentManager manager; @Override protected void setContentView() { setContentView(R.layout.activity_zhaofang); map = new MyFavProjectFragment(); manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.map, map, "map_fragment") .commit(); } @Override protected void initializeViews() { } @Override protected void initializeData() { } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } @Override protected void onRestart() { super.onRestart(); } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override public void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { manager.getFragments().clear(); super.onDestroy(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } }
Markdown
UTF-8
8,356
2.859375
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "IIR Filter | Microsoft Docs" titleSuffix: ML Studio (classic) - Azure description: Learn how to use the IIR Filter module to create an *infinite impulse response* (IIR) filter. ms.custom: "formulas" ms.date: 05/06/2019 ms.service: "machine-learning" ms.subservice: "studio" ms.topic: "reference" author: xiaoharper ms.author: amlstudiodocs manager: cgronlun --- # IIR Filter *Creates an infinite impulse response filter for signal processing* Category: [Data Transformation / Filter](data-transformation-filter.md) [!INCLUDE [studio-ui-applies-label](../includes/studio-ui-applies-label.md)] ## Module overview This article describes how to use the **IIR Filter** module in Azure Machine Learning Studio (classic), to create an *infinite impulse response* (IIR) filter. Filters are an important tool in digital signal processing, and are used to improve the results of image or voice recognition. In general, a filter is a transfer function that takes an input signal and creates an output signal based on the filter characteristics. For more general information about the user of filters in digital signal processing, see [Filter](data-transformation-filter.md). An **IIR filter** is a particular type of filter; typical uses of an IIR filter would be to simplify cyclical data that includes random noise over a steadily increasing or decreasing trend. The IIR filter you cretae with this module defines a set of constants (or coefficients) that alter the signal that is passed through. The word *infinite* in the name refers to the feedback between the outputs and the series values. After you have defined a filter that meets your needs, you can apply the filter to data by connecting a dataset and the filter to the [Apply Filter](apply-filter.md) module. > [!TIP] > A filter is a transfer function that takes an input signal and creates an output signal based on the filter characteristics. For more general information about the user of filters in digital signal processing, see [Filter](data-transformation-filter.md). After you have defined a filter that meets your needs, you can apply the filter to data by connecting a dataset and the filter to the [Apply Filter](apply-filter.md) module. > [!TIP] > Need to filter data from a dataset or remove missing values? Use these modules instead: > > - [Clean Missing Data](clean-missing-data.md): Use this module to remove missing values or replace missing values with placeholders. > - [Partition and Sample](partition-and-sample.md): Use this module to divide or filter your dataset by criteria such as a range of dates, a specific value, or regular expressions. > - [Clip Values](clip-values.md): Use this module to set a range and keep only the values within that range. ## How to configure IIR Filter 1. Add the **IIR Filter** module to your experiment. You can find this module under **Data Transformation**, in the **Filter** category. 2. For **Order**, type an integer value that defines the number of active elements used to affect the filter's response. The *order* of the filter represents the length of the filter window. For an IIR filter, the minimum order is 4. 3. For **Filter kind**, choose the algorithm that is used to compute filter coefficients. The *filter kind* designates the mathematical transfer function that controls frequency response and frequency suppression. Azure Machine Learning supports these kinds of filters commonly used in digital signal processing: **Butterworth**: A Butterworth filter is also called a *maximally flat magnitude filter* because it constrains the response (change in signal) in the passband and the stopband. **Chebyshev Type 1**: Chebyshev filters are intended to minimize the errors between the idealized and the actual filter characteristics over the range of the filter. Type 1 Chebyshev filters leave more ripple in the passband. **Chebyshev Type 2**: Type 2 Chebyshev filters have the same general characteristics as Type 1 Chebyshev filters, but they leave more ripple in the stopband. 4. For **Filter type**, select an option that defines how the filter will affect the values in the input signal. You can specify that the filter exclude values above or below a cutoff point, or specify that the filter either reject or pass through values in a specified frequency range. **LowPass**: Allows low frequency values (below the cutoff value) to pass and attenuates other values. **HighPass**: Allows high frequency values (above the cutoff value) to pass and attenuates other values. **Bandpass**: Allows signals in the range that is specified by the low and high cutoff values to pass and attenuates other values. **BandStop**: Allows signals outside the range specified by the low and high cutoff values to pass and attenuates values within the range. 5. Specify the high or low cutoff values, or both, as a value between 0 and 1, representing a normalized frequency. For **High cutoff**, type a value that represents the upper frequency boundary. For **Low cutoff**, type a value that represents the lower frequency boundary. 6. For **Ripple**, specify the amount of *ripple* to tolerate when you define your filter. Ripple refers to a small variation that occurs periodically. Ripple is usually considered an unwanted effect, but you can compensate for ripple by adjusting other filter parameters, such as the filter length. Not all filters produce ripple. 7. Add the [Apply Filter](apply-filter.md) module to your experiment, and connect the filter you designed, and the dataset containg the values you want to modify. Use the column selector to specify which columns of the dataset to which the filter should be applied. By default, the [Apply Filter](apply-filter.md) module will use the filter for all selected numeric columns. 8. Run the experiment to apply the transformation. > [!NOTE] > The **IIR Filter** module does not provide the option to create an indicator column. Column values are always transformed in place. ## Examples For examples of how filters are used in machine learning, see this experiment in the [Azure AI Gallery](https://gallery.azure.ai/): - [Filters](https://go.microsoft.com/fwlink/?LinkId=525732): This experiment demonstrates all filter types, using an engineered waveform dataset. ## Technical Notes This section contains implementation details, tips, and answers to frequently asked questions. ### Implementation details An IIR filter returns feed forward and feed backward coefficients, which are represented by way of a transfer function. Here is an example representation: ![transfer function for IIR filters](media/aml-firfiltertransferfunction.png "AML_FIRFilterTransferFunction") Where: - `N`: filter order - `bi`: feed forward filter coefficients - `ai`: feed backward filter coefficients - `x[n]`: the input signal - `y[n]`: the output signal ## Module parameters |Name|Range|Type|Default|Description| |----------|-----------|----------|-------------|-----------------| |Order|[4;13]|Integer|5|Specify the filter order| |Filter kind|Any|IIRFilterKind||Select the kind of IIR filter to create| |Filter type|Any|FilterType||Select the filter band type| |Low cutoff|[double.Epsilon;.9999999]|Float|0.3|Set the low cutoff value| |High cutoff|[double.Epsilon;.9999999]|Float|0.7|Set the high cutoff value| |Ripple|>=0.0|Float|0.5|Specify the amount of ripple in the filter| ## Output |Name|Type|Description| |----------|----------|-----------------| |Filter|[IFilter interface](ifilter-interface.md)|Filter implementation| ## Exceptions |Exception|Description| |---------------|-----------------| |NotInRangeValue|Exception occurs if parameter is not in range.| For a list of errors specific to Studio (classic) modules, see [Machine Learning Error codes](errors/machine-learning-module-error-codes.md). For a list of API exceptions, see [Machine Learning REST API Error Codes](https://docs.microsoft.com/azure/machine-learning/studio/web-service-error-codes). ## See also [Filter](data-transformation-filter.md) [Apply Filter](apply-filter.md) [A-Z Module List](a-z-module-list.md)
Python
UTF-8
516
2.703125
3
[]
no_license
import cv2 image=cv2.imread(r'aman.png') image_gray=cv2.imread(r"aman.png",cv2.IMREAD_GRAYSCALE) face_teacher=cv2.CascadeClassifier(r"E:\image processing\haarcascades\haarcascade_frontalface_default.xml") face=face_teacher.detectMultiScale(image_gray,1.3,5) print(face) for x,y,w,h in face: cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2) print("face location is " ,face) print("number of persion is :",len(face)) cv2.imshow("window",image) #cv2.imshow("gray",image_gray) cv2.waitKey() cv2.destroyAllWindows()
Java
UTF-8
319
3
3
[]
no_license
public class Exception1 { public static void main(String[] args) { int x,y,z = 0; x=8; y=0; try { z=x/y; }catch(ArithmeticException e){ System.out.println(e); } System.out.println(z); } }
Java
UTF-8
870
1.859375
2
[]
no_license
package org.jeesl.api.rest.rs.system; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.jeesl.api.rest.i.system.JeeslTestRestInterface; import org.jeesl.interfaces.util.qualifier.JeeslRestSecured; import org.jeesl.model.json.io.ssi.update.JsonSsiUpdate; import org.jeesl.model.json.system.job.JsonSystemJob; @Path("/rest/test") public interface JeeslTestRest extends JeeslTestRestInterface { @GET @Path("/date/time/public") @Produces(MediaType.TEXT_PLAIN) String dateTimePublic(); @JeeslRestSecured @GET @Path("/date/restricted") @Produces(MediaType.TEXT_PLAIN) String dateTimeRestricted(); @GET @Path("/json/update") @Produces(MediaType.APPLICATION_JSON) JsonSsiUpdate jsonUpdate(); @GET @Path("/json/job") @Produces(MediaType.APPLICATION_JSON) JsonSystemJob jsonJob(); }
Python
UTF-8
3,185
2.9375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# -*- coding: utf-8 -*- """ Created on Sun Jul 21 21:30:33 2019 @author: yoelr """ from numpy import asarray, array from biosteam._utils import wegstein_secant, aitken_secant __all__ = ('BubblePoint',) class BubblePoint: __slots__ = ('gamma', 'P', 'T', 'y') rootsolver = staticmethod(aitken_secant) def __init__(self, gamma): self.gamma = gamma def _T_error(self, T, z_over_P, z, VPs): self.y = z_over_P * array([i(T) for i in VPs]) * self.gamma(z, T) return 1. - self.y.sum() def _P_error(self, P, T, z, Psat_gamma): self.y = z * Psat_gamma / P return 1. - self.y.sum() def solve_Ty(self, z, P): """Bubble point at given composition and pressure **Parameters** **z:** [array_like] Liquid phase composition. **P:** [float] Pressure (Pa). **Returns** **T:** [float] Bubble point temperature (K) **y:** [numpy ndarray] Composition of the vapor phase. >>> from biosteam import Species, BubblePoint, Dortmund >>> gamma = Dortmund(*Species('Ethanol', 'Water')) >>> bp = BubblePoint(gamma) >>> bp.solve_Ty(z=(0.6, 0.4), P=101325) (352.2820850833474, array([0.703, 0.297])) """ z = asarray(z) self.P = P try: self.T = self.rootsolver(self._T_error, self.T, self.T+0.01, 1e-6, args=(z/P, z, [s.VaporPressure for s in self.gamma.species])) except: T = (z * [s.Tb for s in self.gamma.species]).sum() self.T = self.rootsolver(self._T_error, T, T+0.01, 1e-6, args=(z/P, z, [s.VaporPressure for s in self.gamma.species])) self.y = self.y/self.y.sum() return self.T, self.y def solve_Py(self, z, T): """Bubble point at given composition and temperature. **Parameters** **z:** [array_like] Liquid phase composotion. **T:** [float] Temperature (K). **Returns** **P:** [float] Bubble point pressure (Pa). **y:** [numpy ndarray] Vapor phase composition. >>> from biosteam import Species, BubblePoint, Dortmund >>> gamma = Dortmund(*Species('Ethanol', 'Water')) >>> bp = BubblePoint(gamma) >>> bp.solve_Py(z=(0.703, 0.297), T=352.28) (103494.17209657285, array([0.757, 0.243])) """ z = asarray(z) Psat = array([i.VaporPressure(T) for i in self.gamma.species]) Psat_gamma = Psat * self.gamma(z, T) self.T = T try: self.P = self.rootsolver(self._P_error, self.P, self.P-1, 1e-2, args=(T, z, Psat_gamma)) except: P = (z * Psat).sum() self.P = self.rootsolver(self._P_error, P, P-1, 1e-2, args=(T, z, Psat_gamma)) self.y = self.y/self.y.sum() return self.P, self.y def __repr__(self): return f"<{type(self).__name__}: gamma={self.gamma}>"
Shell
UTF-8
643
3.0625
3
[ "MIT" ]
permissive
#!/bin/sh cd $(dirname $0) source $(dirname $0)/config if [ $(pgrep -cx panel) -gt 1 ] ; then printf "%s\n" "The panel is already running." >&2 exit 1 fi trap 'trap - TERM; kill 0' INT TERM QUIT EXIT [ -e "$PANEL_FIFO" ] && rm "$PANEL_FIFO" mkfifo "$PANEL_FIFO" bspc config top_padding $PANEL_HEIGHT bspc control --subscribe > "$PANEL_FIFO" & xtitle -sf 'T%s' > "$PANEL_FIFO" & clock -sf 'S%a %Y-%m-%d %I:%M %p' > "$PANEL_FIFO" & ./notify_mpd -d & cat "$PANEL_FIFO" \ | ./panel_bar \ | lemonbar \ -g "$PANEL_GEOMETRY" \ -f "$FONT" \ -F "$COLOR_FOREGROUND" \ -B "$COLOR_BACKGROUND" & wait
Java
UTF-8
2,686
2.546875
3
[]
no_license
package com.sunmw.web.entity.base; import java.io.Serializable; /** * This is an object that contains data related to the check_repeat_no table. * Do not modify this class because it will be overwritten if the configuration file * related to this class is modified. * * @hibernate.class * table="check_repeat_no" */ public abstract class BaseCheckRepeatNo implements Serializable { public static String REF = "CheckRepeatNo"; // constructors public BaseCheckRepeatNo () { initialize(); } /** * Constructor for primary key */ public BaseCheckRepeatNo ( java.lang.String no, java.lang.String type) { this.setNo(no); this.setType(type); initialize(); } protected void initialize () {} private int hashCode = Integer.MIN_VALUE; // primary key private java.lang.String no; private java.lang.String type; /** * @hibernate.property * column=no * not-null=true */ public java.lang.String getNo () { return this.no; } /** * Set the value related to the column: no * @param no the no value */ public void setNo (java.lang.String no) { this.no = no; this.hashCode = Integer.MIN_VALUE; } /** * @hibernate.property * column=type * not-null=true */ public java.lang.String getType () { return this.type; } /** * Set the value related to the column: type * @param type the type value */ public void setType (java.lang.String type) { this.type = type; this.hashCode = Integer.MIN_VALUE; } public boolean equals (Object obj) { if (null == obj) return false; if (!(obj instanceof com.sunmw.web.entity.CheckRepeatNo)) return false; else { com.sunmw.web.entity.CheckRepeatNo checkRepeatNo = (com.sunmw.web.entity.CheckRepeatNo) obj; if (null != this.getNo() && null != checkRepeatNo.getNo()) { if (!this.getNo().equals(checkRepeatNo.getNo())) { return false; } } else { return false; } if (null != this.getType() && null != checkRepeatNo.getType()) { if (!this.getType().equals(checkRepeatNo.getType())) { return false; } } else { return false; } return true; } } public int hashCode () { if (Integer.MIN_VALUE == this.hashCode) { StringBuilder sb = new StringBuilder(); if (null != this.getNo()) { sb.append(this.getNo().hashCode()); sb.append(":"); } else { return super.hashCode(); } if (null != this.getType()) { sb.append(this.getType().hashCode()); sb.append(":"); } else { return super.hashCode(); } this.hashCode = sb.toString().hashCode(); } return this.hashCode; } public String toString () { return super.toString(); } }
Markdown
UTF-8
2,557
3.046875
3
[]
no_license
# Hexagon Enforcement with ArchUnit In this repository we played around with [ArchUnit](https://www.archunit.org). More specifically we assessed the capabilities to enforce the ideas of the hexagonal architecture. A very good and elaborate explanation of these ideas can be found in an excellent article from Herberto Graca [here](https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together/). The **TL;DR** is: Imagining a hexagon or circle or onion with different layers, dependencies of the modules must always point inwards. Obviously you can go arbitrarily crazy on modules and layers. In our scenario we have only four layers and want to enforce the following rules: ``` Primary Adapters --> Application --> Domain <-- Secondary Adapters ``` ## Git Tags We've prepared git tags to exercise the rule enforcement tests without any hassle. ``` git checkout <tagName> ``` We provide the following tags: * **clean** A small hexagon application which adheres to the architectural rules. * **broken** The same application with a few violations added > Please note, that we will likely not support the git tags for long as the repository evolves ## Run the Tests You can run the tests with Maven: ``` ./mvnw test ``` or your favourite IDE of course. ## Results We explored different ways to enforce the rules. ### Access The ArchUnit API provides several functions to describe "access". It seems that one would have to access a method or field of an object. Simply including a class as a field or so does not cause a violation in this case. For all intents and purposes we're after this approach does not seem feasible. ### Layered Architecture ArchUnit provides a way to specify a layered architecture. However, it only allows to specify how layers may be used, not what layers may use. In case of a violation the test will fail, but highlight the layer that was incorrectly accessed, not the layer that caused the violation. ### Class Dependencies There is also a way to specify dependencies and dependents. This method takes a bit more effort, but provides greater control as it allows to specify how layers may be used, but also which layers they may use. We prefer this approach for exactly that reason. ### Framework Dependencies We also attempted to prohibit the domain layer from accessing the spring framework. Specifying dependencies does not seem to cover annotations. However, we can specify a `DescribedPredicate<JavaAnnotation>` which does the trick.
Python
UTF-8
3,704
3.234375
3
[]
no_license
#!/usr/bin/env python #-*- coding:utf-8 -*- # 多类别逻辑回归 使用gluon # 服饰 FashionMNIST 识别 逻辑回归 # 多类模型跟线性回归的主要区别在于输出节点从一个变成了多个 # 简单逻辑回归模型 y=a*X + b from mxnet import ndarray as nd from mxnet import autograd import random from mxnet import gluon import sys sys.path.append('..') import utils #包含了自己定义的一些通用函数 如下载 载入数据集等 #import matplotlib.pyplot as plt#画图 ########################################################## #### 准备输入数据 ### #一个稍微复杂点的数据集,它跟MNIST非常像,但是内容不再是分类数字,而是服饰 ## 准备 训练和测试数据集 batch_size = 256#每次训练 输入的图片数量 train_data, test_data = utils.load_data_fashion_mnist(batch_size) ########################################################### ### 定义模型 ################## # 使用gluon.nn.Sequential()定义一个空的模型 net = gluon.nn.Sequential() with net.name_scope():#照例我们不需要制定每层输入的大小,gluon会做自动推导 net.add(gluon.nn.Flatten())#使用Flatten层将输入数据转成 batch_size x ? 的矩阵 net.add(gluon.nn.Dense(10))#然后输入到10个输出节点的全连接层 net.initialize() ############################################# ### Softmax和交叉熵损失函数 # softmax 回归实现 exp(Xi)/(sum(exp(Xi))) 归一化概率 使得 10类概率之和为1 # 交叉熵损失函数 将两个概率分布的负交叉熵作为目标值,最小化这个值等价于最大化这两个概率的相似度 # 我们需要定义一个针对预测为概率值的损失函数 # 它将两个概率分布的负交叉熵作为目标值,最小化这个值等价于最大化这两个概率的相似度 # 就是 使得 预测的 1*10的概率分布 尽可能 和 标签 1*10的概率分布相等 减小两个概率分布间 的混乱度(熵) # 具体 真实标签 y=1 , y_lab=[0, 1, 0, 0, 0, 0, 0, 0, 0, 0] # 那么交叉熵就是y_lab[0]*log(y_pre[0])+...+y_lab[n]*log(y_pre[n]) # 注意到yvec里面只有一个1,那么前面等价于log(y_pre[y]) ''' 如果你做了上一章的练习,那么你可能意识到了分开定义Softmax和交叉熵会有数值不稳定性。 因此gluon提供一个将这两个函数合起来的数值更稳定的版本 ''' softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss() ############################################### ### 优化模型 ################################# trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.1}) ############################################# ### 训练 ####################### #learning_rate = .1#学习率 epochs = 7##训练迭代 次数 训练整个训练即的次数 for epoch in range(epochs): train_loss = 0.# 损失 train_acc = 0. #准确度 for data, label in train_data:#训练数据集 样本和标签 with autograd.record():#自动微分 output = net(data) #网络输出 loss = softmax_cross_entropy(output, label)#损失 loss.backward()#向后传播 # 将梯度做平均,这样学习率会对batch size不那么敏感 #SGD(params, learning_rate/batch_size) trainer.step(batch_size) train_loss += nd.mean(loss).asscalar()#损失 train_acc += utils.accuracy(output, label) #准确度 test_acc = utils.evaluate_accuracy(test_data, net)#验证数据集的准确度 print("训练次数 %d. 损失Loss: %f, 训练准确度Train acc %f, 测试准确度Test acc %f" % ( epoch, train_loss/len(train_data), train_acc/len(train_data), test_acc))
Java
UTF-8
819
1.773438
2
[]
no_license
package id.delta.whatsapp.implement; import android.app.Activity; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.whatsapp.data.ft; import com.whatsapp.dw; public class z3 implements OnClickListener { Activity activity; /* renamed from: c */ boolean f41c; ft ej; dw gy; /* renamed from: m */ Integer f42m; /* renamed from: z */ boolean f43z; public z3(dw gy, ft ej, Activity activity, Integer m, boolean z, boolean c) { this.ej = ej; this.activity = activity; this.f42m = m; this.f43z = z; this.f41c = c; this.gy = gy; } public void onClick(DialogInterface arg0, int arg1) { this.gy.a(this.ej, this.activity, this.f42m, this.f43z, this.f41c); } }
Java
UTF-8
334
2.140625
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package com.example.hy.wanandroid.event; /** * Created by 陈健宇 at 2018/12/12 */ public class NetWorkChangeEvent { private boolean isConnection; public NetWorkChangeEvent(boolean isConnection) { this.isConnection = isConnection; } public boolean isConnection() { return isConnection; } }
C#
UTF-8
1,143
2.859375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Collections; using System.Globalization; namespace Ktulhu_App { class ListViewItemComparer : IComparer { private int col, por; public ListViewItemComparer() { col = 0; por = 1; } public ListViewItemComparer(int column, int sort_type) { col = column; por = sort_type; } public int Compare(object x, object y) { if(col==0) return por*String.Compare(((ListViewItem)x).SubItems[col].Text.PadLeft(5,'0'), ((ListViewItem)y).SubItems[col].Text.PadLeft(5,'0'), StringComparison.OrdinalIgnoreCase); if (col == 3) return por * DateTime.Compare(DateTime.Parse(((ListViewItem)x).SubItems[col].Text+" AM"), DateTime.Parse(((ListViewItem)y).SubItems[col].Text+" AM")); return por*String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text,StringComparison.OrdinalIgnoreCase); } } }
C#
UTF-8
1,873
3.4375
3
[ "MIT" ]
permissive
using System; namespace Loops { class Program { public static void Main(string[] args) { do { Console.WriteLine("Which exercise would you like to check? Type 0 to exit."); byte exerciseNumber = byte.Parse(Console.ReadLine()); switch (exerciseNumber) { case 0: Console.WriteLine("Terminating the program..."); break; case 1: Solutions.Ex01(); break; case 2: Solutions.Ex02(); break; case 3: Solutions.Ex03(); break; case 4: Solutions.Ex04(); break; case 5: Solutions.Ex05(); break; case 6: Solutions.Ex06(); break; case 7: Solutions.Ex07(); break; case 8: Solutions.Ex08(); break; case 9: Solutions.Ex09(); break; case 10: Solutions.Ex10(); break; default: Console.WriteLine("That is not a valid exercise number."); break; } if(exerciseNumber == 0) { break; } } while (true); } } }
C#
UTF-8
1,055
2.90625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace proyecto { class MenuRestaurante { public MenuRestaurante() { Console.WriteLine("****************MENU RESTAURANTE****************"); Console.WriteLine("Elija una opcion!!"); Console.WriteLine("1. ADMINISTRACION DE RESTAURANTE"); Console.WriteLine("2. MENU MESAS"); Console.WriteLine("3. MENU DEL PERSONAL"); int opcion = Convert.ToInt32(Console.ReadLine()); switch (opcion) { case 1: //admi del restaurante break; case 2: //menu Mesas break; case 3: MenuPersonal mp = new MenuPersonal(); break; default: break; } } } }
Java
UTF-8
259
2.390625
2
[]
no_license
public class BankTesting { public static void main(String[] args) { BankingApp bankingApp = new BankingApp(12345678, 1234); bankingApp.withdrawCash(1200); bankingApp.depositCash(2000); bankingApp.withdrawCash(200); } }
TypeScript
UTF-8
2,864
2.875
3
[]
no_license
// PickHelper class for detecting raycast from the mouse. import {Object3D, Raycaster, Camera} from "three"; import * as $ from "jquery"; const body = $(document.body); export class PickHelper { private raycaster: Raycaster; private hoveredObject: Object3D; private readonly mouseOverArray: Object3D[]; private canvasEl: JQuery; constructor() { this.raycaster = new Raycaster(); this.hoveredObject = null; this.mouseOverArray = []; this.canvasEl = $("#threejs"); } pick(normalizedPosition : {x: number, y: number}, objs : Object3D[], camera : Camera) { this.raycaster.setFromCamera(normalizedPosition, camera); // get the list of objects the ray intersected const intersectedObjects = this.raycaster.intersectObjects(objs); for (let i = 0; i < this.mouseOverArray.length; i++) { const previouslyHoveredObj = this.mouseOverArray[i]; // Should trigger mouseOut if ((intersectedObjects.length && previouslyHoveredObj !== intersectedObjects[0].object) || intersectedObjects.length === 0) { this.mouseOverArray.splice(i, 1); i--; PickHelper.mouseOut(previouslyHoveredObj); } } // Something was intersected if (intersectedObjects.length) { // pick the first object. It's the closest one this.hoveredObject = intersectedObjects[0].object; if (this.mouseOverArray.includes(this.hoveredObject)) { // Was hovered last frame. // Don't need to do anything else } else { // First time the object was hovered. // Trigger mouseIn this.mouseOverArray.push(this.hoveredObject); PickHelper.mouseIn(this.hoveredObject); } } else { this.hoveredObject = null; } return this.hoveredObject; } static mouseIn(obj : Object3D) { if (obj !== null && obj.userData.classObject) { obj.userData.classObject.onHoverStart(); body.addClass("pointer"); } } static mouseOut(obj : Object3D) { if (obj !== null && obj.userData.classObject) { obj.userData.classObject.onHoverEnd(); body.removeClass("pointer"); } } execute() { if (this.hoveredObject !== null && this.hoveredObject.userData.classObject) { this.hoveredObject.userData.classObject.onClick(); return true; } return false; } scroll(deltaY : number) { if (this.hoveredObject !== null && this.hoveredObject.userData.classObject) { this.hoveredObject.userData.classObject.onScroll(deltaY); return true; } return false; } }
Java
UTF-8
4,419
2.265625
2
[]
no_license
package com.thenextmediagroup.dsod.web.controller; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.thenextmediagroup.dsod.service.AuthorService; import com.thenextmediagroup.dsod.util.BaseResult; import com.thenextmediagroup.dsod.util.StateCodeInformationUtil; import com.thenextmediagroup.dsod.util.ValidationUtil; import com.thenextmediagroup.dsod.web.dto.AuthorPO; import com.thenextmediagroup.dsod.web.dto.AuthorQueryPO; @RestController public class AuthorController { @Autowired private AuthorService authorService; private static Logger logger = Logger.getLogger(AuthorController.class); /** * save author * @param authorPO * @return */ @RequestMapping(method = RequestMethod.POST, value = "/v1/author/save") @ResponseBody public BaseResult save(@RequestBody AuthorPO authorPO) { logger.info("AuthorController class save function:" + authorPO); BaseResult baseResult = new BaseResult(); if (null == authorPO) { baseResult.setCode(StateCodeInformationUtil.AUTHOR_IS_NULL); return baseResult; } if (null == authorPO.getFirstName() || "".equals(authorPO.getFirstName().trim())) { baseResult.setCode(StateCodeInformationUtil.FIRST_NAME_IS_NULL); return baseResult; } //Temporary annotation verification code /*if (null == authorPO.getLastName() || "".equals(authorPO.getLastName().trim())) { baseResult.setCode(StateCodeInformationUtil.LAST_NAME_IS_NULL); return baseResult; } if((authorPO.getFirstName().length() + authorPO.getLastName().length()) > 100) { baseResult.setCode(StateCodeInformationUtil.OVERLENGTH_AUTHOR_NAME); return baseResult; } if(null == authorPO.getCellPhone()) { baseResult.setCode(StateCodeInformationUtil.CELL_PHONE_IS_NULL); return baseResult; } if(!ValidationUtil.isNumber(authorPO.getCellPhone().toString())) { baseResult.setCode(StateCodeInformationUtil.CELL_PHONE_IS_WRONG); return baseResult; } if(null == authorPO.getRole() || "".equals(authorPO.getRole().trim())) { baseResult.setCode(StateCodeInformationUtil.ROLE_IS_NULL); return baseResult; } if(null == authorPO.getEmail() || "".equals(authorPO.getEmail().trim())) { baseResult.setCode(StateCodeInformationUtil.EMAIL_IS_NULL); return baseResult; } if(!ValidationUtil.isEmail(authorPO.getEmail())) { baseResult.setCode(StateCodeInformationUtil.EMAIL_TOKEN_INVALID); return baseResult; }*/ return authorService.save(authorPO); } /** * get all author * @param email * @return */ @RequestMapping(method = RequestMethod.POST, value = "/v1/author/getAll") @ResponseBody public BaseResult getAllAuthor(@RequestBody AuthorQueryPO authorQueryPO) { return authorService.getAllAuthor(authorQueryPO); } /** * delete author by id * @param id * @return */ @RequestMapping(method = RequestMethod.POST, value = "/v1/author/deleteOneById") @ResponseBody public BaseResult deleteOneById(@RequestParam String id) { BaseResult baseResult = new BaseResult(); if (ValidationUtil.isBlank(id)) { baseResult.setCode(StateCodeInformationUtil.ID_IS_NULL); return baseResult; } baseResult = authorService.deleteOneById(id); return baseResult; } @RequestMapping(method = RequestMethod.POST, value = "/v1/author/findOneById") @ResponseBody public BaseResult findOneById(@RequestParam String id) { BaseResult baseResult = new BaseResult(); if (ValidationUtil.isBlank(id)) { baseResult.setCode(StateCodeInformationUtil.ID_IS_NULL); return baseResult; } baseResult = authorService.findOneById(id); return baseResult; } @RequestMapping(method = RequestMethod.POST, value = "/v1/author/editOneById") @ResponseBody public BaseResult editOneById(@RequestBody AuthorPO authorPO) { BaseResult baseResult = new BaseResult(); if (ValidationUtil.isBlank(authorPO.get_id())) { baseResult.setCode(StateCodeInformationUtil.ID_IS_NULL); return baseResult; } baseResult = authorService.editOneById(authorPO); return baseResult; } }
C#
UTF-8
5,666
3.59375
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace labs6 { class Program { static void Print(int[,] Array1, int[,] Array2)//печать матриц(6.2) { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { Console.Write(Array1[i, j] + " "); if (j == 1) { Console.WriteLine(); } } } Console.WriteLine(); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { Console.Write(Array2[i, j] + " "); if (j == 1) { Console.WriteLine(); } } } } static void Multiplication(int[,] matrix1, int[,] matrix2)//умножение матриц(6.2) { int a11, a12, a21, a22; a11 = matrix1[0, 0] * matrix2[0, 0] + matrix1[0, 1] * matrix2[1, 0]; a12 = matrix1[0, 0] * matrix2[0, 1] + matrix1[0, 1] * matrix2[1, 1]; a21 = matrix1[1, 0] * matrix2[0, 0] + matrix1[1, 1] * matrix2[1, 0]; a22 = matrix1[1, 0] * matrix2[0, 1] + matrix1[1, 1] * matrix2[1, 1]; Console.WriteLine(a11 + " " + a12 + "\n" + a21 + " " + a22); } static void AverageTemperature(int numberofmonth, int sum, int[] months)//6.3 { months[numberofmonth] = sum / 30; Console.WriteLine($"в {numberofmonth + 1} месяце примерно выпало осадков: " + months[numberofmonth]); } static string decode(string[] passarray, string str) { char[] array = str.ToLower().ToCharArray(); str = str.Replace(" ", string.Empty); int numOfBytes = str.Length / 8; byte[] bytes = new byte[numOfBytes]; for (int i = 0; i < numOfBytes; i++) { string oneBinaryByte = str.Substring(8 * i, 8); bytes[i] = Convert.ToByte(oneBinaryByte, 2); } byte[] bytesOfNewString = bytes; string password = Encoding.UTF8.GetString(bytesOfNewString); for (int i = 0; i < passarray.Length; i++) { if (password == passarray[i]) { return passarray[i]; } } return "неверно"; } static void Main(string[] args) { Console.WriteLine("\nTask 6.2"); int[,] matrix1 = new int[2, 2]; int[,] matrix2 = new int[2, 2]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { Console.WriteLine($"Введите a({i + 1},{j + 1}) для 1ой и 2ой матрицы:"); matrix1[i, j] = int.Parse(Console.ReadLine()); matrix2[i, j] = int.Parse(Console.ReadLine()); } } Console.WriteLine("1 - напечатать матрицы\n2 - перемножить матрицы\nВыберите необходимую операцию: "); try { start: int operation = int.Parse(Console.ReadLine()); if (operation == 1) { Print(matrix1, matrix2); } else if (operation == 2) { Multiplication(matrix1, matrix2); } else { Console.WriteLine("Ошибка: введено неверное число. Повторите ввод, введите число из представленных на экране: "); goto start; } } catch (FormatException) { Console.WriteLine("Ошибка: введён неверный формат."); } Console.WriteLine("\nTask 6.3"); int sum, numberofmonth = 0; Random rnd = new Random(); int[] temperature = new int[30]; int[] months = new int[12]; for (int m = 0; m < 12; m++) { sum = 0; for (int i = 0; i < 30; i++)//заполнение массива { temperature[i] = rnd.Next(12, 30); sum += temperature[i]; } AverageTemperature(numberofmonth, sum, months); //метод для нахождения средних температур в каждом месяце numberofmonth++; //прибавление для метода } for (int k = 0; k < 12; k++) //сортировка полученного массива { for (int m = 0; m < 12; m++) { if (months[k] < months[m]) { int temp = months[k]; months[k] = months[m]; months[m] = temp; } } } Console.WriteLine("Отсортированный массив: " + string.Join(", ", months)); Console.ReadKey(); } } }
JavaScript
UTF-8
3,948
2.75
3
[]
no_license
module.exports = function (io, roomId) { this.players = [] this.board; this.turn; this.init = function () { this.board = this.newBoard(); for (let key in io.sockets.adapter.rooms[roomId].sockets) { this.players.push(key) } let type = Math.floor(Math.random() * 2) + 1 io.sockets.connected[this.players[0]].type = type; type == 1 ? io.sockets.connected[this.players[1]].type = 2 : io.sockets.connected[this.players[1]].type = 1; io.sockets.connected[this.players[0]].emit('my type', io.sockets.connected[this.players[0]].type) io.sockets.connected[this.players[1]].emit('my type', io.sockets.connected[this.players[1]].type) this.turn = 1; // io.sockets.in(roomId).emit('game start') io.sockets.in(roomId).emit('turn', this.turn) } this.newBoard = function () { return [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] } this.showPlayers = function () { console.log(this.players) } this.getTurn = function () { return this.turn; } this.changeTurn = function () { this.turn == 1 ? this.turn = 2 : this.turn = 1; io.sockets.in(roomId).emit('turn', this.turn) } this.check = function (type, row, col) { if (this.getTurn() == type && this.board[row][col] == 0) { this.board[row][col] = type; this.renderBoard(); if(this.gameIsOver()==-1){ this.changeTurn(); }else{ let _this = this; setTimeout(()=>{ this.init(); },3000) } } } this.renderBoard = function () { io.sockets.in(roomId).emit('renderBoard', this.board) } this.gameIsOver = function () { let ret = -1; //verify O win if (this.board[0][0] == 1 && this.board[0][1] == 1 && this.board[0][2] == 1 || this.board[1][0] == 1 && this.board[1][1] == 1 && this.board[1][2] == 1 || this.board[2][0] == 1 && this.board[2][1] == 1 && this.board[2][2] == 1 || this.board[0][0] == 1 && this.board[1][0] == 1 && this.board[2][0] == 1 || this.board[0][1] == 1 && this.board[1][1] == 1 && this.board[2][1] == 1 || this.board[0][2] == 1 && this.board[1][2] == 1 && this.board[2][2] == 1 || this.board[0][0] == 1 && this.board[1][1] == 1 && this.board[2][2] == 1 || this.board[0][2] == 1 && this.board[1][1] == 1 && this.board[2][0] == 1) { ret = 1 io.sockets.in(roomId).emit('gameIsOver', { type: 1 }); //verify X win } else if (this.board[0][0] == 2 && this.board[0][1] == 2 && this.board[0][2] == 2 || this.board[1][0] == 2 && this.board[1][1] == 2 && this.board[1][2] == 2 || this.board[2][0] == 2 && this.board[2][1] == 2 && this.board[2][2] == 2 || this.board[0][0] == 2 && this.board[1][0] == 2 && this.board[2][0] == 2 || this.board[0][1] == 2 && this.board[1][1] == 2 && this.board[2][1] == 2 || this.board[0][2] == 2 && this.board[1][2] == 2 && this.board[2][2] == 2 || this.board[0][0] == 2 && this.board[1][1] == 2 && this.board[2][2] == 2 || this.board[0][2] == 2 && this.board[1][1] == 2 && this.board[2][0] == 2) { ret = 1 io.sockets.in(roomId).emit('gameIsOver', { type: 2 }); } else if(this.board[0][0] != 0 && this.board[0][1] != 0 && this.board[0][2] != 0 && this.board[1][0] != 0 && this.board[1][1] != 0 && this.board[1][2] != 0 && this.board[2][0] != 0 && this.board[2][1] != 0 && this.board[2][2] != 0) { ret = 1 //draw io.sockets.in(roomId).emit('gameIsOver', { type: 0 }); } return ret; } this.init(); }
C#
UTF-8
1,803
3.09375
3
[ "MIT" ]
permissive
// PennyLogger: Log event aggregation and filtering library // See LICENSE in the project root for license information. using PennyLogger.Internals.Reflection; using System.Collections.Generic; using System.Linq; using System.Text.Json; namespace PennyLogger.Internals.Aggregate { /// <summary> /// Base class for objects that track the aggregate values of a single property as an enumerable type. When /// aggregating enumerable types, PennyLogger tracks the Top-N values along with their counts. /// </summary> /// <typeparam name="T"> /// Property type. Nearly all .NET types can be configured as &quot;enumerable&quot; in PennyLogger. For instance, /// an <see cref="int"/> representing an HTTP status code would be enumerable. /// </typeparam> internal abstract class AggregateEnumerableProperty<T> : AggregateProperty<T> { /// <inheritdoc/> protected AggregateEnumerableProperty(PropertyReflector<T> property, PennyPropertyConfig config) : base(property, config) { } /// <summary> /// Derived classes must implement this method to return the top values and their counts, sorted from highest to /// lowest count. /// </summary> /// <returns>Top values and counts</returns> public abstract IEnumerable<KeyValuePair<T, long>> GetSortedCounts(); /// <inheritdoc/> public override void Serialize(Utf8JsonWriter writer) { var topN = GetSortedCounts() .Select(kvp => KeyValuePair.Create(kvp.Key?.ToString() ?? "(null)", kvp.Value)) .Take(Config.Enumerable.Top) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); JsonSerializer.Serialize(writer, topN); } } }
C#
UTF-8
1,235
2.75
3
[]
no_license
using AutoMapper; using Microsoft.EntityFrameworkCore; using SonicState.Contracts.Repositories; using SonicState.Models.ViewModels; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace SonicState.Data { public class DbRepository<TEntity> : IRepository<TEntity>, IDisposable where TEntity : class { private readonly SonicStateDbContext context; protected DbSet<TEntity> set; protected readonly IMapper mapper; public DbRepository(SonicStateDbContext context, IMapper mapper) { this.context = context; this.set = this.context.Set<TEntity>(); this.mapper = mapper; } public Task Add(TEntity entity) { return this.set.AddAsync(entity); } public IEnumerable<TEntity> All() { return this.set; } public void Delete(TEntity entity) { this.set.Remove(entity); } public void Dispose() { this.context.Dispose(); } public Task<int> SaveChanges() { return this.context.SaveChangesAsync(); } } }
Java
UTF-8
1,168
2.703125
3
[]
no_license
package ioexcel; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class Updatingordeletingcellvalue { public static void main(String[] args) throws Exception { FileInputStream fis=new FileInputStream("C:\\Users\\14388\\Desktop\\selenium\\logindata.xlsx"); XSSFWorkbook wb=new XSSFWorkbook(fis); XSSFSheet sheet=wb.getSheet("sheet1"); int row=sheet.getLastRowNum(); int cell=sheet.getRow(0).getLastCellNum(); for(int i=0;i<row;i++) { XSSFRow rows=sheet.getRow(i); for(int j=0;j<cell;j++) { String cells=rows.getCell(j).toString(); } for(int j=0;j<cell;j++) { String cells=rows.getCell(j).toString(); rows.getCell(j).removeCellComment(); System.out.print(" "+cells); System.out.println(); } } } }
Markdown
UTF-8
2,600
2.53125
3
[]
permissive
% tpm2_getsessionauditdigest(1) tpm2-tools | General Commands Manual # NAME **tpm2_getsessionauditdigest**(1) - Retrieve the command audit attestation data from the TPM. # SYNOPSIS **tpm2_getsessionauditdigest** [*OPTIONS*] # DESCRIPTION **tpm2_getsessionauditdigest**(1) - Retrieve the session audit digest attestation data from the TPM. The attestation data includes the session audit digest and a signature over the session audit digest. The session itself is started with the **tpm2_startauthsession** command. # OPTIONS * **-P**, **\--hierarchy-auth**=_AUTH_: Specifies the authorization value for the endorsement hierarchy. * **-c**, **\--key-context**=_OBJECT_: Context object for the signing key that signs the attestation data. * **-p**, **\--auth**=_AUTH_: Specifies the authorization value for key specified by option **-c**. * **-q**, **\--qualification**=_HEX\_STRING\_OR\_PATH_: Data given as a Hex string or binary file to qualify the quote, optional. This is typically used to add a nonce against replay attacks. * **-s**, **\--signature**=_FILE_: Signature output file, records the signature in the format specified via the **-f** option. * **-m**, **\--message**=_FILE_: Message output file, records the quote message that makes up the data that is signed by the TPM. This is the command audit digest attestation data. * **-f**, **\--format**=_FORMAT_: Format selection for the signature output file. * **-g**, **\--hash-algorithm**: Hash algorithm for signature. Defaults to sha256. * **-S**, **\--session**=_FILE_: The path of the session that enables and records the audit digests. ## References [context object format](common/ctxobj.md) details the methods for specifying _OBJECT_. [authorization formatting](common/authorizations.md) details the methods for specifying _AUTH_. [signature format specifiers](common/signature.md) option used to configure signature _FORMAT_. [common options](common/options.md) collection of common options that provide information many users may expect. [common tcti options](common/tcti.md) collection of options used to configure the various known TCTI modules. # EXAMPLES ```bash tpm2_createprimary -Q -C e -c prim.ctx tpm2_create -Q -C prim.ctx -c signing_key.ctx -u signing_key.pub \ -r signing_key.priv tpm2_startauthsession -S session.ctx --audit-session tpm2_getrandom 8 -S session.ctx tpm2_getsessionauditdigest -c signing_key.ctx -m att.data -s att.sig \ -S session.ctx ``` [returns](common/returns.md) [footer](common/footer.md)
C#
UTF-8
1,873
2.59375
3
[ "Apache-2.0", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "Zlib", "MS-PL", "LicenseRef-scancode-free-unknown", "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
// PasswordDialog.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // namespace Ionic.Zip.Forms { using System; using System.Collections.Generic; using System.Windows.Forms; public partial class PasswordDialog : Form { public enum PasswordDialogResult { OK, Skip, Cancel }; public PasswordDialog() { InitializeComponent(); this.textBox1.Focus(); } public PasswordDialogResult Result { get { return _result; } } public string EntryName { set { prompt.Text = "Enter the password for " + value; } } public string Password { get { return textBox1.Text; } } private void btnOk_Click(object sender, EventArgs e) { _result = PasswordDialogResult.OK; this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { _result = PasswordDialogResult.Cancel; this.Close(); } private void button2_Click(object sender, EventArgs e) { _result = PasswordDialogResult.Skip; this.Close(); } private PasswordDialogResult _result; } }
TypeScript
UTF-8
957
2.5625
3
[]
no_license
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { Item } from '../../shared/model/item'; @Injectable({ providedIn: 'root' }) export class ProductService { list: Item; private listUri = "https://playground.barato.com.br/desafio-front/api/offer/" constructor(private http: HttpClient) { } /** Pega todos os itens da lista */ getProduct (id: string): Observable<Item> { return this.http.get<Item>(this.listUri+id) .pipe( map( item => item), catchError(this.handleError<Item>('getProduct')) ); } /** Caso haja um erro inesperado */ private handleError<T> (operation = 'operation', result?: T) { return (error: any): Observable<T> => { // Let the app keep running by returning an empty result. return of(result as T); }; } }
Java
UTF-8
2,925
2.734375
3
[]
no_license
package edu.undav.research.tinygarden; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import edu.undav.research.tinygarden.BasicClasses.EdgeRelabelGraph; import edu.undav.research.tinygarden.BasicClasses.Graph; import edu.undav.research.tinygarden.BasicClasses.PartitionUnionFind; import edu.undav.research.tinygarden.BasicClasses.VecBool; import edu.undav.research.tinygarden.BasicClasses.VecInt; public class RandomSpanningTrees { Graph _graph; public RandomSpanningTrees(Graph g) { _graph = g; } public List<Integer> getEdgeEnumeration() { List<Integer> edgeEnumeration; edgeEnumeration = new LinkedList<Integer>(); for (int i = 0; i < _graph.getNumberOfEdges(); i++) { edgeEnumeration.add(i); } return edgeEnumeration; } public TreeMatsui generateRandomTree() throws Exception { //System.out.println(list); Graph tree = new Graph(_graph.getNumberOfVertices()); List<Integer> edges = getEdgeEnumeration(); java.util.Collections.shuffle(edges); VecBool addedVertexes = new VecBool(_graph.getNumberOfVertices(), false); Map<Integer, Boolean> loopEdges = new HashMap<Integer, Boolean>(); PartitionUnionFind components = new PartitionUnionFind(_graph.getNumberOfVertices()); for (int i = 0; i < edges.size(); i++) { int iE = edges.get(i); int iV0 = _graph.getVertex0(iE); int iV1 = _graph.getVertex1(iE); if (!addedVertexes.get(iV0) || !addedVertexes.get(iV1)) { tree.insertEdge(iV0, iV1); addedVertexes.set(iV0, true); addedVertexes.set(iV1, true); components.join(iV0, iV1); } else { loopEdges.put(iE, true); } } for (Integer iE : loopEdges.keySet()) { int iV0 = _graph.getVertex0(iE); int iV1 = _graph.getVertex1(iE); if (components.checkHasToJoin(iV0, iV1)) { tree.insertEdge(iV0, iV1); components.join(iV0, iV1); loopEdges.put(iE, false); } } for (Integer iE : loopEdges.keySet()) { int iV0 = _graph.getVertex0(iE); int iV1 = _graph.getVertex1(iE); if (loopEdges.get(iE)) { tree.insertEdge(iV0, iV1); } } VecInt identityMapping = new VecInt(tree.getNumberOfEdges(), 0); for (int i = 0; i < identityMapping.size(); i++) { identityMapping.set(i, i); } return new TreeMatsui(new CustomEdgeRelabelGraph(tree, identityMapping, identityMapping)); } public static class CustomEdgeRelabelGraph extends EdgeRelabelGraph { public CustomEdgeRelabelGraph(Graph g, VecInt edgeLabels, VecInt reverseLabels) { super(g); setMapping(edgeLabels, reverseLabels); } protected void relabelEdges() { } } public static void main(String[] args) throws Exception { Graph g = Graph.buildCompleteGraph(20); RandomSpanningTrees generator = new RandomSpanningTrees(g); for (int i = 0; i < 10; i++) { TreeMatsui tree = generator.generateRandomTree(); System.out.println(tree.labiCantZeros()); } } }
C++
UTF-8
1,283
2.59375
3
[ "MIT" ]
permissive
#ifndef FLOW_H_ #define FLOW_H_ #include "common.h" #include "util.h" using namespace std; struct sFlowinfo { int sock; int flowid; int src_pod; int src_edg; int src_index; int dst_pod; int dst_edg; int dst_index; // unsigned int size; uint64_t size; uint64_t rem_size; // unsigned int rem_size; sFlowinfo& operator=(const sFlowinfo& other); void Copy(sFlowinfo); void Init(); }; enum EPrt_State { eInit=0, //Check whether we need a Request eRQ, //Waiting for the response eSTOP, //Stop signal is received eGO //Go signal is received }; /** * Server-Side Flows! * Client has sent its request including data-size, {src,dst} */ class cFlow { public: cFlow(); cFlow(sFlowinfo); void SetFlow(sFlowinfo info){flowinfo=info;}; int SendData(); void SetCtr(sockaddr_in addr,int ctr_sock){ctr_addr=addr;this->ctr_sock=ctr_sock;}; void SetSrcDst(sockaddr_in src,sockaddr_in dst){src_addr=src;dst_addr=dst;}; public: bool qplus_enable; sockaddr_in ctr_addr; sockaddr_in src_addr; sockaddr_in dst_addr; int ctr_sock; pthread_mutex_t lock; sFlowinfo flowinfo; EPrt_State state; bool done; bool fin_msg_sent; bool startListening; }; #endif /* FLOW_H_ */
Python
UTF-8
889
2.875
3
[]
no_license
import time from collections import defaultdict from loss import calculate_loss def test(model, test_loader, device='cpu'): print("-" * 30, "\nTest:\n") start_epoch_time = time.time() model.eval() metrics = defaultdict(float) for images, labels in test_loader: images = images.to(device) labels = labels.to(device) masks = model(images) loss, metrics = calculate_loss(masks, labels, metrics) epoch_time = time.time() - start_epoch_time print('{:.0f}m {:.0f}s'.format(epoch_time // 60, epoch_time % 60)) print('Best metrics: BCE_loss= {:.3f} , Dice_score= {:.3f} , IOU= {:.3f}, || loss = {:.3f}' .format(metrics['BCE_loss'] / len(test_loader), metrics['Dice_score'] / len(test_loader), metrics['IOU'] / len(test_loader), metrics['loss'] / len(test_loader)))
TypeScript
UTF-8
3,557
2.546875
3
[ "MIT" ]
permissive
import { Component, OnInit, Output, EventEmitter } from '@angular/core'; import * as moment from 'moment'; import { Tea, TeaBuilder } from '../../tea'; class InputTea { public name: string; public date: Date; public type: string; public leafgrade: string; public stocked = true; public aging = false; public region: string; public country: string; public flush: string; public year: number; public purchaselocation: string; public purchasedate: Date; public purchaseprice: number; public size: number; public packaging: string; public sample = false; public pictures: string[]; public comments: string; } @Component({ selector: 'hg-bulk', templateUrl: './bulk.component.html', styleUrls: ['./bulk.component.css'] }) export class BulkComponent implements OnInit { @Output() created: EventEmitter<Tea[]> = new EventEmitter<Tea[]>(); @Output() canceled: EventEmitter<boolean> = new EventEmitter<boolean>(); public teas: InputTea[] = []; public _input = JSON.stringify(this.teas); public isValid = true; get input(): string { return this._input; } set input(str: string) { this._input = str; this.teas = this.parse(this._input); } constructor() { } ngOnInit() { } validate(str: string): boolean { let valid = false; try { JSON.parse(str); valid = true; } catch (e) { console.error(e); } finally { return valid; } } parse(str: string): InputTea[] { console.log('parse', str); if (this.validate(str)) { this.isValid = true; return JSON.parse(str); } else { this.isValid = false; return []; } } convertToTeas(teas: InputTea[]): Tea[] { return teas.map(input => { return new TeaBuilder() .id(-1) .timestamp(moment().format('DD/MM/YYYY H:mm:ss')) .name(input.name) .date(input.date) .type(input.type) .stocked(input.stocked) .aging(input.aging) .region(input.region) .country(input.country) .flush(input.flush) .year(input.year) .purchaselocation(input.purchaselocation) .purchasedate(input.purchasedate) .purchaseprice(input.purchaseprice) .size(input.size) .packaging(input.packaging) .sample(input.sample) .comments(input.comments) .pictures(input.pictures) .build(); }); } addDummySample() { this.input = JSON.stringify([this.createSampleDummy()]); } createSampleDummy(): InputTea { const t = new InputTea(); t.name = 'AwesomeTea \'Foobar\''; t.date = moment().subtract(Math.floor((Math.random() * 10) + 1), 'days').toDate(); t.type = 'Oolong'; t.region = 'Keemun'; t.year = 2003; t.flush = 'Spring'; t.purchaselocation = 'awesometea.com'; t.purchasedate = moment().subtract(Math.floor((Math.random() * 70) + 1), 'days').toDate(); t.purchaseprice = 29.98; t.comments = 'Comments here'; t.pictures = ['pic1.jpg', 'pic2.jpg']; t.country = 'China'; t.size = 400; t.packaging = 'Beeng'; return t; } }
Markdown
UTF-8
11,613
2.71875
3
[ "MIT" ]
permissive
# Visible changes in LazyAlgebra ## Wish list for future developments * Traits must be type-stable. That is deciding the value of a specific trait should be done on the sole basis of the the type of the argument(s). * Optimizations and simplifications of expressions involving mappings belong to two categories: * Automatic simplifications performed by`LazyAlgebra`. These can change the values of multipliers but must not change the coefficients of the mappings. Sadly, it is not possible to have every possible automatic simplifications be type-stable. * The user may explicitly call `simplify(A)` to apply further simplifications that may change the coefficients of the mappings in `A`. For example, assuming `a` is an array, `inv(Diag(a))` automatically yields `Inverse(Diag(a))` while `simplify(inv(Diag(a)))` yields `Diag(1 ./ a)`. These simplifications may not be type-stable. For example the multiplier of a scaled mapping becoming equal to one can be eliminated. * Calling BLAS should be avoided in some cases, either because BLAS is slower than optimized Julia code, or because BLAS may use more than one thread in inappropriate places (e.g., Julia multi-threaded code). * As far as possible, make the code more agnostic of the element type of the arguments. This would be useful to deal with arrays whose elements have non-standard numerical types as physical quantities in the `Unitful` package. ## Branch 0.3 ### Breaking changes * Abstract type `Mapping{L}` has a built-in parameter indicating whether the mapping is linbear of not. This breaks compatibility but simplifies a lot many parts of the code and makes the linear trait decidable at compile time. ### Other changes * Methods `multipler`, `unscaled` can be applied to a mapping type to yield the corresponding type. ## Branch 0.2 ### Version 0.2.5 * Make `set_val!` for sparse operators returns the same result as `setindex!`. ### Version 0.2.3 * Simplify and generalize `vfill!` and `vzero!` to be able to work with `Unitful` elements. * Automatically specialize `multiplier_type` for `Unitful.AbstractQuantity`. ### Version 0.2.2 * Improve `promote_multiplier` and make it easy to extend. The work done by `promote_multiplier` is break in sevral functions: `multiplier_type(x)` yields the *element type* corresponding to `x` (which can be a number, an array of numbers, or a number type), `multiplier_floatingpoint_type(args...)` combines the types given by `multiplier_type` for all `args...` to yield a concrete floating-point type. The method `multiplier_type` is intended to be extended by other packages. ### Version 0.2.1 * Replace `@assert` by `@certify`. Compared to `@assert`, the assertion made by `@certify` may never be disabled whatever the optimization level. * Provide default `vcreate` method for Gram operators. ### Version 0.2.0 * Sub-module `LazyAlgebra.Foundations` (previously `LazyAlgebra.LazyAlgebraLowLevel`) exports types and methods needed to extend or implement `LazyAlgebra` mappings. * The finite difference operator was too limited (finite differences were forcibly computed along all dimensions and only 1st order derivatves were implemented) and slow (because the leading dimension was used to store the finite differences along each dimension). The new family of operators can compute 1st or 2nd derivatives along all or given dimensions. The last dimension of the result is used to store finite differences along each chosen dimensions; the operators are much faster (at least 3 times faster for 200×200 arrays for instance). Applying the Gram composition `D'*D` of a finite difference operator `D` is optimized and is about 2 times faster than applying `D` and then `D'`. Type `SimpleFiniteDifferences` is no longer available, use `Diff` instead (`Diff` was available as a shortcut in previous releases). ## Branch 0.1 ### Version 0.1.0 * New rules: `α/A -> α*inv(A)`. * Exported methods and types have been limited to the ones for the end-user. Use `using LazyAlgebra.LazyAlgebraLowLevel` to use low-level symbols. * Large sub-package for sparse operators which are linear mappings with few non-zero coefficients (see doc. for `SparseOperator` and `CompressedSparseOperator`). All common compressed sparse storage formats (COO, CSC and CSR) are supported and easy conversion between them is provided. Generalized matrix-vector multiplication is implemented and is as fast or significantly faster than with `SparseArrays.SparseMatrixCSC`. * Method `∇(A,x)` yields the Jacobian of the mapping `A` at the variables `x`. If `A` is a linear-mapping, then `∇(A,x)` yields `A` whatever `x`. The new type `Jacobian` type is used to denote the Jacobian of a non-linear mapping. The notation `A'`, which is strictly equivalent to `adjoint(A)`, is only allowed for linear mappings and always denote the adjoint (conjugate transpose) of `A`. * Method `gram(A)` yields `A'*A` for the linear mapping `A`. An associated *decorated type* `Gram` is used to denote this specific expression and some constructions are automaticaly recognized as valid Gram operators. Making this work for more complex constructions (like sums and compositions) would require to change the simplification rules (notably for the adjoint of such constructions). * Methods `has_oneto_axes`, `densearray`, `densevector` and `densematrix` have been replaced by `has_standard_indexing` and `to_flat_array` from `ArrayTools`. * The exported constant `I = Identity()` has been renamed as `Id` to avoid conflicts with standard `LinearAlgebra` package. `Id` is systematically exported while `I` was only exported if not already defined in the `Base` module. The constant `LinearAlgebra.I` and, more generally, any instance of `LinearAlgebra.UniformScaling` is recognized by LazyAlgebra in the sense that they behave as the identity when combined with any LazyAlgebra mapping. * `operand` and `operands` are deprecated in favor of `unveil` and `terms` which are less confusing. The `terms` method behaves exactly like the former `operands` method. Compared to `operand`, the `unveil` method has a better defined behavior: for a *decorated* mapping (that is an instance of `Adjoint`, `Inverse` or `InverseAdjoint`), it yields the embedded mapping; for other LazyAlgebra mappings (including scaled ones), it returns its argument; for an instance of `LinearAlgebra.UniformScaling`, it returns the equivalent LazyAlgebra mapping (that is `λ⋅Id`). To get the mapping embedded in a scaled mapping, call the `unscaled` method. * `unscaled` is introduced as the counterpart of `multiplier` so that `multiplier(A)*unscaled(A) === A` always holds. Previously it was wrongly suggested to use `operand` (now `unveil`) for that but, then the strict equality was only true for `A` being a scaled mapping. These methods also work for instances of `LinearAlgebra.UniformScaling`. * `NonuniformScalingOperator` deprecated in favor of `NonuniformScaling`. * In most cases, complex-valued arrays and multipliers are supported. * Argument `scratch` is no longer optional in low-level `vcreate`. * Not so well defined `HalfHessian` and `Hessian` have been removed (`HalfHessian` is somewhat equivalent to `Gram`). * New `gram(A)` method which yields `A'*A` and alias `Gram{typeof(A)}` to represent the type of this construction. * The `CroppingOperators` sub-module has been renamed `Cropping`. * Add cropping and zero-padding operators. * Left multiplication by a scalar and left/right multiplication by a non-uniform scaling (a.k.a. diagonal operator) is optimized for sparse and non-uniform scaling operators. * Provide `unpack!` method to unpack the non-zero coefficients of a sparse operator and extend `reshape` to be applicable to a sparse operator. * Make constructor of a sparse operator (`SparseOperator`) reminiscent of the `sparse` method. Row and column dimensions can be a single scalar. * Provide utility method `dimensions` which yields a dimension list out of its arguments and associated union type `Dimensions`. * A sparse operator (`SparseOperator`) can be converted to a regular array or to a sparse matrix (`SparseMatrixCSC`) and reciprocally. * Trait constructors now return trait instances (instead of type). This is more *natural* in Julia and avoid having different method names. * Skip bound checking when applying a `SparseOperator` (unless the operator structure has been corrupted, checking the dimensions of the arguments is sufficient to insure that inidices are correct). * Provide `lgemv` and `lgemv!` for *Lazily Generalized Matrix-Vector mutiplication* and `lgemm` and `lgemm!` for *Lazily Generalized Matrix-Matrix mutiplication*. The names of these methods are reminiscent of `xGEMV` and `xGEMM` BLAS subroutines in LAPACK (with `x` the prefix corresponding to the type of the arguments). * Deprecated `fastrange` is replaced by `allindices` which is extended to scalar dimension and index intervals. * Complete rewrite of the rules for simplying complex constructions involving compositions and linear combination of mappings. * Add rule for left-division by a scalar. * `UniformScalingOperator` has been suppressed (was deprecated). * `show` has been extend for mapping constructions. * `contents`, too vague, has been suppressed and replaced by `operands` or `operand`. Getter `multiplier` is provided to query the multiplier of a scaled mapping. Methods `getindex`, `first` and `last` are extended. In principle, direct reference to a field of any base mapping structures is no longer needed. * The multiplier of a scaled mapping can now be any number although applying linear combination of mappings is still limited to real-valued multipliers. * Add `fftfreq`, `rfftdims`, `goodfftdim` and `goodfftdims` in `LazyAlgebra.FFT` and re-export `fftshift` and `ifftshift` when `using LazyAlgebra.FFT`. * Add `is_same_mapping` to allow for automatic simplications when building-up sums and compositions. * Optimal, an more general, management of temporaries is now done via the `scratch` argument of the `vcreate` and `apply!` methods. `InPlaceType` trait and `is_applicable_in_place` method have been removed. * `promote_scalar` has been modified and renamed as `promote_multipler`. * Provide `SimpleFiniteDifferences` operator. * Provide `SparseOperator`. * `LinearAlgebra.UniformScaling` can be combined with mappings in LazyAlgebra. * `UniformScalingOperator` has been deprecated in favor of a `Scaled` version of the identity. * Compatible with Julia 0.6, 0.7 and 1.0. * Provide (partial) support for complex-valued arrays. * Traits replace abstract types such as `Endomorphism`, `SelfAdjointOperator`, etc. Some operator may be endomorphisms or not. For instance the complex-to-complex `FFTOperator` is an endomorphism while the real-to-complex FFT is not. Another example: `NonuniformScaling` is self-adjoint if its coefficients are reals, not if they are complexes. This also overcomes the fact that multiple heritage is not possible in Julia. * The `apply!` method has been rewritten to allow for optimized combination to do `y = α*Op(A)⋅x + β*y` (as in LAPACK and optimized if scalars have values 0, ±1): ```julia apply!(α::Real, Op::Type{<:Operations}, A::LinearMapping, x, β::Real, y) apply!(β::Real, y, α::Real, Op::Type{<:Operations}, A::LinearMapping, x) ```
C++
UTF-8
1,929
2.84375
3
[]
no_license
#include"ArrayTree.h" #include"LBT.h" #include"LLBT.h" #include <iostream> using namespace std; int main(){ ArrayTree<int>a; a.buildRoot(10); a.addLeft(10,6); a.addRight(10,8); a.addRight(6,20); a.addLeft(6,12); a.addRight(8,1); a.addLeft(8,2); cout<<"第六章上机第七题"<<endl; cout<<a.closetRoot(12,2)<<endl; //第六章上机第七题 a.levelOrder(); cout<<endl; a.preOrder(a.getRoot()); cout<<endl; a.inOrder(a.getRoot()); cout<<endl; a.postOrder(a.getRoot()); cout<<endl; LBT<int>b,e; b.buildRoot(10); b.addLeft(10,5); b.addRight(10,6); b.addRight(6, 100); b.addLeft(5,1); //b.addRight(5, 113); b.addLeft(1,9); b.addRight(1,3); b.addLeft(9,20); b.addRight(9, 34); b.addLeft(6,18); //b.addLeft(18,30); //b.addRight(18, 111); b.preOrder(b.getRoot()); cout<<endl; b.inOrder(b.getRoot()); cout<<endl; b.postOrder(b.getRoot()); cout<<endl; cout<<"第六章上机第9 题"<<endl; cout<<b.getBreadth(); //第六章上机第9 题 cout<<endl; cout<<"第六单元 14 题"<<endl; cout<<b.numberNode(b.getRoot())<<endl; //第六单元 14 题 e.buildRoot(10); e.addLeft(10,5); e.addRight(10,6); //b.addRight(6, 100); e.addLeft(5,1); //b.addRight(5, 113); e.addLeft(1,9); e.addRight(1,3); e.addLeft(9,20); e.addRight(9, 34); e.addLeft(6,18); cout<<"测试两棵树是否相似"<<endl; cout<<similar(b.getRoot(),e.getRoot())<<endl; LLBT<int>c; c.buildRoot(10); c.addLeft(10,5); c.addRight(10,6); c.addLeft(5,1); c.addLeft(1,9); c.addRight(1,3); c.addLeft(9,20); c.addLeft(6,18); c.addLeft(18,30); c.preOrder(c.getRoot()); cout<<endl; c.inOrder(c.getRoot()); cout<<endl; c.postOrder(c.getRoot()); cout<<endl; cout<<endl; cout<<"第六单元 上机第十二 题"<<endl; //c.findNPpre(10);//测试 // 第六单元 上机第十二 题 c.findNPPost(30); //测试 // 第六单元 上机第十三 题 注意两题不能同时测试 return 0; }
C++
UTF-8
408
2.5625
3
[ "MIT" ]
permissive
/* This file belongs to RendererLib. See LICENSE file in root folder. */ #ifndef ___Renderer_MemoryHeap_HPP___ #define ___Renderer_MemoryHeap_HPP___ #pragma once #include "RendererPrerequisites.hpp" namespace renderer { /** *\~english *\brief * Specifies a memory heap. *\~french *\brief * Spécifie un tas mémoire. */ struct MemoryHeap { uint64_t size; MemoryHeapFlags flags; }; } #endif
Markdown
UTF-8
1,398
2.640625
3
[]
no_license
#### Metodología para crear una relacion ghedsh o extender información ghedsh desde Moodle * Exporto el calificador desde Moodle a CSV, los campos que me interesan * Uso [TableTool](https://github.com/jakob/TableTool) un editor de CSV par mac os muy útil * Con el editor [TableTool](https://github.com/jakob/TableTool) elimino columnas, etc. * Ahora puedo importar el fichero a ghedsh para - Establecer una relacion ghedsh (`new relation file.csv`) - aumentar la información de la gente de la organizacióna (`new people info file.csv`) #### Dudas * ¿Que pasa con el hecho de que GitHub Classroom ahora añade a los alumnos como contributors y no como miembros de la organización? - Véase el issue [[Feature request] Add students as organization member after accepting first assignment #1078](https://github.com/education/classroom/issues/1078) - Fixed. Was a bug of classroom. They changed the behavior * ¿Habrá que añadirle a ghedsh un comando `contributors` para encontrar los alumnos? * ¿Automatizar el paso de contributor a members? * [Converting an outside collaborator to an organization member](https://help.github.com/articles/converting-an-outside-collaborator-to-an-organization-member/) * [Adding outside collaborators to repositories in your organization](https://help.github.com/articles/adding-outside-collaborators-to-repositories-in-your-organization/)
C
UTF-8
3,386
2.59375
3
[]
no_license
/* * OLECLIP.C * * Routines to handle placing Native, ObjectLink, and OwnerLink * information on the clipboard. * * Copyright(c) Microsoft Corp. 1992-1994 All Rights Reserved * Win32 version, January 1994 */ #ifdef MAKEOLESERVER #include <windows.h> #include <ole.h> #include "cosmo.h" #include "oleglobl.h" /* * FOLECopyNative * * Purpose: * Allocates a memory block for Native data and places it on the clipboard, * assuming that the application has opened the clipboard. * * Parameters: * pOLE LPXOLEGLOBALS containing clipboard formats. * * Return Value: * BOOL TRUE if the data was copied, FALSE otherwise. */ BOOL WINAPI FOLECopyNative(LPXOLEGLOBALS pOLE) { HGLOBAL hMem; hMem=HGetPolyline(pGlob->hWndPolyline); //Place Native data on clipboard. if (NULL==hMem) return FALSE; SetClipboardData(pOLE->cfNative, hMem); return TRUE; } /* * FOLECopyLink * * Purpose: * Places ObjectLink OR OwnerLink information on the clipboard. * This function assumes that the application already has the * clipboard open. * * Parameters: * pOLE LPXOLEGLOBALS containing clipboard formats. * fOwnerLink BOOL indicating to set OwnerLink (TRUE)/ObjectLink (FALSE) * pszDoc LPSTR to the document name. * * Return Value: * BOOL TRUE if copying to the clipboard was successful. * FALSE on any failure. */ BOOL WINAPI FOLECopyLink(LPXOLEGLOBALS pOLE, BOOL fOwnerLink, LPSTR pszDoc) { HGLOBAL hMem; OLECLIPFORMAT cf; //Retrieve a handle to the OwnerLink/ObjectLink format. hMem=HLinkConstruct(rgpsz[IDS_CLASSCOSMO], pszDoc, rgpsz[IDS_FIGURE]); if (NULL==hMem) return FALSE; //Set one or the other format. cf=(fOwnerLink) ? (pOLE->cfOwnerLink) : (pOLE->cfObjectLink); hMem=SetClipboardData(cf, hMem); return (NULL!=hMem); } /* * HLinkConstruct * * Purpose: * Builds an ObjectLink and OwnerLink text string for OLE clipboard * interaction in the format of "classname\0document\0object\0\0" * * Parameters: * pszClass LPSTR to the classname. * pszDoc LPSTR to the document name. * pszObj LPSTR to the object name. * * Return Value: * HGLOBAL Global memory handle to an block containing * the three strings with the appropriate separator. */ HGLOBAL WINAPI HLinkConstruct(LPSTR pszClass, LPSTR pszDoc, LPSTR pszObj) { HGLOBAL hMem; UINT cch1, cch2, cch3; LPSTR psz; if (NULL==pszClass || NULL==pszDoc || NULL==pszObj) return NULL; //We'll need lengths later. cch1=lstrlen(pszClass); cch2=lstrlen(pszDoc); cch3=lstrlen(pszObj); //Extra 4 is for the null-terminators. hMem=GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, (DWORD)(4+cch1+cch2+cch3)); if (NULL==hMem) return NULL; psz=GlobalLock(hMem); lstrcpy(psz, pszClass); psz+=cch1+1; lstrcpy(psz, pszDoc); psz+=cch2+1; lstrcpy(psz, pszObj); *(psz+cch3+1)=0; //Add the final null terminator. GlobalUnlock(hMem); return hMem; } #endif //MAKEOLESERVER
Java
UTF-8
986
2.3125
2
[]
no_license
package br.com.rest_assured.steps; import io.cucumber.java.pt.Quando; import io.restassured.response.ValidatableResponse; import static br.com.rest_assured.core.GlobalValidatableResponse.setvResponse; import static io.restassured.RestAssured.given; public class DeleteStep{ ValidatableResponse vResponse; @Quando("^removo a conta com id \"(.*?)\" na rota \"(.*?)\"$") public void removoAContaComIdNaRota(String conta_id, String rota) throws Throwable { vResponse = given() .header("Authorization", "JWT " + BaseStep.token) .when() .delete(rota + "/" + conta_id) .then() ; setvResponse(vResponse); } @Quando("^removo a movimentação com id \"(.*?)\" na rota \"(.*?)\"$") public void removoAMovimentaçãoComIdNaRota(String id, String rota) throws Throwable { vResponse = given() .header("Authorization", "JWT " + BaseStep.token) .when() .delete(rota + "/" + id) .then() ; setvResponse(vResponse); } }
PHP
UTF-8
1,105
2.5625
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateContractItemsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('contract_items', function (Blueprint $table) { $table->unsignedBigInteger('id'); $table->unsignedBigInteger('record_id'); $table->unsignedInteger('type_id'); $table->integer('quantity'); $table->boolean('is_singleton'); $table->boolean('is_included'); $table->primary(['id', 'record_id', 'type_id']); $table->foreign('id')->references('id')->on('contracts')->onDelete('cascade')->onUpdate('cascade'); $table->foreign('type_id')->references('id')->on('types')->onDelete('cascade')->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('contract_items'); } }
Java
UTF-8
1,428
3.1875
3
[]
no_license
package game.logic.cards; import game.graphic.GraphicManager; import game.graphic.PlayerType; import game.logic.LogicManager; import game.logic.battleFields.LineType; public class MagicCatalyst extends CardLogic { MagicCatalyst(String name, int power, int cost, String imageURL, CardType cardType, int specialPower) { super(name, power, cost, imageURL, cardType, specialPower); this.setUpdateGraphics(true); } @Override public void action(LogicManager logicManager, GraphicManager graphicManager, LineType frontLineType, PlayerType playerType) { PlayerType newPlayerType; // Changes the player type to opposite if (playerType == PlayerType.player) { newPlayerType = PlayerType.opponent; } else { newPlayerType = PlayerType.player; } // Increases power of this card by +X for each special card that opponent has in same battle front for (CardLogic cardLogic : logicManager.getFrontLine(frontLineType, newPlayerType).getCardList()) { if (cardLogic.getCardType() != CardType.BattleCard) { this.setCurrentPower(this.getCurrentPower() + getSpecialPower()); } } } @Override public String getDescription() { return "When used this card gets +" + getSpecialPower() + " increased power for every enemy special card on the same battle front."; } }
Rust
UTF-8
1,445
3.203125
3
[ "MIT" ]
permissive
use crate::rom::Rom; pub fn init(rom: Rom) -> Box<Mapper> { match rom.header.mapper() { 0 => Box::new(MapperZero::new(rom)), id @ _ => panic!("Unimplemented mapper {}", id), } } pub trait Mapper { fn read(&self, addr: u16) -> u8; fn write(&mut self, addr: u16, val: u8); fn step(&mut self); } pub struct MapperZero { rom: Rom, bank: usize, } impl MapperZero { pub fn new(rom: Rom) -> MapperZero { MapperZero { rom: rom, bank: 0 } } } impl Mapper for MapperZero { fn read(&self, addr: u16) -> u8 { match addr { 0x0000...0x1FFF => self.rom.chr[addr as usize], 0x6000...0x7FFF => self.rom.sram[(addr - 0x6000) as usize], 0x8000...0xBFFF => self.rom.prg[self.bank * 0x4000 + (addr - 0x8000) as usize], a if a >= 0xC000 => { self.rom.prg [(self.rom.header.prg_rom_size as usize - 1) * 0x4000 + (a - 0xC000) as usize] } _ => panic!("NO!"), } } fn write(&mut self, addr: u16, val: u8) { match addr { 0x0000...0x2000 => self.rom.chr[addr as usize] = val, 0x6000...0x8000 => self.rom.sram[(addr - 0x6000) as usize] = val, a if a >= 0x8000 => self.bank = (val % self.rom.header.prg_ram_size) as usize, _ => println!("Invalid write location {}", addr), } } fn step(&mut self) {} }
C++
UTF-8
1,604
3.34375
3
[]
no_license
#include "Graph.h" template<class NODE,class EDGE> Graph<NODE,EDGE>::Graph(bool (*comp_node)(NODE,NODE),bool (*comp_edge)(EDGE,EDGE) ){ fp_compare_node = comp_node; fp_compare_edge = comp_edge; } template<class NODE,class EDGE> size_t Graph<NODE,EDGE>::add_vertex(NODE node){ std::vector<SpecialNode<NODE,EDGE>> vec; vec.push_back( SpecialNode<NODE,EDGE>(node) ); data.push_back(vec); return data.size()-1; } template<class NODE,class EDGE> size_t Graph<NODE,EDGE>::is_vertex_available(NODE v){ for(size_t c_j=0;c_j<data.size();c_j++){ if ( (*fp_compare_node)(v,data[c_j][0].node) ) return c_j; c_j++; } return -1; } template<class NODE,class EDGE> Graph<NODE,EDGE>& Graph<NODE,EDGE>::add_edge(NODE &from,NODE &to,EDGE &edge){ size_t from_node; if ( ( from_node = is_vertex_available(from) ) == -1 ) from_node = add_vertex(from); if ( is_vertex_available(to) == -1 ) add_vertex(to); SpecialNode<NODE,EDGE> second_vertex(to,edge); data[from_node].push_back(second_vertex); return *this; } template<class NODE,class EDGE> NODE* Graph<NODE,EDGE>::destination_node(NODE &n,EDGE &e){ size_t temp = is_vertex_available(n); if ( temp == -1 ) throw "Node is not present"; // for(auto& each_neighbor : data[temp] ) { if ( (*fp_compare_edge)(e,each_neighbor.edge) ) { return &each_neighbor.node; } } throw "No neighbor is connected from such edge"; } template<class NODE,class EDGE> Graph<NODE,EDGE>::~Graph(){ for( auto& i : data ){ i.clear(); } } ////////////////////////////////////////////
Markdown
UTF-8
2,451
3.265625
3
[]
no_license
### 一、解决方法:当数据库发生这种操作故障时,可以按如下操作步骤可解决此方法,打开数据库里的Sql 查询编辑器窗口,运行以下的命令。 #### 1、修改数据库为紧急模式 ```Python ALTER DATABASE [dbname] SET EMERGENCY ``` #### 2、使数据库变为单用户模式 ```Python ALTER DATABASE [dbname] SET SINGLE_USER ``` #### 3、修复数据库日志重新生成,此命令检查的分配,结构,逻辑完整性和所有数据库中的对象错误。当您指定“REPAIR_ALLOW_DATA_LOSS”作为DBCC CHECKDB命令参数,该程序将检查和修复报告的错误。但是,这些修复可能会导致一些数据丢失 ```Python DBCC CheckDB ([dbname], REPAIR_ALLOW_DATA_LOSS) ``` #### 4、使数据库变回为多用户模式 ```Python ALTER DATABASE [dbname] SET MULTI_USER ``` #### ALTER DATABASE [dbname] SET SINGLE_USER这一句如果程序还在不停重连好像就会一直执行不完,我试过改成这句即可: ```Python ALTERDATABASE [dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE ``` ### 二、MS SQL 数据库状态为SUSPECT的处理方法 ```Python 当SQL SERVER数据库状态为质疑(SUSPECT)状态时,我们可以用以下方法来处理: 1. 修改数据库为紧急模式:ALTER DATABASE DBName SET EMERGENCY . 2. 检查数据库的完整性:DBCC CHECKDB(‘DBName’) 3. 检查没有错误则恢复数据库为正常模式:ALTER DATABASE DBName SET ONLINE; 4 如检查数据库有错误则修改数据库为单用户模式,依情况选择以下命令行进行修复数据; DBCC CHECKDB('DBName', REPAIR_FAST); DBCC CHECKDB('DBName', REPAIR_REBUILD); DBCC CHECKDB('DBName', REPAIR_ALLOW_DATA_LOSS); ``` ```Python ALTER DATABASE DBName SET EMERGENCY /* 修改数据库为紧急模式*/ ALTER DATABASE DBName SET SINGLE_USER /* 修改数据库为单用户模式*/ ALTER DATABASE DBName SET MULTI_USER /* 修改数据库为多用户模式*/ ALTER DATABASE DBName SET ONLINE /* 数据库从紧急&单用户&多用户模式恢复为正常模式*/ DBCC CHECKDB('DBName') /* 检查数据库完整性*/ DBCC CHECKDB('DBName', REPAIR_FAST) /* 快速修复数据库*/ DBCC CHECKDB('DBName', REPAIR_REBUILD) /* 重建索引并修复*/ DBCC CHECKDB('DBName', REPAIR_ALLOW_DATA_LOSS) /*如果必要允许丢失数据修复,数据库修复需在单用户模式下进行 ```
C++
UTF-8
317
2.875
3
[]
no_license
#ifndef DATEIMPL_H #define DATEIMPL_H #include <iostream> #include <iomanip> #include <string> class DateImpl { public: DateImpl( int day, int month ) { d = day; m = month; } virtual void tell() = 0; int getDay() const { return d;} int getMonth() const { return m;} protected: int d, m; }; #endif
Python
UTF-8
4,198
2.8125
3
[]
no_license
import numpy as np import random import pygame sizePixel = 4 fireWidth = 100 fireHeight = 100 debug = False fireColorsPalette = [ (7, 7, 7), (31, 7, 7), (47, 15, 7), (71, 15, 7), (87, 23, 7), (103, 31, 7), (119, 31, 7), (143, 39, 7), (159, 47, 7), (175, 63, 7), (191, 71, 7), (199, 71, 7), (223, 79, 7), (223, 87, 7), (223, 87, 7), (215, 95, 7), (215, 95, 7), (215,103, 15), (207,111, 15), (207,119, 15), (207,127, 15), (207,135, 23), (199,135, 23), (199,143, 23), (199,151, 31), (191,159, 31), (191,159, 31), (191,167, 39), (191,167, 39), (191,175, 47), (183,175, 47), (183,183, 47), (183,183, 55), (207,207,111), (223,223,159), (239,239,199), (255,255,255)] pygame.init() pygame.display.set_caption("Doom Fire") clock = pygame.time.Clock() fonts = (pygame.font.SysFont("Arial", 10), pygame.font.SysFont("Arial", 14)) def start(): createDataFireStructureAndFireSource() renderFire() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() # Number of frames per secong e.g. 60 clock.tick(60) pygame.display.update() calculateFirePropagation() def createDataFireStructureAndFireSource(): global firePixels firePixels = np.zeros((fireHeight, fireWidth)) firePixels[-1, :] = 36 def calculateFirePropagation(): for column in range(0, fireWidth): for row in range(0, fireHeight-1): updateFireIntensity(row,column) renderFire() def updateFireIntensity(currentRow, currentColumn): if currentRow >= fireHeight: return decay = int(random.random()*3) randomColumn = int(random.randint(0, 3)) belowPixelFireIntensity = firePixels[currentRow + 1, currentColumn] if belowPixelFireIntensity - decay >= 0: newFireIntensity = belowPixelFireIntensity - decay else: newFireIntensity = 0 if currentRow - randomColumn >= 0: if currentColumn + randomColumn > fireWidth: firePixels[currentRow, currentColumn - randomColumn] = newFireIntensity else: firePixels[currentRow, currentColumn + randomColumn - 1] = newFireIntensity else: firePixels[currentRow, currentColumn] = newFireIntensity def renderFire(): if debug: debugSize = 40 screen = pygame.display.set_mode( (fireWidth * debugSize + fireWidth + 1, fireHeight * debugSize + fireHeight + 1), 0, 32) screen.fill((0, 0, 0)) for row in range(0, fireHeight): for column in range(0, fireWidth): fireIntensity = int(firePixels[row, column]) positionPixelIndex = (debugSize * column + column + 1, debugSize * row + row + 1) pygame.draw.rect(screen, (255, 255, 255), pygame.Rect(positionPixelIndex, (debugSize, debugSize))) textPixelIndex = fonts[0].render(str(row) + "," + str(column), True, (120, 120, 120)) screen.blit(textPixelIndex, (positionPixelIndex[0] + debugSize - (textPixelIndex.get_width()), positionPixelIndex[1] + textPixelIndex.get_height() / 8)) textFireIntensity = fonts[1].render(str(fireIntensity), True, fireColorsPalette[fireIntensity]) screen.blit(textFireIntensity, ( positionPixelIndex[0] + debugSize / 2 - textFireIntensity.get_width() / 2, positionPixelIndex[1] + debugSize / 2 - textFireIntensity.get_height() / 4)) else: sizeScreen = (fireWidth * sizePixel, fireHeight * sizePixel) screen = pygame.display.set_mode(sizeScreen,0,32) screen.fill(fireColorsPalette[0]) screen.lock() for row in range(0, fireHeight): for column in range(0, fireWidth): fireIntensity = int(firePixels[row, column]) pygame.draw.rect(screen, fireColorsPalette[fireIntensity], [column * sizePixel, row * sizePixel, sizePixel, sizePixel]) screen.unlock() start()
PHP
UTF-8
756
3.21875
3
[ "MIT" ]
permissive
<?php namespace mle86\Enum\Tests\Helper; use mle86\Enum\AbstractEnum; /** * @internal * This dummy enum accepts a few different input values * and they're all different PHP types! * (Except for "97" and "", just to see if ""/`null`/`false` are treated differently) */ class MixedTypeEnum extends AbstractEnum { public const ZSV = ""; public const STRINGV = "97"; public const INTV = 98; public const FLOATV = 99.9; public const NULLV = null; // Yes, that's also a valid enum value here public const BOOLV = false; public static function all(): array { return [ self::ZSV, self::STRINGV, self::INTV, self::FLOATV, self::NULLV, self::BOOLV, ]; } }
Markdown
UTF-8
1,726
3.296875
3
[]
no_license
# MessageApp MessageApp is an mobile application (Android only) for secure messaging that implement different cryptographic methods to obtain a secure communication between users. This project was developed through an Android mobile application that implements the functionalities of a secure communication method. Those functionalities are based on symmetric cryptography, Android software development (SDK) and Java programming techniques. At first sight, application allow the user to choose between the types of communication, meaning that the user can send an encrypted message or an unencrypted message where both types of communication are using Short Message Service (SMS) technology. The part of encrypted message is where the functionalities of symmetric cryptography are used for. For encrypted communication it is necessary to validate between users, this being implemented through the use of the QR Code scanning functionality. This functionality is allowed after the user generates in real time, his own private session key and this key is converted into a QR Code. This key is generated by a random number generator whose entropy underlies the use of the device's accelerometer, and is then used to encrypt messages. Following the validation process, the private session key of each scanned user is stored and this is used in the message decryption process. Through the validation process, the application benefits from the End-to-end encryption type. Both the encryption process and the decryption process are part of the XXTEA cryptosystem algorithm. With all these functionalities, I have developed an application interface that is as user-friendly as possible and as intuitive as possible for any users.
JavaScript
UTF-8
186
3.140625
3
[]
no_license
function str(number) { tmp = "" if (number % 2 == 0) { tmp = "парне"; console.log(tmp); } else { tmp = "непарне"; console.log(tmp); } return tmp; }
Markdown
UTF-8
213
2.578125
3
[]
no_license
### OO Principles - Encapsulate what varies. - Favor composition over inheritance. - Program to interfaces(or superclases) not implementations. - Strive for loosely coupled designs between objects that interact.
C++
UTF-8
399
2.546875
3
[]
no_license
#include "usuario.h" usuario::usuario(){ } usuario::~usuario(){ } void usuario::setUser(string pUser){ user_name = pUser; } string usuario::getUser(){ return user_name; } void usuario::setCorreo(string pCorreo){ correo = pCorreo; } void usuario::setPass(string pPass){ password = pPass; } string usuario::getPass(){ return password; } string usuario::getCorreo(){ return correo; }
Markdown
UTF-8
2,031
3.15625
3
[]
no_license
--- layout: post title: How-to-add-custom-TrendLine-in-Chart | Windows Forms | Syncfusion description: how to add custom trendline in chart platform: windowsforms control: chart documentation: ug --- # How to add custom TrendLine in Chart TrendLines are used to draw lines in the ChartArea. They can be added to the chart using the TrendLineAdder class. TrendLines can also be drawn using the Mouse Events. In this case, you will have to make use of the Utility class to listen to mouse events and convert them into trendlines. You can draw any number of trendlines, and can set different colors to differentiate them. {% tabs %} {% highlight c# %} // Creating Custom Points ChartPoint ptStart = this.chart.ChartArea.GetValueByPoint(start); ChartPoint ptEnd = this.chart.ChartArea.GetValueByPoint(end); ChartSeries series = this.chart.Model.NewSeries("TrendLine", ChartSeriesType.Line); series.Points.Add(ptStart); series.Points.Add(ptEnd); this.chart.Series.Add(series); series.LegendItem.Visible = false; // Specify the color for the lines. series.Style.Interior = new Syncfusion.Drawing.BrushInfo(ptStart.YValues[0] < ptEnd.YValues[0] ? Color.DarkGreen : Color.Red); {% endhighlight %} {% highlight vb %} ' Creating Custom Points Dim tLineAdder As TrendLineAdder Dim ptStart As ChartPoint = Me.chart.ChartArea.GetValueByPoint(start) Dim ptEnd As ChartPoint = Me.chart.ChartArea.GetValueByPoint(end_Renamed) Dim series As ChartSeries = Me.chart.Model.NewSeries("TrendLine", ChartSeriesType.Line) series.Points.Add(ptStart) series.Points.Add(ptEnd) Me.chart.Series.Add(series) series.LegendItem.Visible = False ' Specify the color for the lines. If ptStart.YValues(0) < ptEnd.YValues(0) Then series.Style.Interior = New Syncfusion.Drawing.BrushInfo(Color.DarkGreen) Else series.Style.Interior = New Syncfusion.Drawing.BrushInfo(Color.Red) End If {% endhighlight %} {% endtabs %} ![Chart Trendline](How-to-add-custom-TrendLine-in-Chart_images/How-to-add-custom-TrendLine-in-Chart_img1.jpeg)
Java
UTF-8
1,057
2.734375
3
[]
no_license
package com.sunny._01_static_proxy.proxy; import com.sunny._01_static_proxy.domain.Employee; import com.sunny._01_static_proxy.service.EmployeeService; import com.sunny._01_static_proxy.tx.TransactionManager; public class EmployeeServiceProxy implements EmployeeService { private TransactionManager tx; // 事务管理器 private EmployeeService target; // 真实对象/委托对象 public void setTarget(EmployeeService target) { this.target = target; } public void setTx(TransactionManager tx) { this.tx = tx; } public void save(Employee emp) { // 开启事务 tx.begin(); try { target.save(emp); tx.commit(); } catch (Exception e){ e.printStackTrace(); tx.rollback(); } } public void update(Employee emp) { tx.begin(); try { target.update(emp); tx.commit(); } catch (Exception e){ e.printStackTrace(); tx.rollback(); } } }
C
GB18030
977
4.125
4
[]
no_license
#include <stdbool.h> #include <stdio.h> /* * ת Ϊ˼· 1.֪ ʲô 2.m,n֮˳ķŵ һ鵱ȥ 3.forѭ * Ķ һѪ ﷨ ϸڵע ҪˡϤ̵ָСнΪѧϰݽṹ׼ */ bool isPrime(int number) { int i =2; //жһ Dz for(i = 2; i < number; ++i) if(!(number % i)) return false; return true; } int main(void) { int n, m, sum = 0; //˼·Ļ ͱȽϺдˡ int prime[200] = {0, 2};//һ int i =3,cnt=2; scanf("%d%d", &n, &m); for(i = 3, cnt = 2; cnt <= m; ++i) if(isPrime(i)) prime[cnt++] = i; for(cnt = n; cnt <= m; ++cnt) sum += prime[cnt]; printf("%d\n", sum); return 0; }
PHP
UTF-8
1,430
3.0625
3
[]
no_license
<?php namespace Quince\DataImporter\DataObjects; class AdditionalFields { /** * @var array */ protected $base = []; /** * @var array */ protected $relations = []; /** * @param array $additionalFields */ public function __construct(Array $additionalFields) { if (isset($additionalFields['base'])) { $this->setBase($additionalFields['base']); } if (isset($additionalFields['relations'])) { $this->setRelations($additionalFields['relations']); } } /** * @return array */ public function getBaseFields() { return $this->base; } /** * @param array $base */ public function setBase(Array $base) { $this->base = $base; } /** * @param null|string $relation * @return array */ public function getRelationsFields($relation = null) { if (!is_null($relation)) { return $this->relations[$relation]; } return $this->relations; } /** * @param array $relations */ public function setRelations(Array $relations) { foreach ($relations as $relation => $additionalFields) { $this->relations[$relation] = (array) $additionalFields; } } /** * @param string $relation * @return bool */ public function hasForRelation($relation) { return (isset($this->relations[$relation]) && is_array($this->relations[$relation])); } /** * @return bool */ public function hasForBase() { return (!empty($this->base) && is_array($this->base)); } }
C#
UTF-8
2,711
2.953125
3
[ "MIT" ]
permissive
using System.Collections.Generic; using System.Linq; using SampleCashRegister.Discounts; namespace SampleCashRegister { public class Order { private readonly IList<OrderItem> _items = new List<OrderItem>(); private readonly IList<Discount> _discounts = new List<Discount>(); private readonly IList<Coupon> _coupons = new List<Coupon>(); public IList<OrderItem> Items { get { return _items; } } public IList<Discount> Discounts { get { return _discounts; } } public IList<Coupon> Coupons { get { return _coupons; } } public void AddItem(OrderItem orderItem) { _items.Add(orderItem); } public decimal CalculateTotal() { var total = Items.Sum(i => i.Quantity*i.PricePerUnit); var applicableCoupon = GetApplicableCoupon(total); return applicableCoupon == null ? total : ApplyCoupon(applicableCoupon, total); } private decimal ApplyCoupon(Coupon applicableCoupon, decimal total) { applicableCoupon.HasBeenApplied = true; string adjustmentItem = string.Format( "Coupon ${0} off when the bill total (${1}) exceeds ${2}", applicableCoupon.AmountOff, total, applicableCoupon.Threshold); this.AddItem(adjustmentItem).Quantity(1) .PricePerUnit(-applicableCoupon.AmountOff); return total - applicableCoupon.AmountOff; } private Coupon GetApplicableCoupon(decimal total) { return NonAppliedCoupons .OrderBy(c => c.Threshold) .LastOrDefault(c => c.Threshold <= total); } public void ApplyDiscounts() { foreach (var discount in NonAppliedDiscounts) { discount.Apply(this); discount.HasBeenApplied = true; } } private IEnumerable<Discount> NonAppliedDiscounts { get { return _discounts.Where(d => !d.HasBeenApplied); } } private IEnumerable<Coupon> NonAppliedCoupons { get { return _coupons.Where(c => !c.HasBeenApplied); } } public void AddDiscount(Discount discount) { _discounts.Add(discount); } public void AddCoupon(Coupon coupon) { _coupons.Add(coupon); } } }
Swift
UTF-8
844
2.515625
3
[ "MIT" ]
permissive
// // SwiftGenKit // Copyright © 2020 SwiftGen // MIT Licence // import Foundation import PathKit extension Strings { final class StringsFileParser: StringsFileTypeParser { private let options: ParserOptionValues init(options: ParserOptionValues) { self.options = options } static let extensions = ["strings"] // Localizable.strings files are generally UTF16, not UTF8! func parseFile(at path: Path) throws -> [Strings.Entry] { guard let data = try? path.read() else { throw ParserError.failureOnLoading(path: path) } let dict = try PropertyListDecoder() .decode([String: String].self, from: data) return try dict.map { key, translation in try Entry(key: key, translation: translation, keyStructureSeparator: options[Option.separator]) } } } }
PHP
UTF-8
1,443
2.9375
3
[]
no_license
<?php require_once 'library/facebook/facebook.php'; class Application_Model_Facebook { /** * Facebook application ID. */ const APP_ID = '277351065690291'; /** * Facebook application secret. */ const APP_SECRET = 'a230489cb43bea620029b44414d33176'; /** * Facebook cookie support. */ const COOKIE = true; /** * Base URL of the OAuth dialog. */ const OAUTH_URL = 'https://www.facebook.com/dialog/oauth'; /** * Initialize a Facebook Application. * * The configuration: * - appId: the application ID * - secret: the application secret * - cookie: (optional) boolean true to enable cookie support * - domain: (optional) domain for the cookie * - fileUpload: (optional) boolean indicating if file uploads are enabled * * @param Array $config the application configuration */ public function __construct($config) { // If no appId is specified in the $config array, use self::APP_ID if (!isset($config['appId'])) { $config['appId'] = self::APP_ID; } // If no secret is specified in the $config array, use self::APP_SECRET if (!isset($config['secret'])) { $config['secret'] = self::APP_SECRET; } // If the cookie parameter is not set, use self::COOKIE if (!isset($config['cookie'])) { $config['cookie'] = self::COOKIE; } parent::__construct($config); } public function getUserInfo() { return $this->api('/me'); } }
JavaScript
UTF-8
5,808
2.921875
3
[]
no_license
const USER = 'USER'; const REST = 'REST'; const getByUserId = async (uid, pool) => { const getEvents = `SELECT u.login, u.firstname, u.lastname, u.city AS usercity, res.*, ev.startdate, ev.starttime, ev.eventid FROM events ev INNER JOIN users u ON u.login = ev.userid INNER JOIN restaurants res ON ev.restid = res.id WHERE u.login = $1 AND ev.startdate>=CURRENT_DATE ORDER BY startdate ASC, starttime ASC`; let events; await pool.query(getEvents, [uid]) .then(res => events = res.rows) .catch(err => console.log(err)); return events; } const getFollowingEvents = async (uid, pool) => { let followingEvents = []; const getFollowingList = `SELECT f.sourceFriend, f.destinationFriend FROM friends f WHERE sourceFriend = $1`; let followList; await pool.query(getFollowingList, [uid]) .then(res => followList=res.rows) .catch(err => console.log(err)); followList = followList.map(rowobj => rowobj.destinationfriend); if(followList.length===0){ return followingEvents; } const getEventsByList = `SELECT u.login, u.firstname, u.lastname, u.city AS usercity, res.*, ev.startdate, ev.starttime, ev.eventid FROM events ev INNER JOIN users u ON u.login = ev.userid INNER JOIN restaurants res ON ev.restid = res.id WHERE u.login = ANY ($1) AND ev.startdate>=CURRENT_DATE ORDER BY startdate ASC, starttime ASC`; await pool.query(getEventsByList, [followList]) .then(res => followingEvents = res.rows) .catch(err => console.log(err)); return followingEvents; } const getByRestId = async (uid, pool) => { const getEvents = `SELECT u.login, u.firstname, u.lastname, u.city AS usercity, res.*, ev.eventid, ev.startdate, ev.starttime FROM events ev INNER JOIN users u ON u.login = ev.userid INNER JOIN restaurants res ON ev.restid = res.id WHERE ev.restid = $1 AND ev.startdate>=CURRENT_DATE ORDER BY startdate ASC, starttime ASC`; let events; await pool.query(getEvents, [uid]) .then(res => events = res.rows) .catch(err => console.log(err)); return events; } const addAttendanceInfo = async(eventslist, pool) => { if(eventslist.length===0){ return []; } let eventsids = eventslist.map(obj => obj.eventid); //batch query for performance const getAttendanceList = `SELECT * FROM eventsattendance WHERE eventid = ANY ($1)`; let attendanceList; await pool.query(getAttendanceList, [eventsids]) .then(res => attendanceList=res.rows) .catch(err => console.log(err)); let eventsplus = {}; attendanceList.forEach( (eventobj) => { if( eventobj.eventid in eventsplus){ eventsplus[eventobj.eventid].count++; eventsplus[eventobj.eventid].attendees.push(eventobj.userid); } else { eventsplus[eventobj.eventid] = { count: 1, attendees: [eventobj.userid] }; } }); eventslist = eventslist.map( (eventobj) => { if(eventobj.eventid in eventsplus){ return { ...eventobj, count: eventsplus[eventobj.eventid].count, attendees: eventsplus[eventobj.eventid].attendees } } else { return { ...eventobj, count: 0, attendees: [] } } }); //at this stage we have the logins of the attendess but that is not enough return eventslist; //array reduce to extract login firstname, lastname of attending and count } exports.getFeedEvents = async (usertype, userdata, pool) => { let events = []; switch(usertype){ case USER: await getByUserId(userdata.login, pool) .then(userevents => events = events.concat(userevents)) .catch(err => console.log(err)); await getFollowingEvents(userdata.login, pool) .then(followevents => events = events.concat(followevents)) .catch(err => console.log(err)); await addAttendanceInfo(events, pool) .then(modified => events=modified) .catch(err => console.log(err)); break; case REST: await getByRestId(userdata.id, pool) .then(restevents => events = events.concat(restevents)) .catch(err => console.log(err)); await addAttendanceInfo(events, pool) .then(modified => events=modified) .catch(err => console.log(err)); break; default: console.log("events.js:162 Something has gone terribly wrong here"); } return events; }
PHP
UTF-8
1,279
2.5625
3
[]
no_license
<div class="horses index"> <table cellpadding="0" cellspacing="0" style="font-size:80%"> <tr> <th>Posicion</th> <th>Caballo</th> <th>Win</th> <th>Place</th> <th>Show</th> </tr> <tr> <td>1&ordm; </td> <td> <?php echo $results[1]['horse'] ?> </td> <td> <?php echo $results[1]['win'] ?> </td> <td> <?php echo $results[1]['place'] ?> </td> <td> <?php echo $results[1]['show'] ?> </td> </tr> <tr> <td>2&ordm; </td> <td> <?php echo $results[2]['horse'] ?> </td> <td> - </td> <td> <?php echo $results[2]['place'] ?> </td> <td> <?php echo $results[2]['show'] ?> </td> </tr> <tr> <td>3&ordm; </td> <td> <?php echo $results[3]['horse'] ?> </td> <td> - </td> <td> - </td> <td> <?php echo $results[3]['show'] ?> </td> </tr> <tr> <th colspan='5'> EXA : <?php echo $exotics['exacta'] ?> , TRI : <?php echo $exotics['trifecta'] ?> , SUP : <?php echo $exotics['superfecta'] ?>. </th> </tr> <?php if (!empty ($retires)) : ?> <tr> <th colspan="5"> Retirados en carrera: <br /> <?php foreach($retires as $r){ echo $r.", "; } ?> </th> </tr> <?php endif; ?> </table> </div>
Markdown
UTF-8
4,677
2.734375
3
[ "MIT" ]
permissive
# EzTheme - The Easy Way to Package your Theme for Cydia Easy (hopefully) way to package the icon themes from all themers. It should be easy, but I'm not all the way done as of this commit. ## Instructions To kick things off, clone this repository onto your computer. *You can use `git` or you can just download the .zip file and extract it somewhere* *Personally, I recommend installing and using git, that way I can issue updates directly to you* *and you can have the updated files in a heartbeat.* Open up your computer's terminal and find your way into the repo. If you cloned this repo in your terminal it should just be in your home folder: `cd ~/eztheme` I go more in depth in the next section If you extracted the zip, find where you put it. Here's an example for your standard Downloads folder: `cd ~/Downloads/eztheme` I can make a standalone script for git if you'd like, for simplicity's sake. *Hacker voice* You're in. The hard part is done. To run the installer, type: `./build` If it wont run, no problem, just type: `chmod +x build` and try again. Nothin' to it :) #### Installing and Using Git with this script Step 1: Install it! ``` sudo add-apt-repository ppa:git-core/ppa sudo apt-get update sudo apt-get install git ``` Step 2: Clone my repository ``` cd ~/ git clone https://github.com/Dajakerboss/eztheme/ ``` Step 3: Enter the folder ``` cd ~/eztheme ``` Boom! To update your files when I update the repo: ``` cd ~/eztheme git pull ``` Easy money! ## Guide to `control` Item | Meaning --- | --- Package | This is the name of the package as-installed. Name according to Cydia and `dpkg` Name | The name as appears in Cydia Version | The current version as you set it Section | Just how the repo will organize this. Don't touch unless the repo maintainers tell you. Architecture | Tells the package manager it was meant for iPhones. Don't touch. Depends | Tells the package manager and cydia what to install alongside this. Maintainer | whoever keeps up with the .deb files. You should keep this as me so I can be contacted for errors in my script. Author | Whoever made the package. You. Description | What pops up in Cydia as the description Icon | Tells Cydia what to use as an icon. Don't touch, I've handled it in the script. ### Editing the `control` file: This script uses the easy-to-learn and popular editing tool `nano` There are only a few things you need to know: Write out (^O or Ctrl + O [as in oh not zero]) saves the file, and enter confirms the save Exit command (^X or Ctrl + X) closes `nano` and continues the program I decided against `vi` or `vim` since I didn't want to include a 5 page document on how to edit 8 lines of a file. There are a few lines that will need your attention: ``` Depends: com.anemonethemeing.anemone ``` If you find that your theme works on a specific iOS range (e.g. iOS 8+), then add `firmware (>= [iOS Version])`, where iOS version is the lowest iOS that will be compatible. Example of this line: `Depends: com.anemonethemeing.anemone, firmware (>= 8.0)` for a theme with iOS support for 8 and up. ``` Package: ``` This is the name that iOS uses. Usually, you'd want to keep it in line with how iOS apps usually go: `com.[author].[package]` For instance, take Sutoroku by Ripped Themer: `com.rippedthemer.sutoroku` ### Preinst and Postinst files These are two files that I automatically place inside of the `~/[package name]_[version]/DEBIAN/` folder. These are the two files that will output messages in Cydia when the package is being installed. If you'd like to change these any, feel welcome to it! The standard command to put out text is `echo "[message]"` You can add lines to your liking :-) ### Side note for compiling I have noted that `dpkg` will throw warnings in my script for the control file. Here's what that means: `dpkg` as it has been installed on your system is not accustomed to haveing certain fields on the control file filled out. It specifies these lines as "user-defined" Cydia and the iOS `dpkg` that Saurik included are in fact compatible with these lines, and require a few. I didn't want to censor these messages in case it threw you an actual error and you needed to let me know. If you see these, it's safe to ignore them :-) If you have *any questions* just email me. I love this stuff. By the way, you don't have to, but I think it'd be beneficial if I was listed as the package maintainer This way, if anyone has problems during installation, I can see where things went wrong in the script and issue a fix for you! Have fun! If you need anything more, feel free to reach out!
C++
UTF-8
1,685
2.890625
3
[]
no_license
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector <int> result; /*//vector<int>::iterator it; for (auto it = nums.begin(); it != nums.end()-1;it++) for (auto it2 = it+1; it2 != nums.end(); it2++) { if ((*it) + (*it2) == target) { result.push_back(it-nums.begin()); result.push_back(it2-nums.begin()); return result; } }*/ unordered_map <int,int> check; for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++) { if (check.find(*it) != check.end()) { result.push_back((check[*it])); result.push_back(it-nums.begin()); break; } else { check.emplace((target-*it),it-nums.begin()); } } /*unordered_set<int> check; unordered_map<int,int> value; for (vector<int>::iterator it = nums.begin(); it < nums.end(); it++) { if ( check.find(*it) != check.end()) { result.push_back(value[*it]); result.push_back(it - nums.begin()); break; } else { int kk=*it; check.insert(target-kk); value[target-kk] = it - nums.begin(); } }*/ return result; } };
C++
UTF-8
4,794
2.75
3
[]
no_license
#include "GPSFaker.h" #include <cmath> #include <cstdlib> #include <iostream> #include <csignal> #include <cstring> #include <cerrno> #include <unistd.h> using namespace std; /* Bug in old versions of GCC? using std::atof; using std::atol; using std::errno; using std::strcmp; using std::memcpy; */ GPSFaker* GPSFaker::faker = 0; int main (int argc, char* argv[]) { GPSFaker::main(argc, argv); } void GPSFaker::main (int argc, char* argv[]) { std::signal(SIGINT, signalHandler); std::signal(SIGTERM, signalHandler); FakeDataGenerator* gen; if (argc < 2) exitWithError("Need mode."); if (strcmp(argv[1], "static") == 0) { if (argc < 4) exitWithError("Must specify lat/long."); // argv[2] is longitude errno = 0; double longi = atof(argv[2]); if (errno != 0) exitWithError("Bad longitude"); // argv[3] is latitude double lat = atof(argv[3]); if (errno != 0) exitWithError("Bad latitude"); // argv[4] is flaky bool flaky; if (argc < 5) flaky = false; else if (strcmp(argv[4], "flaky") == 0) flaky = true; else exitWithError("Invalid argument"); gen = new StaticGenerator(flaky, longi, lat); } else if (strcmp(argv[1], "line") == 0) { // argv[2] is start long double start_long = atof(argv[2]); if (errno != 0) exitWithError("Bad start long"); // argv[3] is start lat double start_lat = atof(argv[3]); if (errno != 0) exitWithError("Bad start lat"); // argv[4] is end long double end_long = atof(argv[4]); if (errno != 0) exitWithError("Bad end long"); // argv[5] is end lat double end_lat = atof(argv[5]); if (errno != 0) exitWithError("Bad end lat"); // argv[6] is time long time = atol(argv[6]); if (errno != 0) exitWithError("Bad time"); // argv[7] is flaky bool flaky; if (argc < 8) flaky = false; else if (strcmp(argv[7], "flaky") == 0) flaky = true; else exitWithError("Invalid argument"); gen = new LineGenerator(flaky, start_long, start_lat, end_long, end_lat, time); } cout << "Creating faker..." << endl; faker = new GPSFaker(gen); if (faker->ready()) faker->run(); else exitWithError("Cannot setup faker."); } void GPSFaker::exitWithoutError () { if (faker != 0) delete faker; std::exit(0); return; } void GPSFaker::exitWithError (char* err) { std::cout << "Error: " << err << std::endl; if (faker != 0) delete faker; std::exit(1); return; } void GPSFaker::signalHandler (int signum) { exitWithoutError(); } GPSFaker::GPSFaker (FakeDataGenerator* gen) : generator(gen) { handle = GPSPublishInit(0); } GPSFaker::~GPSFaker () { GPSPublishShutdown(handle, 0); } bool GPSFaker::ready () { return handle; } void GPSFaker::run () { struct timeval time; GPSPosition pos; pos.z = 0; pos.zvalid = true; pos.xyvalid = true; pos.tvalid = true; while (true) { // Update time gettimeofday(&time, 0); generator->updateTime(&time); // Get new position pos.x = generator->getLongitude(); pos.y = generator->getLatitude(); memcpy(&pos.gps_time, &time, sizeof(struct timeval)); memcpy(&pos.sys_time, &time, sizeof(struct timeval)); pos.stale = generator->getValid() ? false : true; // Store position GPSPublishUpdate(handle, &pos); // Delay sleep(1); } return; } StaticGenerator::StaticGenerator (bool new_flaky, double longi, double lat) : flaky(new_flaky), latitude(lat), longitude(longi) {} void StaticGenerator::updateTime (const struct timeval* new_time) {} double StaticGenerator::getLatitude () { return latitude; } double StaticGenerator::getLongitude () { return longitude; } bool StaticGenerator::getValid () { if (!flaky) return true; // 75% valid return std::rand() < (int) std::floor((double) RAND_MAX * 0.75); } LineGenerator::LineGenerator (bool new_flaky, double start_long, double start_lat, double end_long, double end_lat, long total_time) : flaky(new_flaky), curLatitude(start_lat), curLongitude(start_long), startLatitude(start_lat), startLongitude(start_long), endLatitude(end_lat), endLongitude(end_long), totalTime(total_time) { gettimeofday(&startTime, 0); } void LineGenerator::updateTime (const struct timeval* new_time) { long elapsed = new_time->tv_sec - startTime.tv_sec; double frac = (double) elapsed / (double) totalTime; curLatitude += frac * (endLatitude - startLatitude); curLongitude += frac * (endLongitude - startLongitude); return; } double LineGenerator::getLatitude () { return curLatitude; } double LineGenerator::getLongitude () { return curLongitude; } bool LineGenerator::getValid () { if (!flaky) return true; // 75% valid return std::rand() < (int) std::floor((double) RAND_MAX * 0.75); }
Python
UTF-8
4,494
3.25
3
[]
no_license
''' 该文件主要用于将原始数据集分割为train和test两部分。注意该py文件的工作要求是所有的jpg文件和与其同名的label文件在同一个目录下。 而该程序会将图像分成两部分另存到对应的文件夹下,并在两个文件夹下建立对应的总label文件。 该py文件是针对EAST数据集的分割编写的,通用性不强,需要根据实际情况进行修改 ''' import argparse import random import shutil import sys import os FLAGS = None def getfilelist(path, suffix = '.jpg'): #迭代获取当前路径下所有的jpg文件或txt文件,并返回其路径 filelist = [] for i in os.listdir(path): if os.path.isfile(os.path.join(path, i)):#确认是否是文件 if i.endswith(suffix):#确认后缀 filelist.append(os.path.join(path, i)) else: filelist+=(getfilelist(os.path.join(path, i))) return filelist def datasetDivisionSaver(imageList, labelList, savePath): ''' 按照imageList读取图片并转存到savePath下去。 同时会按照labelList读取txt文本,并将所有txt文本的内容按照“文件名 内容”的格式保存在savePath下的一个txt文本中 输入: fileList:由图片绝对路径组成的list labelList:由图片对应的标签文件绝对路径组成的list savePath:图片转存的路径 ''' resultList = [] lenc = len(imageList) assert len(labelList) == lenc #拷贝文件并读取标签文件内容 for i in range(lenc): fileName = os.path.basename(imageList[i])#获取图片名称 f = open(labelList[i])#打开对应的标签文件 label = f.readline() result = [fileName, label] resultList.append(result) f.close() copyPath = os.path.join(savePath, fileName) shutil.copy(imageList[i], copyPath) #将标签文件内容保存 txtPath = os.path.join(savePath, 'sample.txt') f = open(txtPath, "w") for result in resultList: line = ' '.join(result) f.write(line) #f.write('\n') f.close() def datasetDivision(fileListDir, savePath, ratio): ''' 对指定路径下的数据集按照指定的比例分为train和test两部分,该数据及由jpg图像以及与图像同名的txt格式label文件组成 输入: fileListDir:需要分割的数据集路径 ratio:分割比例 输出: ''' #建立结果保存路径 trainPath = os.path.join(savePath, 'train') testPath = os.path.join(savePath, 'test') if not os.path.exists(trainPath):#如果不存在,则创立文件夹 os.mkdir(trainPath) if not os.path.exists(testPath):#如果不存在,则创立文件夹 os.mkdir(testPath) #获得路径列表 imageList = getfilelist(fileListDir) labelList = [i.replace('.jpg', '.txt')for i in imageList] #检查image和label是否顺序对应 lenc = len(imageList) for i in range(lenc): image = os.path.basename(imageList[i]).split('.')[0] label = os.path.basename(labelList[i]).split('.')[0] if(image!=label): print("check fail",image,'----',label) #随机分割为train和test index = list(range(lenc)) random.shuffle(index) gate = int(lenc * ratio) testImageList = [imageList[i] for i in index[0 : gate]] testLabelList = [labelList[i] for i in index[0 : gate]] trainImageList = [imageList[i] for i in index[gate : lenc]] trainLabelList = [labelList[i] for i in index[gate : lenc]] #保存分割结果 datasetDivisionSaver(testImageList, testLabelList, testPath) datasetDivisionSaver(trainImageList, trainLabelList, trainPath) def main(_): datasetDivision(FLAGS.fileListDir, FLAGS.savePath, FLAGS.ratio) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--fileListDir', type=str, default='', help="Path to files" ) parser.add_argument( '--savePath', type=str, default='', help="Path to save" ) parser.add_argument( '--ratio', type=int, default=0.2, help="the ratio of test" ) FLAGS, unparsed = parser.parse_known_args() main([sys.argv[0]] + unparsed)
C++
UTF-8
494
2.953125
3
[]
no_license
#include<process.h> #include<iostream.h> #include<fstream.h> class bank { int acc_no; char name[20]; long int bal; public: void accept(int no) { acc_no=no; cout<<"Enter the name:"; cin>>name; bal=500; cout<<"\nOpening Balance:"<<bal; } void display() { cout<<acc_no<<"\t\t\t"; cout<<name<<"\t\t"; cout<<bal; } int racno() { return acc_no; } long int rbal() { return bal; } void operator+=(int no) { bal=bal+no; } void operator-=(int no) { bal=bal-no; } };
JavaScript
UTF-8
470
2.515625
3
[]
no_license
export const REMOVE_NOTIFICATION = "REMOVE_NOTIFICATION"; export default function reducer(state = { notificationCount: 6, }, action) { switch (action.type) { case REMOVE_NOTIFICATION: return { ...state, notificationCount: state.notificationCount - 1 }; default: return state; } } export const removeNotification = () => dispatch => dispatch({ type: REMOVE_NOTIFICATION })
C#
UTF-8
1,862
3.3125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Net; using System.Text; namespace BasicServerHTTPlistener { class Header { private HttpListenerRequest request; public Header(HttpListenerRequest httpListenerRequest) { this.request = httpListenerRequest; } public NameValueCollection getHeaders() { return request.Headers; } public NameValueCollection getAcceptHeaders() { NameValueCollection headers = getHeaders(); NameValueCollection res = new NameValueCollection(); foreach (string key in headers.AllKeys) { // Tri possible des headers que l'on souhaite afficher /* if (key.Equals(HttpRequestHeader.Accept)) { res.Add(key, headers.Get(key)); } */ res.Add(key, headers.Get(key)); } return res; } public void print(String collectionName, NameValueCollection headers) { Console.WriteLine(collectionName); // Get each header and display each value. foreach (string key in headers.AllKeys) { string[] values = headers.GetValues(key); if (values.Length > 0) { Console.WriteLine("The values of the {0} header are: ", key); foreach (string value in values) { Console.WriteLine(" {0}", value); } } else { Console.WriteLine("There is no value associated with the header."); } } } } }
C#
UTF-8
1,440
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using STPLocalSearch.Graphs; namespace STPLocalSearch.Solve { public static class TMSTV { public static Graph RunSolver(Graph graph, Graph tmst) { HashSet<Vertex> redundantVertices = new HashSet<Vertex>(graph.Vertices); foreach (var mstEdge in tmst.Edges) { var v1 = mstEdge.Either(); var v2 = mstEdge.Other(v1); var path = Algorithms.DijkstraPath(v1, v2, graph); foreach (var vertex in path.Vertices.Where(vertex => redundantVertices.Contains(vertex))) redundantVertices.Remove(vertex); } var solutionVertex = graph.Clone(); foreach (var vertex in redundantVertices) { solutionVertex.RemoveVertex(vertex); } solutionVertex = Algorithms.Kruskal(solutionVertex); var TMSTVremoveVertices = new HashSet<Vertex>(); foreach (var vertex in solutionVertex.Vertices) { if (solutionVertex.GetDegree(vertex) == 1 && !graph.Terminals.Contains(vertex)) TMSTVremoveVertices.Add(vertex); } foreach (var vertex in TMSTVremoveVertices) solutionVertex.RemoveVertex(vertex); return solutionVertex; } } }
PHP
UTF-8
5,974
2.921875
3
[]
no_license
<?php defined('SHOP') or die('Access Denied'); class func { public $mysqli; public function __construct() { $this->mysqli = db::getObject(); } // Распечатка массива public function print_arr($x) { echo '<pre>'; print_r($x); echo '</pre>'; } // Редирект public function redirect($http = false) { if($http) $redirect = $http; else $redirect = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : PATH; header("Location: {$redirect}"); die(); } // Постраничная навигация public function pagination($page, $pages_count) { if($_SERVER['QUERY_STRING']) { $uri = ''; foreach($_GET as $key => $value) { // Формируем строку параметров без номера страницы if($key != 'page') $uri .= "{$key}={$value}&amp;"; } } // Формирование ссылок $back = ''; $forward = ''; $startpage = ''; $endpage = ''; $page2left = ''; $page1left = ''; $page2right = ''; $page1right = ''; if($page > 1) $back = "<a class='nav_link' href='?{$uri}page=".($page-1)."'>&lt;</a>"; if($page < $pages_count) $forward = "<a class='nav_link' href='?{$uri}page=".($page+1)."'>&gt;</a>"; if($page > 3) $startpage = "<a class='nav_link' href='?{$uri}page=1'><<</a>"; if($page < ($pages_count - 2)) $endpage = "<a class='nav_link' href='?{$uri}page={$pages_count}'>>></a>"; if($page - 2 > 0) $page2left = "<a class='nav_link' href='?{$uri}page=".($page-2)."'>".($page-2)."</a>"; if($page - 1 > 0) $page1left = "<a class='nav_link' href='?{$uri}page=".($page-1)."'>".($page-1)."</a>"; if($page + 2 <= $pages_count) $page2right = "<a class='nav_link' href='?{$uri}page=".($page+2)."'>".($page+2)."</a>"; if($page + 1 <= $pages_count) $page1right = "<a class='nav_link' href='?{$uri}page=".($page+1)."'>".($page+1)."</a>"; // Формируем вывод навигации print $startpage.$back.$page2left.$page1left.'<span class="nav_active">'.$page.'</span>'.$page1right.$page2right.$forward.$endpage; } // Ресайз картинок public function resize($target, $dest, $wmax, $hmax, $ext) { /* $target - путь к оригинальному файлу $dest - путь сохранения обработанного файла $wmax - максимальная ширина $hmax - максимальная высота $ext - расширение файла */ list($w_orig, $h_orig) = getimagesize($target); $ratio = $w_orig / $h_orig; // =1 - квадрат, <1 - альбомная, >1 - книжная if(($wmax / $hmax) > $ratio) { $wmax = $hmax * $ratio; } else { $hmax = $wmax / $ratio; } $img = ""; // imagecreatefromjpeg | imagecreatefromgif | imagecreatefrompng switch($ext) { case("gif"): $img = imagecreatefromgif($target); break; case("png"): $img = imagecreatefrompng($target); break; default: $img = imagecreatefromjpeg($target); } $newImg = imagecreatetruecolor($wmax, $hmax); // создаем оболочку для новой картинки if($ext == "png") { imagesavealpha($newImg, true); // сохранение альфа канала $transPng = imagecolorallocatealpha($newImg, 0, 0, 0, 127); // добавляем прозрачность imagefill($newImg, 0, 0, $transPng); // заливка } imagecopyresampled($newImg, $img, 0, 0, 0, 0, $wmax, $hmax, $w_orig, $h_orig); // копируем и ресайзим изображение switch($ext) { case("gif"): imagegif($newImg, $dest); break; case("png"): imagepng($newImg, $dest); break; default: imagejpeg($newImg, $dest); } imagedestroy($newImg); } public function upload_file($id) { $uploaddir = '../userfiles/product_img/photos/'; $file = $_FILES['userfile']['name']; $ext = strtolower(preg_replace('#.+\.([a-z]+)$#i', '$1', $file)); $types = array("image/gif", "image/png", "image/jpeg", "image/pjpeg", "image/x-png"); $res = array(); if($_FILES['userfile']['size'] > SIZE or $_FILES['userfile']['size'] == 0) { $res = array('answer' => 'Ошибка! Максимальный вес файла - 3 Мб!'); exit(json_encode($res)); } if(!isset($file)) { $res = array("answer" => "Ошибка! Возможно, файл слишком большой."); exit(json_encode($res)); } if(!in_array($_FILES['userfile']['type'], $types)) { $res = array("answer" => "Допустимые расширения - .gif, .jpg, .png"); exit(json_encode($res)); } $query = "SELECT img_slide FROM goods WHERE goods_id = ?"; $stmt = $this->mysqli->prepare($query); $stmt->bind_param('i', $id); $stmt->execute(); $stmt->bind_result($img_slide); $row = array(); while($stmt->fetch()) { $row[] = array( 'img_slide' => $img_slide); } if($img_slide) { $images = explode('|', $img_slide); $lastimg = end($images); // Номер последней картинки $lastnum = preg_replace('#\d+_(\d+)\.\w+#', '$1', $lastimg); $lastnum += 1; $newimg = "{$id}_{$lastnum}.{$ext}"; // Имя новой картинки $images = "{$img_slide}|{$newimg}"; // Строка для записи в БД } else { $newimg = "{$id}_0.{$ext}"; // Имя новой картинки $images = $newimg; } $uploadfile = $uploaddir.$newimg; if(@move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { $this->resize($uploadfile, "../userfiles/product_img/thumbs/$newimg", 100, 100, $ext); $query = "UPDATE goods SET img_slide = ? WHERE goods_id = ?"; $stmt = $this->mysqli->prepare($query); $stmt->bind_param('si', $images, $id); $stmt->execute(); } $stmt->close(); $res = array('answer' => 'OK', 'file' => $newimg); exit(json_encode($res)); } }
C++
GB18030
20,734
2.921875
3
[]
no_license
#include "biguint.h" #include<fstream> #include <stdarg.h> #include <algorithm> int BigUInt::Length()const { return m_bits.size(); } int BigUInt::ValidLength() const { return (m_bits.size()>0)?(GetNonZeroIdx()+1):(0); } void BigUInt::TrimHiZeros() { int v = 0; while (m_bits.size() >=1 && (v=m_bits[m_bits.size()-1]) == 0 ) { m_bits.erase(m_bits.begin()+m_bits.size()-1); } if (m_bits.size()==0) { m_bits.push_back(0); } } void BigUInt::AddRadixBits( uint32 val,uint32 pos ) { if (val==0) { return; } //assert(pos); if (pos>=m_bits.size()) { //m_bits.push_front(0); //m_bits.insert(m_bits.begin(),0); //m_bits.push_back(0); m_bits.resize(pos+1,0); } uint32 carry = 0; uint64 v = m_bits[pos]; v = v + val; carry = v / RADIX; v = v % RADIX; m_bits[pos] = v; //ѽλȥ AddRadixBits(carry,pos+1); } //֤ void BigUInt::MinusRadixBits(uint32 val,uint32 pos) { if (val==0) { return; } uint64 v = m_bits[pos]; // if(v<val) { MinusRadixBits(1,pos+1); v = RADIX + v; } v = v - val; m_bits[pos] = v; } void BigUInt::Add( const uint32& ui32 ) { uint64 carry = 0; //ӵλ uint64 v = m_bits[0]; v = v + ui32; carry = v / RADIX; v = v % RADIX; m_bits[0] = (uint32)v; int pos = 1; //λĽλ while (carry>0) { if ((int)m_bits.size()-1-pos<0) { //m_bits.push_front(0); //m_bits.insert(m_bits.begin(),0); m_bits.push_back(0); } uint64 v = m_bits[pos]; v += carry; carry = v / RADIX; v = v % RADIX; m_bits[pos] = (uint32)v; ++pos; } } void BigUInt::Mul( const uint32& ui32 ) { uint64 carry = 0; for (uint32 i=0;i<m_bits.size();i++) { uint64 v = m_bits[i]; v *= ui32; v += carry; carry = v / RADIX; v = v % RADIX; m_bits[i] = (uint32)v; } //λнλ if (carry > 0) { //m_bits.push_front(0); //m_bits.insert(m_bits.begin(),0); m_bits.push_back(0); m_bits[m_bits.size()-1] = (uint32)carry; } } uint32 BigUInt::Mod( const uint32& ui32 ) { uint32 index = m_bits.size() - 1; uint64 v = 0; uint64 quotient = 0; uint64 remainder = 0; do { v = remainder*0x100000000 + m_bits[index]; quotient = v / ui32; remainder = v % ui32; } while (--index>=0); return remainder; } BigUInt BigUInt::DivBy10( BigUInt& Q,uint32 &R ) { BigUInt res; int32 idx = this->GetNonZeroIdx(); uint64 result_ = 0; uint64 remainder = 0; while (idx>=0) { uint64 v = this->GetRadixBits(idx)+remainder*RADIX; result_ = (v / 10); //result ÿӡǡ9*RADIX remainder = v % 10; if(result_>0) res = res + (BigUInt(result_)<<(idx*32)); idx--; } Q = res; R = remainder; return res; } std::string BigUInt::ToString() const { std::string numbers; BigUInt Q = *this; BigUInt R; while(Q>BigUInt("0")) { Fast_BigDiv(Q,BigUInt("10"),Q,R); numbers.insert(numbers.begin(),R.m_bits[0]+'0'); std::string b_right = "114381625757888867669235779976146612010218296721242362562561842935706935245733897830597123563958705058989075147599290026879543541"; char a = numbers[0]; char b = b_right[b_right.size() - numbers.size()]; if (numbers == "3563958705058989075147599290026879543541") { printf("next step will be wrong.."); } if (a!=b) { printf("stop.."); } } //std::reverse(numbers.begin(),numbers.end()); return numbers; } int32 BigUInt::GetNonZeroBitIdx() const /*get_non_zero_bit_idx */ { int hightest_idx = -1; int len = ValidLength(); for (int i=len-1;i>=0;i--) { uint32 v = GetRadixBits(i); if (v) { for (int idx=31;idx>=0;idx--) { if ( (v>>idx) & 1) { hightest_idx = idx + 32*i; goto RETURN; } } } } RETURN: return hightest_idx; } int32 BigUInt::GetNonZeroIdx() const { int hightest_idx = -1; int len = m_bits.size(); for (int i=len-1;i>=0;i--) { uint32 v = GetRadixBits(i); if (v) { hightest_idx =i; goto RETURN; } } RETURN: return hightest_idx; } /* idx_id idx_lo | | 11110000 00001111 11001100 00110011 */ BigUInt BigUInt::GetBitRangBigInt(int bit_idx_hi,int bit_idx_lo) const { if( !(bit_idx_hi>=0 && bit_idx_lo>=0)) { printf("stop."); } assert(bit_idx_hi>=0 && bit_idx_lo>=0 &&"invalid index for GetBitRangeBigInt()!"); BigUInt res; int highest_bit_idx = this->Length()*32 - 1;// this->GetNonZeroBitIdx(); res = (*this)<< (highest_bit_idx-bit_idx_hi);// ƣѸbit_idx_hibitӵ res = (res)>>( (highest_bit_idx-bit_idx_hi) + bit_idx_lo); return res; } bool BigUInt::GetBitByIdx(int bit_idx) const { uint32 v = GetRadixBits(bit_idx/32); uint32 inner_idx = bit_idx % 32; uint32 mask = 1<< (inner_idx); uint32 is_on = v & mask; return is_on; } void BigUInt::Reset() { m_bits.clear(); m_bits.push_back(0); } BigUInt operator+(const BigUInt& X,const BigUInt& Y) { BigUInt Z; BigUInt Smaller; uint32 carry=0; int32 xlen = X.GetNonZeroIdx()+1;//X.Length();// int32 ylen = Y.GetNonZeroIdx()+1;//Y.Length();// if (xlen>=ylen) { Z = X; Smaller = Y; } else { Z = Y; Smaller = X; } for (uint32 i=0;i<std::min<uint32>(xlen,ylen);i++) { Z.AddRadixBits((uint32)Smaller.GetRadixBits(i),i); } return Z; } int32 Compare( const BigUInt & X,const BigUInt & Y ) { int32 idx1 = X.ValidLength() - 1; int32 idx2 = Y.ValidLength() - 1; uint32 v1 = 0; uint32 v2 = 0; //ҵһΪ0 ĸλֵ while( !(v1=X.GetRadixBits(idx1)) && idx1>0) { idx1--; } while( !(v2 = Y.GetRadixBits(idx2)) && idx2>0 ) { idx2--; } int32 result = 0; while (idx1>=0 || idx2 >=0) { if (idx1>idx2) { result = 1; break; } else if (idx2>idx1) { result = -1; break; } else //idx1 == idx2 { if (v1>v2) { result = 1; break; } else if (v2>v1) { result = -1; break; } else // idx1 == idx2 v1 == v2Ҫжһλ { idx1--; idx2--; v1 = X.GetRadixBits(idx1); v2 = Y.GetRadixBits(idx2); } } } return result; } int operator<(const BigUInt& v1,const BigUInt& v2) { return Compare(v1,v2) == -1; } int operator==(const BigUInt& v1,const BigUInt& v2) { return Compare(v1,v2) == 0; } int operator>(const BigUInt& v1,const BigUInt& v2) { return Compare(v1,v2) == 1; } int operator<= (const BigUInt& v1,const BigUInt& v2) { return !(v1>v2); } int operator>= (const BigUInt& v1,const BigUInt& v2) { return !(v1<v2); } int operator!=(const BigUInt& v1,const BigUInt& v2) { return !(v1==v2); } //N1 > N2,ôN1ȴڵN2 BigUInt operator-( const BigUInt&N1,const BigUInt& N2 ) { BigUInt R=N1; for (int index=0;index<N2.ValidLength();index++) { uint32 v = N2.GetRadixBits(index); R.MinusRadixBits(v,index); } R.TrimHiZeros(); return R; } /* a b c :index1 0~2 d e f g :index2 0~3 ------------------------ a*g b*g c*g a*f b*f c*f a*e b*e c*e a*d b*d c*d */ /*use karatsuba algorigthm x = x1*B^N + x2; y = y1*B^N + y2; so x*y is : x*y = x1*y1*B^2N + (x1y2+x2*y1)*B^N + x2*y2; assume a = x1*y1 b = (x1*y2 + x2*y1) c = x2*y2; so that x*y = a*B^2N + b*B^N + c; until, karatsuba algorithm is not more efficiency, because to calculate b ,it costs two multiplications. we find that: b = (x1+x2)*(y1+y2) - x1*y2 - x2*y2,it use three mul and two addition and two minus,but: where x1*y2 and x2*y2 is calculated as a and c. */ BigUInt operator* (const BigUInt& x,const BigUInt&y) { BigUInt R; int x_length = x.ValidLength(); int y_length = y.ValidLength(); if (x_length==1 && y_length==1)// deepest recursion return BigUInt(uint64(x.GetRadixBits(0))*uint64(y.GetRadixBits(0))); BigUInt x1,x2,y1,y2; int max_len = x_length>y_length?x_length:y_length; // x: 87 62736 // y: 66545 46557 //x_length = x1 = x.GetIdxRangeNumber(max_len-1,(max_len)/2); x2 = x.GetIdxRangeNumber((max_len)/2 - 1,0); y1 = y.GetIdxRangeNumber(max_len-1,(max_len)/2); y2 = y.GetIdxRangeNumber((max_len)/2 - 1,0); BigUInt a = x1*y1; BigUInt c = x2*y2; BigUInt b = (x1+x2)*(y1+y2) - a - c; R =( a<<( (max_len/2)*2) ) + (b<<(max_len/2)) + c; return R; } //BigUInt operator*(const BigUInt& N1,const BigUInt& N2) BigUInt nouse(const BigUInt& N1,const BigUInt& N2) { BigUInt R; uint32 carry = 0; uint64 v = 0; int len1 = N1.ValidLength(); int len2 = N2.ValidLength(); for (uint32 index1 = 0;index1<len1;index1++) { uint64 n1 = N1.GetRadixBits(index1); if (n1==0) { continue; } for (uint32 index2 = 0;index2<len2;index2++) { uint64 n2 = N2.GetRadixBits(index2); if (n2==0) { continue; } //עתͲvĽ32λ v = (uint64)n1*(uint64)n2 ; carry = v / BigUInt::RADIX; v = v % BigUInt::RADIX; //ֵͽλӵ if (v>0) { R.AddRadixBits(v,index1+index2); } if (carry>=0) { R.AddRadixBits(carry,index1+index2+1); } } } R.TrimHiZeros(); return R; } BigUInt operator/ (const BigUInt& X,const BigUInt& Y) { BigUInt Q; BigUInt R; return Fast_BigDiv(X,Y,Q,R); } BigUInt operator% (const BigUInt&X,const BigUInt& M) { BigUInt q;// BigUInt r;// Fast_BigDiv(X,M,q,r); return r; } BigUInt operator>>( const BigUInt& X,int bits ) { BigUInt result = X,zero; if (bits>=X.ValidLength()*4*8) { return zero; } int complete_ints = bits/32; int remaind = bits%32; if (complete_ints>0) { result.m_bits.erase(result.m_bits.begin(),result.m_bits.begin() + complete_ints); } //Żremaind > 0 ŽIJҲͲintƶ32bit֮ڴΪ0ֵ // 11110000 11110000 11110000 11110000 //һλ // 01111000 01111000 01111000 01111000 //ƶremaindλhi_mask 31 ~ remaind lo_mask remaind ~ 0λ uint32 hi_mask = 0xffffffff << remaind; uint32 lo_mask = (remaind == 0) ? 0 : 0xffffffff >>(32 - remaind); for (int j=0;remaind && j<result.ValidLength();j++) { uint32 hi_v=result.GetRadixBits(j+1); uint32 bits_from_hi = hi_v & lo_mask; // һλ uint32 v = result.GetRadixBits(j); uint32 bits_from_lo = v & hi_mask; //λbitsƵλ bit֣ٺԭλĸbitµֵ uint32 new_v = (bits_from_hi << (32-remaind) ) | (bits_from_lo>>remaind); result.SetRadixBits(new_v,j); } return result; } BigUInt operator<<( const BigUInt& X,int bits ) { BigUInt result=X; int complete_ints = bits/32; int remaind = bits%32; //remaind 0~31 if (complete_ints>0) { //vectorͷ൱ұߣcomplete_ints0Ҳcomplete_ints*32λ result.m_bits.insert(result.m_bits.begin(),complete_ints,0); } //ƶɢbit: uint32 lo_mask = 0xffffffff << (32 - remaind); uint32 hi_mask = 0xffffffff >> remaind; uint32 old_low_v = 0; int valid_len = result.ValidLength(); for(int idx=0;remaind && idx<=valid_len;idx++) { uint32 hi_v = result.GetRadixBits(idx); uint32 lo_v = old_low_v;//result.GetRadixBits(idx-1); //uint32 new_hi_v = ( (hi_v & lo_mask) << remaind ) | ( ( lo_v & hi_mask ) >> (32 - remaind) ); uint32 new_hi_v = (hi_v & hi_mask)<<remaind | (lo_v & lo_mask )>>(32-remaind); if (idx<valid_len || new_hi_v) { result.SetRadixBits(new_hi_v,idx); } old_low_v= hi_v; } //for(int idx = result.ValidLength();remaind && idx>=0;idx--) //{ // uint32 hi_v = result.GetRadixBits(idx); // uint32 lo_v = result.GetRadixBits(idx-1); // uint32 new_hi_v = ( (hi_v & lo_mask) << remaind ) | ( ( lo_v & hi_mask ) >> (32 - remaind) ); // if (idx < result.ValidLength() ) //λӶĿհuint32,λĿհ // { // result.SetRadixBits(new_hi_v,idx); // } //} return result; } BigUInt operator&(const BigUInt&X,uint32 mask) { uint32 v = X.GetRadixBits(0); v = v & mask; return BigUInt(v); } /* ʽij */ BigUInt BigDiv( const BigUInt& X,const BigUInt& Y,BigUInt &Q,BigUInt&R ) { BigUInt One("1"); BigUInt Result("0"); BigUInt a = X; BigUInt b = Y; int32 na = 0; int32 nb = 0; na = a.GetNonZeroBitIdx(); nb = b.GetNonZeroBitIdx(); int loopcnt = 0; while(a>=b) { na = a.GetNonZeroBitIdx(); int diff = na - nb; //a.Dump("aʼֵ:"); //b.Dump("bʼֵ,²ƫdiff=%d:",diff); BigUInt shift_b = b<<diff; while (diff>0 && a < shift_b) diff--,shift_b = b<<diff; //if ( a >= shift_b ) { //( b<<diff ).Dump("bƶʵƫdiff=%d",diff); Result = Result + ( One <<diff ); //Result.Dump(""); } a = a - shift_b; loopcnt++; //a.Dump("֮a:"); } Q = Result; R = a; return Result; } /* 0x100000000Ƶij õĹֵ㷨ҪصĵڶҲδȫ 2379../29.. : 0082.. ======= 29..| 2379.. 232 ----- 59 58 ----- 1 ڰb루29λ>=5ͨλ(2^n) 9.. ======= 58..| 4758.. 522 > һε̣q = 47/5 == 9,ôq--; ----- ( ======= 58.. | 5858 һ̣q=58 / 5 == ) 82 ======= 58 | 4758 464 > һε㣬 ----- 118 ڶε(q = 11/5 == 2), 116 ------- 2 */ BigUInt Fast_BigDiv(const BigUInt& X,const BigUInt& Y,BigUInt&Q,BigUInt&R) { BigUInt Result("0"); BigUInt a = X; a.TrimHiZeros(); BigUInt b = Y; b.TrimHiZeros(); int adjust_shift = 0; //b,bλ >= RADIX/2 while ( b.GetRadixBits(b.GetNonZeroIdx()) < (BigUInt::RADIX/2)) { b=(b<<1); adjust_shift++; } //bͬʱҲҪa if(adjust_shift>0) { a = a<<adjust_shift; } int a_begin_idx = a.GetNonZeroIdx(); int a_valid_len = a.ValidLength(); int b_begin_idx = b.GetNonZeroIdx(); int b_valid_len = b.ValidLength(); //aijȵbijȣҪaǰ0֤aijȱbٳ1 if(a_valid_len==b_valid_len) { a.m_bits.push_back(0); a_begin_idx++;//ǰһλǰ0ʼ } while(a>=b) { //aλȡb+1uint32 λuit32bitλuint32bit //aǶģaλuint320ܶطLengthValidLength BigUInt a_part = a.GetBitRangBigInt(a_begin_idx*32+31,(a_begin_idx-b_valid_len)*32); //ȡaĸ2λ2uint32bĸ1λ1uint32ֵ̹ uint64 a_part_hi_2 = (uint64)a_part.GetRadixBits(a_part.Length() - 1) << 32 | (uint64)a_part.GetRadixBits(a_part.Length() - 2); uint64 b_part_hi_1 = b.GetRadixBits(b.GetNonZeroIdx()); uint64 guess_v = a_part_hi_2 / b_part_hi_1; int guess_time = 0; while (a_part< b*guess_v)//guess_vʵֵ<2, guess_v-2<= real_v <= guess_v;εƵҪɵµڶ { guess_v--; guess_time++; } //˺guess_vʵֵ assert(guess_time<=2); uint32 carry = guess_v / BigUInt::RADIX; uint32 value = guess_v % BigUInt::RADIX; Result.AddRadixBits(value,a_begin_idx-b_valid_len); Result.AddRadixBits(carry,a_begin_idx-b_valid_len+1); /* a = a - b * ( res << N) = a - b * ( res * 2^^N) = a - b * res * 2^^N = a - */ //carryп>=0Ҫuint64λĹ캯 //a = a - b*(BigInt(guess_v)<<(a_begin_idx-b_valid_len)*32); a = a - (b <<(a_begin_idx-b_valid_len)*32) * guess_v; a_begin_idx--; } Q = Result; R = a>>adjust_shift; return Result; } BigUInt BigDiv2N(const BigUInt&X,const BigUInt& Y,BigUInt&Q,BigUInt&R) { /* e.g X: 1010100111101 index = 12 Y: 10000000 :index=7 */ int bit_idx = Y.GetNonZeroBitIdx(); Q = X>>bit_idx; int complete_int = (1+bit_idx) / 32; int remaind_bits = (1+bit_idx) % 32; for(int i=0;i<complete_int;i++) { R.SetRadixBits(X.GetRadixBits(i),i); } if (remaind_bits) { //1000 0000 0000 0000 0000 0000 0000 0001 uint32 v = Y.GetRadixBits(complete_int); uint32 mask = v-1; uint32 vv = X.GetRadixBits(complete_int); vv = vv & mask; R.SetRadixBits(vv,complete_int); } return Q; } //ŷ㷨XYԼ BigUInt GCD(const BigUInt& X,const BigUInt& Y) { BigUInt Zero("0"); BigUInt a; BigUInt b; BigUInt r; if (X>Y) { a = X; b = Y; } else if (X<Y) { a = Y; b = X; } else //ȣֱӷ { return X; } while (!( b == Zero) ) //a=41606343 b=40144455 { BigUInt tmp = b; b = a%b; a = tmp; } return a; } /* gcd(a,b) = gcd(b,a%b); // 裺 a*x1 + b*y1 = gcd(a,b) // a= b, b = a % b; һεݹ b * x2 + ( a % b ) * y2 = gcd(b,a%b); */ void ExEuclid( BigUInt a, BigUInt b,BigUInt& x,BigUInt&y ) { BigUInt old_a = a; BigUInt old_b = b; //r Ϊ a % b ģҲa / b //q Ϊ a / b //һԶ BigUInt r; BigUInt q; BigUInt tmp = b; Fast_BigDiv(a,b,q,r); b = r; a = tmp; if (b == BigUInt("0")) { x = BigUInt("1"); y = BigUInt("0"); BigUInt tmp = x; x = y; y = tmp - q*y; return; } ExEuclid(a,b,x,y); BigUInt old_x = x; x = y; y = old_x - q*x; } BigUInt ExpMod(const BigUInt& a,const BigUInt& b,const BigUInt& m) { BigUInt res("1"); BigUInt multiplizer = a; BigUInt exp = b; BigUInt Zero("0"); while (exp > Zero) { //ȡһֽ uint32 lowestbit = exp.GetRadixBits(0); while (lowestbit!=0) { if(lowestbit&1) { res = (res * multiplizer)%m; } multiplizer = (multiplizer * multiplizer)%m; lowestbit = lowestbit >> 1; } exp = exp >> 32; } return res; } BigUInt MExpMod(const BigUInt&a,const BigUInt&b,const BigUInt& m) { BigUInt res; return res; }; BigUInt Exp(const BigUInt& a,const BigUInt& b) { BigUInt res("1"); BigUInt multiplizer = a; BigUInt exp = b; BigUInt Zero("0"); while (exp > Zero) { //ȡһֽ uint32 lowestbit = exp.GetRadixBits(0); while (lowestbit!=0) { if(lowestbit&1) { res = (res * multiplizer) ; } multiplizer = (multiplizer * multiplizer) ; lowestbit = lowestbit >> 1; } exp = exp >> 32; } return res; } int FromString( BigUInt& N,const std::string& numbers_ ) { std::string numbers = numbers_; int sign = 0; N.Reset(); int length = 0; for(;(!numbers.empty())&&numbers[length]!='\0';length++); if (numbers[0] == '-') { sign = 1; //1ʾ numbers.erase(numbers.begin());//ɾ } else if(numbers[0]=='+') { sign = 0; numbers.erase(numbers.begin());//ɾ } int base = 10; if (numbers[0]=='0' && (numbers[1]== 'x' || numbers[1]== 'X')) { base = 16; } else if (numbers[0]== 'b' || numbers[0]== 'B') { base = 2; } //N.Dump(); switch (base) { case 2: { for (int i=1;i<length;i++) { int n = numbers[i]-'0'; N.Mul(2); //N.Dump(); N.Add(n); } } break; case 10: { for (int i=0;i<length;i++) { int n = numbers[i]-'0'; N.Mul(10); //N.Dump(); N.Add(n); } } break; case 16: { for (int i=2;i<length;i++) { int n = numbers[i]; if (n==' ')//հ { continue; } N.Mul(16); switch(n) { case 'a': case 'A': N.Add(10); break; case 'b': case 'B': N.Add(11); break; case 'c': case 'C': N.Add(12); break; case 'd': case 'D': N.Add(13); break; case 'e': case 'E': N.Add(14); break; case 'f': case 'F': N.Add(15); break; //for 0~9 default: { n = n -'0'; assert(n>=0 && n<=9); N.Add(n); } } } } break; } return sign; } void DumpBits(const BigUInt& N,const char *fmt,...) { static int idx = 0; idx++; std::ofstream fs; fs.open("bits.txt",std::ios_base::binary | std::ios_base::out | std::ios_base::app); std::string index; char buf[100] = {0}; index = itoa(idx,buf,10); char out[1024]={0}; va_list ap; va_start(ap, fmt); vsnprintf(out, 1024, fmt, ap); va_end(ap); index +=out; index += ":\n"; fs.write(index.c_str(),index.length()); for (int i=0;i<N.m_bits.size();i++) { printf("%d ʮ : %u \n", i,N.m_bits[i]); printf("%d ʮ: 0x%x \n",i,N.m_bits[i]); std::string s; for (int j=0;j<32;j++) { int v = (N.m_bits[N.m_bits.size() - 1 - i]>>(31-j))&1; char c = v + '0'; s +=c; } printf("%d : %s \n",N.m_bits.size() - i,s.c_str()); fs.write(s.c_str(),s.length()); } printf("\n"); fs.write("\n\r",1); fs.close(); }
Java
UTF-8
2,023
1.96875
2
[]
no_license
package com.park61.moduel.dreamhouse.bean; import java.io.Serializable; import java.math.BigDecimal; /** * 加入梦想成功后推荐游戏信息 */ public class AddDreamRecommendGames implements Serializable { private Long requirementPredictionId; private String actAddress; private int actBussinessType; private String actCover; private BigDecimal actPrice; private String actTitle; private int grandTotal; private Long id; private Long refTemplateId; public Long getRequirementPredictionId() { return requirementPredictionId; } public void setRequirementPredictionId(Long requirementPredictionId) { this.requirementPredictionId = requirementPredictionId; } public String getActAddress() { return actAddress; } public void setActAddress(String actAddress) { this.actAddress = actAddress; } public int getActBussinessType() { return actBussinessType; } public void setActBussinessType(int actBussinessType) { this.actBussinessType = actBussinessType; } public String getActCover() { return actCover; } public void setActCover(String actCover) { this.actCover = actCover; } public BigDecimal getActPrice() { return actPrice; } public void setActPrice(BigDecimal actPrice) { this.actPrice = actPrice; } public String getActTitle() { return actTitle; } public void setActTitle(String actTitle) { this.actTitle = actTitle; } public int getGrandTotal() { return grandTotal; } public void setGrandTotal(int grandTotal) { this.grandTotal = grandTotal; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getRefTemplateId() { return refTemplateId; } public void setRefTemplateId(Long refTemplateId) { this.refTemplateId = refTemplateId; } }
Java
UTF-8
641
2.390625
2
[]
no_license
package com.edu.abhi.expressionlanguage.annotation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml"); { Customer obj = (Customer) context.getBean("customerBean"); System.out.println(obj); } { Operators obj = (Operators) context.getBean("operatorBean"); System.out.println(obj); } { Collections obj = (Collections) context.getBean("collectionBean"); System.out.println(obj); } } }
Markdown
UTF-8
740
2.703125
3
[]
no_license
# Digital Humanities The reason I chose **Digital Humanities** as a study subject is so that I can later on work for a company to help making E-Sports more relevant to our modern society. A company I am looking forward to woorking for is *Freaks 4u*. ![Freaks 4u Gaming Logo](https://www.medianet-bb.de/wp-content/uploads/2017/01/Freaks-4U-Gaming-aktuell-600x333.png) They are a company which revolves around the idea to show the competitive aspect of gaming (E-Sports) and help making it more popular by streaming on twitch/youtube or using other social media websites. Here is also a link to their company website. [Freaks 4u Gaming](https://www.freaks4u.de/home) ![Cat GIf](https://media.giphy.com/media/5e6Y1YvmNSgi4/giphy.gif)
C#
UTF-8
3,476
3.59375
4
[]
no_license
using System; namespace домашка { public class ArrayMaster { private static Random rnd = new Random(); //метод для ввода public static int[,] Array(int[,] arr) { for (var i = 0; i < arr.GetLength(0); i++) { for (var j = 0; j < arr.GetLength(1); j++) { arr[i, j] = rnd.Next(-10, 10); } } return arr; } public static void PrintArray(int[,] arr) //метод для вывода { for (var i = 0; i < arr.GetLength(0); i++) { for (var j = 0; j < arr.GetLength(1); j++) { Console.Write(arr[i, j] + " "); } Console.WriteLine(); } Console.WriteLine(); } public static int[,] MultArray(int[,] arr1, int[,] arr2) //метод для умножения { var arrResult = new int[arr1.GetLength(1), arr1.GetLength(0)]; for (var i = 0; i < arr1.GetLength(0); i++) { for (var j = 0; j < arr1.GetLength(1); j++) { for (var k = 0; k < arr1.GetLength(0); k++) { arrResult[i, j] += arr1[i, k] * arr2[k, j]; } } } return arrResult; } public static int[,] SumArray(int[,] arr1, int[,] arr2) //метод для сложения { var arrResult = new int[arr1.GetLength(0), arr1.GetLength(1)]; for (var i = 0; i < arr1.GetLength(0); i++) { for (var j = 0; j < arr1.GetLength(1); j++) { arrResult[i, j] = arr1[i,j] + arr2[i,j]; } } return arrResult; } public static int[,] SubArray(int[,] arr1, int[,] arr2) //метод для вычитания { var arrResult = new int[arr1.GetLength(0), arr1.GetLength(1)]; for (var i = 0; i < arr1.GetLength(0); i++) { for (var j = 0; j < arr1.GetLength(1); j++) { arrResult[i, j] = arr1[i,j] - arr2[i,j]; } } return arrResult; } public static int[,] PowArray(int[,] arr) //метод для возведения в квадрат { var arrPow = new int[arr.GetLength(0), arr.GetLength(1)]; for (var i = 0; i < arr.GetLength(0); i++) { for (var j = 0; j < arr.GetLength(1); j++) { arrPow[i, j] = arr[i,j]*arr[i,j]; } } return arrPow; } public static int[,] TransArray(int[,] arr) //метод для транспонирования { var arrTrans = new int[arr.GetLength(1), arr.GetLength(0)]; for (var i = 0; i < arr.GetLength(1); i++) { for (var j = 0; j < arr.GetLength(0); j++) { arrTrans[i, j] = arr[j, i]; } } return arrTrans; } } }
JavaScript
UTF-8
567
2.671875
3
[ "MIT", "CC-BY-4.0", "CC-BY-SA-4.0", "CC-BY-NC-SA-4.0", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// @flow import {stringToMD5} from '../lib/crypto-utils'; import _ from 'lodash'; export const GRAVATAR_DEFAULT = 'https://www.gravatar.com/avatar/00000000000000000000000000000000?d=mm'; /** * Generate gravatar url from email address */ export function generateGravatarUrl(email: string = ''): string { let emailCopy = email; if (_.isString(email) && _.size(email) > 0) { emailCopy = email.trim().toLocaleLowerCase(); const emailMD5 = stringToMD5(emailCopy); return `https://www.gravatar.com/avatar/${emailMD5}`; } return GRAVATAR_DEFAULT; }
Python
UTF-8
569
2.828125
3
[ "MIT" ]
permissive
""" 33.11% """ class Solution(object): def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ maxlen = 0 cur = [] nums = sorted(set(nums)) for num in nums: if not cur: cur.append(num) else: if cur[-1] + 1 == num or cur[-1] == num: cur.append(num) else: cur[:] = [] cur.append(num) maxlen = max(maxlen, len(cur)) return maxlen
Markdown
UTF-8
1,396
3.140625
3
[ "MIT" ]
permissive
# 双重链表 在计算机科学中, **双向链表**是一种链接数据结构 由一组称为节点的顺序链接记录组成. 每个节点包含 两个字段, 其中称为链接, 是对 节点序列中的 前一个和下一个节点的引用 . 而 开始和结束节点 的 上一个和下一个节点 链接 分别指向某种终结者, 通常是 标记 节点 或 null, 以方便遍历列表. 如果只有一个 标记 节点, 然后列表通过 标记节点 循环链接. 它可以 被概念化为 由 相同数据项 形成的两个单链表, 但是在相反的顺序中. > 如果只有一个标记节点, 具有 开始节点与结束节点 的 引用, 可以让 闭合链表 ![Doubly Linked List](https://upload.wikimedia.org/wikipedia/commons/5/5e/Doubly-linked-list.svg) 两个节点链接 允许 在任一方向上 遍历列表. 在添加 或者删除双向链表中的节点时 需要更改比 单链表 更多的链接. 如果在单链表上进行相同的操作, 操作更简单 可能更有效(对于除第一个节点以外的节点), 因为 在遍历期间, 不需要跟踪前一个节点或者无需 遍历列表以查找上一个节点, 以便可以修改其链接. ## References - [Wikipedia](https://en.wikipedia.org/wiki/Doubly_linked_list) - [YouTube](https://www.youtube.com/watch?v=JdQeNxWCguQ&t=7s&index=72&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
Java
UTF-8
739
3.390625
3
[ "MIT" ]
permissive
package com.sww; import java.util.HashSet; /** * @author sww */ public class WeekThree { public static void main(String[] args) { String str = "pwwkew"; System.out.println(result(str)); } static int result(String str) { int result = 0; int arrayLength = str.length(); HashSet<Character> set = new HashSet<>(16); for (int start = 0, end = 0; start < arrayLength && end < arrayLength;) { Character c = str.charAt(end++); if (set.contains(c)) { set.remove(str.charAt(start++)); } else { set.add(c); result = Math.max(result, set.size()); } } return result; } }
Java
UTF-8
968
3.171875
3
[]
no_license
package NewThread; import java.util.Date; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; /** * Hello world! * */ public class App { public static void main( String[] args ) throws ExecutionException, InterruptedException { MyThreead thread = new MyThreead(); Thread threads = new Thread(new myRunnable()); FutureTask<String> ftask = new FutureTask<String>(new myCallable()); Thread threadt = new Thread(ftask); ExecutorService executorService = Executors.newFixedThreadPool(10); executorService.execute(new myRunnable()); thread.start(); threads.start(); threadt.start(); ftask.get(); System.out.println(ftask.get()); for(int i=0;i<=10;i++){ System.out.println( "Hello World!;"+new Date().getTime() ); } } }
Java
UTF-8
431
2.8125
3
[]
no_license
package exceptionGabarito; public class ExceptionCapturada { public static void main(String[] args) { int i = 0; try { String array[] = { "acapulco", "bariloche", "aruba" }; while (i < 4) { System.out.println(array[i]); i++; } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Resetando o valor do ?ndice"); i = 0; } finally { System.out.println("Ser? sempre impresso"); } } }
Java
UTF-8
4,594
2.53125
3
[]
no_license
package edu.ucdavis.cs.dblp.text; import java.io.File; import java.io.IOException; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import com.google.common.base.Join; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import edu.ucdavis.cs.dblp.ServiceLocator; /** * Loads a cluto/gcluto cluster solution from the file system and provides * clients with access to the assigned clusters from that solution. * * @author pfishero */ @Component public class ClutoClusterSolution { private static final Logger logger = Logger.getLogger(ClutoClusterSolution.class); private File solutionDir; private Map<String, Integer> clusters = Maps.newHashMap(); @Autowired(required=false) public void setSolutionDir(@Qualifier("solutionDir")Resource solutionDirRes) { try { this.solutionDir = solutionDirRes.getFile(); } catch (IOException e) { logger.error("unable to set solutionDir from resource:"+solutionDirRes); } } @PostConstruct public final void loadSolution() { if (solutionDir != null) { File keyFile = new File(solutionDir, "int_data_matrix/rowlabels.rlabel"); File solutionFile = new File(solutionDir, "solution.sol"); Preconditions.checkState(keyFile.canRead()); Preconditions.checkState(solutionFile.canRead()); LineIterator keyIter = null; LineIterator solutionIter = null; try { keyIter = FileUtils.lineIterator(keyFile, "UTF-8"); solutionIter = FileUtils.lineIterator(solutionFile, "UTF-8"); // first two lines in the solutionFile are not important solutionIter.next(); solutionIter.next(); while (keyIter.hasNext() && solutionIter.hasNext()) { Integer clusterNum = Integer.parseInt(solutionIter.nextLine().trim()); clusters.put(keyIter.nextLine().trim(), clusterNum); } assert !keyIter.hasNext() && !solutionIter.hasNext() : "key/solution files had differing number of entries"; } catch (IOException e) { logger .error("error while reading solution file. "+e); } finally { LineIterator.closeQuietly(keyIter); LineIterator.closeQuietly(solutionIter); } } else { logger.info("not loading solution - no solutionDir set"); } } public Multimap<Integer, SimplePub> getClustersFor(Iterable<SimplePub> pubs) { // verify that a non-empty solution was loaded Preconditions.checkState(this.clusters.size() > 0); Multimap<Integer, SimplePub> solution = new HashMultimap<Integer, SimplePub>(); for(SimplePub pub : pubs) { if (clusters.containsKey(convertPubKey(pub))) { solution.put(clusters.get(convertPubKey(pub)), pub); } else { logger.error("solution cluster not found for pub: "+pub); } } return solution; } public Map<SimplePub, Integer> getClusterNumbersFor(Iterable<SimplePub> pubs) { Multimap<Integer, SimplePub> clusters = getClustersFor(pubs); Map<SimplePub, Integer> pubClusterNums = Maps.newHashMap(); for(Integer clusterNum : clusters.keySet()) { for(SimplePub pub : clusters.get(clusterNum)) { pubClusterNums.put(pub, clusterNum); } } return pubClusterNums ; } /** * Converts the key from {@link SimplePub#getKey()} to the format that * the cluto clustered solution uses. * * @param pub * @return */ public static final String convertPubKey(SimplePub pub) { String key = Join.join("", pub.getKey().split("/")).toLowerCase().replaceAll("-", ""); return key; } public static void main(String[] args) throws Exception { ApplicationContext ctx = ServiceLocator.getInstance().getAppContext(); final ClutoClusterSolution solution = (ClutoClusterSolution) ctx.getBean("clutoClusterSolution"); final SpatialTopics st = (SpatialTopics) ctx.getBean("spatialTopics"); Multimap<Integer, SimplePub> clusters = solution.getClustersFor(st.getSimplePubs()); for(Integer clusterNum : clusters.keySet()) { logger.info("pubs for cluster "+clusterNum+'\n'+clusters.get(clusterNum)); } } }
C
UTF-8
2,850
4.09375
4
[]
no_license
#include <stdio.h> #include <stdbool.h> #include <string.h> #include <stdlib.h> struct node { char data[100]; struct node *next; struct node *prev; }; struct node *head = NULL; struct node *last = NULL; // struct node *current = NULL; // Write functions to find from it. Test them. bool isEmpty() { return head == NULL; } void insertFirst(char data[100]) { struct node *link = malloc(sizeof(struct node)); strncpy(link->data, data, 100); if(isEmpty()) { last = link; } else { head->prev = link; } link->next = head; head = link; } void insertLast(char data[100]) { struct node *link = malloc(sizeof(struct node)); strncpy(link->data, data, 100); if(isEmpty()) { last = link; } else { last->next = link; link->prev = last; } last = link; } struct node* deleteFirst() { struct node *tempLink = head; if(head->next == NULL){ last = NULL; } else { head->next->prev = NULL; } head = head->next; return tempLink; } struct node* deleteLast() { struct node *tempLink = last; if(head->next == NULL) { head = NULL; } else { last->prev->next = NULL; } last = last->prev; return tempLink; } struct node* delete(char data[100]) { struct node* current = head; struct node* previous = NULL; if(head == NULL) { return NULL; } while(strncmp(current->data, data, 100) != 0) { if(current->next == NULL) { return NULL; } else { previous = current; current = current->next; } } if(current == head) { head = head->next; } else { current->prev->next = current->next; } if(current == last) { last = current->prev; } else { current->next->prev = current->prev; } return current; } struct node* find(char data[100]) { struct node* current = head; while(strncmp(current->data, data, 100) != 0) { if (current == last) { return NULL; } else { current = current->next; } } printf("(%s) ",current->data); return current; } void displayForward() { struct node *ptr = head; printf("\n[ "); while(ptr != NULL) { printf("(%s) ",ptr->data); ptr = ptr->next; } printf(" ]"); } int main() { insertFirst("10"); insertFirst("20"); insertFirst("30"); insertFirst("1"); insertFirst("40"); insertLast("56"); printf("\nList (First to Last): "); displayForward(); printf("\nList , after deleting first record: "); deleteFirst(); displayForward(); printf("\nList , after deleting last record: "); deleteLast(); displayForward(); printf("\nList , find data with 1: "); find("1"); // displayForward(); printf("\nList , after delete data(20) : "); delete("20"); displayForward(); }