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
2,557
2.265625
2
[ "MIT" ]
permissive
package gui.testing; import com.codahale.metrics.CsvReporter; import common.metrics.Metric; import common.metrics.Metrics; import component.operator.Operator; import component.sink.Sink; import component.source.Source; import query.LiebreContext; import query.Query; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Paths; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit; public class LiebreTestStats { public static void main(String[] args) { /*LiebreContext.setOperatorMetrics(Metrics.file(".")); LiebreContext.setStreamMetrics(Metrics.file(".")); LiebreContext.setUserMetrics(Metrics.file("."));*/ LiebreContext.setOperatorMetrics(Metrics.dropWizard()); LiebreContext.setUserMetrics(Metrics.dropWizard()); LiebreContext.setStreamMetrics(Metrics.dropWizard()); CsvReporter csvReporter = CsvReporter.forRegistry(Metrics.metricRegistry()) .build(Paths.get(".").toFile()); csvReporter.start(1, TimeUnit.SECONDS); Query query = new Query(); Random random = new Random(); Source<Double> src = query.addBaseSource("mySource", () -> { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } return random.nextDouble() * 100; }); Operator<Double, Double> mOp = query.addMapOperator("myMap", integer -> integer * Math.PI); Sink<Double> sink = query.addBaseSink("sadasdas3", myTuple -> { //System.out.println("tuple is " + myTuple); }); query.connect(src, mOp).connect(mOp, sink); query.activate(); //Util.sleep(10000); //query.deActivate(); } private static void startListener() { new Thread(() -> { try { ServerSocket ss = new ServerSocket(); // Unbound socket ss.bind(new InetSocketAddress("localhost", 2004)); // Bind the socket to a specific interface Socket client; while ((client = ss.accept()) != null) { System.out.println(client.toString()); byte[] b = client.getInputStream().readAllBytes(); System.out.println("b: " + Arrays.toString(b)); } } catch (IOException e) { e.printStackTrace(); } }).start(); } }
Markdown
UTF-8
1,241
2.671875
3
[]
no_license
This mongoose plugin allows for double-binding of array values in mongoose schema paths in a way that allows for dynamic population, which the normal path array structure does not. Example: old world: defining a key as an object array in a mongoose scheam like so: var model = Mongoose.model('members', { leads: [{type: Mongoose.Schema.types.ObjectId, ref: 'lead'}] }); is unwieldy in the database, and doesnt allow for implicit array population. new world: var model = Mongoose.model('members', { leads: [{type: Mongoose.Schema.ObjectId, ref: 'lead', linked: true, field: reverseField}] }); What this does: 1. the leads array is no longer stored in the members objects. This keeps the members objects short. 2. now, you can create a new lead, and if the path 'reverseField' for that lead has the ID of a members object, that lead will *automatically* appear in the leads array of the members document Note: this is still a pre-alpha plugin meant to supplement a larger plugin, and is not properly tested, documented, or vetting for widespread use currently. Note: the technical underpinning for this plugin is based on the mongoose virtual populate function released in version 4.5.0
C#
UTF-8
2,123
3.21875
3
[]
no_license
using System; using System.Collections.Generic; namespace Gabriel.MenuExample { class Program { static void Main(string[] args) { var listTc = InitData(); var depHelper = new DepartmentHelper(listTc); var tempList = depHelper.CreatMenu(); foreach (var item in tempList) { Console.WriteLine("{0}--Level:{1}--Id:{2}--Name:{3}--ParentId:{4}--SortId:{5}", BlankSpace(item.Level), item.Level, item.Id, item.Name, item.ParentId, item.SortId); } Console.ReadKey(); } private static List<Department> InitData() { List<Department> listTc = new List<Department> { new Department(1, "财务部", 2) {SortId = 99}, new Department(2, "公司总部", 0), new Department(3, "财务组1", 1), new Department(4, "财务组2", 1), new Department(5, "研发部", 2) {SortId = 98}, new Department(6, "研发组1", 5), new Department(7, "研发组2", 5), new Department(8, "研发组3", 5), new Department(9, "业务部", 2), new Department(10, "业务组1", 9), new Department(11, "业务组2", 9), new Department(12, "业务组3", 9), new Department(13, "研发组1第一小组", 6) {SortId = 99}, new Department(14, "业务组1第一小组", 10), new Department(15, "研发组1第二小组", 6), new Department(16, "研发组1第二小组1", 15), new Department(17, "研发组1第二小组2", 15), new Department(18, "研发组1第二小组2测试1", 17) }; return listTc; } /// <summary> /// 空格缩进 /// </summary> /// <param name="level"></param> /// <returns></returns> private static string BlankSpace(int level) { return "".PadLeft(level * 2, ' '); } } }
PHP
UTF-8
918
2.6875
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use App\Models\Multiuser; class CreateMultiusersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('multiusers', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); $Multiusers = array ( ['name'=>'ใช้งานคนเดียว'], ['name'=>'ใช้งานหลายคน'], ); foreach ($Multiusers as $Multiuser) { Multiuser::create($Multiuser); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('multiusers'); } }
Markdown
UTF-8
1,398
2.96875
3
[]
no_license
# Spacex A SpaceX Launch Explorer The goal of this assignment is to build a SpaceX Launch Explorer in React Native. Android is used as an emulator. <img width="282" alt="androidspacex" src="https://user-images.githubusercontent.com/56556859/107212801-596cc200-69bc-11eb-8933-265346732efa.png"> ## SetUp Instructions You must have Android Studio to use an Android Emulator, or connect your Android Device. To set up, clone this directory to your desktop. Navigate inside directory using terminal, and run "yarn android". Because installing extra dependencies was not allowed, this app does not have navigation. The CreateLaunch screen is partially built out. To view, comment out < LaunchFeed/ > in App.js and comment in < CreateLaunch/ >. ## Building the Screens and Components This app has 3 screens and consumes an open API provided by SpaceX. The mock ups are found here: https://balsamiq.cloud/sjj9rs9/p1zm2z7/r2278 Assignment: Spend 1 - 2 hours building out as much of the app as possible. For the purposes of this interview, it makes the most sense to focus on the Launch List Screen. While there are multiple screens and navigation in the design, for the purposes of this project don’t worry about navigation. You can stub out methods for navigation and only render 1 screen at a time. You should be able to complete the project without installing additional dependencies.
Markdown
UTF-8
1,164
4
4
[ "MIT" ]
permissive
# Daily notes So after I finished part 2, I was looking at other people's solutions and this one stuck out for me given it was so simple. This is Haskell ```haskell fuel = subtract 2 . (`div` 3) part1 = sum . map fuel part2 = sum . map (sum . tail . takeWhile (>= 0) . iterate fuel) ``` The main point that I was thinking about was that `iterate` function, which gives an infinite list back, but uses lazy evaluation, so it won't start creating entries of that list until you start running it (like how they do with `takeWhile`). I was thinking about this of having an infinite list to represent the calculation of taking the mass and doing `floor(n/3)-2` until it hit 0, and that can just be an infinite list technically. Then I remembered that JS now has lazy evaluation functionality using generator functions. So this would create that infinite list in JS: ```js function* generator(i) { let n = i; while (true) { n = Math.floor(n / 3) - 2; yield n; } } ``` and then you can create the generator like so and then pull numbers off of it by calling next ```js const gen = generator(/* some number */) gen.next().value // the next value ```
C
UTF-8
9,640
2.546875
3
[ "MIT", "Apache-2.0" ]
permissive
// Copyright 2015 Juan Luis Álvarez Martínez // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file z80_dasm.h * @brief Provides functions to decode z80 opcodes into human-readable text. * */ #ifndef __Z80_DASM #define __Z80_DASM #include <stdint.h> #ifdef __cplusplus extern "C" { #endif //Opcode branching info #define Z80D_TYPE_NORMAL (1<<0) /**<-- Opcode may continue execution on the next opcode. */ #define Z80D_TYPE_CONST_JUMP (1<<1) /**<-- Opcode has a constant jump address. */ #define Z80D_TYPE_REL_JUMP (1<<2) /**<-- Opcode can perform a calculated jump. */ #define Z80D_TYPE_INDIRECT_JUMP (1<<3) /**<-- Opcode performs a register/stack based jump. */ #define Z80D_TYPE_CONST_LOAD (1<<4) /**<-- Opcode loads an immediate constant (8bit). */ #define Z80D_TYPE_CONST_LOAD16 (1<<5) /**<-- Opcode loads an immediate constant (16bit). */ #define Z80D_TYPE_INDIRECT_LOAD (1<<6) /**<-- Opcode loads indirectly. */ //Opcode type #define Z80D_TYPE_CALL (1<<7) /**<-- Opcode is a call. */ #define Z80D_TYPE_RETURN (1<<8) /**<-- Opcode is a return. */ #define Z80D_TYPE_JUMP (1<<9) /**<-- Opcode is a jump. */ /// Contains all the info regarding an opcode at a given address. struct z80d_opcode_s{ char opcode_str[32]; ///<-- Mnemonic representing the opcode. uint8_t opcode[4]; ///<-- The opcode bytes. uint8_t size; ///<-- Opcode size. uint16_t address; ///<-- Opcode address. //Branch predictions uint16_t address_next; ///<-- Next opcode address if no jump. uint16_t address_jump; ///<-- Next opcode address if jump is effective. int16_t immediate; ///<-- Immediate value. uint16_t flags; ///<-- Opcode properties. }; typedef struct z80d_opcode_s z80d_opcode; /** * Decodes an opcode, writing a sring representing the opcode. * * @param opcode A 4-byte array containing the opcode. * @param size maximum size of the result string. * @param result pointer to the string where the result will be written. * @returns the opcode size in bytes. */ int z80d_decode(const uint8_t* opcode, unsigned int size, char* result); /** * Decodes an opcode, return an z80d_opcode struct. * * @param opcode A 4-byte array containing the opcode. * @param pc_addr The address where the opcode was found (PC). * @returns A z80_opcode struct containg all the opcode info. */ z80d_opcode z80d_decode_op(const uint8_t* opcode, uint16_t pc_addr); /* --- Disasm functions --- */ z80d_opcode zd_ADC_HL_rp(const uint8_t* opcode); z80d_opcode zd_ADD_HL_rp(const uint8_t* opcode); z80d_opcode zd_ADD_IXY_rp(const uint8_t* opcode); z80d_opcode zd_ADD_IXY_rp(const uint8_t* opcode); z80d_opcode zd_alu_IXYp(const uint8_t* opcode); z80d_opcode zd_alu_IXYp(const uint8_t* opcode); z80d_opcode zd_alu_n(const uint8_t* opcode); z80d_opcode zd_alu_r(const uint8_t* opcode); z80d_opcode zd_alu_r_undoc(const uint8_t* opcode); z80d_opcode zd_BIT_b_IXYp(const uint8_t* opcode); z80d_opcode zd_BIT_b_IXYp(const uint8_t* opcode); z80d_opcode zd_BIT_b_r(const uint8_t* opcode); z80d_opcode zd_BIT_b_r(const uint8_t* opcode); z80d_opcode zd_BIT_b_r(const uint8_t* opcode); z80d_opcode zd_bli(const uint8_t* opcode); z80d_opcode zd_CALL_cc_nn(const uint8_t* opcode); z80d_opcode zd_CALL_nn(const uint8_t* opcode); z80d_opcode zd_CCF(const uint8_t* opcode); z80d_opcode zd_CPL(const uint8_t* opcode); z80d_opcode zd_DAA(const uint8_t* opcode); z80d_opcode zd_DEC_IXY(const uint8_t* opcode); z80d_opcode zd_DEC_IXY(const uint8_t* opcode); z80d_opcode zd_DEC_IXYp(const uint8_t* opcode); z80d_opcode zd_DEC_IXYp(const uint8_t* opcode); z80d_opcode zd_DEC_r(const uint8_t* opcode); z80d_opcode zd_DEC_rp(const uint8_t* opcode); z80d_opcode zd_DI(const uint8_t* opcode); z80d_opcode zd_DJNZ_d(const uint8_t* opcode); z80d_opcode zd_EI(const uint8_t* opcode); z80d_opcode zd_EX(const uint8_t* opcode); z80d_opcode zd_EX_DE_HL(const uint8_t* opcode); z80d_opcode zd_EX_SPp_HL(const uint8_t* opcode); z80d_opcode zd_EX_SPp_IXY(const uint8_t* opcode); z80d_opcode zd_EX_SPp_IXY(const uint8_t* opcode); z80d_opcode zd_EXX(const uint8_t* opcode); z80d_opcode zd_HALT(const uint8_t* opcode); z80d_opcode zd_HALT(const uint8_t* opcode); z80d_opcode zd_HALT(const uint8_t* opcode); z80d_opcode zd_IM(const uint8_t* opcode); z80d_opcode zd_IM(const uint8_t* opcode); z80d_opcode zd_IM(const uint8_t* opcode); z80d_opcode zd_IN_A_np(const uint8_t* opcode); z80d_opcode zd_IN_r_Cp(const uint8_t* opcode); z80d_opcode zd_INC_IXY(const uint8_t* opcode); z80d_opcode zd_INC_IXY(const uint8_t* opcode); z80d_opcode zd_INC_IXYp(const uint8_t* opcode); z80d_opcode zd_INC_IXYp(const uint8_t* opcode); z80d_opcode zd_INC_r(const uint8_t* opcode); z80d_opcode zd_INC_rp(const uint8_t* opcode); z80d_opcode zd_JP_cc_nn(const uint8_t* opcode); z80d_opcode zd_JP_HLp(const uint8_t* opcode); z80d_opcode zd_JP_IXYp(const uint8_t* opcode); z80d_opcode zd_JP_IXYp(const uint8_t* opcode); z80d_opcode zd_JP_nn(const uint8_t* opcode); z80d_opcode zd_JR_cc_d(const uint8_t* opcode); z80d_opcode zd_JR_cc_d(const uint8_t* opcode); z80d_opcode zd_JR_cc_d(const uint8_t* opcode); z80d_opcode zd_JR_cc_d(const uint8_t* opcode); z80d_opcode zd_JR_d(const uint8_t* opcode); z80d_opcode zd_LD_A_BCp(const uint8_t* opcode); z80d_opcode zd_LD_A_DEp(const uint8_t* opcode); z80d_opcode zd_LD_A_I(const uint8_t* opcode); z80d_opcode zd_LD_A_nnp(const uint8_t* opcode); z80d_opcode zd_LD_A_R(const uint8_t* opcode); z80d_opcode zd_LD_BCp_A(const uint8_t* opcode); z80d_opcode zd_LD_DEp_A(const uint8_t* opcode); z80d_opcode zd_LD_HL_nnp(const uint8_t* opcode); z80d_opcode zd_LD_I_A(const uint8_t* opcode); z80d_opcode zd_LD_IXY_nn(const uint8_t* opcode); z80d_opcode zd_LD_IXY_nn(const uint8_t* opcode); z80d_opcode zd_LD_IXY_nnp(const uint8_t* opcode); z80d_opcode zd_LD_IXY_nnp(const uint8_t* opcode); z80d_opcode zd_LD_IXYH_n(const uint8_t* opcode); z80d_opcode zd_LD_IXYH_n(const uint8_t* opcode); z80d_opcode zd_LD_IXYL_n(const uint8_t* opcode); z80d_opcode zd_LD_IXYL_n(const uint8_t* opcode); z80d_opcode zd_LD_IXYp_n(const uint8_t* opcode); z80d_opcode zd_LD_IXYp_n(const uint8_t* opcode); z80d_opcode zd_LD_IXYp_r(const uint8_t* opcode); z80d_opcode zd_LD_IXYp_r(const uint8_t* opcode); z80d_opcode zd_LD_nnp_A(const uint8_t* opcode); z80d_opcode zd_LD_nnp_HL(const uint8_t* opcode); z80d_opcode zd_LD_nnp_IXY(const uint8_t* opcode); z80d_opcode zd_LD_nnp_IXY(const uint8_t* opcode); z80d_opcode zd_LD_nnp_rp(const uint8_t* opcode); z80d_opcode zd_LD_R_A(const uint8_t* opcode); z80d_opcode zd_LD_r_IXYp(const uint8_t* opcode); z80d_opcode zd_LD_r_IXYp(const uint8_t* opcode); z80d_opcode zd_LD_r_n(const uint8_t* opcode); z80d_opcode zd_LD_r_r(const uint8_t* opcode); z80d_opcode zd_LD_r_r_undoc(const uint8_t* opcode); z80d_opcode zd_LD_RES(const uint8_t* opcode); z80d_opcode zd_LD_RES(const uint8_t* opcode); z80d_opcode zd_LD_ROT(const uint8_t* opcode); z80d_opcode zd_LD_ROT(const uint8_t* opcode); z80d_opcode zd_LD_rp_nn(const uint8_t* opcode); z80d_opcode zd_LD_rp_nnp(const uint8_t* opcode); z80d_opcode zd_LD_SET(const uint8_t* opcode); z80d_opcode zd_LD_SET(const uint8_t* opcode); z80d_opcode zd_LD_SP_HL(const uint8_t* opcode); z80d_opcode zd_LD_SP_IXY(const uint8_t* opcode); z80d_opcode zd_LD_SP_IXY(const uint8_t* opcode); z80d_opcode zd_NEG(const uint8_t* opcode); z80d_opcode zd_NOP(const uint8_t* opcode); z80d_opcode zd_OUT_Cp_r(const uint8_t* opcode); z80d_opcode zd_OUT_np_A(const uint8_t* opcode); z80d_opcode zd_POP_IXY(const uint8_t* opcode); z80d_opcode zd_POP_IXY(const uint8_t* opcode); z80d_opcode zd_POP_rp2(const uint8_t* opcode); z80d_opcode zd_PUSH_IXY(const uint8_t* opcode); z80d_opcode zd_PUSH_IXY(const uint8_t* opcode); z80d_opcode zd_PUSH_rp2(const uint8_t* opcode); z80d_opcode zd_RES_b_IXYp(const uint8_t* opcode); z80d_opcode zd_RES_b_IXYp(const uint8_t* opcode); z80d_opcode zd_RES_b_r(const uint8_t* opcode); z80d_opcode zd_RET(const uint8_t* opcode); z80d_opcode zd_RET_cc(const uint8_t* opcode); z80d_opcode zd_RETI(const uint8_t* opcode); z80d_opcode zd_RETN(const uint8_t* opcode); z80d_opcode zd_RLA(const uint8_t* opcode); z80d_opcode zd_RLCA(const uint8_t* opcode); z80d_opcode zd_RLD(const uint8_t* opcode); z80d_opcode zd_rot(const uint8_t* opcode); z80d_opcode zd_rot_IXYp(const uint8_t* opcode); z80d_opcode zd_rot_IXYp(const uint8_t* opcode); z80d_opcode zd_RRA(const uint8_t* opcode); z80d_opcode zd_RRCA(const uint8_t* opcode); z80d_opcode zd_RRD(const uint8_t* opcode); z80d_opcode zd_RST_y(const uint8_t* opcode); z80d_opcode zd_SBC_HL_rp(const uint8_t* opcode); z80d_opcode zd_SCF(const uint8_t* opcode); z80d_opcode zd_SET_b_IXYp(const uint8_t* opcode); z80d_opcode zd_SET_b_IXYp(const uint8_t* opcode); z80d_opcode zd_SET_b_r(const uint8_t* opcode); /*Used for empty disasm spots on the decoder table*/ z80d_opcode zd_NULL(const uint8_t* opcode); #ifdef __cplusplus } #endif #endif
Java
UTF-8
10,043
1.898438
2
[ "MIT" ]
permissive
/* * Yahoo!広告 検索広告 API リファレンス / Yahoo! JAPAN Ads Search Ads API Reference * <div lang=\"ja\">Yahoo!広告 検索広告 APIのWebサービスについて説明します。</div> <div lang=\"en\">Search Ads API Web Services supported in Yahoo! JAPAN Ads API.</div> <div><a target=\"_blank\" href=\"https://github.com/yahoojp-marketing/ads-search-api-documents/blob/master/design/v11/Route.yaml\">OpenAPI Specification</a></div> <div lang=\"ja\"><a target=\"_blank\" href=\"https://github.com/yahoojp-marketing/ads-search-api-documents/blob/master/bestpractice/ja\">Best Practice</a></div> <div lang=\"en\"><a target=\"_blank\" href=\"https://github.com/yahoojp-marketing/ads-search-api-documents/blob/master/bestpractice/en\">Best Practice</a></div> * * The version of the OpenAPI document: v11 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package jp.co.yahoo.adssearchapi.v11.model; import java.util.Objects; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.util.ArrayList; import java.util.List; import jp.co.yahoo.adssearchapi.v11.model.AccountCustomizerServiceApprovalStatus; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; /** * &lt;div lang&#x3D;\&quot;ja\&quot;&gt;AccountCustomizerオブジェクトは、アカウントとカスタマイザー属性間の設定情報を格納します。&lt;/div&gt; &lt;div lang&#x3D;\&quot;en\&quot;&gt;AccountCustomizer object contains the configuration information between the account and the customizer attribute.&lt;/div&gt; */ @JsonPropertyOrder({ AccountCustomizer.JSON_PROPERTY_ACCOUNT_ID, AccountCustomizer.JSON_PROPERTY_CUSTOMIZER_ATTRIBUTE_ID, AccountCustomizer.JSON_PROPERTY_VALUE, AccountCustomizer.JSON_PROPERTY_APPROVAL_STATUS, AccountCustomizer.JSON_PROPERTY_DISAPPROVAL_REASON_CODES }) @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class AccountCustomizer { public static final String JSON_PROPERTY_ACCOUNT_ID = "accountId"; private Long accountId; public static final String JSON_PROPERTY_CUSTOMIZER_ATTRIBUTE_ID = "customizerAttributeId"; private Long customizerAttributeId; public static final String JSON_PROPERTY_VALUE = "value"; private String value; public static final String JSON_PROPERTY_APPROVAL_STATUS = "approvalStatus"; private AccountCustomizerServiceApprovalStatus approvalStatus; public static final String JSON_PROPERTY_DISAPPROVAL_REASON_CODES = "disapprovalReasonCodes"; private List<String> disapprovalReasonCodes; public AccountCustomizer() { } public AccountCustomizer accountId(Long accountId) { this.accountId = accountId; return this; } /** * &lt;div lang&#x3D;\&quot;ja\&quot;&gt;アカウントIDです。&lt;br&gt; このフィールドは、レスポンスの際に返却されますが、リクエストの際には無視されます。&lt;/div&gt; &lt;div lang&#x3D;\&quot;en\&quot;&gt;Account ID.&lt;br&gt; Although this field will be returned in the response, it will be ignored on input.&lt;/div&gt; * @return accountId **/ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public Long getAccountId() { return accountId; } @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setAccountId(Long accountId) { this.accountId = accountId; } public AccountCustomizer customizerAttributeId(Long customizerAttributeId) { this.customizerAttributeId = customizerAttributeId; return this; } /** * &lt;div lang&#x3D;\&quot;ja\&quot;&gt;カスタマイザー属性IDです。&lt;br&gt; ADDおよびREMOVE時、このフィールドは必須となります。&lt;/div&gt; &lt;div lang&#x3D;\&quot;en\&quot;&gt;CustomizerAttribute ID.&lt;br&gt; This field is required in ADD and REMOVE operation.&lt;/div&gt; * @return customizerAttributeId **/ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_CUSTOMIZER_ATTRIBUTE_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public Long getCustomizerAttributeId() { return customizerAttributeId; } @JsonProperty(JSON_PROPERTY_CUSTOMIZER_ATTRIBUTE_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setCustomizerAttributeId(Long customizerAttributeId) { this.customizerAttributeId = customizerAttributeId; } public AccountCustomizer value(String value) { this.value = value; return this; } /** * &lt;div lang&#x3D;\&quot;ja\&quot;&gt;属性値です。挿入用広告に挿入されます。&lt;br&gt; 入力仕様の詳細は以下のヘルプを参照してください。&lt;br&gt; ・&lt;a href&#x3D;\&quot;https://ads-help.yahoo.co.jp/yahooads/search/articledetail?lan&#x3D;ja&amp;aid&#x3D;114459\&quot;&gt;アドカスタマイザー属性を関連付ける&lt;/a&gt;&lt;br&gt; ADD時、このフィールドは必須となります。&lt;/div&gt; &lt;div lang&#x3D;\&quot;en\&quot;&gt;The attribute value. It will be inserted into the ad for insertion.&lt;br&gt; See also the help below.&lt;br&gt; * &lt;a href&#x3D;\&quot;https://ads-help.yahoo.co.jp/yahooads/search/articledetail?lan&#x3D;en&amp;aid&#x3D;61568\&quot;&gt;Associate ad customizer attributes&lt;/a&gt;&lt;br&gt; This field is required in ADD operation.&lt;/div&gt; * @return value **/ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_VALUE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public String getValue() { return value; } @JsonProperty(JSON_PROPERTY_VALUE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setValue(String value) { this.value = value; } public AccountCustomizer approvalStatus(AccountCustomizerServiceApprovalStatus approvalStatus) { this.approvalStatus = approvalStatus; return this; } /** * Get approvalStatus * @return approvalStatus **/ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_APPROVAL_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public AccountCustomizerServiceApprovalStatus getApprovalStatus() { return approvalStatus; } @JsonProperty(JSON_PROPERTY_APPROVAL_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setApprovalStatus(AccountCustomizerServiceApprovalStatus approvalStatus) { this.approvalStatus = approvalStatus; } public AccountCustomizer disapprovalReasonCodes(List<String> disapprovalReasonCodes) { this.disapprovalReasonCodes = disapprovalReasonCodes; return this; } public AccountCustomizer addDisapprovalReasonCodesItem(String disapprovalReasonCodesItem) { if (this.disapprovalReasonCodes == null) { this.disapprovalReasonCodes = new ArrayList<>(); } this.disapprovalReasonCodes.add(disapprovalReasonCodesItem); return this; } /** * &lt;div lang&#x3D;\&quot;ja\&quot;&gt;審査否認理由です。&lt;br&gt; このフィールドは、レスポンスの際に返却されますが、リクエストの際には無視されます。&lt;/div&gt; &lt;div lang&#x3D;\&quot;en\&quot;&gt;Reject reason on editorial review.&lt;br&gt; Although this field will be returned in the response, it will be ignored on input.&lt;/div&gt; * @return disapprovalReasonCodes **/ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_DISAPPROVAL_REASON_CODES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public List<String> getDisapprovalReasonCodes() { return disapprovalReasonCodes; } @JsonProperty(JSON_PROPERTY_DISAPPROVAL_REASON_CODES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setDisapprovalReasonCodes(List<String> disapprovalReasonCodes) { this.disapprovalReasonCodes = disapprovalReasonCodes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AccountCustomizer accountCustomizer = (AccountCustomizer) o; return Objects.equals(this.accountId, accountCustomizer.accountId) && Objects.equals(this.customizerAttributeId, accountCustomizer.customizerAttributeId) && Objects.equals(this.value, accountCustomizer.value) && Objects.equals(this.approvalStatus, accountCustomizer.approvalStatus) && Objects.equals(this.disapprovalReasonCodes, accountCustomizer.disapprovalReasonCodes); } @Override public int hashCode() { return Objects.hash(accountId, customizerAttributeId, value, approvalStatus, disapprovalReasonCodes); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AccountCustomizer {\n"); sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n"); sb.append(" customizerAttributeId: ").append(toIndentedString(customizerAttributeId)).append("\n"); sb.append(" value: ").append(toIndentedString(value)).append("\n"); sb.append(" approvalStatus: ").append(toIndentedString(approvalStatus)).append("\n"); sb.append(" disapprovalReasonCodes: ").append(toIndentedString(disapprovalReasonCodes)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
JavaScript
UTF-8
1,502
2.59375
3
[]
no_license
// third party library import http from 'axios'; // actionType import { VIEW_PROCESSING, VIEW_SUCCESS, VIEW_FAILURE, VIEW_ERROR_CLEARED, } from '../action_types/viewEntry'; /** * @param {object} data * @desc checking create loading * @returns {object} type */ export function viewPosting(data) { return { type: VIEW_PROCESSING, payload: data, }; } /** * @desc checking successful create * @returns {object} type */ export function viewSuccess(data) { return { type: VIEW_SUCCESS, payload: data, }; } /** * @param {object} data * @desc checking unsuccessful create * @returns {object} type */ export function viewFailure(data) { return { type: VIEW_FAILURE, payload: data, }; } /** * @param {object} data * @desc clear error while create * @returns {object} type */ export function viewError() { return { type: VIEW_ERROR_CLEARED, }; } export const userViewRequest = () => (dispatch) => { dispatch(viewPosting(true)); const verificationToken = localStorage.getItem('diaryToken'); const id = localStorage.getItem('currentId'); const options = { headers: { 'Content-Type': 'application/json;charset=UTF-8', 'x-access-token': `${verificationToken}` } }; return http .get(`https://my-diary-challenge.herokuapp.com/api/v1/entries/${id}`, options) .then((payload) => { dispatch(viewSuccess(payload.data)); }) .catch((err) => { dispatch(viewFailure(err.data.message)); }); }
Swift
UTF-8
1,762
3.0625
3
[]
no_license
// // LoginViewModel.swift // RecipiesRX // // Created by Yehia Samak on 24/06/2021. // import Foundation import RxSwift protocol LoginViewModelProtocol { var emailTextSubject: PublishSubject<String> {get} var passwordTextSubject: PublishSubject<String> {get} var title: String {get} func isValid() -> Observable<Bool> func loginButtonTapped() } class LoginViewModel: LoginViewModelProtocol{ //MARK: Public Attribute var emailTextSubject = PublishSubject<String>() var passwordTextSubject = PublishSubject<String>() var title = "Login" //MARK: Private attribute private weak var coordinator: LoginCoordinator? init(coordinator: LoginCoordinator) { self.coordinator = coordinator } } //MARK: Public Functions extension LoginViewModel{ func isValid() -> Observable<Bool>{ return Observable.combineLatest(emailTextSubject.asObserver(), passwordTextSubject.asObserver()).map{[weak self] email, password in return self?.isValid(email: email) ?? false && self!.isValid(password: password) } } func loginButtonTapped(){ coordinator?.startRecipes() } } //MARK: Private Function extension LoginViewModel{ private func isValid(email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailPred.evaluate(with: email) } private func isValid(password: String) -> Bool{ let passwordRegEx = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$" let passwordPred = NSPredicate(format:"SELF MATCHES %@", passwordRegEx) return passwordPred.evaluate(with: password) } }
Shell
UTF-8
4,791
2.984375
3
[]
no_license
#!/bin/bash #Note users will require a github account and need to have virtualenv installed setup(){ mkdir ./Dropseq_Alignment_Cookbook cd Dropseq_Alignment_Cookbook wget http://mccarrolllab.com/download/1276/Drop-seq_tools-1.13-3.zip unzip Drop-seq_tools-1.13-3.zip mkdir temp_files wget https://ftp-trace.ncbi.nlm.nih.gov/sra/sdk/2.9.0/sratoolkit.2.9.0-ubuntu64.tar.gz tar -xvzf sratoolkit.2.9.0-ubuntu64.tar.gz wget https://github.com/broadinstitute/picard/releases/download/2.18.0/picard.jar cd .. #First make a directory in which simulation data and programs will be kept mkdir ./Simulation #Install programs in directory cd Simulation #Install RSEM wget https://github.com/deweylab/RSEM/archive/v1.3.0.tar.gz tar -xvzf v1.3.0.tar.gz rm v1.3.0.tar.gz cd RSEM make make install prefix=. cd .. if ! command -v ./RSEM/rsem-generate-data-matrix >/dev/null 2>&1; then echo "Failed to install RSEM" exit 1 else echo "Successfully installed RSEM" fi #Fix bug in RSEM (see https://github.com/deweylab/RSEM/pull/79) git clone https://github.com/jenni-westoby/RSEM.git cp RSEM/simul.h RSEM/simul.h rm -r RSEM #Install Sailfish wget https://github.com/kingsfordgroup/sailfish/releases/download/v0.10.0/SailfishBeta-0.10.0_CentOS5.tar.gz tar -xvzf SailfishBeta-0.10.0_CentOS5.tar.gz rm SailfishBeta-0.10.0_CentOS5.tar.gz export LD_LIBRARY_PATH=`pwd`/SailfishBeta-0.10.0_CentOS5/lib:$LD_LIBRARY_PATH export PATH=`pwd`/SailfishBeta-0.10.0_CentOS5/bin:$PATH if ! command -v ./SailfishBeta-0.10.0_CentOS5/bin/sailfish -h; then echo "Failed to install Sailfish" exit 1 else echo "Successfully installed Sailfish" fi #Install eXpress wget https://pachterlab.github.io/eXpress/downloads/express-1.5.1/express-1.5.1-linux_x86_64.tgz tar -xvzf express-1.5.1-linux_x86_64.tgz rm express-1.5.1-linux_x86_64.tgz if ! command -v ./express-1.5.1-linux_x86_64/express >/dev/null 2>&1; then echo "Failed to install eXpress" exit 1 else echo "Successfully installed eXpress" fi #Install Salmon wget https://github.com/COMBINE-lab/salmon/releases/download/v0.8.2/Salmon-0.8.2_linux_x86_64.tar.gz tar -xvzf Salmon-0.8.2_linux_x86_64.tar.gz rm Salmon-0.8.2_linux_x86_64.tar.gz if ! command -v ./Salmon-0.8.2_linux_x86_64/bin/salmon >/dev/null 2>&1; then echo "Failed to install Salmon" exit 1 else echo "Successfully installed Salmon" fi #Install Kallisto wget https://github.com/pachterlab/kallisto/releases/download/v0.43.1/kallisto_linux-v0.43.1.tar.gz tar -xvzf kallisto_linux-v0.43.1.tar.gz rm kallisto_linux-v0.43.1.tar.gz if ! command -v ./kallisto_linux-v0.43.1/kallisto >/dev/null 2>&1; then echo "Failed to install Kallisto" exit 1 else echo "Successfully installed Kallisto" fi #Install STAR git clone https://github.com/alexdobin/STAR.git if ! command -v ./STAR/bin/Linux_x86_64/STAR >/dev/null 2>&1; then echo "Failed to install STAR" exit 1 else echo "Successfully installed STAR" fi #Install samtools wget https://github.com/samtools/samtools/releases/download/1.5/samtools-1.5.tar.bz2 bzip2 -d samtools-1.5.tar.bz2 tar -xvf samtools-1.5.tar rm samtools-1.5.tar cd samtools-1.5/ ./configure --prefix=`pwd` make make install cd .. if ! command -v ./samtools-1.5/samtools >/dev/null 2>&1; then echo "Failed to install SAMtools" exit 1 else echo "Successfully installed SAMtools" fi #Get drop-seq data ../Dropseq_Alignment_Cookbook/sratoolkit.2.9.0-ubuntu64/bin/prefetch SRR3587500 ../Dropseq_Alignment_Cookbook/sratoolkit.2.9.0-ubuntu64/bin/sam-dump SRR3587500.sra | ./samtools-1.5/samtools view -bS -> ../Dropseq_Alignment_Cookbook/SRR3587500.bam #Install virtualenv and RSeQC git clone https://github.com/pypa/virtualenv.git python virtualenv/virtualenv.py venv source venv/bin/activate pip install RSeQC if ! command -v >/dev/null 2>&1; then echo "Failed to install RSeQC" exit 1 else echo "Successfully installed RSeQC" fi #Make a directory for RNA-seq data including raw and simulated data mkdir data cd data mkdir simulated mkdir temp cd .. #Make a directory for quality control statistics for raw and simulated data mkdir QC_stats cd QC_stats mkdir raw mkdir simulated mkdir temp_raw mkdir temp_simulated cd .. mkdir indices mkdir indices/STAR mkdir indices/Salmon_SMEM mkdir indices/Salmon_quasi mkdir indices/Kallisto mkdir indices/Sailfish mkdir bamfiles mkdir bamfiles/raw mkdir bamfiles/simulated mkdir time_stats mkdir ref mkdir results_matrices mkdir raw_results/data mkdir figures/data mkdir figures/pdfs mkdir figures/pngs } "$@"
C
UTF-8
287
3.484375
3
[]
no_license
#include "lists.h" /** * sum_listint - sum of list * @head: head pointer * Return: sum of all int */ int sum_listint(listint_t *head) { int sum; listint_t *temp; temp = head; for (sum = 0, temp = head; temp != NULL; temp = temp->next) { sum += temp->n; } return (sum); }
C++
UTF-8
3,848
3.203125
3
[]
no_license
#include <iostream> #include <stdio.h> ///STRUCT CON FOPEN using namespace std; struct alumno{ char nombre[100], licenciatura[100]; int saldo, matricula; }; struct alumno llena_alumno() { struct alumno a; cout<<"\n Nombre: "; cin>>a.nombre; cout<<"\n Saldo: "; cin>>a.saldo; cout<<"\n Licenciatura: "; cin>>a.licenciatura; cout<<"\n Matricula: "; cin>>a.matricula; return a; } int leer_fopen(struct alumno a[20]) { FILE *fp; int numero, i; fp=fopen("archivo.txt","r"); if(fp==NULL) { cout<<"\nNo se pudo leer el archivo"<<endl; } else { fscanf(fp,"%d", &numero); cout<<"\nLectura con exito"<<endl; cout<<numero; for(i=0; i<numero; i++) { fscanf(fp,"%s", a[i].nombre); fscanf(fp,"%d", &a[i].saldo); fscanf(fp,"%s", a[i].licenciatura); fscanf(fp,"%d", &a[i].matricula); } fclose(fp); return numero; } } void escribe_fopen(struct alumno a[20], int na) { FILE *fp; int num=0, i; fp=fopen("archivo.txt","w"); if(fp != NULL) { fprintf(fp,"%d\n",na); for(i=0; i<na; i++) { fprintf(fp,"%s\n", a[i].nombre); fprintf(fp,"%d\n", a[i].saldo); fprintf(fp,"%s\n", a[i].licenciatura); fprintf(fp,"%d\n", a[i].matricula); } } fclose(fp); } void print_alumno(struct alumno a){ cout<<"\nImpresion"<<endl; cout<<"\nNombre: "<<a.nombre<<endl; cout<<"\nSaldo: "<<a.saldo<<endl; cout<<"\nLicenciatura: "<<a.licenciatura<<endl; cout<<"\nMatricula: "<<a.matricula<<endl; cout<<"\nTermina la impresion"<<endl; } int elimina_alumno(struct alumno g[20], int na) { int cont=-1, i, x, y; cout<<"\n Introduzca el indice a eliminar: "; cin>>x; for(i=0;i<na; i++) { if(x==g[i].matricula) cont=i; } if(cont!=-1) { for(y=cont; y<na; y++) { g[y]=g[y+1]; } } return cont; } int menu() { int opcion; cout<<"\nMenu Estructuras Dinamicas"<<endl; cout<<"\n1.-Inserta"<<endl; cout<<"\n2.-Muestra"<<endl; cout<<"\n3.-Elimina"<<endl; cout<<"\n4.-Leer con FOPEN"<<endl; cout<<"\n5.-Escribir con FOPEN"<<endl; cout<<"\n6.-Salir"<<endl; cout<<"\nIntroduzca una opcion: "; cin>>opcion; return opcion; } int main() { FILE *fp; int na=0, opcion, i,m; float prueba; struct alumno g[20]; do { opcion=menu(); switch(opcion) { case 1: { g[na]=llena_alumno(); na++; break; } case 2: { for(i=0; i<na; i++) { print_alumno(g[i]); } break; } case 3: { m=elimina_alumno(g,na); if(m==-1) cout<<"\nNo se elimino"<<endl; else { na--; cout<<"\nSi se elimino"<<endl; } break; } case 4: { na=leer_fopen(g); cout<<"\n"<<na<<endl; break; } case 5: { escribe_fopen(g, na); } } }while(opcion!=6); return 0; }
C++
UTF-8
2,651
2.609375
3
[]
no_license
#define HYSTERESIS 2 #define UPDATE_PERIOD 5000 //#define CALIBRATION_FACTOR 1 //#define CALIBRATION_OFFSET 0 #define POT_RANGE_LOW 200//150 #define POT_RANGE_HIGH 200//230 #define IO_COEFF 0.65F #define RELAY_PIN 13 #define THERMISTOR_PIN A0 #define POTENTIOMETER_PIN A1 #define NUMSAMPLES 5 #define SERIESRESISTOR 10000 #define THERMISTORNOMINAL 10000 #define BCOEFFICIENT 3950 #define TEMPERATURENOMINAL 25 void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); pinMode(THERMISTOR_PIN, INPUT); pinMode(POTENTIOMETER_PIN, INPUT); //pinmodes } uint16_t read_and_average(uint8_t pin) { uint32_t average = 0; for (int i = 0; i < NUMSAMPLES; i++) { average += analogRead(pin); delay(1); } average /= NUMSAMPLES; return average; } uint8_t read_measured() { float measured = read_and_average(THERMISTOR_PIN); measured = 1023 / measured - 1; measured = SERIESRESISTOR / measured; Serial.print("Thermistor resistance: "); Serial.print(measured); Serial.println(" Ohms"); float steinhart; steinhart = measured / THERMISTORNOMINAL; // (R/Ro) steinhart = log(steinhart); // ln(R/Ro) steinhart /= BCOEFFICIENT; // 1/B * ln(R/Ro) steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To) steinhart = 1.0 / steinhart; // Invert steinhart -= 273.15; return steinhart * 0.65; } uint8_t read_target() { uint16_t target = read_and_average(POTENTIOMETER_PIN); Serial.print("Pot: "); Serial.print(target); Serial.println(""); return map(target, 0/*depends on the pot and PSU*/, 990/*depends on the pot and PSU1023*/, POT_RANGE_LOW, POT_RANGE_HIGH); } void control_relay(uint8_t estimated, uint8_t target) { static bool activated = true; if (activated) { if (estimated + HYSTERESIS > target) activated = false; } else { if (estimated - HYSTERESIS < target) activated = true; } Serial.print("Relay is in the "); Serial.print(activated ? "on" : "off"); Serial.println(" state."); digitalWrite(RELAY_PIN, activated); //digitalWrite(RELAY_PIN, 0); } void print_temperatures(uint8_t measured, uint8_t estimated, uint8_t target) { Serial.print("Measured inside temp: "); Serial.print(measured); Serial.print(" *C; Estimated outside temp: "); Serial.print(estimated); Serial.print(" *C; Target temp: "); Serial.print(target); Serial.println(" *C"); } void loop() { uint8_t measured = read_measured(); uint8_t target = read_target(); uint8_t estimated = measured * IO_COEFF; print_temperatures(measured, estimated, target); control_relay(measured, target); delay(UPDATE_PERIOD); //Put to sleep? }
Markdown
UTF-8
7,188
2.578125
3
[ "MIT" ]
permissive
--- category: Components group: Data Entry title: Cascader cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*tokLTp73TsQAAAAAAAAAAAAADrJ8AQ/original coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*5-ArSLl5UBsAAAAAAAAAAAAADrJ8AQ/original demo: cols: 2 --- Cascade selection box. ## When To Use - When you need to select from a set of associated data set. Such as province/city/district, company level, things classification. - When selecting from a large data set, with multi-stage classification separated for easy selection. - Chooses cascade items in one float layer for better user experience. ## Examples <!-- prettier-ignore --> <code src="./demo/basic.tsx">Basic</code> <code src="./demo/default-value.tsx">Default value</code> <code src="./demo/custom-trigger.tsx">Custom trigger</code> <code src="./demo/hover.tsx">Hover</code> <code src="./demo/disabled-option.tsx">Disabled option</code> <code src="./demo/change-on-select.tsx">Change on select</code> <code src="./demo/multiple.tsx">Multiple</code> <code src="./demo/showCheckedStrategy.tsx">ShowCheckedStrategy</code> <code src="./demo/size.tsx">Size</code> <code src="./demo/custom-render.tsx">Custom render</code> <code src="./demo/search.tsx">Search</code> <code src="./demo/lazy.tsx">Load Options Lazily</code> <code src="./demo/fields-name.tsx">Custom Field Names</code> <code src="./demo/suffix.tsx" debug>Custom Icons</code> <code src="./demo/custom-dropdown.tsx">Custom dropdown</code> <code src="./demo/placement.tsx">Placement</code> <code src="./demo/status.tsx">Status</code> <code src="./demo/render-panel.tsx" debug>_InternalPanelDoNotUseOrYouWillBeFired</code> ## API Common props ref:[Common props](/docs/react/common-props) ```jsx <Cascader options={options} onChange={onChange} /> ``` | Property | Description | Type | Default | Version | | --- | --- | --- | --- | --- | | allowClear | Show clear button | boolean \| { clearIcon?: ReactNode } | true | 5.8.0: Support object type | | autoFocus | If get focus when component mounted | boolean | false | | | bordered | Whether has border style | boolean | true | | | changeOnSelect | (Work on single select) Change value on each selection if set to true, see above demo for details | boolean | false | | | className | The additional css class | string | - | | | defaultValue | Initial selected value | string\[] \| number\[] | \[] | | | disabled | Whether disabled select | boolean | false | | | displayRender | The render function of displaying selected options | (label, selectedOptions) => ReactNode | label => label.join(`/`) | `multiple`: 4.18.0 | | tagRender | Custom render function for tags in `multiple` mode | (label: string, onClose: function, value: string) => ReactNode | - | | | popupClassName | The additional className of popup overlay | string | - | 4.23.0 | | dropdownRender | Customize dropdown content | (menus: ReactNode) => ReactNode | - | 4.4.0 | | expandIcon | Customize the current item expand icon | ReactNode | - | 4.4.0 | | expandTrigger | expand current item when click or hover, one of `click` `hover` | string | `click` | | | fieldNames | Custom field name for label and value and children | object | { label: `label`, value: `value`, children: `children` } | | | getPopupContainer | Parent Node which the selector should be rendered to. Default to `body`. When position issues happen, try to modify it into scrollable content and position it relative. [example](https://codepen.io/afc163/pen/zEjNOy?editors=0010) | function(triggerNode) | () => document.body | | | loadData | To load option lazily, and it cannot work with `showSearch` | (selectedOptions) => void | - | | | maxTagCount | Max tag count to show. `responsive` will cost render performance | number \| `responsive` | - | 4.17.0 | | maxTagPlaceholder | Placeholder for not showing tags | ReactNode \| function(omittedValues) | - | 4.17.0 | | maxTagTextLength | Max tag text length to show | number | - | 4.17.0 | | notFoundContent | Specify content to show when no result matches | string | `Not Found` | | | open | Set visible of cascader popup | boolean | - | 4.17.0 | | options | The data options of cascade | [Option](#option)\[] | - | | | placeholder | The input placeholder | string | `Please select` | | | placement | Use preset popup align config from builtinPlacements | `bottomLeft` `bottomRight` `topLeft` `topRight` | `bottomLeft` | 4.17.0 | | showSearch | Whether show search input in single mode | boolean \| [Object](#showsearch) | false | | | size | The input size | `large` \| `middle` \| `small` | - | | | status | Set validation status | 'error' \| 'warning' | - | 4.19.0 | | style | The additional style | CSSProperties | - | | | suffixIcon | The custom suffix icon | ReactNode | - | | | value | The selected value | string\[] \| number\[] | - | | | onChange | Callback when finishing cascader select | (value, selectedOptions) => void | - | | | onDropdownVisibleChange | Callback when popup shown or hidden | (value) => void | - | 4.17.0 | | multiple | Support multiple or not | boolean | - | 4.17.0 | | removeIcon | The custom remove icon | ReactNode | - | | | showCheckedStrategy | The way show selected item in box. ** `SHOW_CHILD`: ** just show child treeNode. **`Cascader.SHOW_PARENT`:** just show parent treeNode (when all child treeNode under the parent treeNode are checked) | `Cascader.SHOW_PARENT` \| `Cascader.SHOW_CHILD` | `Cascader.SHOW_PARENT` | 4.20.0 | | searchValue | Set search value, Need work with `showSearch` | string | - | 4.17.0 | | onSearch | The callback function triggered when input changed | (search: string) => void | - | 4.17.0 | | dropdownMenuColumnStyle | The style of the drop-down menu column | CSSProperties | - | | | loadingIcon | The appearance of lazy loading (now is useless) | ReactNode | - | | ### showSearch | Property | Description | Type | Default | Version | | --- | --- | --- | --- | --- | | filter | The function will receive two arguments, inputValue and option, if the function returns true, the option will be included in the filtered set; Otherwise, it will be excluded | function(inputValue, path): boolean | - | | | limit | Set the count of filtered items | number \| false | 50 | | | matchInputWidth | Whether the width of list matches input, ([how it looks](https://github.com/ant-design/ant-design/issues/25779)) | boolean | true | | | render | Used to render filtered options | function(inputValue, path): ReactNode | - | | | sort | Used to sort filtered options | function(a, b, inputValue) | - | | ### Option ```typescript interface Option { value: string | number; label?: React.ReactNode; disabled?: boolean; children?: Option[]; // Determines if this is a leaf node(effective when `loadData` is specified). // `false` will force trade TreeNode as a parent node. // Show expand icon even if the current node has no children. isLeaf?: boolean; } ``` ## Methods | Name | Description | Version | | ------- | ------------ | ------- | | blur() | Remove focus | | | focus() | Get focus | | ## Design Token <ComponentTokenTable component="Cascader"></ComponentTokenTable>
C++
UTF-8
955
3.25
3
[]
no_license
#include <iostream> #include <string> #include <queue> std::queue<int> Queue; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); int N; std::cin >> N; for (int i = 0; i < N; i++) { std::string query; std::cin >> query; if (query == "push") { int number; std::cin >> number; Queue.push(number); continue; } else if (query == "pop") { if (Queue.empty()) { std::cout << -1 << '\n'; continue; } else { std::cout << Queue.front() << '\n'; Queue.pop(); continue; } } else if (query == "size") { std::cout << Queue.size() << '\n'; continue; } else if (query == "empty") { std::cout << Queue.empty() << '\n'; continue; } else if (query == "front") if (Queue.empty()) std::cout << -1 << '\n'; else std::cout << Queue.front() << '\n'; else if (Queue.empty()) std::cout << -1 << '\n'; else std::cout << Queue.back() << '\n'; } }
Java
UTF-8
999
2.09375
2
[]
no_license
package cz.orany.m20f; import io.micronaut.context.ApplicationContext; import io.micronaut.function.FunctionBean; import io.micronaut.function.executor.FunctionInitializer; import javax.inject.Inject; import java.util.function.Function; @FunctionBean(value = "mn-two-zero-function", method = "apply") public class MnTwoZeroFunctionHandler extends FunctionInitializer implements Function<MnTwoZeroFunctionRequest, MnTwoZeroFunctionResponse> { @Inject private MnTwoZeroFunctionService mnTwoZeroFunctionService; @Override public MnTwoZeroFunctionResponse apply(MnTwoZeroFunctionRequest event) { return mnTwoZeroFunctionService.handle(event); } public MnTwoZeroFunctionHandler() { super(); } public MnTwoZeroFunctionHandler(ApplicationContext applicationContext) { super(applicationContext); } public MnTwoZeroFunctionHandler(ApplicationContext applicationContext, boolean inject) { super(applicationContext, inject); } }
C++
UTF-8
83,653
2.578125
3
[]
no_license
#ifdef HAVE_CONFIG_H #include <config.hpp> #endif #include <complex> #include <fstream> #include <iostream> #include <vector> #include <Eigen/Dense> #include <valarray> #include <math.h> #include <chrono> #include <omp.h> using namespace std; using namespace Eigen; using namespace std::chrono; //coordinates in the lattice using coords_t=array<int,4>; //complex double using dcompl=complex<double>; //propagator (12X12) using prop_t=Matrix<dcompl,12,12>; //list of propagators using vprop_t=valarray<prop_t>; using vvprop_t=valarray< valarray<prop_t> >; using vvvprop_t=valarray< valarray< valarray<prop_t> > >; //list of gamma for a given momentum using qline_t=valarray<prop_t>; using vqline_t=valarray<qline_t>; using vvqline_t=valarray<vqline_t>; using vert_t = vvqline_t; //list of jackknife propagators using jprop_t=valarray< valarray<prop_t> >; //list of jackknife vertices using jvert_t=valarray< vert_t >; //valarray of complex double using vd_t=valarray<double>; //valarray of valarray of complex double using vvd_t=valarray< valarray<double> > ; //valarray of valarray of valarray of complex double using vvvd_t=valarray< valarray< valarray<double> > >; using vvvvd_t=valarray<vvvd_t>; using vvvvvd_t=valarray<vvvvd_t>; //valarray of complex double using vdcompl_t=valarray<dcompl>; using vvdcompl_t=valarray< vdcompl_t >; using vvvdcompl_t=valarray< vvdcompl_t >; using vvvvdcompl_t=valarray< vvvdcompl_t >; //valarray of Eigen Vectors using vXd_t=valarray<VectorXd>; //useful notation using jZ_t=vvd_t; using jZbil_t=vvvvd_t; using jproj_t=vvvvd_t; //list of momenta vector<coords_t> mom_list; int nr,nm,nmr; void read_mom_list(const string &path) { //file ifstream input(path); if(!input.good()) { cerr<<"Error opening "<<path<<endl; exit(1); } //loop until end of file while(!input.eof()) { coords_t c; for(int mu=0;mu<4;mu++) input>>c[mu]; if(input.good()) mom_list.push_back(c); } } //read file void read_internal(double &t,ifstream& infile) { infile.read((char*) &t,sizeof(double)); } //template <class T> void read_internal(VectorXd &V, ifstream& infile) { for(int i=0; i<V.size();i++) read_internal(V(i),infile); } template <class T> void read_internal(valarray<T> &v, ifstream& infile) { for(auto &i : v) read_internal(i,infile); } template <class T> void read_vec( T &vec, const char* path) { ifstream infile(path,ifstream::binary); if (infile.is_open()) { for(auto &i : vec) read_internal(i,infile); infile.close(); } else cout << "Unable to open the input file "<<path<<endl; } //factorial int fact(int n) { if(n > 1) return n * fact(n - 1); else return 1; } valarray<VectorXd> fit_chiral_jackknife(const vvd_t &coord, vd_t &error, const vector<vd_t> &y, const int range_min, const int range_max) { int n_par = coord.size(); int njacks = y[0].size(); MatrixXd S(n_par,n_par); valarray<VectorXd> Sy(VectorXd(n_par),njacks); valarray<VectorXd> jpars(VectorXd(n_par),njacks); //initialization S=MatrixXd::Zero(n_par,n_par); for(int ijack=0; ijack<njacks; ijack++) { Sy[ijack]=VectorXd::Zero(n_par); jpars[ijack]=VectorXd::Zero(n_par); } //definition for(int i=range_min; i<range_max; i++) { if(error[i]<1e-50) error[i]+=1e-50; for(int j=0; j<n_par; j++) for(int k=0; k<n_par; k++) if(std::isnan(error[i])==0) S(j,k) += coord[j][i]*coord[k][i]/(error[i]*error[i]); for(int ijack=0; ijack<njacks; ijack++) for(int k=0; k<n_par; k++) if(std::isnan(error[i])==0) Sy[ijack](k) += y[i][ijack]*coord[k][i]/(error[i]*error[i]); } for(int ijack=0; ijack<njacks; ijack++) jpars[ijack] = S.colPivHouseholderQr().solve(Sy[ijack]); return jpars; } valarray< valarray<VectorXd> > fit_chiral_Z_jackknife(const vvd_t &coord, vvd_t &error, const vector<vvd_t> &y, const int range_min, const int range_max) { // cout<<"DEBUG---(a)"<<endl; int n_par = coord.size(); int njacks = y[0].size(); int nbil = y[0][0].size(); // cout<<"DEBUG---(b)"<<endl; valarray<MatrixXd> S(MatrixXd(n_par,n_par),nbil); valarray< valarray<VectorXd> > Sy(valarray<VectorXd>(VectorXd(n_par),njacks),nbil); valarray< valarray<VectorXd> > jpars(valarray<VectorXd>(VectorXd(n_par),njacks),nbil); // cout<<"DEBUG---(c)"<<endl; //initialization for(int ibil=0; ibil<nbil;ibil++) S[ibil]=MatrixXd::Zero(n_par,n_par); // cout<<"DEBUG---(d)"<<endl; for(int ibil=0; ibil<nbil;ibil++) for(int ijack=0; ijack<njacks; ijack++) { //cout<<"a"<<endl; Sy[ibil][ijack]=VectorXd::Zero(n_par); //cout<<"b"<<endl; jpars[ibil][ijack]=VectorXd::Zero(n_par); } // cout<<"DEBUG---(d')"<<endl; //definition for(int i=range_min; i<range_max; i++) { for(int ibil=0; ibil<nbil;ibil++) { if(error[i][ibil]<1e-50) error[i][ibil]+=1e-50; } for(int ibil=0; ibil<nbil;ibil++) for(int j=0; j<n_par; j++) for(int k=0; k<n_par; k++) if(std::isnan(error[i][ibil])==0) S[ibil](j,k) += coord[j][i]*coord[k][i]/(error[i][ibil]*error[i][ibil]); for(int ibil=0; ibil<nbil;ibil++) for(int ijack=0; ijack<njacks; ijack++) for(int k=0; k<n_par; k++) if(std::isnan(error[i][ibil])==0) Sy[ibil][ijack](k) += y[i][ijack][ibil]*coord[k][i]/(error[i][ibil]*error[i][ibil]); } // cout<<"DEBUG---(e)"<<endl; for(int ibil=0; ibil<nbil;ibil++) for(int ijack=0; ijack<njacks; ijack++) jpars[ibil][ijack] = S[ibil].colPivHouseholderQr().solve(Sy[ibil][ijack]); // cout<<"DEBUG---(f)"<<endl; return jpars; //jpars[ibil][ijack][ipar] } valarray< valarray<VectorXd> > fit_chiral_Z_RIp_jackknife(const vvd_t &coord, vvd_t &error, const vector<vvd_t> &y, const int range_min, const int range_max, const double &p_min_value) { // cout<<"DEBUG---(a)"<<endl; int n_par = coord.size(); int njacks = y[0].size(); int nbil = y[0][0].size(); // cout<<"DEBUG---(b)"<<endl; valarray<MatrixXd> S(MatrixXd(n_par,n_par),nbil); valarray< valarray<VectorXd> > Sy(valarray<VectorXd>(VectorXd(n_par),njacks),nbil); valarray< valarray<VectorXd> > jpars(valarray<VectorXd>(VectorXd(n_par),njacks),nbil); // cout<<"DEBUG---(c)"<<endl; //initialization for(int ibil=0; ibil<nbil;ibil++) S[ibil]=MatrixXd::Zero(n_par,n_par); // cout<<"DEBUG---(d)"<<endl; for(int ibil=0; ibil<nbil;ibil++) for(int ijack=0; ijack<njacks; ijack++) { //cout<<"a"<<endl; Sy[ibil][ijack]=VectorXd::Zero(n_par); //cout<<"b"<<endl; jpars[ibil][ijack]=VectorXd::Zero(n_par); } // cout<<"DEBUG---(d')"<<endl; //definition for(int i=range_min; i<range_max; i++) { for(int ibil=0; ibil<nbil;ibil++) { if(error[i][ibil]<1e-50) error[i][ibil]+=1e-50; } if(coord[1][i]>p_min_value) { for(int ibil=0; ibil<nbil;ibil++) for(int j=0; j<n_par; j++) for(int k=0; k<n_par; k++) if(std::isnan(error[i][ibil])==0) S[ibil](j,k) += coord[j][i]*coord[k][i]/(error[i][ibil]*error[i][ibil]); for(int ibil=0; ibil<nbil;ibil++) for(int ijack=0; ijack<njacks; ijack++) for(int k=0; k<n_par; k++) if(std::isnan(error[i][ibil])==0) Sy[ibil][ijack](k) += y[i][ijack][ibil]*coord[k][i]/(error[i][ibil]*error[i][ibil]); } } // cout<<"DEBUG---(e)"<<endl; for(int ibil=0; ibil<nbil;ibil++) for(int ijack=0; ijack<njacks; ijack++) jpars[ibil][ijack] = S[ibil].colPivHouseholderQr().solve(Sy[ibil][ijack]); // cout<<"DEBUG---(f)"<<endl; return jpars; //jpars[ibil][ijack][ipar] } vvvd_t average_Zq(vector<jZ_t> &jZq) { int moms=jZq.size(); int njacks=jZq[0].size(); int nmr=jZq[0][0].size(); vvd_t Zq_ave(vd_t(0.0,nmr),moms), sqr_Zq_ave(vd_t(0.0,nmr),moms), Zq_err(vd_t(0.0,nmr),moms); vvvd_t Zq_ave_err(vvd_t(vd_t(0.0,nmr),moms),2); #pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int mr=0;mr<nmr;mr++) for(int ijack=0;ijack<njacks;ijack++) { Zq_ave[imom][mr]+=jZq[imom][ijack][mr]/njacks; sqr_Zq_ave[imom][mr]+=jZq[imom][ijack][mr]*jZq[imom][ijack][mr]/njacks; } #pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int mr=0;mr<nmr;mr++) Zq_err[imom][mr]=sqrt((double)(njacks-1))*sqrt(fabs(sqr_Zq_ave[imom][mr]-Zq_ave[imom][mr]*Zq_ave[imom][mr])); Zq_ave_err[0]=Zq_ave; Zq_ave_err[1]=Zq_err; return Zq_ave_err; } vvd_t average_Zq_chiral(vector<vd_t> &jZq) { int moms=jZq.size(); int njacks=jZq[0].size(); vd_t Zq_ave(0.0,moms), sqr_Zq_ave(0.0,moms), Zq_err(0.0,moms); vvd_t Zq_ave_err(vd_t(0.0,moms),2); #pragma omp parallel for for(int imom=0;imom<moms;imom++) for(int ijack=0;ijack<njacks;ijack++) { Zq_ave[imom]+=jZq[imom][ijack]/njacks; sqr_Zq_ave[imom]+=jZq[imom][ijack]*jZq[imom][ijack]/njacks; } #pragma omp parallel for for(int imom=0;imom<moms;imom++) Zq_err[imom]=sqrt((double)(njacks-1))*sqrt(fabs(sqr_Zq_ave[imom]-Zq_ave[imom]*Zq_ave[imom])); Zq_ave_err[0]=Zq_ave; Zq_ave_err[1]=Zq_err; return Zq_ave_err; } vvvd_t average_pars(vector<vXd_t> &jZq_pars) { int moms=jZq_pars.size(); int njacks=jZq_pars[0].size(); int pars=jZq_pars[0][0].size(); vvd_t Zq_par_ave(vd_t(0.0,pars),moms), sqr_Zq_par_ave(vd_t(0.0,pars),moms), Zq_par_err(vd_t(0.0,pars),moms); vvvd_t Zq_par_ave_err(vvd_t(vd_t(0.0,pars),moms),2); #pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int ipar=0;ipar<pars;ipar++) for(int ijack=0;ijack<njacks;ijack++) { Zq_par_ave[imom][ipar]+=jZq_pars[imom][ijack](ipar)/njacks; sqr_Zq_par_ave[imom][ipar]+=jZq_pars[imom][ijack](ipar)*jZq_pars[imom][ijack](ipar)/njacks; } #pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int ipar=0;ipar<pars;ipar++) Zq_par_err[imom][ipar]=sqrt((double)(njacks-1))*sqrt(fabs(sqr_Zq_par_ave[imom][ipar]-Zq_par_ave[imom][ipar]*Zq_par_ave[imom][ipar])); Zq_par_ave_err[0]=Zq_par_ave; Zq_par_ave_err[1]=Zq_par_err; return Zq_par_ave_err; } vvvvvd_t average_Z(vector<jZbil_t> &jZ) { int moms=jZ.size(); int njacks=jZ[0].size(); int nmr=jZ[0][0].size(); int nbil=5; vvvvd_t Z_ave(vvvd_t(vvd_t(vd_t(0.0,5),nmr),nmr),moms), sqr_Z_ave(vvvd_t(vvd_t(vd_t(0.0,5),nmr),nmr),moms), Z_err(vvvd_t(vvd_t(vd_t(0.0,5),nmr),nmr),moms); vvvvvd_t Z_ave_err(vvvvd_t(vvvd_t(vvd_t(vd_t(0.0,5),nmr),nmr),moms),2); #pragma omp parallel for collapse(4) for(int imom=0;imom<moms;imom++) for(int mr_fw=0;mr_fw<nmr;mr_fw++) for(int mr_bw=0;mr_bw<nmr;mr_bw++) for(int k=0;k<nbil;k++) for(int ijack=0;ijack<njacks;ijack++) { Z_ave[imom][mr_fw][mr_bw][k]+=jZ[imom][ijack][mr_fw][mr_bw][k]/njacks; sqr_Z_ave[imom][mr_fw][mr_bw][k]+=jZ[imom][ijack][mr_fw][mr_bw][k]*jZ[imom][ijack][mr_fw][mr_bw][k]/njacks; } #pragma omp parallel for collapse(4) for(int imom=0;imom<moms;imom++) for(int mr_fw=0;mr_fw<nmr;mr_fw++) for(int mr_bw=0;mr_bw<nmr;mr_bw++) for(int k=0;k<nbil;k++) Z_err[imom][mr_fw][mr_bw][k]=sqrt((double)(njacks-1))*sqrt(fabs(sqr_Z_ave[imom][mr_fw][mr_bw][k]-Z_ave[imom][mr_fw][mr_bw][k]*Z_ave[imom][mr_fw][mr_bw][k])); Z_ave_err[0]=Z_ave; Z_ave_err[1]=Z_err; return Z_ave_err; } vvvd_t average_Z_chiral(vector<vvd_t> &jZ_chiral) { int moms=jZ_chiral.size(); int njacks=jZ_chiral[0].size(); int nbil=5; vvd_t Z_chiral_ave(vd_t(0.0,nbil),moms), sqr_Z_chiral_ave(vd_t(0.0,nbil),moms), Z_chiral_err(vd_t(0.0,nbil),moms); vvvd_t Z_chiral_ave_err(vvd_t(vd_t(0.0,nbil),moms),2); #pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int k=0;k<nbil;k++) for(int ijack=0;ijack<njacks;ijack++) { Z_chiral_ave[imom][k]+=jZ_chiral[imom][ijack][k]/njacks; sqr_Z_chiral_ave[imom][k]+=jZ_chiral[imom][ijack][k]*jZ_chiral[imom][ijack][k]/njacks; } #pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int k=0;k<nbil;k++) Z_chiral_err[imom][k]=sqrt((double)(njacks-1))*sqrt(fabs(sqr_Z_chiral_ave[imom][k]-Z_chiral_ave[imom][k]*Z_chiral_ave[imom][k])); Z_chiral_ave_err[0]=Z_chiral_ave; Z_chiral_ave_err[1]=Z_chiral_err; return Z_chiral_ave_err; } void plot_Zq_sub(vector<jZ_t> &jZq, vector<jZ_t> &jZq_sub, vector<double> &p2_vector, const string &name, const string &all_or_eq_moms) { vvvd_t Zq = average_Zq(jZq); //Zq[ave/err][imom][nm] vvvd_t Zq_sub = average_Zq(jZq_sub); //Zq[ave/err][imom][nm] ofstream datafile1("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_data.txt"); ofstream datafile2("plot_data_and_script/plot_"+name+"_sub_"+all_or_eq_moms+"_data.txt"); for(size_t imom=0;imom<p2_vector.size();imom++) { datafile1<<p2_vector[imom]<<"\t"<<Zq[0][imom][0]<<"\t"<<Zq[1][imom][0]<<endl; //print only for M0R0 } datafile1.close(); for(size_t imom=0;imom<p2_vector.size();imom++) { datafile2<<p2_vector[imom]<<"\t"<<Zq_sub[0][imom][0]<<"\t"<<Zq_sub[1][imom][0]<<endl; //print only for M0R0 } datafile2.close(); ofstream scriptfile("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"); scriptfile<<"set autoscale xy"<<endl; scriptfile<<"set xlabel '$a^2\\tilde{p}^2$'"<<endl; if(name=="Sigma1") scriptfile<<"set ylabel '$Z_q$'"<<endl; if(name=="Sigma1_em_correction") scriptfile<<"set ylabel '$Z_q^{\\mathrm{em}}$'"<<endl; scriptfile<<"set xrange [0:2.5]"<<endl; //if(name=="Sigma1") scriptfile<<"set yrange [0.73:0.86]"<<endl; //if(name=="Sigma1_em_correction") scriptfile<<"set yrange [-0.08:-0.03]"<<endl; if(name=="Sigma1") scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '${\\small Z_q}$'"<<endl; if(name=="Sigma1") scriptfile<<"replot 'plot_data_and_script/plot_"<<name<<"_sub_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lt 1 lc rgb 'red' title '${\\small Z_q^{\\mathrm{corr.}}}$'"<<endl; if(name=="Sigma1_em_correction") scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '${\\small Z_q^{\\mathrm{em}}}$'"<<endl; if(name=="Sigma1_em_correction") scriptfile<<"replot 'plot_data_and_script/plot_"<<name<<"_sub_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lt 1 lc rgb 'red' title '${\\small Z_q^{\\mathrm{em\\, corr.}}}$'"<<endl; scriptfile<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile<<"set output 'allmoms/"<<name<<"_sub.tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile<<"set output 'eqmoms/"<<name<<"_sub.tex'"<<endl; scriptfile<<"replot"<<endl; scriptfile.close(); string command="gnuplot plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"; system(command.c_str()); } void plot_Zq_chiral_extrapolation(vector<vvd_t> &jZq_equivalent, vector<vXd_t> &jZq_pars, vd_t &m_eff_equivalent_Zq, const string &name, const string &all_or_eq_moms) { int moms=jZq_equivalent.size(); int njacks=jZq_equivalent[0].size(); int neq=jZq_equivalent[0][0].size(); vector<vvd_t> jZq_equivalent_and_chiral_extr(moms,vvd_t(vd_t(neq+1),njacks)); #pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int ijack=0;ijack<njacks;ijack++) { jZq_equivalent_and_chiral_extr[imom][ijack][0]=jZq_pars[imom][ijack](0); } #pragma omp parallel for collapse(3) for(int imom=0;imom<moms;imom++) for(int ijack=0;ijack<njacks;ijack++) for(int ieq=0;ieq<neq;ieq++) { jZq_equivalent_and_chiral_extr[imom][ijack][ieq+1]=jZq_equivalent[imom][ijack][ieq]; } ///////////DEBUG//////////// // for(int ijack=0;ijack<njacks;ijack++) // { // cout<<"JACK: "<<ijack<<" <<DEBUG>>"<<endl; // for(int ieq=0;ieq<neq+1;ieq++) // { // if(ieq==0) cout<<0<<"\t"<<jZq_equivalent_and_chiral_extr[3][ijack][ieq]<<endl; // else cout<<m_eff_equivalent_Zq[ieq]*m_eff_equivalent_Zq[ieq]<<"\t"<<jZq_equivalent_and_chiral_extr[3][ijack][ieq]<<endl; // } // cout<<endl; // } vvvd_t Zq_equivalent = average_Zq(jZq_equivalent_and_chiral_extr); //Zq[ave/err][imom][ieq] vvvd_t Zq_pars=average_pars(jZq_pars); ofstream datafile1("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_data.txt"); for(size_t ieq=0;ieq<m_eff_equivalent_Zq.size()+1;ieq++) { if(ieq==0) datafile1<<0<<"\t"<<Zq_equivalent[0][3][ieq]<<"\t"<<Zq_equivalent[1][3][ieq]<<endl; //print only for p2~1 else datafile1<<m_eff_equivalent_Zq[ieq-1]*m_eff_equivalent_Zq[ieq-1]<<"\t"<<Zq_equivalent[0][3][ieq]<<"\t"<<Zq_equivalent[1][3][ieq]<<endl; //print only for p2~1 } datafile1.close(); double A=Zq_pars[0][3][0]; double B=Zq_pars[0][3][1]; ofstream scriptfile("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"); scriptfile<<"set autoscale xy"<<endl; scriptfile<<"set xlabel '$M_{PS}^2$'"<<endl; if(name=="Sigma1_chiral_extrapolation") scriptfile<<"set ylabel '$Z_q$'"<<endl; if(name=="Sigma1_em_chiral_extrapolation") scriptfile<<"set ylabel '$Z_q^{\\rm \\, em}$'"<<endl; // scriptfile<<"set xrange [-0.003:0.05]"<<endl; // if(name=="Sigma1_chiral_extrapolation")scriptfile<<"set yrange [0.74:0.8]"<<endl; // if(name=="Sigma1_em_chiral_extrapolation")scriptfile<<"set yrange [-0.07:-0.04]"<<endl; if(name=="Sigma1_chiral_extrapolation") scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$Z_q$'"<<endl; if(name=="Sigma1_chiral_extrapolation") scriptfile<<"replot '< head -1 plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 7 lt 1 lc rgb 'black' title '$Z_q$ chiral extr.'"<<endl; if(name=="Sigma1_em_chiral_extrapolation") scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$Z_q^{\\rm \\, em}$'"<<endl; if(name=="Sigma1_em_chiral_extrapolation") scriptfile<<"replot '< head -1 plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 7 lt 1 lc rgb 'black' title '$Z_q^{\\rm \\, em}$ chiral extr.'"<<endl; scriptfile<<"f(x)="<<A<<"+"<<B<<"*x"<<endl; scriptfile<<"replot f(x) lt 2 lc rgb 'red' title 'linear fit'"<<endl; scriptfile<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile<<"set output 'allmoms/"<<name<<".tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile<<"set output 'eqmoms/"<<name<<".tex'"<<endl; scriptfile<<"replot"<<endl; scriptfile.close(); string command="gnuplot plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"; system(command.c_str()); } void plot_Zq_chiral(vector<vd_t> &jZq_chiral, vector<double> &p2_vector, const string &name, const string &all_or_eq_moms) { vvd_t Zq_chiral = average_Zq_chiral(jZq_chiral); //Zq[ave/err][imom] ///**************************/// //linear fit int p2_min=4; //a2p2~1 int p2_max=(int)p2_vector.size(); vvd_t coord_linear(vd_t(0.0,p2_vector.size()),2); for(int i=0; i<p2_vector.size(); i++) { coord_linear[0][i] = 1.0; //costante coord_linear[1][i] = p2_vector[i]; //p^2 } vXd_t jZq_chiral_par=fit_chiral_jackknife(coord_linear,Zq_chiral[1],jZq_chiral,p2_min,p2_max); //jZq_chiral_par[ijack][par] int njacks=jZq_chiral_par.size(); int pars=jZq_chiral_par[0].size(); vd_t Zq_par_ave(0.0,pars), sqr_Zq_par_ave(0.0,pars), Zq_par_err(0.0,pars); vvd_t Zq_par_ave_err(vd_t(0.0,pars),2); for(int ipar=0;ipar<pars;ipar++) for(int ijack=0;ijack<njacks;ijack++) { Zq_par_ave[ipar]+=jZq_chiral_par[ijack](ipar)/njacks; sqr_Zq_par_ave[ipar]+=jZq_chiral_par[ijack](ipar)*jZq_chiral_par[ijack](ipar)/njacks; } for(int ipar=0;ipar<pars;ipar++) Zq_par_err[ipar]=sqrt((double)(njacks-1))*sqrt(sqr_Zq_par_ave[ipar]-Zq_par_ave[ipar]*Zq_par_ave[ipar]); Zq_par_ave_err[0]=Zq_par_ave; //Zq_par_ave_err[ave/err][par] Zq_par_ave_err[1]=Zq_par_err; double A=Zq_par_ave_err[0][0]; double A_err=Zq_par_ave_err[1][0]; double B=Zq_par_ave_err[0][1]; double B_err=Zq_par_ave_err[1][1]; cout<<A<<" +/- "<<A_err<<endl<<endl; ///*****************************/// ofstream datafile1("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_data.txt"); for(size_t imom=0;imom<p2_vector.size();imom++) { datafile1<<p2_vector[imom]<<"\t"<<Zq_chiral[0][imom]<<"\t"<<Zq_chiral[1][imom]<<endl; //print only for M0R0 } datafile1.close(); /* ofstream datafile2("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_data_fit.txt"); datafile2<<"0"<<"\t"<<A<<"\t"<<A_err<<endl; datafile2.close(); */ ofstream scriptfile("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"); scriptfile<<"set autoscale xy"<<endl; // scriptfile<<"set xrange [0:2.5]"<<endl; // if(name=="Sigma1_chiral") scriptfile<<"set yrange [0.74:0.84]"<<endl; // if(name=="Sigma1_chiral_em_correction") scriptfile<<"set yrange [-0.08:-0.03]"<<endl; scriptfile<<"set xlabel '$a^2\\tilde{p}^2$'"<<endl; if(name=="Sigma1_chiral") scriptfile<<"set ylabel '$Z_q$'"<<endl; if(name=="Sigma1_chiral_em_correction") scriptfile<<"set ylabel '$Z_q^{\\rm \\, em}$'"<<endl; if(name=="Sigma1_chiral") scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$Z_q$ chiral'"<<endl; if(name=="Sigma1_chiral_em_correction") scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$Z_q^{\\rm \\, em}$ chiral'"<<endl; scriptfile<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile<<"set output 'allmoms/"<<name<<".tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile<<"set output 'eqmoms/"<<name<<".tex'"<<endl; scriptfile<<"replot"<<endl; scriptfile.close(); string command="gnuplot plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"; system(command.c_str()); } void plot_Zq_RIp_ainv(vector<vd_t> &jZq_chiral, vector<double> &p2_vector, const string &name, const string &all_or_eq_moms) { vvd_t Zq_chiral = average_Zq_chiral(jZq_chiral); //Zq[ave/err][imom] ///**************************/// //linear fit int p2_min=4; //a2p2~1 int p2_max=(int)p2_vector.size(); vvd_t coord_linear(vd_t(0.0,p2_vector.size()),2); for(int i=0; i<p2_vector.size(); i++) { coord_linear[0][i] = 1.0; //costante coord_linear[1][i] = p2_vector[i]; //p^2 } vXd_t jZq_chiral_par=fit_chiral_jackknife(coord_linear,Zq_chiral[1],jZq_chiral,p2_min,p2_max); //jZq_chiral_par[ijack][par] int njacks=jZq_chiral_par.size(); int pars=jZq_chiral_par[0].size(); vd_t Zq_par_ave(0.0,pars), sqr_Zq_par_ave(0.0,pars), Zq_par_err(0.0,pars); vvd_t Zq_par_ave_err(vd_t(0.0,pars),2); for(int ipar=0;ipar<pars;ipar++) for(int ijack=0;ijack<njacks;ijack++) { Zq_par_ave[ipar]+=jZq_chiral_par[ijack](ipar)/njacks; sqr_Zq_par_ave[ipar]+=jZq_chiral_par[ijack](ipar)*jZq_chiral_par[ijack](ipar)/njacks; } for(int ipar=0;ipar<pars;ipar++) Zq_par_err[ipar]=sqrt((double)(njacks-1))*sqrt(fabs(sqr_Zq_par_ave[ipar]-Zq_par_ave[ipar]*Zq_par_ave[ipar])); Zq_par_ave_err[0]=Zq_par_ave; //Zq_par_ave_err[ave/err][par] Zq_par_ave_err[1]=Zq_par_err; double A=Zq_par_ave_err[0][0]; double A_err=Zq_par_ave_err[1][0]; double B=Zq_par_ave_err[0][1]; double B_err=Zq_par_ave_err[1][1]; cout<<A<<" +/- "<<A_err<<endl<<endl; ///*****************************/// ofstream datafile1("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_data.txt"); for(size_t imom=0;imom<p2_vector.size();imom++) { datafile1<<p2_vector[imom]<<"\t"<<Zq_chiral[0][imom]<<"\t"<<Zq_chiral[1][imom]<<endl; //print only for M0R0 } datafile1.close(); ofstream datafile2("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_data_fit.txt"); datafile2<<"0"<<"\t"<<A<<"\t"<<A_err<<endl; datafile2.close(); ofstream scriptfile("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"); scriptfile<<"set autoscale xy"<<endl; // scriptfile<<"set xrange [-0.05:2.5]"<<endl; // if(name=="Sigma1_RIp_ainv") scriptfile<<"set yrange [0.75:0.81]"<<endl; // if(name=="Sigma1_em_RIp_ainv") scriptfile<<"set yrange [-0.08:-0.02]"<<endl; scriptfile<<"set xlabel '$a^2\\tilde{p}^2$'"<<endl; if(name=="Sigma1_RIp_ainv") scriptfile<<"set ylabel '$Z_q$'"<<endl; if(name=="Sigma1_em_RIp_ainv") scriptfile<<"set ylabel '$Z_q^{\\rm \\, em}$'"<<endl; // if(name=="Sigma1_RIp_ainv") scriptfile<<"set yrange [0.75:0.81]"<<endl; // if(name=="Sigma1_em_RIp_ainv") scriptfile<<"set yrange [-0.06:0]"<<endl; if(name=="Sigma1_RIp_ainv") scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$Z_q$ '"<<endl; if(name=="Sigma1_em_RIp_ainv") scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$Z_q^{\\rm \\, em}$ '"<<endl; scriptfile<<"replot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data_fit.txt' u 1:2:3 with errorbars pt 7 lt 1 lc rgb 'red' ps 1 title 'extrapolation'"<<endl; scriptfile<<"f(x)="<<A<<"+"<<B<<"*x"<<endl; scriptfile<<"replot f(x) lw 3 title 'linear fit'"<<endl; scriptfile<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile<<"set output 'allmoms/"<<name<<".tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile<<"set output 'eqmoms/"<<name<<".tex'"<<endl; scriptfile<<"replot"<<endl; scriptfile.close(); string command="gnuplot plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"; system(command.c_str()); } void plot_Z_sub(vector<jZbil_t> &jZ, vector<jZbil_t> &jZ_sub, vector<double> &p2_vector, const string &name, const string &all_or_eq_moms) { vvvvvd_t Z = average_Z(jZ); //Z[ave/err][imom][mr][mr2][k] vvvvvd_t Z_sub = average_Z(jZ_sub); //Z[ave/err][imom][mr][mr2][k] ///////DEBUG if(name=="Z1" && all_or_eq_moms=="eqmoms") for(int imom=0;imom<p2_vector.size();imom++) { cout<<p2_vector[imom]<<"\t"<<jZ[imom][0][0][0][2]<<endl; } cout<<endl; ///////// vector<string> bil={"S","A","P","V","T"}; vector<ofstream> datafile(5), datafile_sub(5); for(int i=0;i<5;i++) { datafile[i].open("plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_data.txt"); datafile_sub[i].open("plot_data_and_script/plot_"+name+"_"+bil[i]+"_sub_"+all_or_eq_moms+"_data.txt"); for(size_t imom=0;imom<p2_vector.size();imom++) { datafile[i]<<p2_vector[imom]<<"\t"<<Z[0][imom][0][0][i]<<"\t"<<Z[1][imom][0][0][i]<<endl; //print only for M0R0-M0R0 datafile_sub[i]<<p2_vector[imom]<<"\t"<<Z_sub[0][imom][0][0][i]<<"\t"<<Z_sub[1][imom][0][0][i]<<endl; } datafile[i].close(); datafile_sub[i].close(); } vector<ofstream> scriptfile(5); for(int i=0;i<5;i++) { scriptfile[i].open("plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_script.txt"); scriptfile[i]<<"set autoscale xy"<<endl; scriptfile[i]<<"set xlabel '$a^2\\tilde{p}^2$'"<<endl; scriptfile[i]<<"set xrange [0:2.5]"<<endl; // if(i==0 && name=="Z1")scriptfile[i]<<"set yrange [0.6:0.82]"<<endl; //S // if(i==1 && name=="Z1")scriptfile[i]<<"set yrange [0.72:0.83]"<<endl; //A // if(i==2 && name=="Z1")scriptfile[i]<<"set yrange [0:0.55]"<<endl; //P // if(i==3 && name=="Z1")scriptfile[i]<<"set yrange [0.62:0.72]"<<endl; //V // if(i==4 && name=="Z1")scriptfile[i]<<"set yrange [0.65:0.95]"<<endl; //T // if(i==0 && name=="Z1_em_correction")scriptfile[i]<<"set yrange [-0.28:-0.0]"<<endl; // if(i==1 && name=="Z1_em_correction")scriptfile[i]<<"set yrange [-0.12:-0.06]"<<endl; // if(i==2 && name=="Z1_em_correction")scriptfile[i]<<"set yrange [-0.35:-0.05]"<<endl; // if(i==3 && name=="Z1_em_correction")scriptfile[i]<<"set yrange [-0.17:-0.11]"<<endl; // if(i==4 && name=="Z1_em_correction")scriptfile[i]<<"set yrange [-0.15:-0.05]"<<endl; if(name=="Z1") scriptfile[i]<<"set ylabel '$Z_"<<bil[i]<<"$'"<<endl; if(name=="Z1_em_correction") scriptfile[i]<<"set ylabel '$\\delta Z_"<<bil[i]<<"$'"<<endl; if(name=="Z1") { scriptfile[i]<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<bil[i]<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '${\\small Z_"<<bil[i]<<"}$'"<<endl; scriptfile[i]<<"replot 'plot_data_and_script/plot_"<<name<<"_"<<bil[i]<<"_sub_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lt 1 lc rgb 'red' title '${\\small Z_"<<bil[i]<<"^{\\mathrm{corr.}}}$'"<<endl; } if(name=="Z1_em_correction") { scriptfile[i]<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<bil[i]<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '${\\small \\delta Z_"<<bil[i]<<"}$'"<<endl; scriptfile[i]<<"replot 'plot_data_and_script/plot_"<<name<<"_"<<bil[i]<<"_sub_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lt 1 lc rgb 'red' title '${\\small \\delta Z_"<<bil[i]<<"^{\\mathrm{corr.}}}$'"<<endl; } scriptfile[i]<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile[i]<<"set output 'allmoms/"<<name<<"_"<<bil[i]<<"_sub.tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile[i]<<"set output 'eqmoms/"<<name<<"_"<<bil[i]<<"_sub.tex'"<<endl; scriptfile[i]<<"replot"<<endl; scriptfile[i]<<"set term unknown"<<endl; scriptfile[i].close(); string command="gnuplot plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_script.txt"; system(command.c_str()); } } void plot_ZPandS_chiral_extrapolation(const string &bil, vector<vvd_t> &jZ_equivalent, vector<vvd_t> &jG_subpole, vector<vXd_t> &jZ_pars, vd_t &m_eff_equivalent_Z, const string &name, const string &all_or_eq_moms) { int moms=jZ_equivalent.size(); int njacks=jZ_equivalent[0].size(); int neq=jZ_equivalent[0][0].size(); // vector<vvd_t> jZ_equivalent_and_chiral_extr(moms,vvd_t(vd_t(neq+1),njacks)); /*#pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int ijack=0;ijack<njacks;ijack++) { jZ_equivalent_and_chiral_extr[imom][ijack][0]=jZ_pars[imom][ijack](0); } #pragma omp parallel for collapse(3) for(int imom=0;imom<moms;imom++) for(int ijack=0;ijack<njacks;ijack++) for(int ieq=0;ieq<neq;ieq++) { jZ_equivalent_and_chiral_extr[imom][ijack][ieq+1]=jZ_equivalent[imom][ijack][ieq]; }*/ vvvd_t Z_equivalent = average_Zq(jZ_equivalent); //Z[ave/err][imom][ieq] vvvd_t Z_pars=average_pars(jZ_pars); vvvd_t G_subpole = average_Zq(jG_subpole); ofstream datafile1("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_data.txt"); ofstream datafile3("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_data_fit.txt"); //datafile1<<0<<"\t"<<Z_pars[0][0]<<"\t"<<Z_pars[1][0]<<endl; datafile3<<0<<"\t"<<Z_pars[0][3][0]<<"\t"<<Z_pars[1][3][0]<<endl; //print only for p2~1 for(size_t ieq=0;ieq<m_eff_equivalent_Z.size();ieq++) { datafile1<<m_eff_equivalent_Z[ieq]*m_eff_equivalent_Z[ieq]<<"\t"<<Z_equivalent[0][3][ieq]<<"\t"<<Z_equivalent[1][3][ieq]<<endl; //print only for p2~1 } datafile1.close(); datafile3.close(); ofstream datafile2("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_data_subpole.txt"); //datafile1<<0<<"\t"<<Z_pars[0][0]<<"\t"<<Z_pars[1][0]<<endl; for(size_t ieq=0;ieq<m_eff_equivalent_Z.size()/*+1*/;ieq++) { datafile2<<m_eff_equivalent_Z[ieq]*m_eff_equivalent_Z[ieq]<<"\t"<<G_subpole[0][3][ieq]<<"\t"<<G_subpole[1][3][ieq]<<endl; //print only for p2~1 } datafile2.close(); double A=Z_pars[0][3][0]; double B=Z_pars[0][3][1]; double C=0; if(Z_pars[0][3].size()==3) C=Z_pars[0][3][2]; ofstream scriptfile("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"); scriptfile<<"set autoscale xy"<<endl; scriptfile<<"set xlabel '$M_{PS}^2$'"<<endl; if(name=="Gp_chiral_extrapolation") scriptfile<<"set ylabel '$\\Gamma_"<<bil<<"$'"<<endl; if(name=="Gs_chiral_extrapolation") scriptfile<<"set ylabel '$\\Gamma_"<<bil<<"$'"<<endl; if(name=="Gp_em_chiral_extrapolation") scriptfile<<"set ylabel '$\\delta \\Gamma_"<<bil<<"$'"<<endl; if(name=="Gs_em_chiral_extrapolation") scriptfile<<"set ylabel '$\\delta \\Gamma_"<<bil<<"$'"<<endl; scriptfile<<"set xrange [-0.003:0.05]"<<endl; // if(name=="Gp_chiral_extrapolation") scriptfile<<"set yrange [0:5]"<<endl; // if(name=="Gs_chiral_extrapolation") scriptfile<<"set yrange [0.9:1.6]"<<endl; // if(name=="Gp_em_chiral_extrapolation") scriptfile<<"set yrange [-1.2:0.6]"<<endl; // if(name=="Gs_em_chiral_extrapolation") scriptfile<<"set yrange [-0.2:0.1]"<<endl; if(name=="Gp_chiral_extrapolation"||name=="Gs_chiral_extrapolation") { scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$\\Gamma_"<<bil<<"$'"<<endl; scriptfile<<"replot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data_subpole.txt' u 1:2:3 with errorbars pt 7 lt 1 lc rgb 'blue' title '$\\Gamma_"<<bil<<"^{sub}$'"<<endl; // scriptfile<<"replot '< head -1 plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 5 lt 1 lc rgb 'black' title '$\\Gamma_"<<bil<<"$ chiral extr.'"<<endl; scriptfile<<"replot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data_fit.txt' u 1:2:3 with errorbars pt 5 lt 1 lc rgb 'black' title '$\\Gamma_"<<bil<<"$ chiral extr.'"<<endl; } if(name=="Gp_em_chiral_extrapolation"||name=="Gs_em_chiral_extrapolation") { scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$\\delta \\Gamma_"<<bil<<"$'"<<endl; scriptfile<<"replot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data_subpole.txt' u 1:2:3 with errorbars pt 7 lt 1 lc rgb 'blue' title '$\\delta \\Gamma_"<<bil<<"^{sub}$'"<<endl; // scriptfile<<"replot '< head -1 plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 5 lt 1 lc rgb 'black' title '$\\Gamma_"<<bil<<"$ chiral extr.'"<<endl; scriptfile<<"replot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data_fit.txt' u 1:2:3 with errorbars pt 5 lt 1 lc rgb 'black' title '$\\delta \\Gamma_"<<bil<<"$ chiral extr.'"<<endl; } if(Z_pars[0][3].size()==2) scriptfile<<"f(x)="<<A<<"+"<<B<<"*x"<<endl; if(Z_pars[0][3].size()==3) scriptfile<<"f(x)=(x > 0) ? "<<A<<"+"<<B<<"*x"<<"+"<<C<<"/x : 1/0"<<endl; scriptfile<<"replot f(x) lt 1 lc rgb 'blue' title 'fit curve'"<<endl; scriptfile<<"g(x)="<<A<<"+"<<B<<"*x"<<endl; scriptfile<<"replot g(x) lt 2 lc rgb 'red' title 'linear fit'"<<endl; scriptfile<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile<<"set output 'allmoms/"<<name<<".tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile<<"set output 'eqmoms/"<<name<<".tex'"<<endl; scriptfile<<"replot"<<endl; scriptfile.close(); string command="gnuplot plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"; system(command.c_str()); } void plot_ZVAT_chiral_extrapolation(const string &bil, vector<vvd_t> &jZ_equivalent, vector<vXd_t> &jZ_pars, vd_t &m_eff_equivalent_Z, const string &name, const string &all_or_eq_moms) { int moms=jZ_equivalent.size(); int njacks=jZ_equivalent[0].size(); int neq=jZ_equivalent[0][0].size(); vector<vvd_t> jZ_equivalent_and_chiral_extr(moms,vvd_t(vd_t(neq+1),njacks)); #pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int ijack=0;ijack<njacks;ijack++) { jZ_equivalent_and_chiral_extr[imom][ijack][0]=jZ_pars[imom][ijack](0); } #pragma omp parallel for collapse(3) for(int imom=0;imom<moms;imom++) for(int ijack=0;ijack<njacks;ijack++) for(int ieq=0;ieq<neq;ieq++) { jZ_equivalent_and_chiral_extr[imom][ijack][ieq+1]=jZ_equivalent[imom][ijack][ieq]; } vvvd_t Z_equivalent = average_Zq(jZ_equivalent_and_chiral_extr); //Z[ave/err][imom][ieq] vvvd_t Z_pars=average_pars(jZ_pars); ofstream datafile1("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_data.txt"); //datafile1<<0<<"\t"<<Z_pars[0][0]<<"\t"<<Z_pars[1][0]<<endl; for(size_t ieq=0;ieq<m_eff_equivalent_Z.size()+1;ieq++) { if(ieq==0) datafile1<<0<<"\t"<<Z_equivalent[0][3][ieq]<<"\t"<<Z_equivalent[1][3][ieq]<<endl; //print only for p2~1 else datafile1<<m_eff_equivalent_Z[ieq-1]*m_eff_equivalent_Z[ieq-1]<<"\t"<<Z_equivalent[0][3][ieq]<<"\t"<<Z_equivalent[1][3][ieq]<<endl; //print only for p2~1 } datafile1.close(); double A=Z_pars[0][3][0]; double B=Z_pars[0][3][1]; ofstream scriptfile("plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"); scriptfile<<"set autoscale xy"<<endl; scriptfile<<"set xlabel '$M_{PS}^2$'"<<endl; if(name=="Gv_chiral_extrapolation") scriptfile<<"set ylabel '$\\Gamma_"<<bil<<"$'"<<endl; if(name=="Ga_chiral_extrapolation") scriptfile<<"set ylabel '$\\Gamma_"<<bil<<"$'"<<endl; if(name=="Gt_chiral_extrapolation") scriptfile<<"set ylabel '$\\Gamma_"<<bil<<"$'"<<endl; if(name=="Gv_em_chiral_extrapolation") scriptfile<<"set ylabel '$\\delta\\Gamma_"<<bil<<"$'"<<endl; if(name=="Ga_em_chiral_extrapolation") scriptfile<<"set ylabel '$\\delta\\Gamma_"<<bil<<"$'"<<endl; if(name=="Gt_em_chiral_extrapolation") scriptfile<<"set ylabel '$\\delta\\Gamma_"<<bil<<"$'"<<endl; // scriptfile<<"set xrange [-0.003:0.05]"<<endl; // if(name=="Gv_chiral_extrapolation") scriptfile<<"set yrange [0.99:1.05]"<<endl; // if(name=="Ga_chiral_extrapolation") scriptfile<<"set yrange [1.15:1.25]"<<endl; // if(name=="Gt_chiral_extrapolation") scriptfile<<"set yrange [1.0:1.05]"<<endl; // if(name=="Gv_em_chiral_extrapolation") scriptfile<<"set yrange [-0.06:0.01]"<<endl; // if(name=="Ga_em_chiral_extrapolation") scriptfile<<"set yrange [-0.13:-0.06]"<<endl; // if(name=="Gt_em_chiral_extrapolation") scriptfile<<"set yrange [-0.06:-0.02]"<<endl; if(name=="Gv_chiral_extrapolation"||name=="Ga_chiral_extrapolation"||name=="Gt_chiral_extrapolation") { scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$\\Gamma_"<<bil<<"$'"<<endl; scriptfile<<"replot '< head -1 plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 5 lt 1 lc rgb 'black' title '$\\Gamma_"<<bil<<"$ chiral extr.'"<<endl; } if(name=="Gv_em_chiral_extrapolation"||name=="Ga_em_chiral_extrapolation"||name=="Gt_em_chiral_extrapolation") { scriptfile<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$\\delta \\Gamma_"<<bil<<"$'"<<endl; scriptfile<<"replot '< head -1 plot_data_and_script/plot_"<<name<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 5 lt 1 lc rgb 'black' title '$\\delta \\Gamma_"<<bil<<"$ chiral extr.'"<<endl; } scriptfile<<"f(x)="<<A<<"+"<<B<<"*x"<<endl; scriptfile<<"replot f(x) lt 2 lc rgb 'red' title 'linear fit'"<<endl; scriptfile<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile<<"set output 'allmoms/"<<name<<".tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile<<"set output 'eqmoms/"<<name<<".tex'"<<endl; scriptfile<<"replot"<<endl; scriptfile.close(); string command="gnuplot plot_data_and_script/plot_"+name+"_"+all_or_eq_moms+"_script.txt"; system(command.c_str()); } void plot_Z_chiral(vector<vvd_t> &jZ_chiral, vector<double> &p2_vector, const string &name, const string &all_or_eq_moms) { // cout<<"DEBUG---(A)"<<endl; vvvd_t Z_chiral = average_Z_chiral(jZ_chiral); //Z_chiral[ave/err][imom][k] // cout<<"DEBUG---(B)"<<endl; ///**************************/// //linear fit int p2_min=5; //a2p2~1 int p2_max=(int)p2_vector.size(); vvd_t coord_linear(vd_t(0.0,p2_vector.size()),2); for(int i=0; i<p2_vector.size(); i++) { coord_linear[0][i] = 1.0; //costante coord_linear[1][i] = p2_vector[i]; //p^2 } ///************************/// // cout<<"DEBUG---(C)"<<endl; valarray<vXd_t> jZ_chiral_par=fit_chiral_Z_jackknife(coord_linear,Z_chiral[1],jZ_chiral,p2_min,p2_max); //jZ_chiral_par[ibil][ijack][ipar] // cout<<"DEBUG---(D)"<<endl; int nbil=jZ_chiral_par.size(); int njacks=jZ_chiral_par[0].size(); int pars=jZ_chiral_par[0][0].size(); vvd_t Z_par_ave(vd_t(0.0,pars),nbil), sqr_Z_par_ave(vd_t(0.0,pars),nbil), Z_par_err(vd_t(0.0,pars),nbil); //Z vvvd_t Z_par_ave_err(vvd_t(vd_t(0.0,pars),nbil),2); //Zq_par_ave_err[ave/err][ibil][par] // cout<<"DEBUG---(E)"<<endl; for(int ibil=0; ibil<nbil;ibil++) for(int ipar=0;ipar<pars;ipar++) for(int ijack=0;ijack<njacks;ijack++) { Z_par_ave[ibil][ipar]+=jZ_chiral_par[ibil][ijack](ipar)/njacks; sqr_Z_par_ave[ibil][ipar]+=jZ_chiral_par[ibil][ijack](ipar)*jZ_chiral_par[ibil][ijack](ipar)/njacks; } // cout<<"DEBUG---(F)"<<endl; for(int ibil=0; ibil<nbil;ibil++) for(int ipar=0;ipar<pars;ipar++) Z_par_err[ibil][ipar]=sqrt((double)(njacks-1))*sqrt(fabs(sqr_Z_par_ave[ibil][ipar]-Z_par_ave[ibil][ipar]*Z_par_ave[ibil][ipar])); // cout<<"DEBUG---(G)"<<endl; Z_par_ave_err[0]=Z_par_ave; //Z_par_ave_err[ave/err][ibil][par] Z_par_ave_err[1]=Z_par_err; // cout<<"DEBUG---(H)"<<endl; vd_t A(0.0,nbil),A_err(0.0,nbil),B(0.0,nbil),B_err(0.0,nbil); for(int ibil=0; ibil<nbil;ibil++) { A[ibil]=Z_par_ave_err[0][ibil][0]; A_err[ibil]=Z_par_ave_err[1][ibil][0]; B[ibil]=Z_par_ave_err[0][ibil][1]; B_err[ibil]=Z_par_ave_err[1][ibil][1]; } ///*****************************/// ////////////////////// vector<string> bil={"S","A","P","V","T"}; vector<ofstream> datafile(5); // vector<ofstream> datafile_fit(5); for(int i=0;i<5;i++) { cout<<endl; cout<<"Z"<<bil[i]<<" = "<<A[i]<<" +/- "<<A_err[i]<<endl; datafile[i].open("plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_data.txt"); for(size_t imom=0;imom<p2_vector.size();imom++) datafile[i]<<p2_vector[imom]<<"\t"<<Z_chiral[0][imom][i]<<"\t"<<Z_chiral[1][imom][i]<<endl; datafile[i].close(); // datafile_fit[i].open("plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_data_fit.txt"); // datafile_fit[i]<<"0"<<"\t"<<A[i]<<"\t"<<A_err[i]<<endl; //datafile_fit[i].close(); } cout<<endl; vector<ofstream> scriptfile(5); for(int i=0;i<5;i++) { scriptfile[i].open("plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_script.txt"); scriptfile[i]<<"set autoscale xy"<<endl; scriptfile[i]<<"set xlabel '$a^2\\tilde{p}^2$'"<<endl; //bil={S,A,P,V,T} // scriptfile[i]<<"set xrange [0:2.5]"<<endl; // if(name=="Z1_chiral"&&i==0) scriptfile[i]<<"set yrange [0.45:0.85]"<<endl; // if(name=="Z1_chiral"&&i==1) scriptfile[i]<<"set yrange [0.72:0.82]"<<endl; // if(name=="Z1_chiral"&&i==2) scriptfile[i]<<"set yrange [0.35:0.7]"<<endl; // if(name=="Z1_chiral"&&i==3) scriptfile[i]<<"set yrange [0.62:0.69]"<<endl; // if(name=="Z1_chiral"&&i==4) scriptfile[i]<<"set yrange [0.65:0.95]"<<endl; // if(name=="Z1_chiral_em_correction"&&i==0) scriptfile[i]<<"set yrange [-0.25:0.05]"<<endl; // if(name=="Z1_chiral_em_correction"&&i==1) scriptfile[i]<<"set yrange [-0.13:-0.06]"<<endl; // if(name=="Z1_chiral_em_correction"&&i==2) scriptfile[i]<<"set yrange [-0.8:0.2]"<<endl; // if(name=="Z1_chiral_em_correction"&&i==3) scriptfile[i]<<"set yrange [-0.18:-0.11]"<<endl; // if(name=="Z1_chiral_em_correction"&&i==4) scriptfile[i]<<"set yrange [-0.15:-0.05]"<<endl; if(name=="Z1_chiral") scriptfile[i]<<"set ylabel '$Z_"<<bil[i]<<"$'"<<endl; if(name=="Z1_chiral_em_correction") scriptfile[i]<<"set ylabel '$\\delta Z_"<<bil[i]<<"$'"<<endl; if(name=="Z1_chiral") scriptfile[i]<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<bil[i]<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$Z_"<<bil[i]<<"$ chiral'"<<endl; if(name=="Z1_chiral_em_correction") scriptfile[i]<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<bil[i]<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$\\delta Z_"<<bil[i]<<"$ chiral'"<<endl; scriptfile[i]<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile[i]<<"set output 'allmoms/"<<name<<"_"<<bil[i]<<".tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile[i]<<"set output 'eqmoms/"<<name<<"_"<<bil[i]<<".tex'"<<endl; scriptfile[i]<<"replot"<<endl; scriptfile[i]<<"set term unknown"<<endl; scriptfile[i].close(); string command="gnuplot plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_script.txt"; system(command.c_str()); } int moms=p2_vector.size(); // int njacks=jZ_chiral[0].size(); vector<vd_t> jZP_over_S(moms,vd_t(0.0,njacks)); #pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int ijack=0;ijack<njacks;ijack++) jZP_over_S[imom][ijack]=jZ_chiral[imom][ijack][2]/jZ_chiral[imom][ijack][0]; vvd_t ZP_over_S=average_Zq_chiral(jZP_over_S); ofstream datafile2; datafile2.open("plot_data_and_script/plot_"+name+"_P_over_S_"+all_or_eq_moms+"_data.txt"); for(size_t imom=0;imom<p2_vector.size();imom++) datafile2<<p2_vector[imom]<<"\t"<<ZP_over_S[0][imom]<<"\t"<<ZP_over_S[1][imom]<<endl; datafile2.close(); ofstream scriptfile2; scriptfile2.open("plot_data_and_script/plot_"+name+"_P_over_S_"+all_or_eq_moms+"_script.txt"); scriptfile2<<"set autoscale xy"<<endl; scriptfile2<<"set xlabel '$a^2\\tilde{p}^2$'"<<endl; // scriptfile2<<"set yrange [0.7:0.9]"<<endl; scriptfile2<<"set ylabel '$Z_P/Z_S$'"<<endl; scriptfile2<<"plot 'plot_data_and_script/plot_"<<name<<"_P_over_S_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$Z_P/Z_S$ chiral'"<<endl; scriptfile2<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile2<<"set output 'allmoms/"<<name<<"_P_over_S.tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile2<<"set output 'eqmoms/"<<name<<"_P_over_S.tex'"<<endl; scriptfile2<<"replot"<<endl; scriptfile2<<"set term unknown"<<endl; scriptfile2.close(); string command2="gnuplot plot_data_and_script/plot_"+name+"_P_over_S_"+all_or_eq_moms+"_script.txt"; system(command2.c_str()); } void plot_ZO_RIp_ainv(vector<vvd_t> &jZ_chiral, vector<double> &p2_vector, const string &name, const string &all_or_eq_moms, const double &p_min_value) { // cout<<"DEBUG---(A)"<<endl; vvvd_t Z_chiral = average_Z_chiral(jZ_chiral); //Z_chiral[ave/err][imom][k] // cout<<"DEBUG---(B)"<<endl; ///**************************/// //linear fit // int p2_min=5; //a2p2~1 int p2_min=0; int p2_max=(int)p2_vector.size(); vvd_t coord_linear(vd_t(0.0,p2_vector.size()),2); for(int i=0; i<p2_vector.size(); i++) { coord_linear[0][i] = 1.0; //costante coord_linear[1][i] = p2_vector[i]; //p^2 } ///************************/// // cout<<"DEBUG---(C)"<<endl; valarray<vXd_t> jZ_chiral_par=fit_chiral_Z_RIp_jackknife(coord_linear,Z_chiral[1],jZ_chiral,p2_min,p2_max,p_min_value); //jZ_chiral_par[ibil][ijack][ipar] // cout<<"DEBUG---(D)"<<endl; int nbil=jZ_chiral_par.size(); int njacks=jZ_chiral_par[0].size(); int pars=jZ_chiral_par[0][0].size(); vvd_t Z_par_ave(vd_t(0.0,pars),nbil), sqr_Z_par_ave(vd_t(0.0,pars),nbil), Z_par_err(vd_t(0.0,pars),nbil); //Z vvvd_t Z_par_ave_err(vvd_t(vd_t(0.0,pars),nbil),2); //Zq_par_ave_err[ave/err][ibil][par] // cout<<"DEBUG---(E)"<<endl; for(int ibil=0; ibil<nbil;ibil++) for(int ipar=0;ipar<pars;ipar++) for(int ijack=0;ijack<njacks;ijack++) { Z_par_ave[ibil][ipar]+=jZ_chiral_par[ibil][ijack](ipar)/njacks; sqr_Z_par_ave[ibil][ipar]+=jZ_chiral_par[ibil][ijack](ipar)*jZ_chiral_par[ibil][ijack](ipar)/njacks; } if(name=="ZO_em_RIp_ainv") { vd_t jdeltaZS(njacks),jdeltaZP(njacks), jdeltaZS_ZP(njacks); double deltaZS_ZP(0.0), sqr_deltaZS_ZP(0.0), deltaZS_ZP_err(0.0); for(int ijack=0;ijack<njacks;ijack++) { jdeltaZS[ijack] = jZ_chiral_par[0][ijack](0); jdeltaZP[ijack] = jZ_chiral_par[2][ijack](0); } jdeltaZS_ZP = jdeltaZS - jdeltaZP; for(int ijack=0;ijack<njacks;ijack++) { deltaZS_ZP += jdeltaZS_ZP[ijack]/njacks; sqr_deltaZS_ZP += jdeltaZS_ZP[ijack]*jdeltaZS_ZP[ijack]/njacks; } deltaZS_ZP_err = sqrt((double)(njacks-1))*sqrt(fabs( sqr_deltaZS_ZP - deltaZS_ZP*deltaZS_ZP)); cout<<endl; cout<<"deltaZS-deltaZP (1/a)"<<endl; cout<<deltaZS_ZP<<"\t"<<deltaZS_ZP_err<<endl; } // cout<<"DEBUG---(F)"<<endl; for(int ibil=0; ibil<nbil;ibil++) for(int ipar=0;ipar<pars;ipar++) Z_par_err[ibil][ipar]=sqrt((double)(njacks-1))*sqrt(fabs(sqr_Z_par_ave[ibil][ipar]-Z_par_ave[ibil][ipar]*Z_par_ave[ibil][ipar])); //ibil={S,A,P,V,T} // cout<<"DEBUG---(G)"<<endl; Z_par_ave_err[0]=Z_par_ave; //Z_par_ave_err[ave/err][ibil][par] Z_par_ave_err[1]=Z_par_err; // cout<<"DEBUG---(H)"<<endl; vd_t A(0.0,nbil),A_err(0.0,nbil),B(0.0,nbil),B_err(0.0,nbil); for(int ibil=0; ibil<nbil;ibil++) { A[ibil]=Z_par_ave_err[0][ibil][0]; A_err[ibil]=Z_par_ave_err[1][ibil][0]; B[ibil]=Z_par_ave_err[0][ibil][1]; B_err[ibil]=Z_par_ave_err[1][ibil][1]; } ///*****************************/// ////////////////////// vector<string> bil={"S","A","P","V","T"}; vector<ofstream> datafile(5); vector<ofstream> datafile_fit(5); //Perturbative estimate from Martinelli-Zhang in RI-MOM at mu=1/a vector<double> pert={-0.0695545,-0.100031,-0.118281,-0.130564,-0.108664}; for(int i=0;i<5;i++) { // cout<<endl; cout<<"Z"<<bil[i]<<" = "<<A[i]<<" +/- "<<A_err[i]<<endl; datafile[i].open("plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_data.txt"); for(size_t imom=0;imom<p2_vector.size();imom++) datafile[i]<<p2_vector[imom]<<"\t"<<Z_chiral[0][imom][i]<<"\t"<<Z_chiral[1][imom][i]<<endl; datafile[i].close(); datafile_fit[i].open("plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_data_fit.txt"); datafile_fit[i]<<"0"<<"\t"<<A[i]<<"\t"<<A_err[i]<<endl; datafile_fit[i].close(); } cout<<endl; if(name=="ZO_em_RIp_ainv") { for(int i=0;i<5;i++) { cout<<"Z"<<bil[i]<<"(fact) = "<<A[i]/pert[i]<<" +/- "<<A_err[i]/pert[i]<<endl; } } cout<<endl; vector<ofstream> scriptfile(5); for(int i=0;i<5;i++) { scriptfile[i].open("plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_script.txt"); scriptfile[i]<<"set autoscale xy"<<endl; scriptfile[i]<<"set xlabel '$a^2\\tilde{p}^2$'"<<endl; // if(i==0 && name=="ZO_RIp_ainv") scriptfile[i]<<"set yrange [0.60:0.76]"<<endl; //S // if(i==1 && name=="ZO_RIp_ainv") scriptfile[i]<<"set yrange [0.72:0.82]"<<endl; //A // if(i==2 && name=="ZO_RIp_ainv") scriptfile[i]<<"set yrange [0.3:0.9]"<<endl; //P // if(i==3 && name=="ZO_RIp_ainv") scriptfile[i]<<"set yrange [0.62:0.69]"<<endl; //V // if(i==4 && name=="ZO_RIp_ainv") scriptfile[i]<<"set yrange [*:*]"<<endl; //T // if(i==0 && name=="ZO_em_RIp_ainv") scriptfile[i]<<"set yrange [-0.3:0.0]"<<endl; //S // if(i==1 && name=="ZO_em_RIp_ainv") scriptfile[i]<<"set yrange [-0.13:-0.07]"<<endl; //A // if(i==2 && name=="ZO_em_RIp_ainv") scriptfile[i]<<"set yrange [-1.2:0.4]"<<endl; //P // if(i==3 && name=="ZO_em_RIp_ainv") scriptfile[i]<<"set yrange [-0.17:-0.11]"<<endl; //V // if(i==4 && name=="ZO_em_RIp_ainv") scriptfile[i]<<"set yrange [-0.14:-0.07]"<<endl; //T scriptfile[i]<<"set xrange [-0.05:2.5]"<<endl; if(name=="ZO_RIp_ainv") scriptfile[i]<<"set ylabel '$Z_"<<bil[i]<<"$'"<<endl; if(name=="ZO_em_RIp_ainv") scriptfile[i]<<"set ylabel '$\\delta Z_"<<bil[i]<<"$'"<<endl; if(name=="ZO_RIp_ainv") scriptfile[i]<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<bil[i]<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$Z_"<<bil[i]<<"$'"<<endl; if(name=="ZO_em_RIp_ainv") scriptfile[i]<<"plot 'plot_data_and_script/plot_"<<name<<"_"<<bil[i]<<"_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$\\delta Z_"<<bil[i]<<"$'"<<endl; scriptfile[i]<<"replot 'plot_data_and_script/plot_"<<name<<"_"<<bil[i]<<"_"<<all_or_eq_moms<<"_data_fit.txt' u 1:2:3 with errorbars pt 7 lt 1 lc rgb 'red' ps 1 title 'extrapolation'"<<endl; scriptfile[i]<<"f(x)="<<A[i]<<"+"<<B[i]<<"*x"<<endl; scriptfile[i]<<"replot f(x) lw 3 title 'linear fit'"<<endl; scriptfile[i]<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile[i]<<"set output 'allmoms/"<<name<<"_"<<bil[i]<<".tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile[i]<<"set output 'eqmoms/"<<name<<"_"<<bil[i]<<".tex'"<<endl; scriptfile[i]<<"replot"<<endl; scriptfile[i]<<"set term unknown"<<endl; scriptfile[i].close(); string command="gnuplot plot_data_and_script/plot_"+name+"_"+bil[i]+"_"+all_or_eq_moms+"_script.txt"; system(command.c_str()); } int moms=p2_vector.size(); // int njacks=jZ_chiral[0].size(); vector<vd_t> jZP_over_S(moms,vd_t(0.0,njacks)); #pragma omp parallel for collapse(2) for(int imom=0;imom<moms;imom++) for(int ijack=0;ijack<njacks;ijack++) jZP_over_S[imom][ijack]=jZ_chiral[imom][ijack][2]/jZ_chiral[imom][ijack][0]; vvd_t ZP_over_S=average_Zq_chiral(jZP_over_S); ofstream datafile2; datafile2.open("plot_data_and_script/plot_"+name+"_P_over_S_"+all_or_eq_moms+"_data.txt"); for(size_t imom=0;imom<p2_vector.size();imom++) datafile2<<p2_vector[imom]<<"\t"<<ZP_over_S[0][imom]<<"\t"<<ZP_over_S[1][imom]<<endl; datafile2.close(); ofstream scriptfile2; scriptfile2.open("plot_data_and_script/plot_"+name+"_P_over_S_"+all_or_eq_moms+"_script.txt"); scriptfile2<<"set autoscale xy"<<endl; scriptfile2<<"set xlabel '$a^2\\tilde{p}^2$'"<<endl; // scriptfile2<<"set yrange [0.7:0.9]"<<endl; scriptfile2<<"set ylabel '$Z_P/Z_S$'"<<endl; scriptfile2<<"plot 'plot_data_and_script/plot_"<<name<<"_P_over_S_"<<all_or_eq_moms<<"_data.txt' u 1:2:3 with errorbars pt 6 lc rgb 'blue' title '$Z_P/Z_S$ chiral'"<<endl; scriptfile2<<"set terminal epslatex color"<<endl; if(strcmp(all_or_eq_moms.c_str(),"allmoms")==0) scriptfile2<<"set output 'allmoms/"<<name<<"_P_over_S.tex'"<<endl; else if(strcmp(all_or_eq_moms.c_str(),"eqmoms")==0) scriptfile2<<"set output 'eqmoms/"<<name<<"_P_over_S.tex'"<<endl; scriptfile2<<"replot"<<endl; scriptfile2<<"set term unknown"<<endl; scriptfile2.close(); string command2="gnuplot plot_data_and_script/plot_"+name+"_P_over_S_"+all_or_eq_moms+"_script.txt"; system(command2.c_str()); } ///*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/// int main(int narg,char **arg) { if (narg!=6){ cerr<<"Number of arguments not valid: <mom file> <nconfs> <njacks> <L> <T>"<<endl; exit(0); } // int nconfs=stoi(arg[2]); int njacks=stoi(arg[3]); // int clust_size=nconfs/njacks; // int conf_id[nconfs]; // double L=stod(arg[4]),T=stod(arg[5]); // size_t nhits=1; //! nm = 5; //! to be passed from command line nr = 2; nmr=nm*nr; int neq = fact(nm+nr-1)/fact(nr)/fact(nm-1); int neq2=nm; read_mom_list(arg[1]); int moms=mom_list.size(); int neq_moms=17; ////////////////// vector<double> p2_vector_allmoms(moms); vector<jZ_t> jZq_allmoms(moms,vvd_t(vd_t(nmr),njacks)), jSigma1_allmoms(moms,vvd_t(vd_t(nmr),njacks)), \ jZq_em_allmoms(moms,vvd_t(vd_t(nmr),njacks)), jSigma1_em_allmoms(moms,vvd_t(vd_t(nmr),njacks)); vector<jZbil_t> jZ_allmoms(moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), jZ1_allmoms(moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), \ jZ_em_allmoms(moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), jZ1_em_allmoms(moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)); vector<jZ_t> jZq_sub_allmoms(moms,vvd_t(vd_t(nmr),njacks)), jSigma1_sub_allmoms(moms,vvd_t(vd_t(nmr),njacks)),\ jZq_em_sub_allmoms(moms,vvd_t(vd_t(nmr),njacks)), jSigma1_em_sub_allmoms(moms,vvd_t(vd_t(nmr),njacks)); vector<jZbil_t> jZ_sub_allmoms(moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), jZ1_sub_allmoms(moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)),\ jZ_em_sub_allmoms(moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), jZ1_em_sub_allmoms(moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)); vector<vvd_t> jGp_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)), jGs_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)),\ jGp_subpole_allmoms(moms,vvd_t(vd_t(neq),njacks)), jGs_subpole_allmoms(moms,vvd_t(vd_t(neq),njacks)); vector<vvd_t> jGp_em_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)), jGs_em_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)), \ jGp_em_subpole_allmoms(moms,vvd_t(vd_t(neq),njacks)), jGs_em_subpole_allmoms(moms,vvd_t(vd_t(neq),njacks)); vector<vvd_t> jGv_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)), jGa_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)),\ jGt_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)); vector<vvd_t> jGv_em_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)), jGa_em_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)),\ jGt_em_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)); vector<vvd_t> jZq_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)), jSigma1_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)),\ jZq_em_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)), jSigma1_em_equivalent_allmoms(moms,vvd_t(vd_t(neq),njacks)); vector<vd_t> jGp_0_chiral_allmoms(moms,vd_t(njacks)),jGa_0_chiral_allmoms(moms,vd_t(njacks)),jGv_0_chiral_allmoms(moms,vd_t(njacks)),\ jGs_0_chiral_allmoms(moms,vd_t(njacks)),jGt_0_chiral_allmoms(moms,vd_t(njacks)); vector<vd_t> jGp_em_a_b_chiral_allmoms(moms,vd_t(njacks)),jGa_em_a_b_chiral_allmoms(moms,vd_t(njacks)),jGv_em_a_b_chiral_allmoms(moms,vd_t(njacks)), \ jGs_em_a_b_chiral_allmoms(moms,vd_t(njacks)),jGt_em_a_b_chiral_allmoms(moms,vd_t(njacks)); vector<vd_t> jZq_chiral_allmoms(moms,vd_t(njacks)),jSigma1_chiral_allmoms(moms,vd_t(njacks)); vector<vd_t> jZq_em_chiral_allmoms(moms,vd_t(njacks)),jSigma1_em_chiral_allmoms(moms,vd_t(njacks)); vector<vvd_t> jZ_chiral_allmoms(moms,vvd_t(vd_t(5),njacks)),jZ1_chiral_allmoms(moms,vvd_t(vd_t(5),njacks)); vector<vvd_t> jZ_em_chiral_allmoms(moms,vvd_t(vd_t(5),njacks)),jZ1_em_chiral_allmoms(moms,vvd_t(vd_t(5),njacks)); vector< vXd_t > jGp_pars_allmoms(moms,vXd_t(VectorXd(3),njacks)), jGs_pars_allmoms(moms,vXd_t(VectorXd(3),njacks)), \ jGp_em_pars_allmoms(moms,vXd_t(VectorXd(3),njacks)), jGs_em_pars_allmoms(moms,vXd_t(VectorXd(3),njacks)); vector< vXd_t > jGv_pars_allmoms(moms,vXd_t(VectorXd(2),njacks)), jGa_pars_allmoms(moms,vXd_t(VectorXd(2),njacks)),\ jGt_pars_allmoms(moms,vXd_t(VectorXd(2),njacks)), jGv_em_pars_allmoms(moms,vXd_t(VectorXd(2),njacks)),\ jGa_em_pars_allmoms(moms,vXd_t(VectorXd(2),njacks)), jGt_em_pars_allmoms(moms,vXd_t(VectorXd(2),njacks)); vector< vXd_t > jZq_pars_allmoms(moms,vXd_t(VectorXd(2),njacks)), jSigma1_pars_allmoms(moms,vXd_t(VectorXd(2),njacks)),\ jZq_em_pars_allmoms(moms,vXd_t(VectorXd(2),njacks)), jSigma1_em_pars_allmoms(moms,vXd_t(VectorXd(2),njacks)); vector<vd_t> jSigma1_RIp_ainv_allmoms(moms,vd_t(0.0,njacks)),jSigma1_em_RIp_ainv_allmoms(moms,vd_t(0.0,njacks)); vector<vvd_t> jZO_RIp_ainv_allmoms(moms,vvd_t(vd_t(5),njacks)),jZO_em_RIp_ainv_allmoms(moms,vvd_t(vd_t(5),njacks)); vd_t m_eff_equivalent(1.0,neq); vd_t m_eff_equivalent_Zq(0.0,neq2); vector<double> p2_vector_eqmoms(neq_moms); vector<jZ_t> jZq_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)), jSigma1_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)),\ jZq_em_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)), jSigma1_em_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)); vector<jZbil_t> jZ_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), jZ1_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)),\ jZ_em_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), jZ1_em_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)); vector<jZ_t> jZq_sub_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)), jSigma1_sub_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)),\ jZq_em_sub_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)), jSigma1_em_sub_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)); vector<jZbil_t> jZ_sub_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), jZ1_sub_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)),\ jZ_em_sub_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), jZ1_em_sub_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)); vector<vvd_t> jGp_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)), jGs_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)),\ jGp_subpole_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)), jGs_subpole_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)); vector<vvd_t> jGp_em_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)), jGs_em_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)), \ jGp_em_subpole_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)), jGs_em_subpole_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)); vector<vvd_t> jGv_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)), jGa_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)),\ jGt_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)); vector<vvd_t> jGv_em_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)), jGa_em_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)),\ jGt_em_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq),njacks)); vector<vvd_t> jZq_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq2),njacks)), jSigma1_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq2),njacks)),\ jZq_em_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq2),njacks)), jSigma1_em_equivalent_eqmoms(neq_moms,vvd_t(vd_t(neq2),njacks)); vector<vd_t> jGp_0_chiral_eqmoms(neq_moms,vd_t(njacks)),jGa_0_chiral_eqmoms(neq_moms,vd_t(njacks)),jGv_0_chiral_eqmoms(neq_moms,vd_t(njacks)),\ jGs_0_chiral_eqmoms(neq_moms,vd_t(njacks)),jGt_0_chiral_eqmoms(neq_moms,vd_t(njacks)); vector<vd_t> jGp_em_a_b_chiral_eqmoms(neq_moms,vd_t(njacks)),jGa_em_a_b_chiral_eqmoms(neq_moms,vd_t(njacks)),jGv_em_a_b_chiral_eqmoms(neq_moms,vd_t(njacks)), \ jGs_em_a_b_chiral_eqmoms(neq_moms,vd_t(njacks)),jGt_em_a_b_chiral_eqmoms(neq_moms,vd_t(njacks)); vector<vd_t> jZq_chiral_eqmoms(neq_moms,vd_t(njacks)),jSigma1_chiral_eqmoms(neq_moms,vd_t(njacks)); vector<vd_t> jZq_em_chiral_eqmoms(neq_moms,vd_t(njacks)),jSigma1_em_chiral_eqmoms(neq_moms,vd_t(njacks)); vector<vvd_t> jZ_chiral_eqmoms(neq_moms,vvd_t(vd_t(5),njacks)),jZ1_chiral_eqmoms(neq_moms,vvd_t(vd_t(5),njacks)); vector<vvd_t> jZ_em_chiral_eqmoms(neq_moms,vvd_t(vd_t(5),njacks)),jZ1_em_chiral_eqmoms(neq_moms,vvd_t(vd_t(5),njacks)); vector< vXd_t > jGp_pars_eqmoms(neq_moms,vXd_t(VectorXd(3),njacks)), jGs_pars_eqmoms(neq_moms,vXd_t(VectorXd(3),njacks)), \ jGp_em_pars_eqmoms(neq_moms,vXd_t(VectorXd(3),njacks)), jGs_em_pars_eqmoms(neq_moms,vXd_t(VectorXd(3),njacks)); vector< vXd_t > jGv_pars_eqmoms(neq_moms,vXd_t(VectorXd(2),njacks)), jGa_pars_eqmoms(neq_moms,vXd_t(VectorXd(2),njacks)),\ jGt_pars_eqmoms(neq_moms,vXd_t(VectorXd(2),njacks)), jGv_em_pars_eqmoms(neq_moms,vXd_t(VectorXd(2),njacks)),\ jGa_em_pars_eqmoms(neq_moms,vXd_t(VectorXd(2),njacks)), jGt_em_pars_eqmoms(neq_moms,vXd_t(VectorXd(2),njacks)); vector< vXd_t > jZq_pars_eqmoms(neq_moms,vXd_t(VectorXd(2),njacks)), jSigma1_pars_eqmoms(neq_moms,vXd_t(VectorXd(2),njacks)),\ jZq_em_pars_eqmoms(neq_moms,vXd_t(VectorXd(2),njacks)), jSigma1_em_pars_eqmoms(neq_moms,vXd_t(VectorXd(2),njacks)); vector<vd_t> jSigma1_RIp_ainv_eqmoms(neq_moms,vd_t(0.0,njacks)),jSigma1_em_RIp_ainv_eqmoms(neq_moms,vd_t(0.0,njacks)); vector<vvd_t> jZO_RIp_ainv_eqmoms(neq_moms,vvd_t(vd_t(5),njacks)),jZO_em_RIp_ainv_eqmoms(neq_moms,vvd_t(vd_t(5),njacks)); #define READ(NAME) \ read_vec(NAME##_##allmoms,"allmoms/"#NAME); \ read_vec(NAME##_##eqmoms,"eqmoms/"#NAME) READ(p2_vector); READ(jZq); READ(jSigma1); READ(jZq_em); READ(jSigma1_em); READ(jZ); READ(jZ1); READ(jZ_em); READ(jZ1_em); READ(jZq_sub); READ(jSigma1_sub); READ(jZq_em_sub); READ(jSigma1_em_sub); READ(jZ_sub); READ(jZ1_sub); READ(jZ_em_sub); READ(jZ1_em_sub); READ(jGp_equivalent); READ(jGs_equivalent); READ(jGp_subpole); READ(jGs_subpole); READ(jGv_equivalent); READ(jGa_equivalent); READ(jGt_equivalent); READ(jGp_em_equivalent); READ(jGs_em_equivalent); READ(jGp_em_subpole); READ(jGs_em_subpole); READ(jGv_em_equivalent); READ(jGa_em_equivalent); READ(jGt_em_equivalent); READ(jZq_equivalent); READ(jSigma1_equivalent); READ(jZq_em_equivalent); READ(jSigma1_em_equivalent); READ(jGp_0_chiral); READ(jGa_0_chiral); READ(jGv_0_chiral); READ(jGs_0_chiral); READ(jGt_0_chiral); READ(jGp_em_a_b_chiral); READ(jGa_em_a_b_chiral); READ(jGv_em_a_b_chiral); READ(jGs_em_a_b_chiral); READ(jGt_em_a_b_chiral); READ(jZq_chiral); READ(jSigma1_chiral); READ(jZq_em_chiral); READ(jSigma1_em_chiral); READ(jZ_chiral); READ(jZ1_chiral); READ(jZ_em_chiral); READ(jZ1_em_chiral); READ(jGp_pars); READ(jGp_em_pars); READ(jGs_pars); READ(jGs_em_pars); READ(jGv_pars); READ(jGv_em_pars); READ(jGa_pars); READ(jGa_em_pars); READ(jGt_pars); READ(jGt_em_pars); READ(jZq_pars); READ(jZq_em_pars); READ(jSigma1_pars); READ(jSigma1_em_pars); READ(jSigma1_RIp_ainv); READ(jSigma1_em_RIp_ainv); READ(jZO_RIp_ainv); READ(jZO_em_RIp_ainv); #undef READ read_vec(m_eff_equivalent,"allmoms/m_eff_equivalent"); read_vec(m_eff_equivalent_Zq,"allmoms/m_eff_equivalent_Zq"); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Zq with subtraction ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ // plot_Zq_sub(jZq_eqmoms,jZq_sub_eqmoms,p2_vector_eqmoms,"Zq","eqmoms"); plot_Zq_sub(jSigma1_eqmoms,jSigma1_sub_eqmoms,p2_vector_eqmoms,"Sigma1","eqmoms"); // vector<jZ_t> jZq_with_em_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)), jSigma1_with_em_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)); // vector<jZ_t> jZq_sub_with_em_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)), jSigma1_sub_with_em_eqmoms(neq_moms,vvd_t(vd_t(nmr),njacks)); // #pragma omp parallel for collapse(3) // for(int imom=0;imom<neq_moms;imom++) // for(int mr=0;mr<nmr;mr++) // for(int ijack=0;ijack<njacks;ijack++) // { // jZq_with_em_eqmoms[imom][ijack][mr]=jZq_eqmoms[imom][ijack][mr]+jZq_em_eqmoms[imom][ijack][mr]; // jSigma1_with_em_eqmoms[imom][ijack][mr]=jSigma1_eqmoms[imom][ijack][mr]+jSigma1_em_eqmoms[imom][ijack][mr]; // jZq_sub_with_em_eqmoms[imom][ijack][mr]=jZq_sub_eqmoms[imom][ijack][mr]+jZq_em_sub_eqmoms[imom][ijack][mr]; // jSigma1_sub_with_em_eqmoms[imom][ijack][mr]=jSigma1_sub_eqmoms[imom][ijack][mr]+jSigma1_em_sub_eqmoms[imom][ijack][mr]; // } // plot_Zq_sub(jZq_with_em_eqmoms,jZq_sub_with_em_eqmoms,p2_vector_eqmoms,"Zq_with_em","eqmoms"); // plot_Zq_sub(jSigma1_with_em_eqmoms,jSigma1_sub_with_em_eqmoms,p2_vector_eqmoms,"Sigma1_with_em","eqmoms"); // plot_Zq_sub(jZq_em_eqmoms,jZq_em_sub_eqmoms,p2_vector_eqmoms,"Zq_em_correction","eqmoms"); plot_Zq_sub(jSigma1_em_eqmoms,jSigma1_em_sub_eqmoms,p2_vector_eqmoms,"Sigma1_em_correction","eqmoms"); vvvd_t Sigma1 = average_Zq(jSigma1_em_eqmoms); //Zq[ave/err][imom][nm] vvvd_t Sigma1_sub = average_Zq(jSigma1_em_sub_eqmoms); //Zq[ave/err][imom][nm] cout<<endl; cout<<"Zq"<<endl<<"-------------DEBUG (m0 r0) -----------------"<<endl<<endl; for(size_t imom=0;imom<p2_vector_eqmoms.size();imom++) { cout<<p2_vector_eqmoms[imom]<<"\t"<<Sigma1[0][imom][0]<<"\t"<<Sigma1[1][imom][0]<<endl; //print only for M0R0 } cout<<endl<<"Zq_SUB"<<endl<<"----------DEBUG (m0 r0) --------------------"<<endl; for(size_t imom=0;imom<p2_vector_eqmoms.size();imom++) { cout<<p2_vector_eqmoms[imom]<<"\t"<<Sigma1_sub[0][imom][0]<<"\t"<<Sigma1_sub[1][imom][0]<<endl; //print only for M0R0 } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Zq chiral extrapolation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ // plot_Zq_chiral_extrapolation(jZq_equivalent_eqmoms,jZq_pars_eqmoms,m_eff_equivalent_Zq,"Zq_chiral_extrapolation","eqmoms"); plot_Zq_chiral_extrapolation(jSigma1_equivalent_eqmoms,jSigma1_pars_eqmoms,m_eff_equivalent_Zq,"Sigma1_chiral_extrapolation","eqmoms"); plot_Zq_chiral_extrapolation(jSigma1_em_equivalent_eqmoms,jSigma1_em_pars_eqmoms,m_eff_equivalent_Zq,"Sigma1_em_chiral_extrapolation","eqmoms"); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Zq chiral ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ // cout<<"Zq chiral"<<endl; //plot_Zq_chiral(jZq_chiral_eqmoms,p2_vector_eqmoms,"Zq_chiral","eqmoms"); cout<<"Sigma1 chiral"<<endl; plot_Zq_chiral(jSigma1_chiral_eqmoms,p2_vector_eqmoms,"Sigma1_chiral","eqmoms"); // vector<vd_t> jZq_chiral_with_em_eqmoms(neq_moms,vd_t(njacks)), jSigma1_chiral_with_em_eqmoms(neq_moms,vd_t(njacks)); // #pragma omp parallel for collapse(2) // for(int imom=0;imom<neq_moms;imom++) // for(int ijack=0;ijack<njacks;ijack++) // { // jZq_chiral_with_em_eqmoms[imom][ijack]=jZq_chiral_eqmoms[imom][ijack]+jZq_em_chiral_eqmoms[imom][ijack]; // jSigma1_chiral_with_em_eqmoms[imom][ijack]=jSigma1_chiral_eqmoms[imom][ijack]+jSigma1_em_chiral_eqmoms[imom][ijack]; // } //cout<<"Zq chiral with em"<<endl; // plot_Zq_chiral(jZq_chiral_with_em_eqmoms,p2_vector_eqmoms,"Zq_chiral_with_em","eqmoms"); //cout<<"Sigma1 chiral with em"<<endl; //plot_Zq_chiral(jSigma1_chiral_with_em_eqmoms,p2_vector_eqmoms,"Sigma1_chiral_with_em","eqmoms"); // cout<<"Zq chiral em correction"<<endl; // plot_Zq_chiral(jZq_em_chiral_eqmoms,p2_vector_eqmoms,"Zq_chiral_em_correction","eqmoms"); cout<<"Sigma1 chiral em correction"<<endl; plot_Zq_chiral(jSigma1_em_chiral_eqmoms,p2_vector_eqmoms,"Sigma1_chiral_em_correction","eqmoms"); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Zq over Sigma1 chiral ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ // vector<vd_t> jZq_over_Sigma1_eqmoms(neq_moms,vd_t(njacks)), jZq_over_Sigma1_with_em_eqmoms(neq_moms,vd_t(njacks)); // #pragma omp parallel for collapse(2) // for(int imom=0;imom<neq_moms;imom++) // for(int ijack=0;ijack<njacks;ijack++) // { // jZq_over_Sigma1_eqmoms[imom][ijack]=jZq_chiral_eqmoms[imom][ijack]/jSigma1_chiral_eqmoms[imom][ijack]; // jZq_over_Sigma1_with_em_eqmoms[imom][ijack]=jZq_chiral_with_em_eqmoms[imom][ijack]/jSigma1_chiral_with_em_eqmoms[imom][ijack]; // } // cout<<"Zq over Sigma1 chiral"<<endl; // plot_Zq_chiral(jZq_over_Sigma1_eqmoms,p2_vector_eqmoms,"Zq_over_Sigma1_chiral","eqmoms"); // cout<<"Zq over Sigma1 chiral with em"<<endl; // plot_Zq_chiral(jZq_over_Sigma1_with_em_eqmoms,p2_vector_eqmoms,"Zq_over_Sigma1_chiral_with_em","eqmoms"); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Z with subtraction ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ // plot_Z_sub(jZ_eqmoms,jZ_sub_eqmoms,p2_vector_eqmoms,"Z","eqmoms"); plot_Z_sub(jZ1_eqmoms,jZ1_sub_eqmoms,p2_vector_eqmoms,"Z1","eqmoms"); // vector<jZbil_t> jZ_with_em_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), jZ1_with_em_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)); // vector<jZbil_t> jZ_sub_with_em_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)), jZ1_sub_with_em_eqmoms(neq_moms,jZbil_t(vvvd_t(vvd_t(vd_t(5),nmr),nmr),njacks)); // #pragma omp parallel for collapse(5) // for(int imom=0;imom<neq_moms;imom++) // for(int mr_fw=0;mr_fw<nmr;mr_fw++) // for(int mr_bw=0;mr_bw<nmr;mr_bw++) // for(int ijack=0;ijack<njacks;ijack++) // for(int k=0;k<5;k++) // { // jZ_with_em_eqmoms[imom][ijack][mr_fw][mr_bw][k]=jZ_eqmoms[imom][ijack][mr_fw][mr_bw][k]+jZ_em_eqmoms[imom][ijack][mr_fw][mr_bw][k]; // jZ1_with_em_eqmoms[imom][ijack][mr_fw][mr_bw][k]=jZ1_eqmoms[imom][ijack][mr_fw][mr_bw][k]+jZ1_em_eqmoms[imom][ijack][mr_fw][mr_bw][k]; // jZ_sub_with_em_eqmoms[imom][ijack][mr_fw][mr_bw][k]=jZ_sub_eqmoms[imom][ijack][mr_fw][mr_bw][k]+jZ_em_sub_eqmoms[imom][ijack][mr_fw][mr_bw][k]; // jZ1_sub_with_em_eqmoms[imom][ijack][mr_fw][mr_bw][k]=jZ1_sub_eqmoms[imom][ijack][mr_fw][mr_bw][k]+jZ1_em_sub_eqmoms[imom][ijack][mr_fw][mr_bw][k]; // } // plot_Z_sub(jZ_with_em_eqmoms,jZ_sub_with_em_eqmoms,p2_vector_eqmoms,"Z_with_em","eqmoms"); // plot_Z_sub(jZ1_with_em_eqmoms,jZ1_sub_with_em_eqmoms,p2_vector_eqmoms,"Z1_with_em","eqmoms"); // plot_Z_sub(jZ_em_eqmoms,jZ_em_sub_eqmoms,p2_vector_eqmoms,"Z_em_correction","eqmoms"); plot_Z_sub(jZ1_em_eqmoms,jZ1_em_sub_eqmoms,p2_vector_eqmoms,"Z1_em_correction","eqmoms"); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Z chiral extrapolation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ plot_ZPandS_chiral_extrapolation("P",jGp_equivalent_eqmoms,jGp_subpole_eqmoms,jGp_pars_eqmoms,m_eff_equivalent,"Gp_chiral_extrapolation","eqmoms"); plot_ZPandS_chiral_extrapolation("S",jGs_equivalent_eqmoms,jGs_subpole_eqmoms,jGs_pars_eqmoms,m_eff_equivalent,"Gs_chiral_extrapolation","eqmoms"); plot_ZVAT_chiral_extrapolation("V",jGv_equivalent_eqmoms,jGv_pars_eqmoms,m_eff_equivalent,"Gv_chiral_extrapolation","eqmoms"); plot_ZVAT_chiral_extrapolation("A",jGa_equivalent_eqmoms,jGa_pars_eqmoms,m_eff_equivalent,"Ga_chiral_extrapolation","eqmoms"); plot_ZVAT_chiral_extrapolation("T",jGt_equivalent_eqmoms,jGt_pars_eqmoms,m_eff_equivalent,"Gt_chiral_extrapolation","eqmoms"); plot_ZPandS_chiral_extrapolation("P",jGp_em_equivalent_eqmoms,jGp_em_subpole_eqmoms,jGp_em_pars_eqmoms,m_eff_equivalent,"Gp_em_chiral_extrapolation","eqmoms"); plot_ZPandS_chiral_extrapolation("S",jGs_em_equivalent_eqmoms,jGs_em_subpole_eqmoms,jGs_em_pars_eqmoms,m_eff_equivalent,"Gs_em_chiral_extrapolation","eqmoms"); plot_ZVAT_chiral_extrapolation("V",jGv_em_equivalent_eqmoms,jGv_em_pars_eqmoms,m_eff_equivalent,"Gv_em_chiral_extrapolation","eqmoms"); plot_ZVAT_chiral_extrapolation("A",jGa_em_equivalent_eqmoms,jGa_em_pars_eqmoms,m_eff_equivalent,"Ga_em_chiral_extrapolation","eqmoms"); plot_ZVAT_chiral_extrapolation("T",jGt_em_equivalent_eqmoms,jGt_em_pars_eqmoms,m_eff_equivalent,"Gt_em_chiral_extrapolation","eqmoms"); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Z chiral ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ // cout<<"Z chiral"<<endl; // plot_Z_chiral(jZ_chiral_eqmoms,p2_vector_eqmoms,"Z_chiral","eqmoms"); cout<<"Z1 chiral"<<endl; plot_Z_chiral(jZ1_chiral_eqmoms,p2_vector_eqmoms,"Z1_chiral","eqmoms"); // vector<vvd_t> jZ_chiral_with_em_eqmoms(neq_moms,vvd_t(vd_t(5),njacks)), jZ1_chiral_with_em_eqmoms(neq_moms,vvd_t(vd_t(5),njacks)); // #pragma omp parallel for collapse(3) // for(int imom=0;imom<neq_moms;imom++) // for(int ijack=0;ijack<njacks;ijack++) // for(int k=0;k<5;k++) // { // jZ_chiral_with_em_eqmoms[imom][ijack][k]=jZ_chiral_eqmoms[imom][ijack][k]+jZ_em_chiral_eqmoms[imom][ijack][k]; // jZ1_chiral_with_em_eqmoms[imom][ijack][k]=jZ1_chiral_eqmoms[imom][ijack][k]+jZ1_em_chiral_eqmoms[imom][ijack][k]; // } // cout<<"Z chiral with em"<<endl; // plot_Z_chiral(jZ_chiral_with_em_eqmoms,p2_vector_eqmoms,"Z_chiral_with_em","eqmoms"); //cout<<"Z1 chiral with em"<<endl; //plot_Z_chiral(jZ1_chiral_with_em_eqmoms,p2_vector_eqmoms,"Z1_chiral_with_em","eqmoms"); //cout<<"Z chiral em correction"<<endl; //plot_Z_chiral(jZ_em_chiral_eqmoms,p2_vector_eqmoms,"Z_chiral_em_correction","eqmoms"); cout<<"Z1 chiral em correction"<<endl; plot_Z_chiral(jZ1_em_chiral_eqmoms,p2_vector_eqmoms,"Z1_chiral_em_correction","eqmoms"); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Z RIp_ainv ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ cout<<"Z1(1/a) -- p_min>1"<<endl; plot_ZO_RIp_ainv(jZO_RIp_ainv_eqmoms,p2_vector_eqmoms,"ZO_RIp_ainv","eqmoms",1.0); cout<<"Z1(1/a) em correction -- p_min>1"<<endl; plot_ZO_RIp_ainv(jZO_em_RIp_ainv_eqmoms,p2_vector_eqmoms,"ZO_em_RIp_ainv","eqmoms",1.0); cout<<"Z1(1/a) -- p_min>0.9"<<endl; plot_ZO_RIp_ainv(jZO_RIp_ainv_eqmoms,p2_vector_eqmoms,"ZO_RIp_ainv","eqmoms",0.9); cout<<"Z1(1/a) em correction -- p_min>0.9"<<endl; plot_ZO_RIp_ainv(jZO_em_RIp_ainv_eqmoms,p2_vector_eqmoms,"ZO_em_RIp_ainv","eqmoms",0.9); cout<<"Z1(1/a) -- p_min>1.1"<<endl; plot_ZO_RIp_ainv(jZO_RIp_ainv_eqmoms,p2_vector_eqmoms,"ZO_RIp_ainv","eqmoms",1.1); cout<<"Z1(1/a) em correction -- p_min>1.1"<<endl; plot_ZO_RIp_ainv(jZO_em_RIp_ainv_eqmoms,p2_vector_eqmoms,"ZO_em_RIp_ainv","eqmoms",1.1); cout<<"Sigma1(1/a)"<<endl; plot_Zq_RIp_ainv(jSigma1_RIp_ainv_eqmoms,p2_vector_eqmoms,"Sigma1_RIp_ainv","eqmoms"); cout<<"Sigma1(1/a) em correction"<<endl; plot_Zq_RIp_ainv(jSigma1_em_RIp_ainv_eqmoms,p2_vector_eqmoms,"Sigma1_em_RIp_ainv","eqmoms"); vvvd_t eff_mass_array(vvd_t(vd_t(0.0,2),nmr),nmr); ifstream input_effmass; input_effmass.open("eff_mass_array",ios::binary); for(int mr_fw=0;mr_fw<nmr;mr_fw++) for(int mr_bw=0;mr_bw<nmr;mr_bw++) for(int i=0;i<2;i++) { double temp; input_effmass.read((char*)&temp,sizeof(double)); if(not input_effmass.good()) { cerr<<"Unable to read from eff_mass_array mr_fw: "<<mr_fw<<", mr_bw: "<<mr_bw<<", i: "<<i<<endl; exit(1); } eff_mass_array[mr_fw][mr_bw][i]=temp; //store } // cout<<"***DEBUG***"<<endl; // for(int mr_fw=0;mr_fw<nmr;mr_fw++) // for(int mr_bw=0;mr_bw<nmr;mr_bw++) // for(int i=0;i<2;i++) // cout<<eff_mass_array[mr_fw][mr_bw][i]<<endl; // cout<<"***DEBUG***"<<endl; vvd_t eff_mass(vd_t(0.0,nmr),nmr); for(int mr_fw=0;mr_fw<nmr;mr_fw++) for(int mr_bw=0;mr_bw<nmr;mr_bw++) eff_mass[mr_fw][mr_bw] = eff_mass_array[mr_fw][mr_bw][0]; cout<<endl; cout<<"r_fw \t m_fw \t r_bw \t m_bw \t eff_mass"<<endl; for(int mr_fw=0;mr_fw<nmr;mr_fw++) for(int mr_bw=0;mr_bw<nmr;mr_bw++) cout<<mr_fw%nr<<"\t"<<(mr_fw - mr_fw%nr)/nr<<"\t"<<mr_bw%nr<<"\t"<<(mr_bw - mr_bw%nr)/nr<<"\t"<<eff_mass[mr_fw][mr_bw]<<endl; // cout<<"eff_mass: "<<eff_mass_array[0]<<" +- "<<eff_mass_array[1]<<endl; return 0; } // vvvd_t Zq_allmoms=average_Zq(jZq_allmoms), Zq_eqmoms=average_Zq(jZq_eqmoms), Zq_sub_allmoms=average_Zq(jZq_sub_allmoms), Zq_sub_eqmoms=average_Zq(jZq_sub_eqmoms); // vvvd_t Sigma1_allmoms=average_Zq(jSigma1_allmoms), Sigma1_eqmoms=average_Zq(jSigma1_eqmoms),\ // Sigma1_sub_allmoms=average_Zq(jSigma1_sub_allmoms), Sigma1_sub_eqmoms=average_Zq(jSigma1_sub_eqmoms); // vvvd_t Zq_em_allmoms=average_Zq(jZq_em_allmoms), Zq_em_eqmoms=average_Zq(jZq_em_eqmoms), Zq_em_sub_allmoms=average_Zq(jZq_em_sub_allmoms), Zq_em_sub_eqmoms=average_Zq(jZq_em_sub_eqmoms); // vvvd_t Sigma1_em_allmoms=average_Zq(jSigma1_em_allmoms), Sigma1_em_eqmoms=average_Zq(jSigma1_em_eqmoms),\ // Sigma1_em_sub_allmoms=average_Zq(jSigma1_em_sub_allmoms), Sigma1_em_sub_eqmoms=average_Zq(jSigma1_em_sub_eqmoms); // vvd_t Zq_chiral_allmoms=average_Zq_chiral(jZq_chiral_allmoms), Zq_chiral_eqmoms=average_Zq_chiral(jZq_chiral_eqmoms); // vvvvvd_t /*Z_allmoms=average_Z(jZ_allmoms),*/ Z_eqmoms=average_Z(jZ_eqmoms),/*Z1_allmoms=average_Z(jZ1_allmoms),*/ Z1_eqmoms=average_Z(jZ1_eqmoms); // vvvvvd_t /*Z_sub_allmoms=average_Z(jZ_sub_allmoms),*/ Z_sub_eqmoms=average_Z(jZ_sub_eqmoms),/*Z1_sub_allmoms=average_Z(jZ1_sub_allmoms),*/ Z1_sub_eqmoms=average_Z(jZ1_sub_eqmoms);
JavaScript
UTF-8
4,525
2.78125
3
[]
no_license
jQuery(function($){ /*** ANIMATION DU MENU ***/ /* Animation du menu via un ajout de classe aux balises HTML concernées. */ $('#menu_banner').click(function(){ $(this).toggleClass("active"); $('#menu_links').toggleClass("active"); }); /*** TRAITEMENT DES COMMENTAIRES ***/ /* Fonction permettant de récupérer les commentaires. */ function get_comments(){ $.ajax({ url: 'getting_comments.php', method: 'GET', //type de données attendues du serveur : JSON dataType: 'json', timeout: 2000, error: function(jqXHR, textStatus, errorThrown){ $('#comments_errors_display').html("Les commentaires n'ont pas pu être récupérés.<br/>Rapport d'erreur : " + textStatus + ". Erreur HTTP : " + errorThrown + ".") }, success: function(data){ display_comments(data); //les commentaires sont affichés grâce à la fonction "display_comments()" $('#comments_errors_display').html(""); } }); }; /* Fonction permettant l'affichage des commentaires. Arg: données en format JSON. */ function display_comments(commentsJson){ $('#comments_sub').empty(); for(var i = 0 ; i < commentsJson.length ; i++){ var cPs = commentsJson[i].pseudo; var cTxt = commentsJson[i].comment_txt; var cDate = commentsJson[i].date_fr; $('#comments_sub').append("<div class=\"comment_block\"><p class=\"comments_p\">" + cTxt + "<br/><em class=\"comment_pseudo\">" + cPs + "</em> - " + cDate + "</p></div>"); //les " entourant les attributs sont échappés afin qu'ils soient pris en compte } }; //les commentaires sont récupérées et affichées au chargement de la page get_comments(); /* Lorsque l'utilisateur clique sur le bouton "Envoyer", les données sont transmises grâce à AJAX à 'saving_comments.php', qui l'enregistre en base de données. */ $('#send_comment_btn').click(function(){ //récupération des données entrées par l'utilisateur var pseudo = $('#pseudo').val(); var comment_txt = $('#comment_txt').val(); if(pseudo && comment_txt){ $.ajax({ url: 'saving_comments.php', method: 'POST', //données transmises via la méthode 'POST' data: { pseudo: pseudo, comment_txt: comment_txt }, //temps (en ms) au delà duquel la requête sera considérée comme n'ayant pu aboutir timeout: 2000, //fonction appelée en cas d'erreur error: function(jqXHR, textStatus, errorThrown){ $('#comments_errors_form').html("Votre commentaire n'a pas pu être envoyé.<br/>Rapport d'erreur : " + textStatus + ". Erreur HTTP : " + errorThrown + "."); }, //fonction appelée en cas de succès success: function(){ get_comments(); //récupération et affichage des commentaires $('#comments_errors_form').html(""); $('#comment_txt').val(""); } }); } else{ $('#comments_errors_form').html("Merci d'entrer un pseudo et un commentaire."); } }); /*** STRUCTURE DU DOM EN JSON ***/ /* Array permettant d'obtenir la représentation textuelle du type de noeud. */ var nodeTypesDef = { 1: "Node.ELEMENT_NODE", 3: "Node.TEXT_NODE", 7: "Node.PROCESSING_INSTRUCTION_NODE", 8: "Node.COMMENT_NODE", 9: "Node.DOCUMENT_NODE", 10: "Node.DOCUMENT_TYPE_NODE", 11: "Node.DOCUMENT_FRAGMENT_NODE" }; /* Fonction parcourant de manière récursive les noeuds enfants de "parent" et agrémentant l'objet "obj" avec certaines de leurs propriétés. */ function domToObject(parent, obj){ var obj = { nodeName: parent.nodeName, nodeType: nodeTypesDef[parent.nodeType], //type de noeud childNodesNumber: parent.childNodes.length //nombre de noeuds enfants }; if(parent.childNodes.length){ obj.childNodes = [] //tableau comprenant les noeuds enfants for(var i = 0 ; i < parent.childNodes.length ; i++){ obj.childNodes[i] = domToObject(parent.childNodes[i], obj.childNodes); } } return obj; }; /* Fonction retournant la représentation en JSON de la structure du DOM du document. */ function getDocDomToJson(){ return JSON.stringify(domToObject(document, {}), null, 2); }; /* En cas de clic sur "DOM to JSON" dans "index.php", les données retournées par getDocDomToJson() sont données en valeur de l'input caché du formulaire '#dom_to_json_form', qui est ensuite envoyé. */ $('#dom_to_json').click(function(){ var dom_json = getDocDomToJson(); $('#dom_input').val(dom_json); $('#dom_to_json_form').submit(); }); });
Go
UTF-8
971
3.328125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package languagecode // Format represents a specific language code format with a specific // serialization. type Format int const ( // FormatAlpha3 is an ISO-639-2 language code. FormatAlpha3 Format = iota // FormatAlpha3B is an ISO-639-2/B language code. FormatAlpha3B // FormatAlpha2 is an ISO-639-1 language code. FormatAlpha2 formatsCount ) // Serialize the specified Language into a language code string of the Format. func (f Format) Serialize(language Language) string { return codes[language.code][f] } // Deserialize the specified language code string of the Format into a // Language. func (f Format) Deserialize(languageCode string) Language { return languages[f][languageCode] } var languages = func() (l [formatsCount]map[string]Language) { for f := Format(0); f < formatsCount; f++ { l[f] = make(map[string]Language, len(codes)) for j, languageCodes := range codes { l[f][languageCodes[f]] = Language{code: code(j)} } } return }()
C#
UTF-8
954
2.90625
3
[]
no_license
using BankCadwise.Models; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; namespace BankCadwise.Utils { class SerializePerson { XmlSerializer formatter = new XmlSerializer(typeof(List<Person>)); public void Serialize(Person person) { using (FileStream fs = new FileStream("people.xml", FileMode.Open)) { List<Person> persons = (List<Person>)formatter.Deserialize(fs); fs.Position = 0; foreach (var item in persons) { if (item.Id == person.Id) { item.Balance = person.Balance; formatter.Serialize(fs,persons); fs.Close(); return; } } } } } }
Java
UTF-8
1,345
2.046875
2
[]
no_license
package project.hrms.entities.concretes; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.time.LocalDate; import java.util.List; @Entity @Data @AllArgsConstructor @NoArgsConstructor @Table(name="curriculum_vitaes") public class CurriculumVitae { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") private int id; @ManyToOne() @JoinColumn(name = "candidate_id") private Candidate candidate; @Column(name = "github_address") private String githubAddress; @Column(name = "linkedin_address") private String linkedinAddress; @Column(name = "abilities") private String abilities; @Column(name = "cover_letter") private String coverLetter; @JsonIgnore @Column(name = "created_Date") private LocalDate createdDate = LocalDate.now(); @OneToMany(mappedBy = "curriculumVitae") @JsonIgnore private List<JobExperience> jobExperiences; @OneToMany(mappedBy = "curriculumVitae") @JsonIgnore private List<School> schools; @OneToMany(mappedBy = "curriculumVitae") @JsonIgnore private List<ForeignLanguage> foreignLanguages; }
Java
UTF-8
1,283
2.28125
2
[]
no_license
package com.example.loginapp.models.services; import com.example.loginapp.models.entities.UserEntity; import com.example.loginapp.models.forms.UserForm; import com.example.loginapp.models.mappers.UserFormToUserEntityMapper; import com.example.loginapp.models.repositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class UserService { @Autowired private UserRepository userRepository; @Autowired UserSession userSession; public boolean saveUserForm(UserForm userForm) { if(!userRepository.existsByEmail(userForm.getEmail())) { userRepository.save(new UserFormToUserEntityMapper().map(userForm)); return true; } else return false; } public boolean login(UserForm userForm) { Optional<UserEntity> userWhoTriesToLogin = userRepository.getByEmail(userForm.getEmail()); if(userWhoTriesToLogin.isPresent() && userForm.getPassword().equals(userWhoTriesToLogin.get().getPassword())){ userSession.setLogin(true); userSession.setUserEntity(userWhoTriesToLogin.get()); return true; } return false; } }
Python
UTF-8
748
3.4375
3
[]
no_license
import pylab import random def simulated_stock_prices(num_iterations): assert num_iterations > 0 prices = [] price = 0 for i in xrange(num_iterations): change_in_price = random.random() * 2 - 1 price += change_in_price prices.append(price) return prices def final_stock_price_after_simulation(prices): return prices[-1] def multi_trial_stock_prices(num_trials, num_iterations_in_trial): assert num_trials > 1 all_prices = [] for trial in xrange(num_trials): all_prices.append(final_stock_price_after_simulation(simulated_stock_prices(num_iterations_in_trial))) return all_prices simulated_prices = simulated_stock_prices(100) pylab.plot(simulated_prices) pylab.show()
C++
UTF-8
691
3.046875
3
[]
no_license
#include<iostream> #include<algorithm> #include<climits> using namespace std; int change(int arr[],int size,int &max,int mini) { int counter=0; for(int i=mini;i<size-1;i++) { swap(arr[i],arr[i+1]); counter++; } if(mini<max) { max--; } for(int i=max;i>0;i--) { swap(arr[i],arr[i-1]); counter++; } return counter; } int main () { int *arr,size,max,mini,maxindex,miniindex; while(cin>>size) { max=INT_MIN ; mini=INT_MAX; arr=new int[size]; for(int i=0;i<size;i++) { cin>>arr[i]; if(arr[i]<=mini) { mini=arr[i]; miniindex=i; } if(arr[i]>max) { max=arr[i]; maxindex=i; } } cout<<change(arr,size,maxindex,miniindex)<<endl; } return 0; }
Python
UTF-8
4,058
2.859375
3
[]
no_license
from PIL import Image import numpy as np import matplotlib.pyplot as plt import random from random import randint def GenerateSearchField(length): # Generate the alphabetical characters of the search field Field = [] for i in range(0, length): Field.append(random.choice('TGAC')) return Field #============================================================================================= def EncodeField(outputField, inputField, EncodeDepth, width): # Convert the letters in the search field to black & white encoded images for i, val in enumerate(inputField): # Get encoded character EncodedCharacter = EncodeCharacters(val) outputField[EncodeDepth * int(i/width): EncodeDepth * int(i/width)+EncodeDepth , int(i%width) ] = EncodedCharacter return outputField #============================================================================================= def EncodeCharacters(Character): if Character == 'T': Encode = [1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,1,1,1] elif Character == 'G': Encode = [0,1,0,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,1,0,1,0] elif Character == 'A': Encode = [1,1,0,0,0,0,1,1,1,0,0,1,1,0,0,1,1,1,0,0,0,0,1,1] elif Character == 'C': Encode = [0,0,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,0,0] return Encode #============================================================================================= def EmbedTarget(Reference, targetSize, target): # target size = [row, cols] = [y, x] print ('Target Size ') , targetSize M = 1000 N = 1000 targetX = targetSize[0] targetY = targetSize[1] print ('target X'), targetX print ('target Y'), targetY print ('Reference X: '), len(Reference[0]) print ('Reference Y: '), len(Reference) PadX = int(np.floor(0.5*(M-targetX))) PadY = int(np.floor(0.5*(N-targetY))) plt.figure(num=2, facecolor='white') ax2 = plt.gca() ax2.xaxis.set_visible(False) ax2.yaxis.set_visible(False) ax2.set_xticks([]) ax2.set_yticks([]) resizedTarget = np.lib.pad(target, ((PadX, PadX), (PadY, PadY)), 'constant', constant_values=(0, 0)) target = resizedTarget plt.imshow(target, cmap='Greys') plt.draw() plt.pause(0.01) plt.imsave('target.png', target, cmap=plt.cm.gray_r, vmin=0, vmax = 1) return target #============================================================================================= def ComputeFilter(target): # Compute Filter targetFT = np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(target))) plt.draw() plt.pause(0.001) # print targetFT conjugatePhaseTargetFT = -(np.angle(targetFT)) binaryConjugatePhaseTargetFT = ((conjugatePhaseTargetFT > 0.0)).astype(int) # binaryConjugatePhaseTargetFT = conjugatePhaseTargetFT #binaryConjugatePhaseTargetFT = conjugatePhaseTargetFT plt.figure(num=3, facecolor='white') ax3 = plt.gca() ax3.xaxis.set_visible(False) ax3.yaxis.set_visible(False) ax3.set_xticks([]) ax3.set_yticks([]) plt.imshow(binaryConjugatePhaseTargetFT, cmap='Greys', vmin=0, vmax=1.0) # plt.savefig('FourierFilter.png', bbox_inches='tight', pad_inches=0) plt.draw() plt.pause(0.01) return binaryConjugatePhaseTargetFT #============================================================================================= def ShowMatrix(Matrix): plt.figure(num=1, facecolor='white') ax1 = plt.gca() ax1.xaxis.set_visible(False) ax1.yaxis.set_visible(False) ax1.set_xticks([]) ax1.set_yticks([]) plt.imshow(Matrix, cmap='Greys', vmin=0, vmax=1) plt.draw() plt.pause(0.001) #============================================================================================= def InputSnippets(Reference, target, EncodeDepth, width, gapSize, Rows): for Y in np.arange(100, Rows, 100): for X in np.arange(0, width - len(target[0]), len(target[0])+gapSize ): Reference[Y:Y+EncodeDepth, X:X+len(target[0])] = target return Reference
Java
UTF-8
650
3.53125
4
[]
no_license
//Timothy Hinds public class WeightConversion { public static void main(String[] args) { //The table header System.out.print("Kilograms\tPounds"); System.out.println(); //extra line printed so the numbers dont start on the table header line for(int i=1; i<200; i++) { System.out.println(i +"\t\t" + Math.round(i * 2.2 * 10) / 10.0); //the loop starts at 1 and ends at 199 //at first i just used spaces to separate the columns //but i searched the book and found on pg 126 the escape sequence for tab to tab the lines over //I was getting numbers like 22.000000008 so I had to round the pounds to one decimal } } }
Python
UTF-8
110
3.15625
3
[]
no_license
#this is a list l=['28','27','68','78','prathu'] for i in l: if i==27: print('yes') else : print('no')
Python
UTF-8
1,097
3.65625
4
[ "MIT" ]
permissive
# Advent of Code 2020 Day 9-2 # James Plante import sys import string import itertools SUM = 15690279 """ Computes wheter the subarray equals k in a brute-force way. Will change if the running time is slow enough. """ def array_sum_equals_k(num_list: list, k: int): for length in range(2, len(num_list) + 1): for start in range(len(num_list) - length): total = sum(num_list[start: start + length]) if total == SUM: print(min(num_list[start: start + length]) + max(num_list[start: start + length])) return """ Main solution function """ def main_problem(input_string: str): all_numbers = [int(number) for number in [x for x in input_string.split('\n') if x != '']] array_sum_equals_k(all_numbers, SUM) if __name__ == "__main__": if len(sys.argv) >= 3: SUM = int(sys.argv[2]) if len(sys.argv) >= 2: input_string = "" with open(sys.argv[1]) as f: input_string = f.read() main_problem(input_string) exit(0) else: print("Not enough arguments")
JavaScript
UTF-8
3,030
3.3125
3
[]
no_license
let targetElm; let sensitivity; let clicked = false; let previousX = 0; let previousY = 0; let offsetX = 0; let offsetY = 0; let movedX = 0; let movedY = 0; let mouseLook = { setMouseLook: function(target, sens){ targetElm = target; sensitivity = sens; movedX = 0; movedY = 0; targetElm.addEventListener("mousedown", this.mouseDown, false); document.addEventListener("mousemove", this.mouseMove, false); document.addEventListener("mouseup", this.mouseUp, false); }, mouseDown: function(event){ event.preventDefault(); clicked = true; previousX = event.clientX; previousY = event.clientY; }, mouseMove: function(event){ event.preventDefault(); if (clicked == true){ let aspect = targetElm.width / targetElm.height; //let multiplyerX = Math.abs(aspect*(1000/window.innerWidth)); //let multiplyerY = Math.abs(aspect*(1000/window.innerWidth)); let multiplyerX = Math.abs(aspect*(targetElm.height / 500)); let multiplyerY = Math.abs(aspect*(targetElm.width / 500)); offsetX = -(previousX - event.clientX) * sensitivity*multiplyerX/2; offsetY = (previousY - event.clientY) * sensitivity*multiplyerY/2; movedX += offsetX; movedY += offsetY; previousX = event.clientX; previousY = event.clientY; } }, mouseUp: function(event){ event.preventDefault(); offsetX = 0; offsetY = 0; clicked = false; } } /*let sensitivity; let clicked; let previousX; let previousY; let offsetX; let offsetY; let movedX; let movedY; function setMouseLook(targetElm, sens){ sensitivity = sens; movedX = 0; movedY = 0; targetElm.addEventListener("mousedown", mouseDown, false); document.addEventListener("mousemove", mouseMove, false); document.addEventListener("mouseup", mouseUp, false); } function mouseDown(event){ event.preventDefault(); clicked = true; previousX = event.clientX; previousY = event.clientY; } function mouseMove(event){ event.preventDefault(); if (clicked == true){ let aspect = window.innerWidth / window.innerHeight; let multiplyerX = Math.abs(aspect*(1000/window.innerWidth)); let multiplyerY = Math.abs(aspect*(1000/window.innerWidth)); //console.log(window.innerHeight / window.innerWidth+" >> "+multiplyerY); offsetX = -(previousX - event.clientX) * sensitivity*multiplyerX; offsetY = (previousY - event.clientY) * sensitivity*multiplyerY; movedX += offsetX; movedY += offsetY; previousX = event.clientX; previousY = event.clientY; } } function mouseUp(event){ event.preventDefault(); clicked = false; }*/
Python
UTF-8
493
3.578125
4
[]
no_license
import sys def sum_of_squares(natural_number): sum = 0 for i in range(0,natural_number): sum += (i + 1) ** 2 return sum def square_of_sum(natural_number): sum = 0 for n in range(0, natural_number): sum += n + 1 return sum **2 def difference(natural_number): diff = square_of_sum(natural_number) - sum_of_squares(natural_number) return diff if __name__ == "__main__": difference = difference(int(sys.argv[1])) print difference
C#
UTF-8
12,314
2.875
3
[]
no_license
using System; using System.IO; using System.Security; using System.Threading; using System.Windows; using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.pdf.parser; namespace WpfApplication.Models.Main { /// <summary> /// /// </summary> internal class PdfFileClass : IDisposable { /// <summary> /// Имя файла /// </summary> // ReSharper disable once MemberCanBePrivate.Global public string FileName { get; private set; } /// <summary> /// Семафор /// </summary> private readonly SemaphoreSlim _semaphore = new SemaphoreSlim( 1, 1 ); /// <summary> /// Подпрограмма выдачи сообщения об ошибке /// </summary> private readonly Action< Exception, string > _showErrorMessage = App.MyWindows.ShowFormErrorCommand.Execute; /// <summary> /// Конструктор /// </summary> /// <param name="fileName"></param> public PdfFileClass( string fileName ) { fileName = string.IsNullOrWhiteSpace( fileName ) ? "default.pdf" : fileName; if ( !System.IO.Path.IsPathRooted( fileName ) ) { FileName = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, fileName ); } } /// <summary> /// Use C# destructor syntax for finalization code. /// This destructor will run only if the Dispose method /// does not get called. /// It gives your base class the opportunity to finalize. /// Do not provide destructors in types derived from this class. /// </summary> ~PdfFileClass() { Dispose( false ); } /// <inheritdoc /> /// <summary> /// Подпрограмма выполняющая определяемые приложением задачи, /// связанные с удалением, высвобождением или сбросом неуправляемых ресурсов. /// </summary> public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } /// <summary> /// /// </summary> /// <remarks> /// Track whether Dispose has been called. /// ReSharper disable once RedundantDefaultMemberInitializer /// </remarks> private bool _disposed = false; /// <summary> /// /// </summary> /// <param name="disposing"></param> private void Dispose( bool disposing ) { // Check to see if Dispose has already been called. if ( _disposed ) return; // If disposing equals true, dispose all managed and unmanaged resources. if ( disposing ) { // Dispose managed resources. _semaphore.Dispose(); } // Dispose native ( unmanaged ) resources, if exits // Note disposing has been done. _disposed = true; } /// <summary> /// Подпрограмма чтения текста /// </summary> /// <returns></returns> public string Read() { _semaphore.Wait(); var str = string.Empty; // считаем, что программе передается один аргумент - имя файла using ( var reader = new PdfReader( FileName ) ) { // нумерация страниц в PDF начинается с единицы. for ( var i = 1; i <= reader.NumberOfPages; ++i ) { var strategy = new SimpleTextExtractionStrategy(); str += PdfTextExtractor.GetTextFromPage( reader, i, strategy ); } } _semaphore.Release(); return str; } /// <summary> /// Подпрограмма записи текста и установки фона /// </summary> /// <param name="str"></param> /// <param name="backColor"></param> public void Write( string str, BaseColor backColor ) { // Создание шрифта var font = GetFont(); _semaphore.Wait(); try { // Создание файла using ( var file_stream = new FileStream( FileName, FileMode.Create ) ) { // Создание документа using ( var document = new Document() ) { PdfWriter.GetInstance( document, file_stream ); // Книжная ориентация var rec = new Rectangle( PageSize.A4 ) { // Альбомная ориентация // PageSize.A4.Rotate() BackgroundColor = backColor }; // Установка размера страницы document.SetPageSize( rec ); //document.SetMargins( 0, 0, 0, 0 ); // Открытие документа document.Open(); // Создание параграфа var paragraph = new Paragraph( str, font ); // Изменение межстрочного расстояния // Корректировка параметра paragraph.Leading; paragraph.SetLeading( 1, 1 ); // Запись текстовых данных document.Add( paragraph ); //var res = Application.GetResourceStream( // new Uri( App.MyGmainTest.ConfigProgram.ImageUri, // UriKind.RelativeOrAbsolute ) ); //if ( res != null ) { // using ( var stream_file = new FileStream( "newRiver.jpg", FileMode.Create ) ) { // res.Stream.CopyTo( stream_file ); // } // var jpg = Image.GetInstance( "pack://application:,,,/models/icon/kret.png" ); // jpg.Alignment = Element.ALIGN_CENTER; // document.Add( jpg ); //} // Warning CA2202: не удаляйте объекты несколько раз // http://msdn.microsoft.com/library/ms182334.aspx //document.Close(); } //using ( var writer = PdfWriter.GetInstance( document, stream ) ) { // writer.DirectContent.BeginText(); // writer.DirectContent.SetFontAndSize( base_font, 12f ); // writer.DirectContent.ShowTextAligned( Element.ALIGN_TOP, str, 0, 750, 0 ); // writer.DirectContent.EndText(); //} } } catch ( ArgumentNullException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( ArgumentOutOfRangeException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( ArgumentException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( PlatformNotSupportedException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( NotSupportedException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( SecurityException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( FileNotFoundException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( DirectoryNotFoundException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( PathTooLongException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( UnauthorizedAccessException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( DocumentException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } catch ( IOException exc ) { _showErrorMessage( exc, "Создание pdf-файла" ); } finally { _semaphore.Release(); } } /// <summary> /// Подпрограмма создание шрифта /// </summary> /// <param name="nameFont"></param> /// <returns></returns> private Font GetFont( string nameFont = "PTM55F.ttf" ) { Font font_mono = null; try { //@"C:\Windows\Fonts\arial.ttf" //var fonts_uri = System.IO.Path.Combine( // Environment.GetFolderPath( Environment.SpecialFolder.Fonts ), "arial.ttf" ); //var base_font = BaseFont.CreateFont( fonts_uri, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED ); //var arial = new Font(base_font, Font.DEFAULTSIZE, Font.NORMAL, BaseColor.BLACK); // Создание шрифта var uri = new Uri( "/Models/Font/" + nameFont, UriKind.Relative ); var info = Application.GetResourceStream( uri ); if ( info != null ) { var assembly_data = new byte[ info.Stream.Length ]; // ReSharper disable once UnusedVariable var readed = info.Stream.Read( assembly_data, 0, assembly_data.Length ); var base_font = BaseFont.CreateFont( nameFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, BaseFont.CACHED, assembly_data, null ); font_mono = new Font( base_font, Font.DEFAULTSIZE, Font.NORMAL, BaseColor.BLACK ); } } catch ( ArgumentNullException exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } catch ( ArgumentOutOfRangeException exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } catch ( ArgumentException exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } catch ( FileLoadException exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } catch ( FileNotFoundException exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } catch ( BadImageFormatException exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } catch ( NotImplementedException exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } catch ( NotSupportedException exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } catch ( IOException exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } catch ( ObjectDisposedException exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } catch ( Exception exc ) { _showErrorMessage( exc, "Создание шрифта для pdf-файла" ); } return font_mono; } } }
C#
UTF-8
8,183
2.53125
3
[]
no_license
using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using UnityEngine; /// <summary> /// 加载Resources文件夹下的资源 /// </summary> public class ResourcesLoader : Singleton<ResourcesLoader>, IResource { public Dictionary<string, string> m_filesDic = new Dictionary<string, string>();//资源名称——资源路径 public Dictionary<string, SingleResource> m_resoucesDic = new Dictionary<string, SingleResource>(); public string m_resourcePath; public ResourcesLoader() { if (Application.platform != RuntimePlatform.WindowsEditor) { //获取Resources下面的所有资源,并且进行缓存,写入表格 LoadPathFile(); } else { //读取表格,进行缓存 m_resourcePath = Application.dataPath + "/Resources/"; GetFileInfo(new DirectoryInfo(m_resourcePath)); SaveFileInfo(); } } private void LoadPathFile() { var info = Resources.Load("resourceInfo") as TextAsset; var xml = LoadXML(info.text); for (int i = 0; i < xml.Children.Count; i += 2) { var key = xml.Children[i] as System.Security.SecurityElement; var value = xml.Children[i + 1] as System.Security.SecurityElement; m_filesDic.Add(key.Text, value.Text); } } //TODO private SecurityElement LoadXML(string xml) { try { SecurityParser securityParser = new SecurityParser(); securityParser.LoadXml(xml); return securityParser.ToXml(); } catch (System.Exception ex) { Debug.Log("error"); return null; } } private void GetFileInfo(DirectoryInfo path) { var dirInfos = path.GetDirectories().Where(t => t.Name.StartsWith(".") == false); FileInfo[] fileInfos = path.GetFiles(); foreach (DirectoryInfo item in dirInfos) { GetFileInfo(item); } foreach (FileInfo item in fileInfos) { string value = item.FullName.Replace("\\", "/").Replace(m_resourcePath, ""); string key = GetFilePathWithoutExtention(item.Name); //string final = CombinePath(value, key); if (!IsResource(item.FullName.Replace("\\", "/"))) continue; if (!m_filesDic.ContainsKey(key)) { value = GetFilePathWithoutExtention(value); m_filesDic.Add(key, value); } else { //Debug.Log("file already exist"); } } } private string CombinePath(string path, string name) { //先计算出有几个/ int count = 0; int startIndex = 0; while (true) { int y = path.IndexOf("/", startIndex); if (y != -1) { count++; startIndex = y + 1; } else { break; } } string final = ""; for (int i = 0; i < count; i++) { final = final + '.'; } return final + name; } private bool IsResource(string path) { string[] filter = new string[] { ".meta", ".xml", ".dds", ".unity" }; for (int i = 0; i < filter.Length; i++) { if (path.EndsWith(filter[i], System.StringComparison.OrdinalIgnoreCase)) { return false; } } return true; } private void SaveFileInfo() { SecurityElement root = new SecurityElement("root"); foreach (var item in m_filesDic) { root.AddChild(new SecurityElement("k", item.Key)); root.AddChild(new SecurityElement("v", item.Value)); } SaveText(m_resourcePath + "resourceInfo.xml", root.ToString()); } //TODO private void SaveText(string fileName, string text) { if (!Directory.Exists(GetDirectoryName(fileName))) { Directory.CreateDirectory(GetDirectoryName(fileName)); } if (File.Exists(fileName)) { File.Delete(fileName); } using (FileStream fs = new FileStream(fileName, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs)) { //开始写入 sw.Write(text); //清空缓冲区 sw.Flush(); //关闭流 sw.Close(); } fs.Close(); } } public string GetDirectoryName(string fileName) { return fileName.Substring(0, fileName.LastIndexOf('/')); } public string GetFilePathWithoutExtention(string fileName) { return fileName.Substring(0, fileName.LastIndexOf('.')); } //资源加载API public Object LoadAsset(string name, bool isPath = false) { string path = null; if (isPath) { path = name; } else { if (m_filesDic.ContainsKey(name)) { path = m_filesDic[name]; } else { Debug.LogError("No such File " + name); return null; } } return Load(path); } //释放资源 public void ReleaseAsset(string name) { if (m_resoucesDic.ContainsKey(name)) { m_resoucesDic[name].referenceCount--; } } public void ReleaseInstance(GameObject obj) { GameObject.Destroy(obj); ReleaseAsset(obj.name); } public Object LoasAssetPath(string path) { return Load(path); } private Object Load(string path) { SingleResource resource; bool flag = m_resoucesDic.TryGetValue(path, out resource); if (!flag) { resource = new SingleResource(path); resource.Load(); m_resoucesDic.Add(path, resource); } //引用加1 resource.referenceCount++; return resource.obj; } private T Load<T>(string path) where T : Object { SingleResource resource; bool flag = m_resoucesDic.TryGetValue(path, out resource); if (!flag) { resource = new SingleResource(path); resource.Load<T>(); m_resoucesDic.Add(path, resource); } //引用加1 resource.referenceCount++; return (T)resource.obj; } public T LoadAsset<T>(string name, bool isPath = false) where T : Object { string path = null; if (isPath) { path = name; } else { if (m_filesDic.ContainsKey(name)) { path = m_filesDic[name]; } else { Debug.LogError("No such File " + name); return null; } } return Load<T>(path); } public T LoasAssetPath<T>(string path) where T : Object { return Load<T>(path); } public GameObject LoadInstance(string name, Vector3 pos, Quaternion rotation, bool isPath = false) { Object asset = isPath ? LoadAsset(name, true) : LoadAsset(name, false); GameObject obj = null; if (asset != null) { obj = (GameObject)GameObject.Instantiate(asset, pos, rotation); } return obj; } } //资源的封装 public class SingleResource { public UnityEngine.Object obj; public string path; public int referenceCount; public SingleResource(string path) { this.path = path; } public void Load() { obj = Resources.Load(path); } public void Load<T>() where T : Object { T t = Resources.Load<T>(path); obj = (Object)t; } } //interface public interface IResource { Object LoadAsset(string name, bool isPath = false); T LoadAsset<T>(string name, bool isPath = false) where T : Object; Object LoasAssetPath(string path); T LoasAssetPath<T>(string path) where T : Object; GameObject LoadInstance(string name, Vector3 pos, Quaternion rotation, bool isPath = false); //GameObject LoadInstance(string path, Vector3 pos, Quaternion rotation); void ReleaseAsset(string name); void ReleaseInstance(GameObject obj); }
Java
UTF-8
429
2.703125
3
[]
no_license
package testpack; public class Record { public int id; public String name; public boolean status; public int pr_id; public Record(int id, String name, boolean status, int pr_id) { this.id = id; this.name = name; this.status = status; this.pr_id = pr_id; } public String toString() { return "Record [id=" + id + ", name=" + name + ", status=" + status + ", pr_id=" + pr_id + "]"; } }
PHP
UTF-8
1,478
3.09375
3
[]
no_license
<?php $monthList = [ 'january' => '1', 'february' => '2', 'march' => '3', 'april' => '4', 'may' => '5', 'june' => '6', 'july' => '7', 'august' => '8', 'september' => '9', 'october' => '10', 'november' => '11', 'december' => '12' ]; //date du jour courant $currentdate = time(); //variable qui récupèrent le jour, le mois et l'année $day = date('d', $currentdate); $month = (int)($monthList[$_POST['month']]); $year = (int)$_POST['year']; //récupère le premier jour du mois $first_day = mktime(0, 0, 0, $month, 1, $year); //récupère le nom du mois setlocale(LC_TIME, 'fr.UTF-8'); $monthName = strftime('%B', $first_day); //récupère quel jour tombe le 1er de chaque mois $day_of_week = date('D', $first_day); //détermine le nombre de jour qu'il ya dans le mois courant $days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year); //compte les jours du mois en partant de 1 $day_count = 1; //représente le numéro du premier jour du mois $day_num = 1; //Permet de rendre les cases vides avant le 1er de chaque moi $blank = null; switch ($day_of_week) { case 'Mon': $blank = 0; break; case 'Tue': $blank = 1; break; case 'Wed': $blank = 2; break; case 'Thu': $blank = 3; break; case 'Fri': $blank = 4; break; case 'Sat': $blank = 5; break; case 'Sun'; $blank = 6; break; }
Markdown
UTF-8
873
2.71875
3
[ "MIT" ]
permissive
# steven's dotfiles My workbench for writing software (and some stuff just for fun). ## Setup __If you fork or clone this repo, please change `~/.gitconfig` file so you don't commit as me:__ > Note: You probably don't want to do actually do this, but its here for you to browse if you'd like! :) ```sh cd ~ git init git remote add origin git@github.com:stevenschobert/dotfiles.git git pull origin master ./setup.sh ``` ## Misc ### Visual Tweaks If you want to hide the readme and license files from your home directory, run these commands: ```sh SetFile -a "V" ~/README.md SetFile -a "V" ~/LICENSE SetFile -a "V" ~/Brewfile SetFile -a "V" ~/setup.sh ``` ### Thanks Thanks to [@soffes](https://github.com/soffes) for putting up [his dotfiles](https://github.com/soffes/dotfiles). I really liked the simplicity of his setup over others, and modeled this repo after his.
Python
UTF-8
1,637
2.6875
3
[]
no_license
from flask import Flask, render_template, request from werkzeug.utils import secure_filename import torch import torchvision from CNN_Model import model from torchvision import transforms from PIL import Image app = Flask(__name__) app.config["DEBUG"] = True cnn_model = model() cnn_model.load_state_dict(torch.load('weather_model_4.pth', map_location=torch.device('cpu'))) cnn_model.eval() classes = ['Cloudy', 'Rain', 'Shine', 'Sunrise'] @app.route('/', methods=['GET']) def home(): return render_template('index.html', data = None) @app.route('/predict', methods =['POST']) def predict(): if request.method == 'POST': f = request.files['file'] if f is not None: input_tensor = transform_image(f) prediction_idx = get_prediction(input_tensor) class_name = classes[prediction_idx] print("Class name: ", class_name) return render_template("index.html", data=class_name, show_prediction_output=True) def get_prediction(input_tensor): outputs = cnn_model.forward(input_tensor) _, y_hat = outputs.max(1) prediction = y_hat.item() return prediction def transform_image(infile): input_transforms = [transforms.Resize((224,224)), transforms.ToTensor()] my_transforms = transforms.Compose(input_transforms) image = Image.open(infile) timg = my_transforms(image) timg.unsqueeze_(0) return timg if __name__ == '__main__': app.run(debug = True)
Java
UTF-8
6,943
3.015625
3
[]
no_license
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Exercise04Impl implements Exercise04 { private List<Person> persons = new ArrayList<Person>(); public Exercise04Impl() { // import data.csv file importDataFile(); } private void importDataFile() { try (BufferedReader br = new BufferedReader(new FileReader(new File("src\\data.csv")))) { String[] lines = br.lines().toArray(String[]::new); for (int i = 1; i < lines.length; i++) { String address = lines[i].split("\"")[1]; String[] personInfos = lines[i].split("\\,\"")[0].split(","); Person person = new Person(); person.setAddress(address); person.setFullName(personInfos[0]); person.setId(personInfos[1]); person.setGender(personInfos[2]); person.setBirthYear(personInfos[3]); persons.add(person); } } catch (IOException ex) { ex.printStackTrace(); } } @Override public boolean findByFirstName(String firstname) throws RemoteException { return persons.stream().parallel().anyMatch(p -> p.getFullName().indexOf(firstname) != -1); } @Override public int countByLastName(String lastname) throws RemoteException { return (int) persons.stream().parallel().filter(p -> p.getFullName().indexOf(lastname) != -1).count(); } @Override public boolean findById(String id) throws RemoteException { return persons.stream().parallel().anyMatch(p -> p.getId().equals(id)); } @Override public float getMeanAge() throws RemoteException { return (float) persons.stream().parallel() .mapToInt(p -> Integer.parseInt(p.getBirthYear())) .average() .getAsDouble(); } @Override public int getMinBD() throws RemoteException { return persons.stream().parallel() .mapToInt(p -> Integer.parseInt(p.getBirthYear())) .min() .getAsInt(); } @Override public int getMaxBD() throws RemoteException { // TODO Auto-generated method stub return persons.stream().parallel() .mapToInt(p -> Integer.parseInt(p.getBirthYear())) .max() .getAsInt(); } @Override public int countByGender(String gender) throws RemoteException { // TODO Auto-generated method stub return (int) persons.stream().parallel() .filter(p -> p.getGender().equals(gender)) .count(); } @Override public List<Person> getInfo(String address) throws RemoteException { // TODO Auto-generated method stub return persons.stream().parallel().filter(p -> p.getAddress().equals(address)).collect(Collectors.toList()); } @Override public int countByState(String stateName) throws RemoteException { // TODO Auto-generated method stub return (int)persons.stream().parallel().peek(p -> System.out.println(getState(p.getAddress()))).filter(p -> mapperState(getState(p.getAddress())) == mapperState(stateName)).count(); } private String getState(String address) { String[] parts = address.split(",")[1].trim().split("\s+"); return parts[parts.length - 2]; } private int mapperState(String state) { switch (state) { case("United States of America"): case("US"): return 0; case("Alabama"): case("AL"): return 1; case("Alaska"): case("AK"): return 2; case("Arizona"): case("AZ"): return 3; case("Arkansas"): case("AR"): return 4; case("California"): case("CA"): return 5; case("Colorado"): case("CO"): return 6; case("Connecticut"): case("CT"): return 7; case("Delaware"): case("DE"): return 8; case("District of Columbia"): case("DC"): return 9; case("Florida"): case("FL"): return 10; case("Georgia"): case("GA"): return 11; case("Hawaii"): case("HI"): return 12; case("Idaho"): case("ID"): return 13; case("Illinois"): case("IL"): return 14; case("Indiana"): case("IN"): return 15; case("Iowa"): case("IA"): return 16; case("Kansas"): case("KS"): return 17; case("Kentucky"): case("KY"): return 18; case("Louisiana"): case("LA"): return 19; case("Maine"): case("ME"): return 20; case("Maryland"): case("MD"): return 21; case("Massachusetts"): case("MA"): return 22; case("Michigan"): case("MI"): return 23; case("Minnesota"): case("MN"): return 24; case("Mississippi"): case("MS"): return 25; case("Missouri"): case("MO"): return 26; case("Montana"): case("MT"): return 27; case("Nebraska"): case("NE"): return 28; case("Nevada"): case("NV"): return 29; case("New Hampshire"): case("NH"): return 30; case("New Jersey"): case("NJ"): return 31; case("New Mexico"): case("NM"): return 32; case("New York"): case("NY"): return 33; case("North Carolina"): case("NC"): return 34; case("North Dakota"): case("ND"): return 35; case("Ohio"): case("OH"): return 36; case("Oklahoma"): case("OK"): return 37; case("Oregon"): case("OR"): return 38; case("Pennsylvania"): case("PA"): return 39; case("Rhode Island"): case("RI"): return 40; case("South Carolina"): case("SC"): return 41; case("South Dakota"): case("SD"): return 42; case("Tennessee"): case("TN"): return 43; case("Texas"): case("TX"): return 44; case("Utah"): case("UT"): return 45; case("Vermont"): case("VT"): return 46; case("Virginia"): case("VA"): return 47; case("Washington"): case("WA"): return 48; case("West Virginia"): case("WV"): return 49; case("Wisconsin"): case("WI"): return 50; case("Wyoming"): case("WY"): return 51; case("American Samoa"): case("AS"): return 52; case("Guam"): case("GU"): return 53; case("Northern Mariana Islands"): case("MP"): return 54; case("Puerto Rico"): case("PR"): return 55; case("U.S. Virgin Islands"): case("VI"): return 56; case("Baker Island"): case("XB"): return 57; case("Howland Island"): case("XH"): return 58; case("Jarvis Island"): case("XQ"): return 59; case("Johnston Atoll"): case("XU"): return 60; case("Kingman Reef"): case("XM"): return 61; case("Midway Islands"): case("QM"): return 62; case("Navassa Island"): case("XV"): return 63; case("Palmyra Atoll[c]"): case("XL"): return 64; case("Wake Island"): case("QW"): return 65; case("Micronesia"): case("FM"): return 66; case("Marshall Islands"): case("MH"): return 67; case("Palau"): case("PW"): return 68; case("U.S. Armed Forces – Americas"): case("AA"): return 69; case("U.S. Armed Forces – Europe"): case("AE"): return 70; case("U.S. Armed Forces – Pacific"): case("AP"): return 71; default: return -1; } } }
C++
UTF-8
1,620
2.5625
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
// This is mul/ipts/ipts_orientation_pyramid.cxx #include "ipts_orientation_pyramid.h" //: // \file // \brief Compute edge orientations at each level of a scale space pyramid // \author Tim Cootes #include <vil/algo/vil_orientations.h> #include <vimt/vimt_image_2d_of.h> #include <cassert> #ifdef _MSC_VER # include "vcl_msvc_warnings.h" #endif //: Compute edge orientations at each level of a scale space pyramid. // smooth_pyramid must be of type float. orient_pyramid is set to be of type vxl_byte. // Uses vil_orientations_at_edges() on each level of the pyramid. void ipts_orientation_pyramid(const vimt_image_pyramid& smooth_pyramid, vimt_image_pyramid& orient_pyramid, float grad_threshold, unsigned n_orientations) { if (smooth_pyramid.n_levels()==0) return; assert(smooth_pyramid(0).is_a()=="vimt_image_2d_of<float>"); int n_levels = smooth_pyramid.n_levels(); // Compute entropies for all levels of an image pyramid orient_pyramid.resize(n_levels,vimt_image_2d_of<vxl_byte>()); for (int i=0;i<n_levels;++i) { const auto& smooth_im = static_cast<const vimt_image_2d_of<float>&>(smooth_pyramid(i)); auto& orient_im = static_cast<vimt_image_2d_of<vxl_byte>&>(orient_pyramid(i)); vil_image_view<float> grad_i,grad_j,grad_mag; vil_sobel_3x3(smooth_im.image(),grad_i,grad_j); vil_orientations_at_edges(grad_i,grad_j,orient_im.image(),grad_mag, grad_threshold,n_orientations); orient_im.set_world2im(smooth_im.world2im()); } }
JavaScript
UTF-8
1,734
2.640625
3
[ "MIT" ]
permissive
var GitterClient = require('./../lib/GitterClient'); var config = require('./../utils/config'); var noop = function() {}; var emptySubscriber = function() { return { send: noop, disconnect: noop }; }; var msgCall = function(msg) { return { model: { text: msg } } ;}; describe('GitterClient test', function() { beforeEach(function() { config.reset(); }); it('should rollback to defaults', function() { var bot = new GitterClient(); expect(bot.room).to.equals(config.get("room")); expect(bot.key).to.equals(config.get("key")); }); it('should correctly set room ID', function() { var room = "username/room"; var bot = new GitterClient({room: room}); expect(bot.room).to.equals(room); }); it('should throw an error (no Gitter key)', function() { config.set("key", null); expect(GitterClient).to.throw(Error); }); it('should throw an error (no room in config)', function() { config.set("room", null); expect(GitterClient).to.throw(Error); }); it('should skip un-calc messages', function() { var bot = new GitterClient(); bot.subscriber = emptySubscriber(); var result = bot.onMessages(msgCall("Hello!")); expect(result).to.not.exist; }); it('should notify when empty expression is found', function() { var bot = new GitterClient(); bot.subscriber = emptySubscriber(); var result = bot.onMessages(msgCall("calc")); expect(result).to.equals(config.get("calcMessages").expressionEmpty); }); it('should calculate simple expression', function() { var bot = new GitterClient(); var expression = "calc (100 - 60) + 100/4 + (11 - 34)"; bot.subscriber = emptySubscriber(); var result = bot.onMessages(msgCall(expression)); expect(result).to.equals(42); }); });
Python
UTF-8
827
4.03125
4
[]
no_license
# Smirnov Artem lesson 1 Dz 4 import random print('Ведите границы для случайного целого числа:') Num1 = int(input('Number 1 = ')) Num2 = int(input('Number 2 = ')) print('Ведите границы для случайного вещественного числа:') Mat1 = float(input('Material 1 = ')) Mat2 = float(input('Material 2 = ')) print('Ведите границы для случайной буквы:') Ch1 = input('char1 = ').upper() Ch2 = input('char2 = ').upper() r_int = random.randint(Num1, Num2) r_float = random.uniform(Mat1, Mat2) r_char = chr(random.randint(ord(Ch1), ord(Ch2))) print(f'Случайное целое число: {r_int}\n' f'Случайное вещественное число: {r_float}\n' f'Случайная буква: "{r_char}"')
Markdown
UTF-8
4,202
3.921875
4
[]
no_license
# required修饰符 # 普通子类 通常情况下,一说到`required`修饰符,我们最先想到的应该就是普通类(class)的`init()`方法了。比如下面这个类: ``` class MyClass { var str:String init(str:String) { self.str = str } } ``` 当我们定义一个`MyClass`的子类(subclass)并实例化这个子类时,我们一般会如何做呢?没错,通常情况下都会是这样: ``` class MyClass { var str:String init(str:String) { self.str = str } } class MySubClass:MyClass { } var MySubClass(str:"Hello Swift") ``` 大伙应该已经注意到了,在实例化`MySubClass`时,其实是继承了它父类`MyClass`的`init()`方法。那我们再来看看子类的初始化方法。 ## 子类的初始化方法 如果我们在子类中添加一个`init()`方法,像这样: ``` class MyClass { var str:String init(str:String) { self.str = str } } class MySubClass:MyClass { override init(str:String) { super.init(str:str) } } var MySubClass(str:"Hello Swift") ``` 那么我们首先要在`init()`方法前加上`override`修饰符,表示`MySubClass`重写了其父类的`init()`方法,然后还要调用父类的`init()`方法,并将参数一并传给父类的方法。 在实际运用中,也有另外一种情况,当子类的初始化方法参数类型与父类的初始化方法参数类型不同时,我们就不必在子类的初始化方法前加`override`修饰符了,但是要把子类初始化方法的参数类型转换为符合父类初始化方法的参数类型,然后传给父类的初始化方法: ``` class MyClass { var str:String init(str:String) { self.str = str } } class MySubClass:MyClass { init(i:Int) { super.init(str:String(i)) } } MySubClass(i: 10) ``` ## required修饰符 我们给父类的`init()`方法加上`required`修饰符后会发生什么呢,我们来看看: ``` class MyClass { var str:String required init(str:String) { self.str = str } } class MySubClass:MyClass { init(i:Int) { super.init(str:String(i)) } // 编译错误 } MySubClass(i: 10) ``` 我们可以看到上面的代码在编译会发生错误,因为我们没有实现父类中要去必须要实现的方法。我们应该这样写: ``` class MyClass { var str:String required init(str:String) { self.str = str } } class MySubClass:MyClass { required init(str:String) { super.init(str: str) } init(i:Int) { super.init(str:String(i)) } } MySubClass(i: 10) ``` 从上面的代码示例中不难看出,如果子类需要添加异于父类的初始化方法时,必须先要实现父类中使用`required`修饰符修饰过的初始化方法,并且也要使用`required`修饰符而不是`override`。 如果子类中不需要添加任何初始化方法,我们则可以忽略父类的`required`初始化方法: ``` class MyClass { var str:String required init(str:String) { self.str = str } } class MySubClass:MyClass { } MySubClass(str: "hello swift") ``` 在这种情况下,编译器不会报错,因为如果子类没有任何初始化方法时,[Swift](http://lib.csdn.net/base/1 "undefined")会默认使用父类的初始化方法。在[Apple的文档](https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_339)中也有相关描述: > You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initialiser. ## required修饰符的使用规则 1. `required`修饰符只能用于修饰类初始化方法。 2. 当子类含有异于父类的初始化方法时(初始化方法参数类型和数量异于父类),子类必须要实现父类的`required`初始化方法,并且也要使用`required`修饰符而不是`override`。 3. 当子类没有初始化方法时,可以不用实现父类的`required`初始化方法。
Java
UTF-8
107
1.84375
2
[]
no_license
package Utiles; public class Escudo extends Instrumentos{ public Escudo(){ super(); } }
Ruby
UTF-8
72
3.40625
3
[]
no_license
ary = [1, 3, 5, 7, 8, 9, 10] res = ary.bsearch {|x| x ==3} print res
Python
UTF-8
1,453
3.0625
3
[ "MIT" ]
permissive
import os, sys inf = 2**31 def all_pair_shortest_path(matrix, printing=None): n = len(matrix) p_cache = [[None] * n for i in range(n)] for mid in range(n): for start in range(n): for end in range(n): temp = matrix[start][mid] + matrix[mid][end] if temp < matrix[start][end] and matrix[start][mid]!=inf and matrix[mid][end]!=inf: matrix[start][end] = temp p_cache[start][end] = mid if printing: def print_path(start, end): print(end, end='') if matrix[start][end] != inf: print(' < ', end='') else: print(' Not Exist ', end='') if p_cache[start][end]: print_path(start, p_cache[start][end]) if not p_cache[start][end]: print(start) for i in range(n): for j in range(n): print_path(i, j) return matrix if __name__=='__main__': sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'DS', 'graph')) from graph import Graph g = Graph(n_node=4) g.add_edge(Graph.Edge( 0, 1, 5 )) g.add_edge(Graph.Edge( 0, 3, 10 )) g.add_edge(Graph.Edge( 1, 2, 3 )) g.add_edge(Graph.Edge( 2, 3, 1 )) cost_matrix = all_pair_shortest_path(g.matrix, printing=True) print() for c in cost_matrix: print(*c)
Python
UTF-8
6,043
3.046875
3
[]
no_license
import os import numpy as np import urllib.request import cv2 NAMES = [ "Pizza in a box", "Pizza top view", "The bottom of the pizza top view", "Pizza bottom view at an angle", "Pizza sides view at an angle of 90", "Pizza sides view at an angle", "Cheque", "Pizza, view from a small angle" ] class Parser: """ Класс для работы с информцией о дефектах """ def __init__(self, path_to_csv='data/controlling_ml.csv'): """ Конструктор, распаковывает данные из файла :param path_to_csv: Путь к файлу """ with open(path_to_csv, encoding="utf8") as csv_file: lines = csv_file.readlines() self.data = [row.replace('\n', '').split(',') for row in lines[1:]] self.DEFECTS_NAMES = lines[0].replace('\n', '').split(',')[10:] self.NUMBER_OF_COLUMNS = len(self.data[0]) self.FIRST_DEFECT = self.data[0].index('0') # TODO: ну ты сам поял, ты там давай, не умирай def show_by_defects(self, defects_list=[], pic_nums=[]): for row in self.data: defects = row[self.FIRST_DEFECT:] comp_array = ['0'] * (self.NUMBER_OF_COLUMNS - self.FIRST_DEFECT) for defect in defects_list: comp_array[defect - self.FIRST_DEFECT] = '1' if defects == comp_array: for pic_num in pic_nums: try: img = self.url_to_image(row[2 + pic_num]) img = cv2.resize(img, (img.shape[1] // 2, img.shape[0] // 2)) cv2.imshow(NAMES[pic_num], img) except: print(f'fail for {row[2 + pic_num]}') cv2.waitKey(0) def save_by_defects(self, folder, pic_num, defects_list=[], start=0, end=1000): """ Сохранение изображений :param folder: Название папки :param defects_list: Список присутствующий дефектов :param pic_num: Номер фотографии :param start: Ограничение по количеству фотографий :param end: Ограничение по количеству фотографий :return: """ counter = -1 for row in self.data: defects = row[self.FIRST_DEFECT:] comp_array = ['0'] * (self.NUMBER_OF_COLUMNS - self.FIRST_DEFECT) for defect in defects_list: comp_array[defect - self.FIRST_DEFECT] = '1' path_to_folder = os.path.join('data', folder) if not os.path.exists(path_to_folder): os.makedirs(path_to_folder) if defects == comp_array: counter += 1 if counter < start or end <= counter: continue try: url = row[2 + pic_num] img = self.url_to_image(url) im_name = os.path.join(path_to_folder, url[url.rfind('/') + 1:]) cv2.imwrite(im_name, img) except: print(f'fail for {url}') def save_by_defects_or(self, folder, pic_num, defects_list=[], start=0, end=1000): """ Сохранение изображений :param folder: Название папки :param defects_list: Список присутствующий дефектов :param pic_num: Номер фотографии :param start: Ограничение по количеству фотографий :param end: Ограничение по количеству фотографий :return: """ counter = -1 for row in self.data: defects = row # [self.FIRST_DEFECT:] arg = False for defect in defects_list: if defects[defect] == '0': arg = True if arg: continue path_to_folder = os.path.join('data', folder) if not os.path.exists(path_to_folder): os.makedirs(path_to_folder) counter += 1 if counter < start or end <= counter: continue try: url = row[2 + pic_num] img = self.url_to_image(url) im_name = os.path.join(path_to_folder, url[url.rfind('/') + 1:]) cv2.imwrite(im_name, img) except: print(f'fail for {url}') @staticmethod def url_to_image(url): """ download the image, convert it to a NumPy array, and then read it into OpenCV format :param url: Url-addres :return: """ # download the image, convert it to a NumPy array, and then read # it into OpenCV format resp = urllib.request.urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) # return the image return image if __name__ == '__main__': parser = Parser('data/controlling_ml.csv') # parser.save_by_defects(folder='test1', defects_list=[15], pic_num=2, start=0, end=5) # pic_nums=[2, 3], parser.save_by_defects_or(folder='test2', defects_list=[22], pic_num=1, start=0, end=10) # pic_nums=[2, 3], # parser.save_by_defects(folder='test/white_bottom', defects_list=[15], pic_num=2, start=200) # pic_nums=[2, 3], # parser.save_by_defects(folder='black_bottom', defects_list=[17], pic_num=2) # pic_nums=[2, 3], # parser.save_by_defects(folder='white_side', defects_list=[14], pic_num=2) # pic_nums=[2, 3], # parser.save_by_defects(folder='black_side', defects_list=[16], pic_num=2) # pic_nums=[2, 3], # parser.save_by_defects(folder='test/normal', defects_list=[], pic_num=2, limit=200) # pic_nums=[2, 3],
Java
UTF-8
1,267
2.375
2
[]
no_license
package com.dsliusar.web.controller; import com.dsliusar.services.service.MovieService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value = "/v1") public class PosterController { private final Logger LOGGER = LoggerFactory.getLogger(getClass()); @Autowired private MovieService genericMovieService; @RequestMapping(value = "/poster/{movieId}", method = RequestMethod.GET, produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE}) public ResponseEntity<byte[]> getMoviePosterById(@PathVariable Integer movieId) { LOGGER.info("Sending request to get poster for movie with id = {}", movieId); long startTime = System.currentTimeMillis(); byte[] moviePoster = genericMovieService.getMoviePoster(movieId); LOGGER.info("Movie poster successfully send to client, it took {}", System.currentTimeMillis() - startTime); return new ResponseEntity<>(moviePoster, HttpStatus.OK); } }
C#
UTF-8
1,519
2.65625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using Vuforia; public class Tracking : MonoBehaviour { private bool isDone = false; public GameObject inbetweenPrefab; private GameObject clone; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update () { // Get the Vuforia StateManager StateManager sm = TrackerManager.Instance.GetStateManager (); // Query the StateManager to retrieve the list of // currently 'active' trackables //(i.e. the ones currently being tracked by Vuforia) IEnumerable<TrackableBehaviour> activeTrackables = sm.GetActiveTrackableBehaviours (); if (activeTrackables.Count() == 2 && !isDone) { var transform1 = transform; clone = (GameObject) Instantiate(inbetweenPrefab, transform1.position, transform1.rotation, inbetweenPrefab.transform.parent); clone.transform.localScale = new Vector3(.1f, .1f, .1f); isDone = true; } else if (activeTrackables.Count() < 2) { isDone = false; } // Iterate through the list of active trackables // Debug.Log ("List of trackables currently active (tracked): "); foreach (TrackableBehaviour tb in activeTrackables) { // Debug.Log("Trackable: " + tb.TrackableName); } } }
JavaScript
UTF-8
1,807
3.609375
4
[]
no_license
// IMPORT MODULES under test here: // import { example } from '../example.js'; import { add, subtract, multiply, divide } from '../utilities.js'; const test = QUnit.test; test('time to test an add', (expect) => { //Arrange // Set up your arguments and expectations const x = 4; const y = 5; const sum = 9; //Act // Call the function you're testing and set the result to a const const result = add(x, y); //Expect // Make assertions about what is expected versus the actual result expect.equal(result, sum); }); test('time to test a subtract', (expect) => { //Arrange // Set up your arguments and expectations const x = 6; const y = 5; const subtract = 1; //Act // Call the function you're testing and set the result to a const const result = subtract(x, y); //Expect // Make assertions about what is expected versus the actual result expect.equal(result, subtract); }); test('time to test a multiply', (expect) => { //Arrange // Set up your arguments and expectations const x = 4; const y = 5; const multiply = 20; //Act // Call the function you're testing and set the result to a const const result = multiply(x, y); //Expect // Make assertions about what is expected versus the actual result expect.equal(result, multiply); }); test('time to test a divide', (expect) => { //Arrange // Set up your arguments and expectations const x = 20; const y = 5; const divide = 4; //Act // Call the function you're testing and set the result to a const const result = divide(x, y); //Expect // Make assertions about what is expected versus the actual result expect.equal(result, divide); });
Markdown
UTF-8
12,938
2.515625
3
[]
no_license
--- layout: default Lastmod: 2020-07-27T15:11:20.515369+00:00 date: 2020-07-27T15:11:20.514860+00:00 title: "光绪皇帝容貌成谜,教科书里的大头照已删" author: "言九林" tags: [照片,光绪,光绪皇帝,故宫,慈禧] --- 说一说光绪皇帝的容貌问题。 在使用至2016年的旧人教版初中八年级(上册)历史教材中,收有一张大头像,号称是光绪皇帝。如下图所示: ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_png/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEK59Ku6XnGOjGsHtE4EHxRuZ1icIkHicmj3cGqDUwhHDnhEybwzqTBOvg/640%3Fwx_fmt%3Dpng) 图:旧教材中的“光绪帝”照片 这张大头像流传极广。在中文网络上,几乎已成了光绪皇帝的“标准照”。不过,**最新版的统编本初中历史教材,已经将这张照片删除了**。删除的原因是:这张大头像来历可疑,缺乏足够的证据来说明他就是光绪皇帝。 ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_png/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEMAYTtsgZFpbT29bFMvRJFx0rxB2ZwulUHYLRr6FJK33tMicfphJPg2g/640%3Fwx_fmt%3Dpng) 图:新教材删去光绪像,增入了一张严复的照片 造成光绪容貌失传的一个重要原因,是**故宫没有光绪的照片留存下来**。 1990年,故宫出版《故宫旧藏人物照片集》;1994年,故宫又出版《故宫珍藏人物照片荟萃》,收录有故宫博物院所藏慈禧、奕譞、奕訢、载沣、光绪帝后妃、溥仪、婉容、文绣、太监宫女、八国联军乃至入宫表演的戏剧人物的诸多照片,其中**唯独没有光绪的照片。** 据这两本书披露,“在紫禁城内,直到光绪二十九年(1903),才由年已69岁的慈禧太后开始用照相机拍摄个人照片”,“这些照片及底片,在1924年11月5日溥仪迁出故宫后,全部由故宫博物院集中保存下来”。 对于故宫内无光绪照片传世这件事,书中给出了一种解释: “再查查晚清大事,她(慈禧)热衷于为自己拍照、树立个人威仪之时,正是……倡导变法的光绪皇帝一直被她长期软禁于瀛台之际。这又不难使我们理解:何以故宫旧藏慈禧照片如此之多,而光绪皇帝的照片一张也没有!” ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_png/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEX5btia8J3nrGibIu6jRb2lRvUEuqjPBAwZuKG7QTCsGbI1PC4bFxoKXQ/640%3Fwx_fmt%3Dpng) 图:慈禧像 这种解释,可以在**德龄的《清宫禁二年记》**(相比她后来所写的那些迎合市场猎奇趣味的回忆录,《清宫禁二年记》要朴实、可信许多)中得到佐证。德龄喜好摄影,为慈禧做御前女官时,曾在宫中摆弄过摄影仪器。据德龄回忆,一次偶然的机会,她与光绪皇帝谈及外国画师为慈禧绘制油画一事。光绪流露出一种也想绘一幅油画像的情绪,却又自觉这是不可能的事,因为慈禧不会同意。于是就有了下面这样一段对话: **德龄**:你真想给自己画一张油画?(果否欲画一像?) **光绪**:这问题我不太好回答。其实我究竟应不应该画,你是知道答案的。我看太后拍了很多肖像照片,连太监们都拍了。(欲吾答此,殊属为难。惟吾究应绘与否,尔知之稔矣。吾见太后摄肖像甚多,下至太监辈亦有之。) **德龄**:我拿个小型摄影机过来给你拍照,你愿意吗?(果以小摄影器来,为摄影,究愿之否?) **光绪**:你也会摄影吗?如果能保证没危险,等有机会了可以试一下。你不要忘了这个事。不过,一定要小心谨慎。(尔亦能摄影否?苟此举而不危险,俟有机遇,试为之可也。尔必毋忘。但行此必审慎耳。) 显然,**在慈禧的严密控制下,光绪是没有拍照自由的。**慈禧禁止光绪拍照,用意也是显而易见: (1)慈禧为了改善自己的政治形象,找了洋画师来做油画像、找了洋人来拍肖像照,然后将油画和照片赠送给外国政要。她当然不会希望光绪皇帝也如法炮制,通过拍照绘像这种活动,来重塑他的政治存在感。 (2)自戊戌年后,慈禧一直致力于对外营造一种光绪皇帝身体状况极其糟糕的印象。她绝不会希望光绪真实的身体状况,通过照片流传的形式,引起朝野乃至各国使节的揣测与议论。 于是,就造成了**紫禁城内存有许多慈禧照片、却无一张光绪照片**的诡异状况。 ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_jpg/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEjOsweFmgHS8OsUV6XYj9TEpg51zMSapib1VAB6VXPzsxut4LlN078XQ/640%3Fwx_fmt%3Djpeg) 图:德龄(右三)与慈禧等人合影 **不但光绪没有拍照自由,他喜爱的珍妃(死于1900年8月)也没有留下可信的历史照片。**与光绪可疑的大头像类似,坊间流传甚广的“珍妃像”(下图),也是一张高度存疑的照片。该照片虽然存于故宫,且被收录进了故宫出版的《故宫珍藏人物照片荟萃》,但照片本身没有原始标注,底片上的“贞贵妃肖像”五个字,是后人用旧底片复制时加上去的。 对这张号称“珍妃”的可疑照片,有学者考据认为,**照片中女子所留发型源于青楼,绝无可能是宫中嫔妃的装扮**: “额前有极短一行刘海的发型称作“满天星”,是1900年代才从青楼中传出的一种时髦发型。……旗籍贵族女性没有留刘海的习惯,特别是在婚后,头发会经过中分或偏分,梳起来,不会剪短额前的头发。全民都有刘海是五四运动之后才流行起来的。因此,这张流传甚广的珍妃像,很可能是拍摄于1910年代的汉族姑娘。” ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_png/ibYIE3gDV7K7F4umqChiaS02EzJNadkK0YETggmoejnc7kuzgPPYtiay4ScFkpO8NEr854W5tX2KK6Jw6DmZCibGzw/640%3Fwx_fmt%3Djpeg) 图:存疑的“珍妃像” **那张号称光绪的可疑大头像,究竟出自何人之手、拍摄于何时何地,目前均无从查考。**它被当成光绪皇帝,至晚始于1920年代。下面这两张报纸截图,一张来自1920年的《时报图画周刊》,另一张来自1925年的《环球画报》。两家媒体以大头照为光绪,但都没有提供照片的任何来源信息。 ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_png/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEaHswo9xM0Hhg8CXYr9SicuCvLlnCLkqBG65ibkPogXPmdeatwYj5fFUQ/640%3Fwx_fmt%3Dpng) 《时报图画周刊》1920年第3期 ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_png/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEdiauTabS8Is7uuianCXlfsckPibqvNWLfY6KJJZSkqTjKwibvzG9Kmp6iaw/640%3Fwx_fmt%3Dpng) 图:《环球画报》1925年第5期 与这张可疑大头照有关的,还有另一张近代史上著名的伪照——光绪、康有为、梁启超的“三人合影”(见下图)。**这张伪照里的所谓光绪,与可疑大头照里的所谓光绪,显然是同一人。** ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_jpg/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEtJpHEGSQyCqJgxJxsoU9FU5an9aRQZGeKdDhkicoficr4AHnvVuPWzSA/640%3Fwx_fmt%3Djpeg) 这张伪照首次面世,是在1936年4月11日,由《北晨画刊》以《四十年前之摄影技术》为题在首页刊出。照片说明中写道: “彼时摄影术初传入我国,其技巧已颇可观。图中三人,中为逊清光绪帝,左康有为,右梁启超,当时君臣相得情形,于此像可见一斑矣。刘宝山赠刊。” **之所以说这是一张伪照,是因为考之史料,梁启超并未受过光绪皇帝的直接接见,他不可能有机会与光绪合影。**至于这张伪照是何人所造,就不得而知了。该照片公开刊出时,康有为、梁启超均已去世。既有可能是康梁伪造了照片作为政治活动的资本,也有可能是其他人伪造了照片卖给藏家牟利。 ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_png/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEktxqGbfdxIxecTUC5S8jNQtWLFVtLUMmw7HeuiaX4kC1IWZJ4IsFbQg/640%3Fwx_fmt%3Dpng) 有学者认为,光绪虽然丧失了“拍照自由”,但**也曾因极偶然的机会,留下了一张看不见面容的身影照。**也就是下面这张照片的红圈中之人。据吴永的《庚子西狩丛谈》和美国作家立德夫人《我的北京花园》的记述,时为1902年1月,光绪随慈禧结束逃亡返回京城,在正阳门下轿时,被城墙上围观的外国人拍了下来。当年的法文报纸刊登这张照片时,用的标题是“光绪皇帝生前的瞬间快照”。 ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_png/ibYIE3gDV7K7F4umqChiaS02EzJNadkK0YGd7USIuWiaYiaMHMicWgROHodo0Akz4jncUz7WWlR0DpFjEEfQ3Yj80hQ/640%3Fwx_fmt%3Djpeg) 图:光绪身影照 除此之外,**从民国报刊中,也还能找到一张看不清面容的光绪照片**。下面这两张图片,一张取自1925年的《环球画报》,题为“庚子拳乱议和各国公使覲見光绪帝摄影”。一张取自1935年的《绸缪月刊》,照片说明是:“上图为逊清光绪引见各国公使之仪式,与现代共和国家礼节绝对不同。此为佛山李氏所藏,颇有历史价值”。 这两张图片,显然出自同一张照片。光绪皇帝虽然失去了“拍照自由”,但慈禧无法阻止外国使节带着摄影师进入皇宫——早在1898年,德国亨利亲王来华觐见光绪时,已被许可由随从人员带着摄像设备入宫。于是得以留下了这样一张照片。遗憾的是,照片中的光绪,仍看不清面目。 ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_jpg/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEr4NyRlIxmnM8JH6cqCJzJOpMdrEte0qXuE1RvNX20xlPia44Edwb4hg/640%3Fwx_fmt%3Djpeg) 图:《环球画报》1925年第1期 ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_png/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaE8yYupoUkXNTKiacXBtOSiaSlNtggv2nkFTc90oheWSyVSyKKGasgjOYw/640%3Fwx_fmt%3Dpng) 图:出自《绸缪月刊》1935年第2卷第3期 1903年,由外国传教士创办的、中国发行量最大的报纸《万国公报》,也曾刊登过一张题为**“中国今上光绪皇帝”**的照片(见下图),但报纸没有提供任何照片说明。此时,光绪皇帝尚在人世;慈禧太后也正在兴致勃勃地扮成观音,与太监宫女们留影。考虑到《万国公报》由林乐知主编,李提摩太、丁韪良等游走于清廷高层者也会参与编撰,且该报的用户上抵李鸿章、张之洞等朝廷重臣,似不至于随便以来历不明的相片充当光绪。 ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_png/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEkDozGDzw3kRNnXppd9lqvJeLynBr5sp7zmv1V5moOwiaNlhicicL7a9Lg/640%3Fwx_fmt%3Dpng) 图:取自《万国公报》1903年第178期25页 **可供与之对照的,是下面这张图片。**该图片载于故宫博物院官网,题为《清德宗光绪皇帝爱新觉罗·载湉像》——清代帝王有留下肖像画的传统,自康雍乾时代起,宫廷绘画还采用了西洋写实画法。这使得今人能够通过这些肖像画,了解到清代帝王的一些基本的面部特征。可以看到,这一照一图的面部轮廓,确有诸多相似之处,但照片是不是光绪,仍须更多证据。(完) ![](https://images.weserv.nl/?url=https%3A//mmbiz.qpic.cn/mmbiz_jpg/ibYIE3gDV7K43WMHyc5G4a8o8YLAia2uaEfG7iagIDDqW5v8vnNDU9vsoib52HftH8sF6Y5BiaBMej6YHhpbFxibic3XA/640%3Fwx_fmt%3Djpeg) 图:故宫博物院官网所载光绪传世画像 **参考资料** ①人教版《中国历史》(八年级上册),2001年审定,第34页。 ②统编本《中国历史》(八年级上册),2017年7月第1版,第28~31页。 ③刘北汜、李毅华主编,《故宫旧藏人物照片集》,紫禁城出版社,1990,前言。 ④刘北汜,《珍妃像》,收录于:《故宫新语》,上海文化出版社,1984,第137页。 ⑤徐家宁,《光绪珍妃传世照片多为误认?》,北京日报2017年4月11日。 ⑥http://www.dpm.org.cn/court/lineage/226254.html ⑦德龄,《清宫禁二年记》。 _在这个话题无孔不入且热爱阅读的新媒体编辑部,我们经常在各种五花八门的公众号上,遇到或曲高和寡或趣味小众、但非常有意思的新鲜玩意儿。_ _现在,它们都将一一出现在这个栏目里。_ _我们也随时欢迎您的参与,留言向我们推荐您读到的低调好文。_ ___本文由公众号「短史记」(______ID:____tengxun\_lishi____)授______权转载,欢迎点击「阅读原文」访问关注。___
Java
UTF-8
6,975
2.265625
2
[]
no_license
package com.chenxi.eventsbeltreviewer.controllers; import java.util.List; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.chenxi.eventsbeltreviewer.models.User; import com.chenxi.eventsbeltreviewer.models.Event; import com.chenxi.eventsbeltreviewer.models.Message; import com.chenxi.eventsbeltreviewer.models.State; import com.chenxi.eventsbeltreviewer.services.MainService; import com.chenxi.eventsbeltreviewer.validators.UserValidator; @Controller public class MainController { @Autowired private MainService service; @Autowired private UserValidator validator; @GetMapping("/") public String index(@ModelAttribute("user") User emptyuser, HttpSession session, Model model) { if (session.getAttribute("user_id") != null) { return "redirect:/events"; } List<State> states = this.service.findAllStates(); model.addAttribute("states", states); return "index.jsp"; } @PostMapping("/registration") public String registration(@Valid @ModelAttribute("user") User filledUser, BindingResult result, HttpSession session, Model model) { validator.validate(filledUser, result); if (result.hasErrors()) { List<State> states = this.service.findAllStates(); model.addAttribute("states", states); return "index.jsp"; } User user = this.service.register(filledUser); session.setAttribute("user_id", user.getId()); return "redirect:/events"; } @PostMapping("/login") public String login(@RequestParam("email") String email, @RequestParam("password") String password, Model model, HttpSession session, RedirectAttributes flashMessages) { if (!service.loginAuth(email, password)) { flashMessages.addFlashAttribute("error", "INVALID LOGIN"); return "redirect:/"; } User user = this.service.findByEmail(email); session.setAttribute("user_id", user.getId()); return "redirect:/events"; } // dashboard @GetMapping("/events") public String dashboard(HttpSession session, Model model, @ModelAttribute("event") Event emptyEvent) { if (session.getAttribute("user_id") == null) { return "redirect:/"; } User user = this.service.findUserById((Long) session.getAttribute("user_id")); model.addAttribute("user", user); List<State> states = this.service.findAllStates(); model.addAttribute("states", states); // show events List<Event> events = this.service.allEvents(); for (Event event : events) { System.out.println(event.getName()); } model.addAttribute("events", events); return "dashboard.jsp"; } @GetMapping("/logout") public String logout(HttpSession session) { session.setAttribute("user_id", null); return "redirect:/"; } @PostMapping("/events") public String createEvent(@Valid @ModelAttribute("event") Event filledEvent, BindingResult result, HttpSession session, Model model) { if (result.hasErrors()) { User user = this.service.findUserById((Long) session.getAttribute("user_id")); model.addAttribute("user", user); List<State> states = this.service.findAllStates(); model.addAttribute("states", states); // show events List<Event> events = this.service.allEvents(); for (Event event : events) { System.out.println(event.getName()); } model.addAttribute("events", events); return "dashboard.jsp"; } service.createEvent(filledEvent); return "redirect:/events"; } // user join event @GetMapping("/events/{event_id}/{attendee_id}") public String RSVP(@PathVariable("event_id") Long event_id, @PathVariable("attendee_id") Long attendee_id) { service.addAttendee(event_id, attendee_id); return "redirect:/events"; } // user cancel rsvp @GetMapping("/events/cancel/{event_id}/{attendee_id}") public String cancelRSVP(@PathVariable("event_id") Long event_id, @PathVariable("attendee_id") Long attendee_id) { service.removeAttendee(event_id, attendee_id); return "redirect:/events"; } // edit event @GetMapping("/events/{event_id}/edit") public String editEvent(HttpSession session, @PathVariable("event_id") Long event_id, Model model) { if (session.getAttribute("user_id") == null) { return "redirect:/"; } Event event = this.service.findEventById(event_id); Long user_id = (Long) session.getAttribute("user_id"); // long is an object so it cannot use "==" directly if (!event.getHost().getId().equals(user_id)) { System.out.println(event.getHost().getId()); System.out.println(user_id); System.out.println("they are not equal"); return "redirect:/events"; } model.addAttribute("event", event); List<State> states = this.service.findAllStates(); model.addAttribute("states", states); return "eventEdit.jsp"; } @PutMapping("/events/{event_id}/edit") public String update(@PathVariable("event_id") Long id, @Valid @ModelAttribute("event") Event event, BindingResult result, Model model) { if (result.hasErrors()) { List<State> states = this.service.findAllStates(); model.addAttribute("states", states); return "eventEdit.jsp"; } else { this.service.updateEvent(id, event); return "redirect:/events"; } } // delete event @GetMapping("/events/{event_id}/delete") public String deleteEvent(@PathVariable("event_id") Long id, HttpSession session) { // user not log in if (session.getAttribute("user_id") == null) { return "redirect:/"; } // user not host // if correct this.service.deleteEvent(id); return "redirect:/events"; } // event show page @GetMapping("/events/{event_id}") public String eventShow(@PathVariable("event_id") Long id, HttpSession session, Model model, @ModelAttribute("message") Message emptyMessage) { if (session.getAttribute("user_id") == null) { return "redirect:/"; } Event event = this.service.findEventById(id); int counts = event.getAttendees().size(); model.addAttribute("event", event); model.addAttribute("counts", counts); return "eventShow.jsp"; } @PostMapping("/events/{event_id}/addMessage") public String addMessage(@PathVariable("event_id") Long id, @ModelAttribute("message") Message filledMessage) { this.service.saveMessage(filledMessage); return "redirect:/events/" + id; } }
Java
UTF-8
2,746
3.328125
3
[]
no_license
package com.hummingbird.common.util; public class LuhnUtils { public static void main(String[] args) { // System.out.println(luhnTest("49927398716")); // System.out.println(luhnTest("49927398717")); //System.out.println(luhnTest("1234567812345678")); System.out.println("此银行卡合法性--"+luhnTest("6226900906317074")); System.out.println("检验码为--"+getCheckNum("622690090631707")); } //验证银行卡号是否合法 public static boolean luhnTest(String number){ //定义s1为奇数位总和,s2为偶数位总和 int s1 = 0, s2 = 0; // 从最末一位开始提取,每一位上的数值 String reverse = new StringBuffer(number).reverse().toString(); for(int i = 0 ;i < reverse.length();i++){ int digit = Character.digit(reverse.charAt(i), 10); //奇数位处理 if(i % 2 == 0){ s1 += digit; }else{ //偶数位处理,如果位数值乘以2大于10,取两位数之和,不大于10直接取乘积 s2 += 2 * digit; if(digit >= 5){ s2 -= 9; } } } //将奇数位和与偶数位和相加,除以10,如果能整除则为合法,否则为不合法 return (s1 + s2) % 10 == 0; } //获取校验码 public static int getCheckNum(String number){ //定义s1为奇数位总和,s2为偶数位总和 int s1 = 0, s2 = 0; int checkNum = 0; // 从最末一位开始提取,每一位上的数值 String reverse = new StringBuffer(number).reverse().toString(); for(int i = 0 ;i < reverse.length();i++){ int digit = Character.digit(reverse.charAt(i), 10); //奇数位处理 if(i % 2 == 0){ s2 += 2 * digit; if(digit >= 5){ s2 -= 9; } }else{ //偶数位处理,如果位数值乘以2大于10,取两位数之和,不大于10直接取乘积 s1 += digit; } } //将奇数位和与偶数位和相加,除以10,如果能整除则为合法,否则为不合法,取出尾数 String str = String.valueOf(s1 + s2); int lastNum = Integer.parseInt(String.valueOf(str.charAt(str.length()-1))); //检验位得出 if(lastNum==0){ checkNum = 0; } else{ checkNum = 10-lastNum; } return checkNum; } }
Markdown
UTF-8
9,107
3.03125
3
[]
no_license
# Dependency Injection Note: This article is actual as of v6.0.0. In this article: * [Container services](#container-services) * [Injectable factory](#injectable-factory) * [Binding](#binding) * [See also](#see-also) There are two classes repsonsibe for the dependency injection in EspoCRM: * Container – `Espo\Core\Container` [class](https://github.com/espocrm/espocrm/blob/master/application/Espo/Core/Container.php); * InjectableFactory – `Espo\Core\InjectableFactory` [class](https://github.com/espocrm/espocrm/blob/master/application/Espo/Core/InjectableFactory.php). ## Container services Note: Not to be confused with *Service* classes. The Contanier contains services. These services are supposed to be used in multiple places throughout the system. **Lazy initialization** is used, meaning that a service is not loaded until it's asked (as a dependency or implicitly). Container services are defined: * by loader classes in `Espo\Core\Loaders` namespace (can be customized in `Espo\Custom\Core\Loaders`); * in [metadata](metadata.md) (app > containerServices). Note: The best practice is not to require the *container* in your classes, and never use it directly. A specific service can be required in a constructor or with Aware interface. Console command that prints all available container services with their implementing classes: ``` php command.php app-info --container ``` Most used container services are listed [here](container-services.md). ### Defining in metadata If you need to define your custom container services, do it in metadata. In your module or in the custom folder: * `application/Espo/Modules/{YourModule}/Resources/metadata/app/containserServices.json`; * `custom/Espo/Custom/Resources/metadata/app/containserServices.json`. A definition example: ```json { "myService": { "className": "Espo\\Modules\\MyModule\\MyService" } } ``` Needed dependencies will be passed to a class constructor. Class constructor parameter names and type hinting will be used to detect dependencies. For example, if a parameter name is `$entityManager`, then *entityMaanger* container service will be passed. ```php <?php namespace Espo\Modules\MyModule; use Espo\Core\ORM\EntityManager; class MyService { protected $entityManager; public function __construct(EntityManager $entityManager) { $this->entityManager = $entityManager; } } ``` If there's no service with a matching name but a type hint for the parameter is a class, then a new instance of that class will be instantiated (by Injectable Factory). ## Injectable factory Injectable Factory creates objects by a given class names resolving dependencies. It is available as a service in *container*. That means that *injectableFactory* can be required as a dependency. Requiring *injectableFactory* as a dependency: ```php <?php namespace Espo\Modules\MyModule; use Espo\Core\InjectableFactory; use Espo\Modules\MyModule\Something; /** * It's a good practice to use factory classes for creating instances of specific types. * Your class will require the factory rather than `injectableFactory` service. */ class SomeFactory { protected $injectableFactory; public function __construct(InjectableFactory $injectableFactory) { $this->injectableFactory = $injectableFactory; } public function create(): Something { return $this->injectableFactory->create(Something::class); } } ``` ### Constructor injection #### Service dependencies Constructor parameter names are used to detect dependencies on services. For example, if the parameter name is `$entityManager`, then *entityManager* service will be passed. Class: ```php <?php namespace Espo\Custom; use Espo\Core\ORM\EntityManager; class SomeClass { protected $entityManager; // There's a service with the name 'entityManager'. public function __construct(EntityManager $entityManager) { $this->entityManager = $entityManager; } } ``` Note: A type hint for a parameter should match a class of a service or be a parent class or interface. Otherwise the service won't be passed but a new instance will be created and passed into the constructor. #### Non-service dependencies If there's no service with the name that matches a parameter name, and a parameter's type hint is a class, then an instance will be created and passed as a dependency. A new instance will be created every time the dependency is requested. See below. ```php <?php namespace Espo\Custom; use Espo\Modules\MyModule\SomeClass; class SomeClass { protected $something; // There's no service with the name 'something' and type hint is a class. // Hence an instance of SomeClass is created and passed to the constructor. public function __construct(SomeClass $something) { $this->something = $something; } } ``` ### Setter method injection Can be used along with the constructor injection. If a class implements *Aware* interface, the factory will use a corresponding setter function to inject a dependency. Setter traits can be utilized for adding setter functions into your class. Example: ```php <?php namespace Espo\Custom; use Espo\Core\Di; class MyClass implements Di\EntityManagerAware, Di\MetadataAware { use Di\EntityManagerSetter; use Di\MetadataSetter; public function someMethod(): void { $entityManager = $this->entityManager; $metadata = $this->metadata; } } ``` Using setter injections may be reasonable when you are extending from an existing class and want to add additional dependencies. Important: Only services can be injected via setters. ### Manual instantiating ```php <?php use Espo\Custom\SomeClass; $injectableFactory->create(SomeClass::class); ``` You can specify constructor injections explicitly using *createdWith* method. Those that are not specified, will be tried to be resolved using *ReflectionClass*. ```php <?php $injectableFactory->createWith($className, [ 'parameterName1' => $value1, 'parameterName2' => $value2, ]); ``` ### Classes created by injectableFactory The following classes are created by *injectableFactory*: * ApplicationRunners - `Espo\Core\ApplicationRunners` * Controllers - `Espo\Controllers` * Services - `Espo\Services` * Hooks - `Espo\Hooks` * Jobs - `Espo\Jobs` * EntryPoints - `Espo\EntryPoints` * Repositories - `Espo\Repositories` * SelectManagers - `Espo\SelectManagers` * Notificators - `Espo\Notificators` * Acl - `Espo\Acl` * Formula Functions * Cleanup - defined in metadata: app > cleanup * AppParams - defined in metadata: app > appParams And many others. You can use `grep -R 'injectableFactory'` to find where it's used in Espo. ## Binding Available as of v6.1.0. There is the ability to bind interfaces to implementations and bind parameter names to specific values. Binding is used for resolving dependencies passed through a constructor. Binding can be processed in the `Binding` classes in every module and in *Custom* namespace: * `Espo\Modules\{ModuleName}\Binding` * `Espo\Custom\Binding` Note: A module order parameter is used when binding is processed. Meaning that modules with a lower order value will be processed first. CLI command to print all bindings: ``` php command.php app-info --binding ``` Default binding is processed in `Espo\Core\Binding\DefaultBinding`. ### Example File `application/Espo/Modules/MyModule/Binding.php`: ```php <?php namespace Espo\Modules\MyModule; use Espo\Core\Binding\Binder; class Binding { public function process(Binder $binder): void { $binder ->bindService('Espo\\SomeServiceName', 'someServiceName') ->bindImplementation('Espo\\SomeInterface', 'Espo\\SomeImplementation'); $binder ->bindService('Espo\\SomeServiceName $name', 'anotherServiceName'); $binder ->for('Espo\\SomeClass') ->bindImplementation('Espo\\SomeInterface', 'Espo\\SomeImplementation') ->bindValue('$paramName', 'Some Value') ->bindCallback( '$anotherParamName', // callback arguments are resolved automatically function (SomeDependency $dependency) { return $dependency->getSomething(); } ); } } ``` Explanation: * If any class requires `Espo\SomeServiceName`, give the container service `someServiceName`. * If any class requires `Espo\SomeInterface`, give an instance of `Espo\SomeImplementation`. * If any class requires `Espo\SomeServiceName ` and a parameter name is `$name`, then give `anotherServiceName` service. * When `Espo\SomeClass` requires `Espo\SomeInterface`, give an instance of `Espo\SomeImplementation`. * When `Espo\SomeClass` is instantiated, pass the value 'Same Value' for the parameter `$paramName`. * When `Espo\SomeClass` is instantiated, use the callback to resolve a value of the parameter `$anotherParamName`. ## See also * [Container services](container-services.md)
Markdown
UTF-8
6,793
3.140625
3
[ "MIT" ]
permissive
--- layout: post title: Single Responsibility Principle categories: [OOP] tags: [SOLID] description: 객체 지향 설계 5원칙 - SRP fullview: false comments: true --- 객체의 4대 특성과 개념을 인지함으로써, 객체 지향 프로그램을 작성할 수 있는 도구를 얻었다. 하지만, 아무리 좋은 도구를 가지고 있다고 해도 올바르게 사용하지 않으면 없느니만 못하다. 도구가 올바르게 사용하는 법이 있는 것처럼, 객체 지향의 특성을 올바르게 사용하는 방법, 즉 객체 지향 언어를 이용해 객체 지향 프로그램을 올바르게 설계해 나가는 방법이나 원칙이 있는데 바로 **객체 지향 설계(OOD; Object Oriented Design)의 SOLID**이다. SOLID는 아래 다섯가지 원칙의 앞머리 알파벳을 따 부른다. * SRP(Single Responsibility Principle) : 단일 책임 원칙 * OCP(Open Closed Principle) : 개방 폐쇄 원칙 * LSP(Liskov Subsisution Principle) : 리스코프 치환 원칙 * ISP(Interface Segregation Principle) : 인터페이스 분리 원칙 * DIP(Dependcy Inversion Principle) : 의존 역전 원칙 이 다섯가지 원칙은 결국 **응집도는 높이고(High COhesion), 결합도는 낮추라(Loose Coupling)**는 고전 원칙을 객체 지향의 관점에서 재정립 한 것이다. > 응집도 : 하나의 모듈 내부에 존재하는 구성 요소들의 기능적 관련성으로, 응집도가 높은 모듈은 하나의 책임에 집중하고 독립성이 높아져 재사용이나 기능의 수정, 유지보수가 용이하다. > 결합도 : 모듈(클래스)간 상호 의존 정도로서 결합도가 낮으면 모듈 간의 상호 의존성이 줄어들어 객체의 재사용, 수정, 유지보수가 용이하다. 우선 첫번째로 S를 뜻하는 **SRP(Single Responsibility Principle)**에 대해 자세하게 정리해보자. ## SRP **A class should have only one reason to change.** 어떤 클래스를 변경해야 하는 이유는 오직 하나뿐이어야 한다. 변경의 이유가 단 하나여야 하는 이유는 무엇일까? 크게 두가지 이유로 생각해 볼 수 있다. 1. A라는 책임과 B라는 책임을 갖고 있는 클래스가 있을 경우, A만 필요로 하는 애플리케이션을 불필요하게 B를 들고 다녀야 한다. 2. 불필요한 변경 임팩트가 발생한다. A와 B 두가지 책임을 가진 클래스에서 A가 변경되었을 경우, B만 필요로 하는 애플리케이션은 불필요하게 다시 컴파일해야하고 리테스트 및 재배포까지 진행해야 한다. 그렇기 때문에, **클래스는 하나의 책임을 가져야 하는 것**이다. 여기서 말하는 **책임**은 단순히 하나의 메소드를 말하는 것이 아니라, 사용자에 대한, 변경의 원천에 대한 것이라고 생각할 수 있다. > 따라서 책임은 하나의 특정 액터를 위한 기능 집합이다. ### 잘못된 예시와 개선 사례 (1) ```java class dog { final static Boolean male = true; final static Boolean female = false; Boolean sex; ... void pee(){ if(this.sex == male){ //한쪽 다리를 들고 소변을 본다. } else { // 뒷 다리 두 개를 굽혀 앉은 자세로 소변을 본다. } } } ``` 이 예제를 보면, 강아지가 암컷이냐 수컷이냐에 따른 pee()행위가 분기처리 되는 것을 볼 수 있다. 여기서는 수컷 강아지의 행위와 암컷 강아지의 행위를 모두 구현하려고 하기에 단일 책임 원칙을 위배하고 있다. 메서드가 단일 책임 원칙을 지키지 않을 경우 나타나는 대표적인 냄새가 바로 분기 처리를 위한 if문이다. 이런경우 아래와 같이 리팩터링하여 개선할 수 있다. ```java class dog { abstract void pee() } class maleDog extends dog{ void pee(){ //한쪽 다리를 들고 소변을 본다. } } class femaleDog extends dog{ void pee(){ //뒷다리 두 개로 앉은 자세로 소변을 본다. } } ``` 위와 같이 상속을 통해 적용하면, 암컷 강아지의 행위와 수컷 강아지의 행위가 각각 분리된 것을 알 수 있다. ### 잘못된 예시와 개선 사례 (2) 책과 각종 포스트를 통해 익힌 SRP를 곰곰히 곱씹어보며, 최근 업무를 하며 본 어떤 코드가 SRP를 적용하지 않은 것을 발견하였다(!) ```java public void getReview(){ if(){ //본인이 셀프리뷰 조회 } else if(){ //협업동료가 리뷰 및 동료리뷰 조회 } else { //리더가 대상자의 리뷰, 협업동료 리뷰, 리더 리뷰 조회 } } ``` 구성원이 목표 항목을 수립하고, 해당 목표 완료시 셀프리뷰/동료리뷰/부서장리뷰를 조회하는 함수이다. 본인 / 협업동료 / 리더가 해당 목표 조회시 조회를 할 수 있는 범위도 다르고, 접근 가능/불가여부도 각각 다른데 이 함수에서 `if`, `else`로 조건만 걸어 계속 처리해준 것을 알 수 있다. 즉, 이 함수에서는 본인, 협업동료, 리더의 목표조회 책임을 한 함수 내에 처리했다. 아래와 같이 리팩토링하면 각각의 역할에 따른 비즈니스 로직에 더 집중할 수 있지 않을까? ```java public interface ReviewReader{ public void getReview(); } class User implements ReviewReader{ @Override public void getReview(){ //본인이 셀프리뷰 조회 } } class PeerUser implements ReviewReader{ @Override public void getReview(){ //협업동료가 리뷰 및 동료리뷰 조회 } } class LeaderUser implement ReviewReader{ @Override public void getReview(){ //리더가 대상자의 리뷰, 협업동료 리뷰, 리더 리뷰 조회 } } ``` ### 결론 위 코드를 보고 객체 지향의 4대 특성에 대해 생각해보면, 단일 책임 원칙과 가장 관계가 깊은 것은 바로 모델링 과정을 담당하는 **추상화**임을 알 수 있다. 단일 책임 원칙은 코드를 작성할 때 항상 고려해야 한다. 단일 책임 원칙은 클래스와 모듈 설계에 지대한 영향을 미치고, 이 원칙이 잘 지켜지면 의존성이 적고 가벼운, 결합도가 낮은 설계로 이어지기 때문이다. *** 참고 자료 1. [스프링 입문을 위한 객체 지향의 원리와 이해](http://www.yes24.com/Product/Goods/17350624) 2. [[객체지향 SW 설계의 원칙] ② 사례연구, 단일 책임 원칙](https://zdnet.co.kr/view/?no=00000039135552) 3. [SOLID원칙(1-Single Responsibility Principle)](https://medium.com/@homekeeper89/solid-%EC%9B%90%EC%B9%99-1-single-responsibility-principle-108bdf77fa19) 4. [SOLID: 1부 - 단일 책임 원칙](https://code.tutsplus.com/ko/tutorials/solid-part-1-the-single-responsibility-principle--net-36074)
Java
UTF-8
1,758
2.765625
3
[]
no_license
package ua.lviv.iot.lab9; import javax.persistence.*; @Entity @Table(name = "clothes") public class Clothes { public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name = "brand") private String brand; @Column(name = "color") private String color; @Column(name = "price") private int price; @Column(name = "typesForWearing") private ua.lviv.iot.lab9.TypesForWearing typesForWearing; public Clothes() { } public Clothes(final String brand, final String color, final int price, final ua.lviv.iot.lab9.TypesForWearing typesForWearing) { this.brand = brand; this.color = color; this.price = price; this.typesForWearing = typesForWearing; } public String getBrand() { return brand; } public String getColor() { return color; } public int getPrice() { return price; } public void setBrand( String brand) { this.brand = brand; } public void setColor( String color) { this.color = color; } public void setPrice( int price) { this.price = price; } public TypesForWearing getTypesForWearing() { return typesForWearing; } public void setTypesForWearing( TypesForWearing typesForWearing) { this.typesForWearing = typesForWearing; } @Override public String toString() { return " Clothes " + "\n" + " brand= " + brand + "\n" + " color= " + color + "\n" + " price= " + price + "\n" + " TypesForWearing= " + typesForWearing + "\n"; } }
Java
UTF-8
1,672
3.046875
3
[]
no_license
// -*- mode: Java; -*- package sanka.test; import sanka.lang.Object; class Globals { static int[] RESULTS; } abstract class EmptyBase {} class Adder extends EmptyBase { int base; Adder(base); int add(int value) { Globals.RESULTS.add(this.base + value); } } class Subtracter extends EmptyBase { int base; Subtracter(base); int subtract(int value) { Globals.RESULTS.add(this.base - value); } } class TypeswitchTest extends BaseTest { void use(Object o, int value) { typeswitch (o) { case Adder a: a.add(value); break; case Subtracter s: s.subtract(value); break; default: Globals.RESULTS.add(value); break; } } /* void useBase(EmptyBase b, int value) { typeswitch (b) { case Adder a: a.add(value); break; case Subtracter s: s.subtract(value); break; default: Globals.RESULTS.add(value); break; } } */ void testInterfaceTypeswitch() { Globals.RESULTS = new int[]; use(new Adder(100), 17); use(new Subtracter(200), 17); use(this, 17); assertEquals(3, Globals.RESULTS.length, "length"); assertEquals(117, Globals.RESULTS[0], "adder"); assertEquals(183, Globals.RESULTS[1], "subtracter"); assertEquals( 17, Globals.RESULTS[2], "default"); } static int main(String[] argv) { var test = new TypeswitchTest(); test.testInterfaceTypeswitch(); return test.exit(); } }
Markdown
UTF-8
28,644
3.578125
4
[]
no_license
- [js 数据类型](#js-数据类型) - [为什么会有BigInt的提案?](#为什么会有bigint的提案) - [js 类型判断](#js-类型判断) - [typeOf](#typeof) - [Object.prototype.toString.call(\*\*\*)](#objectprototypetostringcall) - [instanceof](#instanceof) - [手写instanceof](#手写instanceof) - [判断数组的方式](#判断数组的方式) - [null和undefined区别](#null和undefined区别) - [0.1+0.2!==0.3](#010203) - [类型转换](#类型转换) - [抽象方法ToPrimitive](#抽象方法toprimitive) - [ToPrimitive 转换为原始值的规则](#toprimitive-转换为原始值的规则) - [`valueOf方法和toString方法解析`](#valueof方法和tostring方法解析) - [String、Boolean、Number、对象之间的相互转换](#stringbooleannumber对象之间的相互转换) - [其他类型转为字符串类型❗️](#其他类型转为字符串类型️) - [其他类型转为Number类型❗️](#其他类型转为number类型️) - [其他类型转为Boolean类型](#其他类型转为boolean类型) - [对象转为其他类型(原始类型)](#对象转为其他类型原始类型) - [包装类型](#包装类型) - [隐式类型转换](#隐式类型转换) - [数学运算符中的隐式类型转换](#数学运算符中的隐式类型转换) - [减、乘、除](#减乘除) - [加法](#加法) - [逻辑语句中的类型转换](#逻辑语句中的类型转换) - [单个变量](#单个变量) - [比较运算符](#比较运算符) - [使用 == 比较中的5条规则](#使用--比较中的5条规则) - [几道经典例题:](#几道经典例题) - [`==,===,Object.is()`有什么区别?](#objectis有什么区别) - [显示类型转换](#显示类型转换) - [ToString](#tostring) - [`String()、toString()`的基本类型值的字符串化规则:](#stringtostring的基本类型值的字符串化规则) - [JSON.stringify()](#jsonstringify) - [ToNumber](#tonumber) - [ToBoolean](#toboolean) - [附录:类型转换表](#附录类型转换表) # js 数据类型 js有8种数据类型: 1. Null 2. Undefined, 3. Boolean, 4. Number 5. String, 6. Symbol(new in es6),表示独一无二的值 7. BingInt 8. Object 其中前7中为**基本(原始)数据类型**。 Object为**引用类型**,包括:Object 类型、Array 类型、Date 类型、RegExp 类型、Function 类型 等。 两种类型的区别在于存储位置的不同: - `原始数据类型`直接存储在`栈`(stack)中的简单数据段,占据空间小、大小固定,属于被频繁使用数据,所以放入栈中存储; - `引用数据类型`存储在`堆`(heap)中的对象,占据空间大、大小不固定。如果存储在栈中,将会影响程序运行的性能;引用数据类型在栈中存储了指针,该指针指向堆中该实体的起始地址。当解释器寻找引用值时,会首先检索其在栈中的地址,取得地址后从堆中获得实体。 >堆和栈的概念存在于数据结构和操作系统内存中,在数据结构中: > >1. `栈`中数据的存取方式为先进后出。 >2. `堆`是一个优先队列,是按优先级来进行排序的,优先级可以按照大小来规定。 > >在操作系统中,内存被分为栈区和堆区: > >1. `栈`区内存由编译器自动分配释放,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构中的栈。 >2. `堆`区内存一般由开发着分配释放,若开发者不释放,程序结束时可能由垃圾回收机制回收。 ## 为什么会有BigInt的提案? JavaScript中Number.MAX_SAFE_INTEGER表示最⼤安全数字,计算结果是9007199254740991,即在这个数范围内不会出现精度丢失(⼩数除外)。但是⼀旦超过这个范围,js就会出现计算不准确的情况,这在⼤数计算的时候不得不依靠⼀些第三⽅库进⾏解决,因此官⽅提出了BigInt来解决此问题。 # js 类型判断 ## typeOf ```js typeof 1 ---> 'number' typeof 'hello' ---> 'string' typeof function() {} ---> 'function' typeof undefined ---> 'undefined' typeof Symbol() ---> 'symbol' typeof false ---> 'boolean' typeof b ---> 'undefined' // b 没有声明,但是还会显示 undefined typeof 10n ---> 'bigint' typeof [1,2,3] ---> 'object' typeof {a:1,b:2} ---> 'object' typeof new Date() ---> 'object' typeof /12/g ---> 'object' typeof new Set() ---> 'object' typeof new Map() ---> 'object' typeof null ---> 'object' // 原因:在系统存储变量的方式中,000 开头代表是对象,然而 null 表示为全零 typeof NaN ---> 'number' ``` typeof是用来判断变量**基本类型**的关键字,但`typeof null==='object'`,是个js的老bug ## Object.prototype.toString.call(***) toString是Object的原型方法,而Array、function等类型作为Object的实例,都**重写了toString方法**。不同的对象类型调用toString方法时,根据原型链的知识,调用的是对应的重写之后的toString方法(function类型返回内容为函数体的字符串,Array类型返回元素组成的字符串…),而不会去调用Object上原型toString方法(返回对象的具体类型),因此可以得到正确的类型。 ```js var number = 1; // [object Number] var string = '123'; // [object String] var boolean = true; // [object Boolean] var und = undefined; // [object Undefined] var nul = null; // [object Null] var obj = {a: 1} // [object Object] var array = [1, 2, 3]; // [object Array] var date = new Date(); // [object Date] var error = new Error(); // [object Error] var reg = /a/g; // [object RegExp] var func = function a(){}; // [object Function] function foo(){} console.log(Object.prototype.toString.call(new foo())); //[object Object] ``` 从**react源码**中获取判断变量类型的灵感: ```js const getType = (a) => Object.prototype.toString.call(a).split(" ") .slice(1) .join(" ") .split("]")[0]; ``` ## instanceof instanceof原理:用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上。 instanceof**无法判断数组、日期类型** ```js [] instanceof Array // true [] instanceof Object // true ``` 原因:Array的原型是Object,而instanceof的实现原理是在原型链上遍历 ### 手写instanceof ```js function myInstanceof(left,right) { // left.__proto__ == Object.getPrototypeOf(left) // Object.getPrototypeOf() 方法返回指定对象的原型 let proto = left.__proto__; // 获取对象的原型 let prototype = right.prototype // 获取构造函数的prototype对象 while(true) { //查找到尽头,还没找到 if(proto === null) return false; //找到相同的原型对象 if(proto === prototype) return true; proto = proto.__proto__; // 如果没有找到,就继续从其原型上找 } } function Student(name, age) { this.name = name; this.age = age; } function Teacher(name, age) { this.name = name; this.age = age; } const a = new Student('LIN', 12); console.log(myInstanceof(a, Student)); console.log(myInstanceof(a, Teacher)); ``` # 判断数组的方式 1. Object.prototype.toString.call() `Object.prototype.toString.call(obj).slice(8,-1) === 'Array';` 2. 通过原型链做判断 `obj.__proto__ === Array.prototype;` 3. 通过ES6的Array.isArray()做判断 `Array.isArrray(obj);` 4. 通过Array.prototype.isPrototypeOf `Array.prototype.isPrototypeOf(obj)` # null和undefined区别 - 首先 `Undefined` 和 `Null` 都是基本数据类型,这两个基本数据类型分别都只有一个值,就是 undefined 和 null。 - `undefined` 代表的含义是未定义,`null` 代表的含义是空对象。一般变量声明了但还没有定义的时候会返回 undefined,null主要用于赋值给一些可能会返回对象的变量,作为初始化。 - undefined 在 js 中不是一个**保留字**,这意味着可以使用 undefined 来作为一个变量名,这样的做法是非常危险的 - 使用 typeof 进行判断时,Null 类型化会返回 “object”,这是一个历史遗留问题,因为在系统存储变量的方式中,000 开头代表是对象,然而 null 表示为全零。`typeof undefined`会返回undefined - 当使用双等号比较undefined与null时会返回 true,使用三个等号时会返回 false。 # 0.1+0.2!==0.3 计算机是通过二进制的方式存储数据的,所以计算机计算0.1+0.2的时候,实际上是计算的两个数的二进制的和。`0.1的`二进制是`0.0001100110011001100...`(1100循环),`0.2`的二进制是:`0.00110011001100...`(1100循环),这两个数的二进制都是无限循环的数。由于存储空间有限,最后计算机会舍弃后面的数值,所以我们最后就只能得到一个近似值。 **这就导致了`精度丢失`** **因为两次`存储`时的`精度丢失`加上一次`运算`时的`精度丢失`,最终导致了 0.1 + 0.2 !== 0.3** **如何解决 0.1+0.2!=0.3** 1. 将`浮点数`转化成`整数` 最好的方法就是我们想办法规避掉这类小数计算时的精度问题就好了,那么最常用的方法就是将`浮点数`转化成`整数`计算。因为整数都是可以精确表示的。 对于0.1 + 0.02 我们需要转化成 ( 10 + 2 ) / 1e2 对于0.1 * 0.02 我们则转化成 1 * 2 / 1e3 2. 设置一个误差范围,通常称为**机器精度** 对js来说,这个值通常为`2-52`,在ES6中,提供了`Number.EPSILON`属性,而它的值就是2-52,只要判断0.1+0.2-0.3是否小于Number.EPSILON,如果小于,就可以判断为0.1+0.2 ===0.3 # 类型转换 在 JavaScript 有两种类型转换的方式,分别是**隐式类型转换**和**显示类型转换**。 因为 JavaScript 是一种弱类型的语言,在一个表达式中,运算符两边的类型可以不同(比如一个字符串和一个数字相加),JavaScript 解释器会在运算之前将它们的类型进行转换 ## 抽象方法ToPrimitive 在介绍隐式类型转换之前先看看ToPrimitive,和String、Boolean、Number、对象之间的相互转换 在对象转原始类型的时候,一般会调用内置的 ToPrimitive 方法,而 ToPrimitive 方法则会调用 OrdinaryToPrimitive 方法。 `ToPrimitive(input, PreferredType?)` * input是要转换的值, * PreferredType是可选参数,可以是Number或String类型。默认值是`Number`。他只是一个转换标志,转化后的结果并不一定是这个参数所值的类型,但是转换结果一定是一个原始值(或者报错)。 ### ToPrimitive 转换为原始值的规则 * 如果PreferredType被标记为Number,则会进行下面的操作流程来转换输入的值。 1. 如果输入的值已经是一个原始值,则`直接返回`它 2. 否则,如果输入的值是一个对象,则调用该对象的`valueOf()`方法, 如果valueOf()方法的返回值是一个原始值,则返回这个原始值。 3. 否则,调用这个对象的`toString()`方法,如果toString()方法返回的是一个原始值,则返回这个原始值。 4. 否则,抛出TypeError异常。 * 如果PreferredType被标记为String 1. 如果输入的值已经是一个原始值,则`直接返回`它 2. 否则,调用这个对象的`toString()`方法,如果toString()方法返回的是一个原始值,则返回这个原 始值。 3. 否则,如果输入的值是一个对象,则调用该对象的`valueOf()`方法, 如果valueOf()方法的返回值是一个原始值,则返回这个原始值。 4. 否则,抛出TypeError异常。 **结论:ToPrimitive规则,是引用类型向原始类型转变的规则,如果没有特别指定PreferredType,则默认为Number,它遵循`先valueOf后toString`的模式期望得到一个原始类型。** ### `valueOf方法和toString方法解析` 该两个方法一定在对象中存在 **1. valueOf()** * `Number, Boolean, String`这三种构造函数生成的基础值的对象形式,通过valueOf转换后会变成相应的原始值 ```js var num = new Number('123'); num.valueOf(); // 123 var str = new String('12df'); str.valueOf(); // '12df' var bool = new Boolean('fd'); bool.valueOf(); // true ``` * Date这种特殊的对象,会被转换为日期的毫秒的形式的数值 ```js var a = new Date(); a.valueOf(); // 1515143895500 ``` * 除此之外返回的都为this,即对象本身 ```js var a = new Array(); a.valueOf() === a; // true var b = new Object({}); b.valueOf() === b; // true ``` **2. tostring()** * `Number、Boolean、String、Array、Date、RegExp、Function`这几种构造函数生成的对象,通过toString转换后会变成相应的字符串的形式,因为这些构造函数上封装了自己的toString方法。 ```js var num = new Number('123sd'); num.toString(); // 'NaN' var str = new String('12df'); str.toString(); // '12df' var bool = new Boolean('fd'); bool.toString(); // 'true' var arr = new Array(1,2); arr.toString(); // '1,2' var d = new Date(); d.toString(); // "Wed Oct 11 2017 08:00:00 GMT+0800 (中国标准时间)" var func = function () {} func.toString(); // "function () {}" ``` * 除这些对象及其实例化对象之外,其他对象返回的都是该对象的类型,都是继承的`Object.prototype.toString`方法。 ```js var obj = new Object({}); obj.toString(); // "[object Object]" Math.toString(); // "[object Math]" ``` ## String、Boolean、Number、对象之间的相互转换 ### 其他类型转为字符串类型❗️ * `null`:转为`"null"`。 * `undefined`:转为`"undefined"`。 * `Boolean`:true转为"true",false转为"false"。 * `Number`:11转为"11",科学计数法11e20转为"1.1e+21"。 * 数组: * 空数组`[]` 转为空字符串`""` * 如果数组中的元素有null或者undefined,同样当做`空字符串`处理, * [1,2,3,4]转为"1,2,3,4",相当于调用数组的`.join(',')`方法。PS:['1','2','3','4']也是转为"1,2,3,4" * 函数:`function a(){}`转为字符串是"function a(){}"。 * 一般对象:相当于调用对象的`toString()`方法,返回的是"[object,object]"。 ### 其他类型转为Number类型❗️ * `null`:转为 `0`。 * `undefined`:转为`NaN`。 * `Boolean`:true转为1,false转为0。 * `字符串`: * 如果是`纯数字`的字符串,则转为对应的十进制`数字`,如11转为"11", * 如果字符串中包含有效的`浮点`格式 ,则将其转换为对应的浮点数值, 如"1.1"转为1.1,"1.1e+21"转为1.1e+21, * 如果字符串中包含有效的十六进制格式,则将其转换为相同大小的`十进制数`,如"0xf"转为15 * `空字符串转为0`, * 其余情况则为`NaN`。 * `数组`或`对象`:数组首先会被转换成`原始类型`,即primitive value(参考`ToPrimitive`),得到原始类型后再根据上面的转换规则转换。 * :star:`ToPrimitive规则`,是引用类型向原始类型转变的规则,它遵循`先valueOf后toString`的模式期望得到一个原始类型。 ### 其他类型转为Boolean类型 只有`null,undefined,0,false,NaN,空字符串`这6种情况转为布尔值结果为`false`,其余全部为true ### 对象转为其他类型(原始类型) * 当对象转为其他原始类型时,会先调用对象的`valueOf()`方法,如果valueOf()方法返回的是原始类型,则直接返回这个原始类型 * 如果valueOf()方法返回的是不是原始类型或者valueOf()方法不存在,则继续调用对象的toString()方法,如果toString()方法返回的是原始类型,则直接返回这个原始类型,如果不是原始类型,则直接报错`抛出异常`。 * Date对象会先调用`toString()` # 包装类型 在 JavaScript 中,基本类型是没有属性和方法的,但是为了便于操作基本类型的值,在调用基本类型的属性或方法时 JavaScript 会在后台隐式地将基本类型的值转换为对象,如: ```js const a = "abc"; a.length; // 3 a.toUpperCase(); // "ABC" ``` 在访问'abc'.length时,JavaScript 将'abc'在后台转换成String('abc'),然后再访问其length属性。 ECMAScript 提供了 3 个特殊的引用类型:`Boolean`、`Number`和 `String`。 引用类型与基本包装类型的区别在于对象的生存期:使用new操作符创建的引用类型的实例,在执行流离开当前作用域之前都一直保存在内存中,而自动创建的基本包装类型的对象,则只存在于一行代码的执行瞬间,然后立即销毁。 使用new调用基本包装类型的构造函数,与直接调用同名的转型函数式不一样的。 ```js var value = "25"; var number = Number(value); //转型函数 alert(typeof number); //"number" var obj = new Number(value); //构造函数 alert(typeof obj); //"object" ``` > https://static.kancloud.cn/a6065380280/learnjs/295727 ## 隐式类型转换 > 参考链接:https://www.freecodecamp.org/chinese/news/javascript-implicit-type-conversion/#--2 隐式转换就是自动转换,通常发生在一些数学运算中。 JavaScript 中,表达式中包含以下运算符时,会发生**隐式类型转换**:; * 逻辑运算符:逻辑与(&&)、逻辑或(||)、逻辑非(!); * 算术运算符:加(+)、减(-)、乘(*)、除(/)、取模(%) * 字符串运算符:+、+=。 * 比较运算符:>, >=, <, <=, ==, ===, !=, !=== ### 数学运算符中的隐式类型转换 #### 减、乘、除 :star:**我们在对各种非Number类型运用数学运算符(- * /)时,会先将非Number类型转换为Number类型。** 转换规则参考《其他类型转为Number类型》章节 ```js 1 - true // 0, 首先把 true 转换为数字 1, 然后执行 1 - 1 1 - null // 1, 首先把 null 转换为数字 0, 然后执行 1 - 0 1 * undefined // NaN, undefined 转换为数字是 NaN ['5'] - true // 4 , ['5']变成5, true变成1 2 * ['5'] // 10, ['5']首先会变成 '5', 然后再变成数字 5 2 * [1,2,3] // NaN, [1,2,3]会先变成转成原始类型'1,2,3',然后再转成Number类型变成‘NaN’ ``` #### 加法 :star:**为什么加法要区别对待?因为JS里 +还可以用来拼接字符串。谨记以下3条:(优先级由高到低)** 1. 当一侧为`String`类型,被识别为**字符串拼接**,并会优先将另一侧转换为`字符串`类型。 2. 当一侧为`Number`类型,另一侧为`原始类型`,则将原始类型转换为`Number`类型。 3. 当一侧为`Number`类型,另一侧为`引用类型`,将引用类型和Number类型转换成`字符串`后拼接。 4. 当两侧不为`String`或`Number`, 将其转换成`字符串`后拼接。 ```js 123 + '123' // '123123' (规则1) 123 + null // 123 (规则2) 123 + true // 124 (规则2) 123 + {} // '123[object Object]' (规则3) [1,2,3] + '1' // '1,2,31' (规则1) ['1','2','3'] + '1' // '1,2,31' (规则1) [1, 2] + [2, 1] // '1,22,1' (规则4) 'a' + + 'b' // "aNaN" (规则1) // 因为相当于'a' + (+ 'b'), 而(+ 'b')相当于字符串转为number类型,结果为NaN,所以'a' + NaN = 'aNaN' ``` ### 逻辑语句中的类型转换 当我们使用 if while for 语句时,我们期望表达式是一个Boolean,所以一定伴随着隐式类型转换。而这里面又分为三种情况 #### 单个变量 :star:**如果只有单个变量,会先将变量转换为Boolean值。** 只有 `null, undefined, '', NaN, 0, false` 这几个是 `false`,其他的情况都是 true,比如 {} , []。 #### 比较运算符 1. 如果是对象,就通过 toPrimitive 转换对象 2. 如果是字符串,就通过 unicode 字符索引来比较 ```js console.log('a' < 'b') // true console.log([] < 'b') // true ``` #### 使用 == 比较中的5条规则 1. 规则 1:`NaN`和其他任何类型比较永远返回false(包括和他自己)。 ```js NaN == NaN // false ``` 2. 规则 2:Boolean 和其他任何类型比较,`Boolean` 首先被转换为 `Number` 类型。 ```js true == 1 // true true == '2' // false, 先把 true 变成 1,而不是把 '2' 变成 true true == ['1'] // true, 先把 true 变成 1, ['1']拆箱成 '1', 再参考规则3 true == ['2'] // false, 同上 undefined == false // false ,首先 false 变成 0,然后参考规则4 null == false // false,同上 ``` 3. 规则 3:String和Number比较,先将`String`转换为`Number`类型。 ```js 123 == '123' // true, '123' 会先变成 123 '' == 0 // true, '' 会首先变成 0 ``` 4. 规则 4:null == undefined比较结果是true,除此之外,null、undefined和其他任何结果的比较值都为false。 5. 规则 5: 原始类型和引用类型做比较时,`引用类型`会依照`ToPrimitive规则`转换为原始类型。 >ToPrimitive规则,是引用类型向原始类型转变的规则,它遵循先valueOf后toString的模式期望得到一个原始类型。 如果还是没法得到一个原始类型,就会抛出 `TypeError`。 ```js '[object Object]' == {} // true, 对象和字符串比较,对象通过 toString 得到一个基本类型值 '1,2,3' == [1, 2, 3] // true, 同上 [1, 2, 3]通过 toString 得到一个基本类型值 ``` 6. 规则 6: 类型相同时,没有类型转换,内存地址不同,则返回false。 ```js let a = [1,2,3] let a = [1,2,3] console.log(a == b) // false ``` ### 几道经典例题: 例题一: ```js var a = { valueOf: function () { return 1; }, toString: function () { return '123' } } true == a // true; // 首先,x与y类型不同,x为boolean类型,先转为number类型 1。 // 接着,x为number,y为object类型,对y进行原始转换,ToPrimitive(a, ?),没有指定转换类型,默认number类型。首先调用`valueOf`方法,返回1,得到原始类型1。 // 最后 1 == 1, 返回true。 ``` 例题二: ```js [] == !{} // true /** 1、! 运算符优先级高于==,故先进行!运算。 2、!{}运算结果为false(转Boolean类型,调用ToNumber()),结果变成 [] == false比较。 3、根据规则 2,将[]转成Number类型。结果变成 [] == 0。 4、按照规则5,比较变成ToPrimitive([]) == 0。 按照上面规则进行原始值转换,[]会先调用valueOf函数,返回this。 不是原始值,继续调用toString方法,x = [].toString() = ''。 故结果为 '' == 0比较。 5、根据规则 3,等式左边x = ToNumber('') = 0。 所以结果变为: 0 == 0,返回true,比较结束。 */ ``` 例题三: ```js const a = { i: 1, toString: function () { return a.i++; } } if (a == 1 && a == 2 && a == 3) { console.log('hello world!'); // 可以打印 } /** 1、当执行a == 1 && a == 2 && a == 3 时,会从左到右一步一步解析,首先 a == 1,根据规则5转换。ToPrimitive(a, Number) == 1。 2、ToPrimitive(a, Number),按照上面原始类型转换规则,会先调用valueOf方法,a的valueOf方法继承自Object.prototype。返回a本身,而非原始类型,故会调用toString方法。 3、因为toString被重写,所以会调用重写的toString方法,故返回1,注意这里是i++,而不是++i,它会先返回i,在将i+1。故ToPrimitive(a, Number) = 1。也就是1 == 1,此时i = 1 + 1 = 2。 4、执行完a == 1返回true,会执行a == 2,同理,会调用ToPrimitive(a, Number),同上先调用valueOf方法,在调用toString方法,由于第一步,i = 2此时,ToPrimitive(a, Number) = 2, 也就是2 == 2, 此时i = 2 + 1。 5、同上可以推导 a == 3也返回true。故最终结果 a == 1 && a == 2 && a == 3返回true */ ``` 例题四: ```js [undefined] == false // true /** * 1. 根据规则2, Boolean 首先被转换为 Number 类型。变成[undefined] == 0 * 2. 根据规则5, [undefined]转为原始类型。[undefined]先调用valueOf会返回本身,再调用toString()(undefined会被当成空字符串处理), 变成''。此时变成 '' == 0 * 3. 根据规则规则3, ''转为number类型为0.此时变成 0 == 0。所以结果为true * */ ``` ### `==,===,Object.is()`有什么区别? * === 叫做严格相等,是指:左右两边不仅值要相等,`类型`也要相等,例如'1'===1的结果是false,因为一边是string,另一边是number。 * == 不像 === 那样严格,对于一般情况,只要值相等,就返回true,但==还涉及一些`类型转换`,它的转换规则如下: * 两边的类型是否相同,相同的话就比较值的大小,例如1==2,返回false * 判断的是否是null和undefined,是的话就返回true * 判断的类型是否是String和Number,是的话,把String类型转换成Number,再进行比较 * 判断其中一方是否是Boolean,是的话就把Boolean转换成Number,再进行比较 * 如果其中一方为Object,且另一方为String、Number或者Symbol,会将Object转换成字符串,再进行比较 ```js console.log({a: 1} == true); // false console.log({a: 1} == "[object Object]"); // true ``` * 使用 `Object.is` 来进行相等判断时,一般情况下和三等号的判断相同,它处理了一些特殊的情况,比如 **-0 和 +0 不再相等,两个 NaN 是相等**的。 ## 显示类型转换 >参考链接:https://juejin.cn/post/6844903877175672845 JavaScript 中,强制类型转换主要是通过调用全局函数来实现的,例如 Number()、Boolean()、parseInt()、parseFloat() 等。 ### ToString ToString负责处理非字符串到字符串的强制类型转换,常用的字符串化方法`String()、toString()`。 #### `String()、toString()`的基本类型值的字符串化规则: * `null`转换为'null' * `undefined`转换为'undefined' * `true`转化为'true' * `数字`的字符串化遵循通用规则,极大值或者极小值采用科学计数法表示 * `普通对象`在字符串化时,实际执行Object.prototype.toString(),返回该对象的类型[object type] ```js var test = {a : 'test'} console.log(test.toString()) // '[object Object]' console.log(String(test)) // '[object Object]' ``` * 但是当`对象有自己的toString方法`时,字符串化时就会调用该方法并返回该方法的返回值 ```js var obj = { a: 'test', toString: function () { return 1 } } console.log(obj.toString()) // 1 console.log(String(obj)) // 1 ``` * 数组在做字符串化时,将数组所有元素字符串化再用`,`连接。 ```js var arr = [1, 2, 3] console.log(arr.toString()) // '1,2,3' console.log(String(arr)) // '1,2,3' ``` #### JSON.stringify() * JSON.stringify()在将JSON对象序列化为字符串时,也涉及到了字符串化的相关规则。 对大多数简单值来说,JSON字符串化和`toString()的效果基本相同`。 ```js console.log(JSON.stringify("test")) // ""test"" console.log(JSON.stringify(1)) // "1" console.log(JSON.stringify(null)) // "null" ``` * 但是JSON.stringify()在对象中遇到function() {}、undefined、Symbol时会自动将其`忽略`,在数组中则会返回`null` ```js var obj1 = { a: undefined, b: function () {}, c: Symbol() } console.log(JSON.stringify(obj1)) // "{}" console.log(JSON.stringify([undefined, function () {}, 1])) // "[null, mull, 1]" ``` * 当对象执行JSON.stringify()方法时,如果对象中存在`toJSON方法`,用它的返回值来进行序列化 ```js var obj2 = { a: undefined, b: function () {}, c: Symbol(), toJSON: function () { return {a: 'replace'} } } console.log(JSON.stringify(obj2)) // "{"a":"replace"}" ``` ### ToNumber ToNumber负责将非数字转化为数字,`Number()、parseInt()和parseFloat()`都可以将非数字转化为数字。 规则同 *《其他类型转为Number类型》* 章节 ### ToBoolean 只有`null,undefined,0,false,NaN,空字符串`这6种情况转为布尔值结果为`false`,其余全部为true。 常用于转化为布尔类型的方法有`Boolean()`或者`!!` ## 附录:类型转换表 <img src='./picture/convert-table.png'/>
Markdown
UTF-8
2,716
3.21875
3
[ "MIT" ]
permissive
# Logging [TOC] ### Motivation The logging module, just like error-and-exception-util, is an infrastructure of the entire lib. This module offers you an uniform and succinct interface to log messages, in different severity level (e.g. `INFO`, `WARNING` etc.), to specified destination (`stderr` or a file). ### DLOG/LOG macro The general syntax for using this facility is ``` c++ #include "kbase/logging.h" // Configurate logging with default settings. kbase::ConfigureLoggingSettings(kbase::LoggingSettings()); LOG(INFO) << "something happend"; LOG(ERROR) << "something goes wrong"; LOG_IF(WARNING, result != true) << "the expression doesn't evaluate to true!"; ``` `DLOG` is same as `LOG` but only enabled in DEBUG mode. A log message with the most detailed header looks like: > [20160127 01:27:07,416 INFO logging_unittest.cpp(80)]something happend. ### Severity Levels As you can see from the sample above, `logging` supports the hierarchy of severity levels, providing a convenient approach to distinct log messages in different severity levels. You can also set up a **minimum severity level**, any log message that has lower severity level will be simply ignored and discarded. Doing that by calling `ConfigureLoggingSettings`. See next section. ### Configure Logging Settings For being flexible, `logging` allows you to configure its settings to meet your needs. Configurable settings include: - minimum severity level - message header parameters - logging destination - how to dispose(replace or append) an old file if logging to it - specify logging file name/path Generally, you should configurate these settings at the start of the program, because calling the configuration function is **not thread-safe**. class `LoggingSettings` contains setting information, and its default constructor uses default settings too. Note that, if you didn't call `ConfigureLoggingSettings()` at the start, default settings are employed; However, if you also want logging to file, there will be a race condition in creation of the file. Therefore, again, **you are supposed to call `ConfigureLoggingSettings()` at the start of the program**. ### Some Details About Logging To File If it being the case, it's better for you to know some details. Logging to the file is **not only thread-safe but also process-safe**. Thanks to Windows kernel. As for the file name, if you didn't specify one, `logging` first tries to use the name like `[your-exe-name]_debug_message.log`, and put the file in the same folder that contains the executable; If this fails, it then tries to put the file in the current working directory. If both trials failed, `logging` automatically skips file writting.
Java
UTF-8
3,706
3.203125
3
[]
no_license
package net.avax.findunusedint; // From Programming Pearls, Second Edition, by Jon Bentley, Addison-Wesley, // Inc., 2000, ISBN 0-201-65788-0: // // Given a sequential file that contains at most four billion integers in // random order, find a 32-bit integer that isn't in the file (and there must // be at least one missing--why?). How would you solve this problem with ample // quantities of main memory? How would you solve it if you could use several // external "scratch" files but only a few hundred bytes of main memory? import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.Scanner; public class Main { private static final long COUNT_MAX = 4000000000L; private static final int INPUT_BITS = 32; private static final long INPUT_SIZE = 1L << INPUT_BITS; private static final int INPUT_BITS_PER_BIT_SET = 28; private static final long BIT_SET_SIZE = 1L << INPUT_BITS_PER_BIT_SET; private static final int BIT_SET_COUNT = (int) (INPUT_SIZE / BIT_SET_SIZE); private static BitSet activeBitSet = null; private static int activeBitSetNum = -1; private static List<Path> bitSetPaths = null; private static void saveActiveBitSet() throws IOException { try (ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream( bitSetPaths.get(activeBitSetNum).toFile()))) { oos.writeObject(activeBitSet); } } private static void activateBitSet(int bitSetNum) throws IOException, ClassNotFoundException { if (bitSetNum == activeBitSetNum) { return; } saveActiveBitSet(); try (ObjectInputStream ois = new ObjectInputStream( new FileInputStream( bitSetPaths.get(bitSetNum).toFile()))) { activeBitSet = (BitSet) ois.readObject(); } activeBitSetNum = bitSetNum; } private static void recordUsedInt(long n) throws IOException, ClassNotFoundException { int bitSetNum = (int) (n / BIT_SET_SIZE); int bitNum = (int) (n % BIT_SET_SIZE); activateBitSet(bitSetNum); activeBitSet.set(bitNum); } private static long findLowestUnusedInt() throws IOException, ClassNotFoundException { for (int bitSetNum = 0; bitSetNum < bitSetPaths.size(); bitSetNum++) { activateBitSet(bitSetNum); int clearBit = activeBitSet.nextClearBit(0); if (clearBit >= 0) { return bitSetNum * BIT_SET_SIZE + clearBit; } } return -1; } public static void main(String[] args) throws IOException, ClassNotFoundException { bitSetPaths = new ArrayList<>(); for (int bitSetNum = 0; bitSetNum < BIT_SET_COUNT; bitSetNum++) { Path path = Files.createTempFile("find-unused-int-", ".tmp"); path.toFile().deleteOnExit(); bitSetPaths.add(path); activeBitSet = new BitSet(); activeBitSetNum = bitSetNum; saveActiveBitSet(); } long n; long count = 0; Scanner sc = new Scanner(System.in); while (sc.hasNextLong() && (n = sc.nextLong()) >= 0 && n < INPUT_SIZE && count < COUNT_MAX) { recordUsedInt(n); count++; } System.out.println("Read " + count + " " + INPUT_BITS + "-bit unsigned integer(s)."); n = findLowestUnusedInt(); System.out.println(n + " is the lowest unused integer."); } }
C
UTF-8
846
3.375
3
[ "MIT" ]
permissive
#include <stdlib.h> #include "d_array.h" array_t *array_new() { array_t *array = malloc(sizeof(array_t)); array->length = 0; array->free = NULL; array->capacity = DEFAULT_STARTING_CAPACITY; array->data = malloc(array->capacity * sizeof(void *)); return array; } void array_add(array_t *array, void *element) { if (array->length >= array->capacity) { array->capacity *= DEFAULT_GROW_FACTOR; array->data = realloc(array->data, array->capacity * sizeof(void *)); } array->data[array->length++] = element; } void *array_get(array_t *array, size_t index) { if (index <= array->length) { return array->data[index]; } return NULL; } void array_destroy(array_t *array) { if (array->free != NULL) { while (array->length > 0) { array->free(array->data[--array->length]); } } free(array->data); free(array); }
C++
UTF-8
2,998
2.890625
3
[]
no_license
//作者:邓智豪 #include "gene.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> #include <time.h> Gene bestGene; void freeGene( Gene gene ){ free( gene.genes ); } void freePopulation( Population population ){ for( int i = population.populationSize - 1; i >= 0; --i ){ free( population.individuals[i].genes ); } free( population.individuals ); } void printGene( Gene gene ){ for( int i = 0; i < gene.geneLength; i++ ){ printf("%d", gene.genes[i] ); } printf("\n"); } void printPopulation( Population population ){ int populationSize = population.populationSize; for( int i = populationSize - 1; i >= 0; --i ){ printGene( population.individuals[i] ); } } // 根据问题描述生成指定大小的新种群 Population newPopulation( int populationSize, DescribeTable table ){ srand( time( NULL ) ); const int componentCount = table.componentCount; Population population; int geneLength = 0; int jobCount; int geneIndex; for( int i = 0; i < componentCount; i++ ){ //计算基因长度 geneLength += table.components[i].jobCount; } population.individuals = (Gene*)malloc( sizeof( Gene ) * populationSize ); population.populationSize = populationSize; for( int i = 0; i < populationSize; i++ ){ //遍历个体 population.individuals[i].genes = (ComponentIndex*)malloc( sizeof( ComponentIndex ) * geneLength ); population.individuals[i].geneLength = geneLength; memset( population.individuals[i].genes, -1, geneLength * sizeof( ComponentIndex ) ); for( int j = 0; j < componentCount; j++ ){ //遍历组件 jobCount = table.components[j].jobCount; for( int _ = 0; _ < jobCount; _++ ){ //遍历工序 geneIndex = rand() % geneLength; //先随机生成 while( population.individuals[i].genes[geneIndex] != -1 ){ //直到是空 ++geneIndex; //否则循环遍历 if( geneIndex >= geneLength ){ geneIndex = 0; } } population.individuals[i].genes[geneIndex] = j; //填写基因 } } } return population; } int sortGene( Gene a, Gene b ){ return a.timeSpan < b.timeSpan; } void sortGenes( Gene* genes, int size ){ std::sort( genes, genes + size, sortGene ); } void selectPopulation( Population p1, Population p2 ){ Gene* tmp = (Gene*)malloc( sizeof( Gene ) * ( p1.populationSize + p2.populationSize ) ); //printPopulation( p1 ); for( int i = 0; i < p1.populationSize; i++ ){ tmp[i] = p1.individuals[i]; } for( int i = 0; i < p2.populationSize; i++ ){ tmp[i + p1.populationSize] = p2.individuals[i]; } // 按照适应度排序 sortGenes( tmp, p1.populationSize + p2.populationSize ); // 选出最优的 for( int i = 0; i < p1.populationSize; i++ ){ p1.individuals[i] = tmp[i]; } for( int i = 0; i < p2.populationSize; i++ ){ p2.individuals[i] = tmp[i + p1.populationSize]; } free( tmp ); }
Swift
UTF-8
2,295
2.734375
3
[]
no_license
// // Netdata.swift // cnbetazixun // // Created by 尤献利 on 16/1/13. // Copyright © 2016年 尤献利. All rights reserved. // //获取首页新闻 //https://cnbeta1.com/api/getArticles //获取更多新闻 //https://cnbeta1.com/api/getMoreArticles/{fromArticleID} {fromArticleID}是上次获取的最后一条新闻的ID //获取新闻详情 //https://cnbeta1.com/api/getArticleDetail/{ArticleID} {ArticleID}是新闻的ID import UIKit class Netdate: NSObject { var m_CnbetaUrl = "https://cnbeta1.com/api/" func netCnbeta(article:String,completion:(([CnbetaObject]?)->Void)){ m_CnbetaUrl += article // print(m_CnbetaUrl) let url = NSURL(string: m_CnbetaUrl) let config = NSURLSessionConfiguration.defaultSessionConfiguration() let urlsession = NSURLSession(configuration: config) let task = urlsession.dataTaskWithURL(url!) { (data, _, error) -> Void in if error != nil{ print("error!.userInfo:\(error!.userInfo)") }else{ do{ let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [NSDictionary] let m_json_Dic = json!.map({ (danarray:NSDictionary) -> CnbetaObject in var newitem = ["article_id" : danarray["article_id"] as! String] newitem["title"] = danarray["title"] as? String newitem["Description"] = danarray["intro"] as? String newitem["img"] = danarray["topic"] as? String // newitem["readed"] = "false" // print("newitem:\(newitem)") return CnbetaObject(dict: newitem) }) // print("m_json_Dic:\(m_json_Dic[0].m_Description!)") dispatch_sync(dispatch_get_main_queue(), { () -> Void in completion(m_json_Dic) print("获取完成!!!!!!!!!!") }) }catch { print("error:\(error)") } } } task.resume() } }
Markdown
UTF-8
44,327
3.0625
3
[]
no_license
# Kaggle_House_Prices_Analysis My R markdown for the Housing Prices Kaggle competition. --- title: "Housing_Competition" author: "Mitchell O'Brien" date: "July 27, 2018" output: html_document: keep_md: true --- ```{r setup, include=FALSE, cache=TRUE} knitr::opts_chunk$set(echo = TRUE) ``` #Introduction Ask a home buyer to describe their dream house, and they probably won't begin with the height of the basement ceiling or the proximity to an east-west railroad. But this playground competition's dataset proves that much more influences price negotiations than the number of bedrooms or a white-picket fence. With 79 explanatory variables describing (almost) every aspect of residential homes in Ames, Iowa, this competition challenges you to predict the final price of each home. #Foreword on my Analysis This is my first Kaggle competition. A lot of decisions I made, and procedures I followed were based on the book Applied Predictive Modeling. As I progressed in my analysis, it became apparent that decisions I made in coding, were not efficient. For example, at the beginning, I kept the training set and test set completely separate. Other competitors made note of which were training and which were test before combining them into one data frame. There were other instances similar to this one, where my code was somewhat inefficient. However, it provided a learning experience for the next data set I analyze. ```{r, include=FALSE} library(plyr) library(dplyr) library(ggplot2) library(car) library(caret) library(e1071) library(gridExtra) library(readr) setwd("C:/Users/Mitchell/Desktop/Summer Projects/Housing Project") train<-read.csv("train.csv", header = TRUE, stringsAsFactors = F) test<-read.csv("test.csv", header = TRUE, stringsAsFactors = F) ``` #Data Cleaning and Variable Coding I started this competition by thoroughly reading the data description and becoming familiar with what each variable represented. The goal was to become acquainted with how the data was coded and any possible issues in my analysis. Next, I was curious about how many missing values or NA's I had in the data set. I found that there were a few variables with many missing values. To investigate, I checked the data data description for added information on the troubling variables. The problem was that the csv was written with "NA" being used as none. For example the variable PoolQC had 1453 missing values. Reason being, that a lot of the homes didn't have a pool, so they were entered as NA. I had to change each similar variable to something other than NA. ```{r} sort(apply(train, 2, function(x){sum(is.na(x))}), decreasing = TRUE) sort(apply(test, 2, function(x){sum(is.na(x))}), decreasing = TRUE) ``` ##MSSubClass MSSubClass is a factor variable. However, the way it was entered into the csv is problematic. A number is used to represent a category. I changed this to match the data description. ```{r} train$MSSubClass<-as.factor(train$MSSubClass) train$MSSubClass<-revalue(train$MSSubClass, c("20"="1-STORY 1946 & NEWER ALL STYLES", "30"="1-STORY 1945 & OLDER", "40"="1-STORY W/FINISHED ATTIC ALL AGES", "45"="1-1/2 STORY - UNFINISHED ALL AGES", "50"="1-1/2 STORY FINISHED ALL AGES", "60"="2-STORY 1946 & NEWER", "70"="2-STORY 1945 & OLDER", "75"="2-1/2 STORY ALL AGES", "80"="SPLIT OR MULTI-LEVEL", "85"="SPLIT FOYER", "90"="DUPLEX - ALL STYLES AND AGES", "120"="1-STORY PUD (Planned Unit Development) - 1946 & NEWER", "150"="1-1/2 STORY PUD - ALL AGES", "160"="2-STORY PUD - 1946 & NEWER", "180"="PUD - MULTILEVEL - INCL SPLIT LEV/FOYER", "190"="2 FAMILY CONVERSION - ALL STYLES AND AGES")) test$MSSubClass<-as.factor(test$MSSubClass) test$MSSubClass<-revalue(test$MSSubClass, c("20"="1-STORY 1946 & NEWER ALL STYLES", "30"="1-STORY 1945 & OLDER", "40"="1-STORY W/FINISHED ATTIC ALL AGES", "45"="1-1/2 STORY - UNFINISHED ALL AGES", "50"="1-1/2 STORY FINISHED ALL AGES", "60"="2-STORY 1946 & NEWER", "70"="2-STORY 1945 & OLDER", "75"="2-1/2 STORY ALL AGES", "80"="SPLIT OR MULTI-LEVEL", "85"="SPLIT FOYER", "90"="DUPLEX - ALL STYLES AND AGES", "120"="1-STORY PUD (Planned Unit Development) - 1946 & NEWER", "150"="1-1/2 STORY PUD - ALL AGES", "160"="2-STORY PUD - 1946 & NEWER", "180"="PUD - MULTILEVEL - INCL SPLIT LEV/FOYER", "190"="2 FAMILY CONVERSION - ALL STYLES AND AGES")) ``` ##MSZoning I made MSZoning a factor variable and dealt with the missing value. ```{r} train$MSZoning[is.na(train$MSZoning)]<-"Undefined" test$MSZoning[is.na(test$MSZoning)]<-"Undefined" train$MSZoning<-as.factor(train$MSZoning) test$MSZoning<-as.factor(test$MSZoning) ``` ##LotFrontage LotFrontage has 259 missing values. One way to handle this would be to omit each observation with a missing value for LotFrontage. However, a lot of information would be lost if I chose this path. Instead, I imputed the mean LotFrontage for each missing value. ```{r} train$LotFrontage<-ifelse(is.na(train$LotFrontage), mean(train$LotFrontage, na.rm=TRUE), train$LotFrontage) test$LotFrontage<-ifelse(is.na(test$LotFrontage), mean(test$LotFrontage, na.rm=TRUE), test$LotFrontage) ``` ##Street I made Street a factor variable. Due to the difference in the count for Grvl and Pave, I figured Street would get thrown out later during modeling. But, I thought best to keep it for now. ```{r} train%>% group_by(Street)%>% summarise(n = n()) train$Street<-as.factor(train$Street) test$Street<-as.factor(test$Street) ``` ##Alley Alley was one of the variables that had NA entered when the intention was no alley. There were1 369 missing values. I recoded, and made alley a factor variable. I was curious if different levels of Alley yielded different SalePrices. It appears that Paved and no Alley had higher average SalePrices than Grvl. I found it interesting to look into, but likely not a strong influence on SalePrice. ```{r} train$Alley[is.na(train$Alley)]<-"no" train$Alley<-as.factor(train$Alley) test$Alley[is.na(test$Alley)]<-"no" test$Alley<-as.factor(test$Alley) ggplot(train, aes(Alley, SalePrice))+ geom_point()+ geom_point(stat = "summary", fun.y = "mean", size = 6, col = "red")+ ggtitle("SalePrice by Alley")+ theme(plot.title = element_text(hjust = .5)) ``` ##LotShape I made LotShape a factor variable. ```{r} train$LotShape<-as.factor(train$LotShape) test$LotShape<-as.factor(test$LotShape) ``` ##LandContour I made LandContour a factor variable. ```{r} train$LandContour<-as.factor(train$LandContour) test$LandContour<-as.factor(test$LandContour) ``` ##Utilities Since there was near zero variance in Utilities, no information is provided by this variable. I decided to drop Utilities from my analysis. ```{r} table(train$Utilities) table(test$Utilities) train$Utilities<-NULL test$Utilities<-NULL ``` ##LotConfiguration I made LotConfiguration a factor variable. ```{r} train$LotConfig<-as.factor(train$LotConfig) test$LotConfig<-as.factor(test$LotConfig) ``` ##LandSlope To me, LandSlope has a ranking of it's categories. Thus, I made LandSlope as an ordinal variable by coding it as an integer. ```{r} train$LandSlope<-as.integer(revalue(train$LandSlope, c(Gtl=0, Mod=1, Sev=2))) test$LandSlope<-as.integer(revalue(test$LandSlope, c(Gtl=0, Mod=1, Sev=2))) ``` ##Neighborhood I decided that Neighborhood is a factor variable. I guessed that Neighborhood has a great influence on SalePrice. I held off on investigating until the exploratory analysis part. ```{r} train$Neighborhood<-as.factor(train$Neighborhood) test$Neighborhood<-as.factor(test$Neighborhood) ``` ##Condition1 and Condition2 I decided that both Condition1 and Condition2 are factor variables. ```{r} train$Condition1<-as.factor(train$Condition1) test$Condition1<-as.factor(test$Condition1) train$Condition2<-as.factor(train$Condition2) test$Condition2<-as.factor(test$Condition2) ``` ##BldgType I went back and forth on making this variable a factor or ordinal. There is a degree of ranking among the categories. But, in the end, I decided to make it a factor. Perhaps I could go back, make it ordinal, and check if my model performs better in a later analysis. ```{r} train$BldgType<-as.factor(train$BldgType) test$BldgType<-as.factor(test$BldgType) ``` ##HouseStyle Similar to BldgType, there is a degree of ranking among the categories. However the rankings were necessarily clear, so I decided to make HouseStyle a factor variable. ```{r} train$HouseStyle<-as.factor(train$HouseStyle) test$HouseStyle<-as.factor(test$HouseStyle) ``` ##OverallQual and OverallCond OverallQual and OverallCond are clearly a ordinal variables. They are already coded as integers, so I did not need to change anything about them. ##YearBuilt and YearRemodAdd YearBuilt and YearRemodAdd were already coded as integers, so there was nothing for me to change. ##RoofStyle I decided that RoofStyle would be a factor variable. ```{r} train$RoofStyle<-as.factor(train$RoofStyle) test$RoofStyle<-as.factor(test$RoofStyle) ``` ##RoofMat1 I decided that RoofStyle would be a factor variable. ```{r} train$RoofMatl<-as.factor(train$RoofMatl) test$RoofMatl<-as.factor(test$RoofMatl) ``` ##Exterior1st and Exterior2nd I decided to make Exterior1st and Exterior2nd factor variables. There were missing values in the test set though that needed to be addressed first. ```{r} #Exterior1st is factor test$Exterior1st[is.na(test$Exterior1st)]<-"Undefined" train$Exterior1st<-as.factor(train$Exterior1st) test$Exterior1st<-as.factor(test$Exterior1st) #Exterior2nd is factor test$Exterior2nd[is.na(test$Exterior2nd)]<-"Undefined" train$Exterior2nd<-as.factor(train$Exterior1st) test$Exterior2nd<-as.factor(test$Exterior2nd) ``` ##MasVnrType As with other variables in this dataset, the lack of MasVnrType was coded as NA. I changed this to "no" so no problems arise. After the change, I made MasVnrType a factor variable. ```{r} train$MasVnrType[is.na(train$MasVnrType)]<-"no" train$MasVnrType<-as.factor(train$MasVnrType) test$MasVnrType[is.na(test$MasVnrType)]<-"no" test$MasVnrType<-as.factor(test$MasVnrType) ``` ##MasVnrArea There were a few missing values in MasVnrArea. I decided to impute the mean for each of these. A more careful approach would be to check what the value of MasVnrType was and enter 0 for Area when Type is "no". ```{r} train$MasVnrArea<-ifelse(is.na(train$MasVnrArea), mean(train$MasVnrArea, na.rm = TRUE), train$MasVnrArea) test$MasVnrArea<-ifelse(is.na(test$MasVnrArea), mean(test$MasVnrArea, na.rm = TRUE), test$MasVnrArea) ``` ##Exterior Quality and Condition Both are clearly ordinal. ```{r} train$ExterQual<-as.integer(revalue(train$ExterQual, c("Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) test$ExterQual<-as.integer(revalue(test$ExterQual, c("Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) train$ExterCond<-as.integer(revalue(train$ExterCond, c("Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) test$ExterCond<-as.integer(revalue(test$ExterCond, c("Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) ``` ##Foundation I made foundation a factor variable. ```{r} train$Foundation<-as.factor(train$Foundation) test$Foundation<-as.factor(test$Foundation) ``` ##BsmtQual Similar to other Basement variables, I had to change the way no basement was coded. I made BsmtQual ordinal since the was a ranking to the categories. Intuitively, I thought that having a nice basement would have an impact on SalePrice. To test my intuition, I created a plot with the mean filled in red. There appeared not to be a huge difference in SalePrice of homes with no basement, a poor basement, or a typical basement. However, there is a jump from typical to good, and an even bigger jump from good to excellent. I included counts for added information. ```{r} train$BsmtQual[is.na(train$BsmtQual)]<-"no" test$BsmtQual[is.na(test$BsmtQual)]<-"no" train$BsmtQual<-as.integer(revalue(train$BsmtQual,c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) test$BsmtQual<-as.integer(revalue(test$BsmtQual, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) ggplot(train, aes(BsmtQual, SalePrice))+ geom_point()+ geom_point(stat = "summary", fun.y = "mean", size = 6, col = "red")+ geom_text(stat = "count", aes(label = ..count..), y = 700000, col = "blue" )+ ggtitle("SalePrice by BsmtQual")+ theme(plot.title = element_text(hjust = .5)) ``` ##BsmtCond I had to change the coding of no basement. After that, I made BsmtCond an ordinal variable. As with BsmtQual, I wanted to further investigate. It appeared the overwhelming number of basements have a condition score 3 with a count of 1311. I noticed a dip in price from no basement to poor basement, but, that is because of the small number of observations for poor basements. Other than that, higher condition basements receive a higher average SalePrice. Exactly what one would expect. ```{r} train$BsmtCond[is.na(train$BsmtCond)]<-"no" #train$BsmtCond<-as.factor(train$BsmtCond) test$BsmtCond[is.na(test$BsmtCond)]<-"no" #test$BsmtCond<-as.factor(test$BsmtCond) train$BsmtCond<-as.integer(revalue(train$BsmtCond,c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) test$BsmtCond<-as.integer(revalue(test$BsmtCond, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) ggplot(train, aes(BsmtCond, SalePrice))+ geom_point()+ geom_point(stat = "summary", fun.y = "mean", size = 6, col = "red")+ geom_text(stat = "count", aes(label = ..count..), y = 700000, col = "blue" )+ ggtitle("SalePrice by BsmtCond")+ theme(plot.title = element_text(hjust = .5)) ``` ##BsmtExposure BsmtExposure could have been an ordinal variable. But, for simplicity, I made it a factor variable. I was curious about how Exposure might impact SalePrice. I found that SalePrice increases with the degree of BsmtExposure. ```{r} train$BsmtExposure[is.na(train$BsmtExposure)]<-"nope" train$BsmtExposure<-as.factor(train$BsmtExposure) test$BsmtExposure[is.na(test$BsmtExposure)]<-"nope" test$BsmtExposure<-is.factor(test$BsmtExposure) ggplot(train, aes(reorder(BsmtExposure, SalePrice), SalePrice))+ geom_boxplot()+ geom_point(stat = "summary", fun.y = "mean", size = 4, col = "red")+ ggtitle("SalePrice by BsmtExposure")+ xlab("BsmtExposure")+ theme(plot.title = element_text(hjust = .5)) ``` ##BsmtFinType1 and BsmtFinType2 I fixed the coding issues, and then made both variables ordinal. ```{r} finish<-c("no"=0, "Unf"=1, "LwQ"=2, "Rec"=3, "BLQ"=4, "ALQ"=5, "GLQ"=6) train$BsmtFinType1[is.na(train$BsmtFinType1)]<-"no" #train$BsmtFinType1<-as.factor(train$BsmtFinType1) test$BsmtFinType1[is.na(test$BsmtFinType1)]<-"no" #test$BsmtFinType1<-as.factor(test$BsmtFinType1) train$BsmtFinType1<-as.integer(revalue(train$BsmtFinType1, finish)) test$BsmtFinType1<-as.integer(revalue(test$BsmtFinType1, finish)) ``` ##BsmtSF There were a few missing values for square feet in the test set. I made sure that when a home did not have a basement, the square feet was entered as 0. ```{r} #BsmtFinSF1 test$BsmtFinSF1[is.na(test$BsmtFinSF1)]<-0 #BsmtFinSF2 test$BsmtFinSF2[is.na(test$BsmtFinSF2)]<-0 #BsmtUnfSF test$BsmtUnfSF[is.na(test$BsmtUnfSF)]<-0 #TotalBsmtSF test$TotalBsmtSF[is.na(test$TotalBsmtSF)]<-0 ``` ##Heating Heating is a factor variable ```{r} train$Heating<-as.factor(train$Heating) test$Heating<-as.factor(test$Heating) ``` ##Heating QC Heating QC is an ordinal variable. ```{r} train$HeatingQC<-as.integer(revalue(train$HeatingQC,c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) test$HeatingQC<-as.integer(revalue(test$HeatingQC,c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) ``` ##Central Air Central Air is a factor ```{r} train$CentralAir<-as.factor(train$CentralAir) test$CentralAir<-as.factor(test$CentralAir) ``` ##Electrical Electrical is a factor. There was a missing value in the training set. ```{r} #Electrical is factor train$Electrical[is.na(train$Electrical)]<-"Undefined" train$Electrical<-as.factor(train$Electrical) test$Electrical<-as.factor(test$Electrical) ``` ##1st and 2nd Floor SF Neither variable had any missing values and both were already coded as integers so I did not have to do anything here. ##LowQualFinSF No missing values. Already an integer. ##GrLivArea No missing values. Already an integer. ##Bsmt Bathrooms There were some missing values for these two variables. The missing observations seemed to correspond with homes with no basement. Thus, I replaced NA with 0. ```{r} #BsmtFullBath train$BsmtFullBath[is.na(train$BsmtFullBath)]<-0 test$BsmtFullBath[is.na(test$BsmtFullBath)]<-0 #BsmtHalfBath train$BsmtHalfBath[is.na(train$BsmtHalfBath)]<-0 test$BsmtHalfBath[is.na(test$BsmtHalfBath)]<-0 ``` ##BedroomAbvGr I left this variable as an integer. I wanted to investigate the impact on SalePrice. Due to unbalanced number of observations, it was difficult to establish a clear pattern. There does seem to be a positive relationship between BedroomAbvGr and SalePrice for Bedrooms 2,3, and 4. In a later version, I will bin the bedrooms with a small number of observations. It seemed to me like this variable would be highly correlated with other predictors such as total rooms above ground. I will deal with multicollinearity later in the analysis. ```{r} ggplot(train, aes(as.factor(BedroomAbvGr), SalePrice))+ geom_boxplot(col = "blue")+ geom_text(stat = "count", aes(label = ..count..),y = 700000)+ ggtitle("SalePrice by BedroomAbvGr")+ xlab("BedroomAbvGr")+ theme(plot.title = element_text(hjust = .5)) cor(train$BedroomAbvGr, train$TotRmsAbvGrd) ``` ##Kitchen Kitchen was already coded as an integer. ##KitchenQual KitchenQual is an ordinal variable. There were missing values in the test set that I had to fix. I have always heard how important the kitchen is in selling a home. I wanted to test this by looking at the distribution of SalePrice across KitchenQual. As suspected, SalePrice goes up with KitchenQual. ```{r} test$KitchenQual[is.na(test$KitchenQual)]<-"no" train$KitchenQual<-as.integer(revalue(train$KitchenQual,c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) test$KitchenQual<-as.integer(revalue(test$KitchenQual, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) ggplot(train, aes(as.factor(KitchenQual), SalePrice))+ geom_boxplot(col = "blue")+ ggtitle("SalePrice by KitchenQual")+ xlab("KitchenQual")+ theme(plot.title = element_text(hjust = .5)) ggplot(train, aes(SalePrice, fill = as.factor(KitchenQual)))+ geom_histogram()+ ggtitle("SalePrice by KitchenQual")+ theme(plot.title = element_text(hjust = .5))+ guides(fill = guide_legend(title = "KitchenQual")) ``` ##TotRmsAbvGrd TotRmsAbvGrd was already an integer. ##Functional Functional had missing values in the test set that I had to deal with. I made Functional a factor variable. ```{r} test$Functional[is.na(test$Functional)]<-"Undefined" train$Functional<-as.factor(train$Functional) test$Functional<-as.factor(test$Functional) ``` ##Fireplaces An integer variable. ##FireplaceQu I fixed the missing value issue then made FireplaceQu an ordinal variable. ```{r} train$FireplaceQu[is.na(train$FireplaceQu)]<-"no" #train$FireplaceQu<-as.factor(train$FireplaceQu) test$FireplaceQu[is.na(test$FireplaceQu)]<-"no" #test$FireplaceQu<-as.factor(test$FireplaceQu) train$FireplaceQu<-as.integer(revalue(train$FireplaceQu, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) test$FireplaceQu<-as.integer(revalue(test$FireplaceQu, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) ``` ##GarageType I fixed the missing values then made GarageType a factor variable. I further looked into Garage Type and found that the average SalePrice was most for Attached and Built in garages. This makes sense, as one would see these in nicer homes. Detached would yield less money. A possible explanation is people would not want to walk to their garage in the cold during the winter months. Thus, Attached and Built in are more expensive more money. ```{r} train$GarageType[is.na(train$GarageType)]<-"no" train$GarageType<-as.factor(train$GarageType) test$GarageType[is.na(test$GarageType)]<-"no" test$GarageType<-as.factor(test$GarageType) ggplot(train, aes(reorder(GarageType,SalePrice), SalePrice))+ geom_point()+ geom_point(stat = "summary", fun.y = "mean", size = 6, col = "red")+ geom_text(stat = "count", aes(label = ..count..), y = 700000, col = "blue")+ ggtitle("SalePrice by GarageType")+ xlab("GarageType")+ theme(plot.title = element_text(hjust = .5)) ``` ##GarageYrBlt To fix the missing values for GarageYrBlt, I observed the relationship between GarageYrBlt and YearBlt. I figured that in general, people had their garage built at the same time as their home. Therefore, I thought analyzing YearBlt was a reasonable thing to do. With a $r=.85$, I felt that imputing YearBlt for GarageYrBlt was the best avenue to take in correcting missing values. I checked other variables for a stronger correlation, but none were as strong as YearBlt. ```{r} ggplot(train, aes(GarageYrBlt, YearBuilt))+ geom_point()+ geom_smooth(method = "lm", se = FALSE) ggplot(train, aes(GarageYrBlt, YearRemodAdd))+ geom_point()+ geom_smooth(method = "lm", se = FALSE) ggplot(train, aes(GarageYrBlt, YrSold))+ geom_point()+ geom_smooth(method = "lm", se = FALSE) train$GarageYrBlt[is.na(train$GarageYrBlt)]<-train$YearBuilt[is.na(train$GarageYrBlt)] test$GarageYrBlt[is.na(test$GarageYrBlt)]<-test$YearBuilt[is.na(test$GarageYrBlt)] ``` ##GarageFinish I made GarageFinish ordinal. ```{r} train$GarageFinish[is.na(train$GarageFinish)]<-"no" #train$GarageFinish<-as.factor(train$GarageFinish) test$GarageFinish[is.na(test$GarageFinish)]<-"no" #test$GarageFinish<-as.factor(test$GarageFinish) train$GarageFinish<-as.integer(revalue(train$GarageFinish, c("no"=0, "Unf"=1, "RFn"=2, "Fin"=3))) test$GarageFinish<-as.integer(revalue(test$GarageFinish, c("no"=0, "Unf"=1, "RFn"=2, "Fin"=3))) ``` ##GarageCars GarageCars is an integer variable. ```{r} #Garage Cars test$GarageCars[is.na(test$GarageCars)]<-0 ``` ##GarageArea GarageArea is an integer variable. ```{r} #Garage Area test$GarageArea[is.na(test$GarageArea)]<-0 ``` ##GarageQual An ordinal variable. ```{r} train$GarageQual[is.na(train$GarageQual)]<-"no" #train$GarageQual<-as.factor(train$GarageQual) test$GarageQual[is.na(test$GarageQual)]<-"no" #test$GarageQual<-as.factor(test$GarageQual) train$GarageQual<-as.integer(revalue(train$GarageQual, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) test$GarageQual<-as.integer(revalue(test$GarageQual, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) ``` ##GarageCond An ordinal variable. ```{r} train$GarageCond[is.na(train$GarageCond)]<-"no" #train$GarageCond<-as.factor(train$GarageCond) test$GarageCond[is.na(test$GarageCond)]<-"no" #test$GarageCond<-as.factor(test$GarageCond) train$GarageCond<-as.integer(revalue(train$GarageCond, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) test$GarageCond<-as.integer(revalue(test$GarageCond, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) ``` ##Paved Driveway A factor variable. ```{r} train$PavedDrive<-as.factor(train$PavedDrive) test$PavedDrive<-as.factor(test$PavedDrive) ``` ##WoodDeckSF An integer variable. ##Porch Variables OpenPorchSF, EnclosedPorch, ScreenPorch, and 3SsnPorch are integer variables. ##PoolArea An integer variable. ##PoolQC After dealing with missing values, converted to an ordinal variable. ```{r} train$PoolQC[is.na(train$PoolQC)]<-"no" #train$PoolQC<-as.factor(train$PoolQC) test$PoolQC[is.na(test$PoolQC)]<-"no" #test$PoolQC<-as.factor(test$PoolQC) train$PoolQC<-as.integer(revalue(train$PoolQC, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) test$PoolQC<-as.integer(revalue(test$PoolQC, c("no"=0,"Po"=1, "Fa"=2, "TA"=3, "Gd"=4, "Ex"=5))) ``` ##Fence An factor variable. ```{r} train$Fence[is.na(train$Fence)]<-"no" train$Fence<-as.factor(train$Fence) test$Fence[is.na(test$Fence)]<-"no" test$Fence<-as.factor(test$Fence) ``` ##MiscFeature A factor variable. ```{r} train$MiscFeature[is.na(train$MiscFeature)]<-"no" train$MiscFeature<-as.factor(train$MiscFeature) test$MiscFeature[is.na(test$MiscFeature)]<-"no" test$MiscFeature<-as.factor(test$MiscFeature) ``` ##MiscVal An integer variable. Already coded as integer so there was nothing for me to do here. ##MoSold A factor variable. ```{r} train$MoSold<-as.factor(train$MoSold) test$MoSold<-as.factor(test$MoSold) ``` ##YrSold An integer variable. ##SaleType The test set had a missing value. After taking care of it, I converted to factor a variable. ```{r} test$SaleType[is.na(test$SaleType)]<-"Undefined" train$SaleType<-as.factor(train$SaleType) test$SaleType<-as.factor(test$SaleType) ``` ##SaleCondition A factor variable. ```{r} train$SaleCondition<-as.factor(train$SaleCondition) test$SaleCondition<-as.factor(test$SaleCondition) ``` #Exploratory analysis To some degree, I have already done some exploratory analysis. In this section, I wanted to dig a bit further. While there are near endless theories to test, I only checked into the most interesting ones to me. These were the variables that I wanted to investigate and see if they told any more of the story. ##Exploration of MSZoning I thought a good place to start was checking which zones have the highest SalePrice. I found that Residential low density and Floating Villages generally sold for a higher price. It makes sense for Residential low density to be more expensive, but, why was Floating Village? I decided to keep investigating what made Floating villages so expensive. ```{r} ggplot(train, aes(reorder(as.factor(MSZoning), SalePrice),SalePrice))+ geom_boxplot()+ geom_text(stat = "count", aes(label = ..count..), y = 700000, col = "red")+ ggtitle("SalePrice by MSZoning")+ xlab("MSZoning")+ theme(plot.title = element_text(hjust = .5)) ``` In trying to figure out why Floating Villages were getting more money, I thought that perhaps Floating Villages had a larger lot size. According to the table below, Floating Zones have the second smallest lot size. Thus, lot size does not explain why Floating Zones were most expensive. ```{r} train%>% group_by(as.factor(MSZoning))%>% summarise(Avg_LotArea=mean(LotArea), Avg_SalePrice=mean(SalePrice))%>% arrange(desc(Avg_LotArea)) ``` My second thought on why Floating Zones were so expensive, had to do with Neighborhoods. Maybe all of the Floating Zone homes were located in an expensive neighborhood. I started by checking which neighborhoods were most expensive. Based on the figure below, clearly a top three exists. The table below shows that all Floating Zone homes are in Somerst. Somerst is the sixth most expensive neighborhood. This partially explains why Floating Zones are so expensive. Looking at residential low density and the neighborhoods they correspond to, you see that there are a lot of low density homes in cheaper neighborhoods which could bring down the average price. ```{r} ggplot(train, aes(reorder(as.factor(Neighborhood),SalePrice), SalePrice))+ geom_point(stat = "summary", fun.y = "mean", col = "black", size=5)+ geom_point(stat = "summary", fun.y = "mean", col = "red", size = 3)+ xlab("Neighborhood")+ ggtitle("Mean SalePrice by Neighborhood")+ geom_text(stat = "count", aes(label = ..count..), y = 92500, col = "blue")+ theme(plot.title = element_text(hjust = .5), axis.text.x = element_text(angle = 45, vjust = .5,hjust = .5)) train%>% group_by(as.factor(MSZoning), as.factor(Neighborhood))%>% summarise(n=n(), Avg_SalePrice = mean(SalePrice), Avg_LotArea = mean(LotArea))%>% arrange(desc(Avg_SalePrice))%>% print(n = 42) ``` Another possible explanation of why Floating Zones are more money, is that more expensive types of homes are built there. I started by looking at which types of homes are most expensive. According to the figure below, 1Story, 2 story, and 2.5Fin are the three most expensive types of homes. The figure below offers a different look at the distributions of each type of home. Having established which home types are expensive, I wanted to check what the prominent type of home built in floating zones was. The table below shows that floating zones are mostly 2story homes, with the rest being 1 story. Again, I think this partially explains why floating zones are expensive. ```{r} ggplot(train, aes(reorder(as.factor(HouseStyle), SalePrice), SalePrice))+ geom_boxplot(col = "blue")+ ggtitle("Boxplots of SalePrice by HouseStyle")+ xlab("HouseStyle")+ theme(plot.title = element_text(hjust = .5)) ggplot(train, aes(SalePrice, fill = HouseStyle))+ geom_histogram()+ ggtitle("Histograms of SalePrice by HouseStyle")+ theme(plot.title = element_text(hjust = .5)) train%>% filter(as.factor(MSZoning)=="FV")%>% group_by(as.factor(MSZoning), as.factor(HouseStyle))%>% summarise(n = n())%>% arrange(desc(n)) ``` My last hypothesis into explaining Floating Zones was about KitchenQuality. From what I know about selling homes, Kitchen is always an important selling point. Therefore, I thought it necessary to look into. As one would imagine, the figures below showed that the higher kitchen quality, the higher the selling price. Tha table below, confirms my suspicion that floating zones have higher quality of kitchen. For floating zones, 94% of kitchens are either good or excellent. While for low density residential, that number is only 50%. While this does not explain the whole phenomena, it does start to add detail to the picture. ```{r} ggplot(train, aes(reorder(KitchenQual, SalePrice), SalePrice))+ geom_boxplot(col = "blue")+ ggtitle("Boxplots of SalePrice by KitchenQual")+ xlab("KitchenQualR")+ theme(plot.title = element_text(hjust = .5)) ggplot(train, aes(SalePrice, color = as.factor(KitchenQual)))+ geom_density()+ facet_wrap(~KitchenQual, ncol = 1)+ ggtitle("Densities of SalePrice by KitchenQual")+ theme(plot.title = element_text(hjust = .5)) #FV is almost all good kitchens train%>% group_by(as.factor(MSZoning), as.factor(KitchenQual))%>% summarise(n = n()) ``` Not totally happy with my answers to the floating zone price question, I decided to read up on Floating Zones in Ames, Iowa. My understanding is that places labeled a Floating Village receive more flexibility in terms of what the building can be used for. If this is the case, it makes sense for people to pay more money for added flexibility. Adding this definition with everything else I found out about floating zone homes, I am satisfied with why floating zones are the most expensive. #Modeling ##Feature Engineering This feature engineering section is not very long or complicated. There were a couple variables that seemed to be overkill such as the porch variables which I consolidated into one. Additionally, I thought a total square foot variable would be important to include. ```{r} TotalSF_train<-train$GrLivArea+train$TotalBsmtSF PorchSF_train<-train$OpenPorchSF+train$EnclosedPorch+train$X3SsnPorch+train$ScreenPorch TotalSF_test<-test$GrLivArea+test$TotalBsmtSF PorchSF_test<-test$OpenPorchSF+test$EnclosedPorch+test$X3SsnPorch+test$ScreenPorch ggplot(train, aes(TotalSF_train, SalePrice))+ geom_point()+ geom_smooth(method = "lm", se = FALSE) ggplot(train, aes(PorchSF_train, SalePrice))+ geom_point()+ geom_smooth(method = "lm", se = FALSE) ``` ##Numeric Variables ###Multicolinearity Multidisciplinary is when there are strong correlations between numeric predictors. This is problematic because it makes model coefficients unstable. Interpretability and model performance can be negatively impacted by multicollinearity. To deal with this, I used caret's findCorrelation function. The function returns an index of columns that it recommends you to get rid of. Before use, it is necessary to separate numeric and factor variables. ```{r} #find the numeric predictors minus ID, SalePrice, TotalSF, and PorchSF #separate numeric and factors numeric_predictors_train<-train[,sapply(train, is.numeric)] numeric_predictors_test<-test[,sapply(test, is.numeric)] factor_predictors_train<-train[,sapply(train, is.factor)] factor_predictors_test<-test[,sapply(test, is.factor)] #drop Id and SalePrice from the numeric predictors #drop the porch variables since I created a new one which adds them all numeric_predictors_train<-numeric_predictors_train[,-c(1, 50)] numeric_predictors_train<-numeric_predictors_train[,!(names(numeric_predictors_train) %in% c("OpenPorchSF", "EnclosedPorch", "X3SsnPorch", "ScreenPorch"))] numeric_predictors_test<-numeric_predictors_test[,-c(1,50)] numeric_predictors_test<-numeric_predictors_test[,!(names(numeric_predictors_test) %in% c("OpenPorchSF", "EnclosedPorch", "X3SsnPorch", "ScreenPorch"))] #find correlations between predictors correlations<-cor(numeric_predictors_train) highCorr<-findCorrelation(correlations, cutoff = .75) names(numeric_predictors_train[,highCorr]) filtered_numeric_predictors_train<-numeric_predictors_train[,-highCorr] filtered_numeric_predictors_test<-numeric_predictors_test[,-highCorr] filtered_numeric_predictors_train<-cbind(filtered_numeric_predictors_train,TotalSF_train) filtered_numeric_predictors_train<-cbind(filtered_numeric_predictors_train,PorchSF_train) filtered_numeric_predictors_test<-cbind(filtered_numeric_predictors_test,TotalSF_test) filtered_numeric_predictors_test<-cbind(filtered_numeric_predictors_test,PorchSF_test) ``` ###Skewness Skewness is a statistic which measures the skew of a numeric variable's distribution. The function I used is called skewness. Skewness comes from the e1071 package. Before I used it, I separated true numeric variables. After identifying the degree of skew for each variable, I applied $log (x+1)$ transformation. The plus one is to deal with values of 0, since you cannot take the $log$ of 0. The histograms for the top four skewed variables are shown below to visualize what skew looks like. ```{r} true_numeric_predictors_train<-filtered_numeric_predictors_train[,names(filtered_numeric_predictors_train) %in% c("LotFrontage", "LotArea", "MasVnrArea", "BsmtUnfSF", "X1stFlrSf", "X2ndFlrSF", "LowQualFinSF", "BsmtFullBath", "BsmtHalfBath", "FullBath", "HalfBath", "BedroomAbvGr", "KitchenAbvGr", "TotRmsAbvGrd", "Fireplaces", "GarageArea", "WoodDeckSF", "TotalSF_train", "PorchSF_train")] true_numeric_predictors_test<-filtered_numeric_predictors_test[,names(filtered_numeric_predictors_test) %in% c("LotFrontage", "LotArea", "MasVnrArea", "BsmtUnfSF", "X1stFlrSf", "X2ndFlrSF", "LowQualFinSF", "BsmtFullBath", "BsmtHalfBath", "FullBath", "HalfBath", "BedroomAbvGr", "KitchenAbvGr", "TotRmsAbvGrd", "Fireplaces", "GarageArea", "WoodDeckSF", "TotalSF_test", "PorchSF_test")] other_numeric_predictors_train<-filtered_numeric_predictors_train[,!(names(filtered_numeric_predictors_train) %in% c("LotFrontage", "LotArea", "MasVnrArea", "BsmtUnfSF", "X1stFlrSf", "X2ndFlrSF", "LowQualFinSF", "BsmtFullBath", "BsmtHalfBath", "FullBath", "HalfBath", "BedroomAbvGr", "KitchenAbvGr", "TotRmsAbvGrd", "Fireplaces", "GarageArea", "WoodDeckSF", "TotalSF_train", "PorchSF_train"))] other_numeric_predictors_test<-filtered_numeric_predictors_test[,!(names(filtered_numeric_predictors_test) %in% c("LotFrontage", "LotArea", "MasVnrArea", "BsmtUnfSF", "X1stFlrSf", "X2ndFlrSF", "LowQualFinSF", "BsmtFullBath", "BsmtHalfBath", "FullBath", "HalfBath", "BedroomAbvGr", "KitchenAbvGr", "TotRmsAbvGrd", "Fireplaces", "GarageArea", "WoodDeckSF", "TotalSF_test", "PorchSF_test"))] #Center and Scale / skew #true_numeric_predictors_train<-na.omit(true_numeric_predictors_train) #true_numeric_predictors_test<-na.omit(true_numeric_predictors_test) a<-ggplot(train, aes(LotArea))+ geom_histogram() b<-ggplot(train, aes(LowQualFinSF))+ geom_histogram() c<-ggplot(train, aes(KitchenAbvGr))+ geom_histogram() d<-ggplot(train, aes(BsmtHalfBath))+ geom_histogram() grid.arrange(a,b,c,d, ncol = 2) var_skew<-apply(true_numeric_predictors_train, 2, skewness) head(sort(var_skew, decreasing = TRUE)) ``` ```{r} true_numeric_predictors_train<-as.data.frame( apply(true_numeric_predictors_train, 2, FUN = function(x){log(x+1)})) true_numeric_predictors_test<-as.data.frame( apply(true_numeric_predictors_test, 2, FUN = function(x){log(x+1)})) ``` ###Center and Scale Center and scaling numeric variables is done by subtracting the column mean and dividing by the column standard deviation. The purpose is to make the mean = 0 and standard deviation = 1. Center and scaling grants numerical stability and might help with multicollinearity. Also, the Lasso requires the predictors to be centered and scaled. ```{r} true_numeric_predictors_train<-as.data.frame(apply(true_numeric_predictors_train, 2, scale)) true_numeric_predictors_test<-as.data.frame(apply(true_numeric_predictors_test, 2, scale)) all_numeric_predictors_train<-cbind(true_numeric_predictors_train, other_numeric_predictors_train) all_numeric_predictors_test<-cbind(true_numeric_predictors_test, other_numeric_predictors_test) ``` ##Factor Variables ###Near Zero Variance While numeric variables are filtered for multicollinearity, factor variables are filtered for near zero variance. Near zero variance occurs when a factor variable does not have a balanced amount of data across levels. Or in other words, the variable has the same value for all observations or almost all observations. The caret package offers a function called nearZeroVar which handles this problem. Similar to findCorrelation, it returns the column index of variables you should remove. To use this function, you need to code factor variables as dummy variables. I did this using caret's dummyVars. ```{r} dummy_variables_train<-dummyVars(~., data = factor_predictors_train) dummy_variables_test<-dummyVars(~., data = factor_predictors_test) factor_predictors_train_dummy<-as.data.frame(predict(dummy_variables_train, factor_predictors_train)) factor_predictors_test_dummy<-as.data.frame(predict(dummy_variables_test, factor_predictors_test)) #filter for near zero variance zero_var<-nearZeroVar(factor_predictors_train_dummy) names(factor_predictors_train_dummy[,zero_var]) factor_predictors_train_dummy<-factor_predictors_train_dummy[,-zero_var] factor_predictors_test_dummy<-factor_predictors_test_dummy[,names(factor_predictors_test_dummy) %in% (names(factor_predictors_train_dummy))] factor_predictors_train_dummy<-factor_predictors_train_dummy[,names(factor_predictors_train_dummy) %in% (names(factor_predictors_test_dummy))] ``` ##Combine Numeric and Factor Variables I combined numeric and factor variables and then added in SalePrice, TotalSF, and PorchSF. ```{r} dim(factor_predictors_train_dummy) dim(all_numeric_predictors_train) all_predictors_train<-cbind(all_numeric_predictors_train, factor_predictors_train_dummy) all_predictors_test<-cbind(all_numeric_predictors_test, factor_predictors_test_dummy) dim(all_predictors_train) all_predictors_train$SalePrice<-train$SalePrice #all_predictors_train<-na.omit(all_predictors_train) colnames(all_predictors_train)[colnames(all_predictors_train)=="TotalSF_train"] <- "TotalSF" colnames(all_predictors_train)[colnames(all_predictors_train)=="PorchSF_train"] <- "PorchSF" all_predictors_test$SalePrice<-test$SalePrice #all_predictors_test<-na.omit(all_predictors_test) colnames(all_predictors_test)[colnames(all_predictors_test)=="TotalSF_test"] <- "TotalSF" colnames(all_predictors_test)[colnames(all_predictors_test)=="PorchSF_test"] <- "PorchSF" ``` ##Linear Regression ###SalePrice (Response) In regression, it is important to have a normally distributed response variable. The figure shows that SalePrice is skewed. Taking the logarithm sometimes fixes this issue. I applied the $log$ transformation and found that the skewed distribution was fixed. According to the figure below, the distribution of $log(SalePrice)$ is approximately normal. Thus, I will use $log (SalePrice)$ as my response variable. ```{r} ggplot(all_predictors_train, aes(SalePrice))+ geom_histogram()+ ggtitle("Distribution of SalePrice")+ theme(plot.title = element_text(hjust = .5)) ggplot(all_predictors_train, aes(log(SalePrice)))+ geom_histogram()+ ggtitle("Distribution of log(SalePrice)")+ theme(plot.title = element_text(hjust = .5)) ``` ###Outlier Detection and Removal It is important to keep track of outliers when modeling. I wanted to check out Cook's distance an residuals vs fitted values plot for outlier detection. Upon doing so, I found observation 1299 and 524 to be heavy outliers. Since two values is small relative to the amount of data I have, I threw out these two observations. ```{r} linmod<-lm(log(SalePrice)~., data = all_predictors_train) par(mfrow = c(2,2)) plot(linmod) ``` I re-ran the outlier detection scheme and found the graphs to be more assuring. ```{r} par(mfrow=c(2,2)) plot(lm(log(SalePrice)~., data = all_predictors_train[-c(524,1299),])) ``` ###Lasso To create my Lasso model, I used the train function in the caret package. To make my results reproducible, I set the seed to 11. The model was trained based on 10-fold cross validation. ```{r} set.seed(11) ctrl<-trainControl(method = "cv", number = 10) lasso.mod<-train(log(SalePrice)~., data = all_predictors_train[-c(524,1299),], method = "glmnet", trControl = ctrl, tuneGrid = expand.grid(alpha = 1, lambda = seq(0, .05, length = 30))) ``` My best model used a $\lambda=.001724138$. My train RMSE was .1183659. ```{r} lasso.mod$results min(lasso.mod$results$RMSE) lasso.mod$bestTune ``` Here I get it ready for submission and check the dimensions to make sure I didn't miss anything. ```{r} predictions<-as.data.frame(test$Id) predictions$SalePrice<-exp(predict(lasso.mod, all_predictors_test)) colnames(predictions)<-c("Id", "SalePrice") head(predictions) ```
PHP
UTF-8
459
3.921875
4
[]
no_license
<?php //変数の宣言と表示(if文) // 変数を宣言し、その変数の中身によって以下の表示を行ってください。 // ⇒値が 1 なら「1です!」 // ⇒値が 2 なら「プログラミングキャンプ!」 // ⇒それ以外なら「その他です!」 $num1 = 1; if ($num1 == 1) { echo "1です!"; } elseif ($num1 == 2) { echo "プログラミングキャンプ!"; } else{ echo "その他です!"; } ?>
Python
UTF-8
113
2.8125
3
[]
no_license
class Icon(object): def __init__(self, surf, rect): self.surf = surf.copy() self.rect = rect
Java
UTF-8
638
2.546875
3
[]
no_license
package com.frank.hound.core.support; import com.frank.hound.core.common.Closeable; import lombok.NonNull; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; /** * @author frank */ public class HoundAutoCloser { private Set<Closeable> closerList = new LinkedHashSet<>(); public void registerAutoCloser(@NonNull Closeable... closers) { if(closers.length == 0) { return; } closerList.addAll(Arrays.asList(closers)); } public void exec() { for(Closeable closer:closerList) { closer.close(); } } }
Java
UTF-8
3,206
2.921875
3
[]
no_license
package ru.avalon.java.dev.j10.labs.models; import ru.avalon.java.dev.j10.labs.commons.Address; import java.time.LocalDate; /** * Представление о паспортных данных человека. * <p> * Паспортные данные должны включать: * <ol> * <li> серию и номер документа; * <li> имя; * <li> фамилию; * <li> отчество; * <li> второе имя; * <li> день рождения; * <li> дату выдачи; * <li> орган, выдавший документ. * </ol> */ public class Passport { private int passportNumber; private int passportSeria; private String name; private String surname; private String fathername; private String secondName; private LocalDate birthday; private LocalDate dateOfIssuing; private Address address; public Passport(int passportNumber, int passportSeria, String name, String surname, String fathername, String secondName, LocalDate birthday, LocalDate dateOfIssuing, Address address) { this.passportNumber = passportNumber; this.passportSeria = passportSeria; this.name = name; this.surname = surname; this.fathername = fathername; this.secondName = secondName; this.birthday = birthday; this.dateOfIssuing = dateOfIssuing; this.address = address; } /* * TODO(Студент): Закончить определение класса. * * 1. Объявить атрибуты класса. * * 2. Определить необходимые методы класса. Подумайте о * том, какие методы должны существовать в классе, * чтобы обеспечивать получение всей необходимой * информации о состоянии объектов данного класса. * Все ли поля обязательно будут проинициализированы * при создании экземпляра? * * 3. Создайте все необходимые конструкторы класса. * * 4. Помните о возможности существования перегруженных * конструкторов. * * 5. Обеспечте возможность использования класса за * пределами пакета. */ public int getPassportNumber() { return passportNumber; } public int getPassportSeria() { return passportSeria; } public String getName() { return name; } public String getSurname() { return surname; } public String getFathername() { return fathername; } public String getSecondName() { return secondName; } public LocalDate getBirthday() { return birthday; } public LocalDate getDateOfIssuing() { return dateOfIssuing; } public Address getAddress() { return address; } }
Python
UTF-8
1,160
3.359375
3
[]
no_license
# 210 class Solution: WHITE = 1 GRAY = 2 BLACK = 3 def findOrder(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int] """ graph = {} isCycle = False for i in range(numCourses): graph[i] = list() for u, v in prerequisites: graph[v].append(u) color = [Solution.WHITE] * numCourses order = list() def dfs(node): nonlocal isCycle if isCycle: return color[node] = Solution.GRAY if node in graph.keys(): for neighbor in graph[node]: if color[neighbor] == Solution.GRAY: isCycle = True return elif color[neighbor] == Solution.WHITE: dfs(neighbor) color[node] = Solution.BLACK order.append(node) for v in graph.keys(): if color[v] == Solution.WHITE: dfs(v) return order[::-1] if not isCycle else []
C
UTF-8
849
2.8125
3
[]
no_license
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int uint32_t ; /* Variables and functions */ int ARSH (int,int) ; __attribute__((used)) static void add_f256(uint32_t *d, const uint32_t *a, const uint32_t *b) { uint32_t w, cc; int i; cc = 0; for (i = 0; i < 9; i ++) { w = a[i] + b[i] + cc; d[i] = w & 0x3FFFFFFF; cc = w >> 30; } w >>= 16; d[8] &= 0xFFFF; d[3] -= w << 6; d[6] -= w << 12; d[7] += w << 14; cc = w; for (i = 0; i < 9; i ++) { w = d[i] + cc; d[i] = w & 0x3FFFFFFF; cc = ARSH(w, 30); } }
Java
UTF-8
311
1.78125
2
[]
no_license
package com.wqb.dao.customer; import com.wqb.common.BusinessException; import com.wqb.model.Customer; import java.util.List; public interface CustomerDao { Customer queryCusByAcc(String accountID) throws BusinessException; List<Customer> queryCusBath(List<String> list) throws BusinessException; }
Python
UTF-8
2,082
2.875
3
[]
no_license
import logging import requests import boto3 from botocore.exceptions import ClientError BUCKET_NAME = 'reactvang' def upload_file(file_name, object_name=None, bucket = BUCKET_NAME): """Upload a file to an S3 bucket :param file_name: File to upload :param bucket: Bucket to upload to :param object_name: S3 object name. If not specified then file_name is used :return: True if file was uploaded, else False """ # Upload the file s3_client = boto3.client('s3') try: response = s3_client.upload_file(file_name, bucket, object_name) if type(file_name) == str else s3_client.upload_fileobj(file_name, BUCKET_NAME, object_name) except ClientError as e: logging.error(e) return False return True def list_bucket_objects(): # # Create a client # client = boto3.client('s3', region_name='us-west-2') # # Create a reusable Paginator # paginator = client.get_paginator('list_objects') # # Create a PageIterator from the Paginator # page_iterator = paginator.paginate(Bucket='my-bucket') # for page in page_iterator: # print(page['Contents']) s3 = boto3.resource('s3') bucket_objects = s3.Bucket(name=BUCKET_NAME).objects.all() for bucket in bucket_objects: print(bucket) # delete_bucket_object(bucket.key) def delete_bucket_object(key): s3 = boto3.resource('s3') s3.Object(BUCKET_NAME, key).delete() def downloand(url="https://vanguardia.com.mx/sites/default/files/styles/paragraph_image_large_desktop_1x/public/amlo-pemex-lopez-obrador-plan-nacional-gas-petroleo-gob-mx.jpg_114089499.jpg"): return requests.get(url, stream=True, headers={'User-agent': 'Mozilla/5.0'}) # img_raw = downloand().raw # img = img_raw.read() # s3 = boto3.resource('s3') # s3.Bucket(name=BUCKET_NAME).put_object(Key="amloq.jpg", Body=img) # upload_file(img_raw, BUCKET_NAME, "DIRECTORY/THAT/YOU/WANT/TO/CREATE/amloqe.jpg",) # delete_bucket_object("amlo.jpg") # list_bucket_objects() # s3 = boto3.client('s3') # s3.download_file(BUCKET_NAME, 'amlo.jpg', 'amlo.jpg')
SQL
UTF-8
1,517
3.015625
3
[]
no_license
SELECT * FROM mapssrs.dbo.reportlog order by id desc USE IRRISCENTRAL INSERT INTO rptReportMaster( ReportName, DisplayText, Description, ReportPath, CategoryID, DeletedYN, CreatedBY, CreatedDate) SELECT 'Orientation Survey','Orientation Survey','Survey Details','/MAPSSRS/Orientation Survey',-1,0,1,GETDATE() use rolesqa INSERT INTO rptReports( ReportID ,ReportName ,DisplayText ,Description ,ReportPath ,CategoryID ,DeletedYN ,CreatedBY ,CreatedDate ,ReportType) SELECT -47,'Orientation Survey','Orientation Survey','Survey Details','/MAPSSRS/Orientation Survey',-1,0,1,GETDATE(),1 INSERT INTO rptFilters ( ReportID ,FieldName ,DisplayText ,FieldType ,sequence ,LookUpId ,DefaultValue ) SELECT -47,'s.Parent_name','Parent Name',1,3,Null,'' UNION ALL SELECT -47,'s.Email','Email',1,4,Null,'' UNION ALL SELECT -47,'s.City','City',1,5,Null,'' UNION ALL SELECT -47,'s.Phone','Phone',1,6,Null,'' UNION ALL SELECT -47,'s.CaseNumber','CaseNumber',1,7,Null,'' UNION ALL SELECT -47,'FORMAT(s.Survey_Completion_Date,''yyyy-MM-dd'')','Survey Completion Date',4,8,Null,'' UNION ALL SELECT -47,'s.Question','Question',8,1,41,'' UNION ALL SELECT -47,'s.Answer','Answer',8,2,42,'' INSERT INTO lkplookuptable( LkpName ,DisplayField ,ValueField ,Query ) VALUES ('SurveyName','SurveyName','SurveyName' ,'SELECT DISTINCT campaign_id,campaign AS SurveyName FROM surveypro_campaigns ORDER BY campaign ASC')
TypeScript
UTF-8
1,979
3.75
4
[]
no_license
// function identity<T>(arg:T):T { // return arg; // } // let output=identity<string>("myString"); // console.log(output); // let output1=identity("myString1"); // console.log(output1); // function loggingIdentity<T>(arg:T[]):T[]{ // console.log(arg.length); // return arg; // } // function loggingIdentity<T>(arg:Array<T>):Array<T>{ // console.log(arg.length); // return arg; // } // let logging=loggingIdentity(["a","b"]); //泛型类型 // function identity<T>(arg:T):T{ // return arg; // } // let myIdentity:<T>(arg:T)=>T=identity; // let output=myIdentity("aaa"); // console.log(output); //泛型接口 // interface GenericIdentityFn{ // <T>(arg:T):T; // } // function identity<T>(arg:T):T{ // return arg; // } // let myIdentity:GenericIdentityFn=identity; // console.log(myIdentity(1)); //泛型类 /** * GenericNumber<T> */ // class GenericNumber<T> { // zeroValue:T; // add:(x:t,y:T)=>T; // } // let myGenericNumber=new GenericNumber<number>(); // myGenericNumber.zeroValue=0; // myGenericNumber.add=function(x,y){return x+y;}; // console.log(myGenericNumber.add(1,2)); //泛型约束 // interface Lengthwise { // length: number; // } // function loggingIdentity<T extends Lengthwise>(arg: T): T { // console.log(arg.length); // Now we know it has a .length property, so no more error // return arg; // } // loggingIdentity({length: 10, value: 3}); //在泛型里使用类类型 // function create<T>(c: {new(): T; }): T { // return new c(); // } // class BeeKeeper { // hasMask: boolean; // } // class ZooKeeper { // nametag: string; // } // class Animal { // numLegs: number; // } // class Bee extends Animal { // keeper: BeeKeeper; // } // class Lion extends Animal { // keeper: ZooKeeper; // } // function findKeeper<A extends Animal, K> (a: {new(): A;prototype: {keeper: K}}): K { // return a.prototype.keeper; // } // findKeeper(Lion).nametag; // typechecks!
C#
UTF-8
869
3.5625
4
[]
no_license
using System; namespace Happy_index_VisualStudio { class Program { static void Main(string[] args) { Console.WriteLine("On a scale of zero to ten, how happy are you?"); int userInput = Convert.ToInt32(Console.ReadLine()); if (userInput == 0) Console.WriteLine("...That's so sad!! Talk to me."); else if (userInput >= 1 && userInput <= 3) Console.WriteLine("That's terrible. Shall we have a coffee?"); else if (userInput >= 4 && userInput <= 6) Console.WriteLine("Hmm... we should think on how to improve this!"); else if (userInput >= 7 && userInput <= 8) Console.WriteLine("Pretty good! :-)"); else Console.WriteLine("Great!"); } } }
Markdown
UTF-8
1,317
2.671875
3
[ "MulanPSL-2.0", "LicenseRef-scancode-mulanpsl-2.0-en", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- --- --- title: 《译文》创刊号前记[677] --- 读者诸君:你们也许想得到,有人偶然得一点空工夫,偶然读点外国作品,偶然翻译了起来,偶然碰在一处,谈得高兴,偶然想在这“杂志年”里来加添一点热闹,终于偶然又偶然的找得了几个同志,找得了承印的书店,于是就产生了这一本小小的《译文》。 原料没有限制:从最古以至最近。门类也没固定:小说,戏剧,诗,论文,随笔,都要来一点。直接从原文译,或者间接重译:本来觉得都行。只有一个条件:全是“译文”。 文字之外,多加图画。也有和文字有关系的,意在助趣;也有和文字没有关系的,那就算是我们贡献给读者的一点小意思,复制的图画总比复制的文字多保留得一点原味。 并不敢自夸译得精,只能自信尚不至于存心潦草;也不是想竖起“重振译事”的大旗来,——这种登高一呼的野心是没有的,不过得这么几个同好互相研究,印了出来给喜欢看译品的人们作为参考而已。倘使有些深文周纳的惯家以为这又是什么人想法挽救“没落”的法门,那我们只好一笑道:“领教!领教!诸公的心事,我们倒是雪亮的!”
C++
UTF-8
1,375
3.625
4
[]
no_license
// Created by Gabriel Batista Cristiano // TIA: 32090722 // Referencia: https://www.dobitaobyte.com.br/como-criar-arrays-dinamicos-em-c/ #include <iostream> using namespace std; int main() { int size, secondSize, input; char choice; cout << "Digite o tamanho do array: "; cin >> size; int* array = new int[size]; for (int i=0; i < size; i++) { cout << "\nInforme o número positivo para o elemento " << i << ": \n"; cin >> input; if(input < 0) { for (int j = i; j<size; j++) { array[j] = -1; } break; } array[i] = input; if(i == size - 1) { cout << "Limite do array atingido. Deseja aumentar o tamanho do array? \n[s/n]: "; cin >> choice; if(choice == 's') { cout << "Ïnforme o novo valor do array: "; cin >> secondSize; if (secondSize <= size) { cout << "O tamanho do novo array não pode ser menor ou igual ao atual. \nEncerrando..."; break; } size = secondSize; } } } for(int i=0; i < size; i++) { cout << "\narray[" << i << "]: "<< "= " << array[i]; } delete [] array; array = nullptr; cout << "\n"; }
SQL
UHC
7,144
4.0625
4
[]
no_license
< > : ȣ , ο - Ŭ ͺ̽ ġϸ, ⺻ Ǵ SYS SYSTEM SCOTT ( : ) HR ( : ó , 11g ) - ͺ̽ : ڰ ͺ̽ ü(̺, ) Ư ְ . ټ ڰ ϴ ͺ̽ . ͺ̽ ϴ ڸ ٸ Ѱ ο. - : ڰ Ư ̺ ֵ ϰų, ش ̺ SQL(SELECT/INSERT/UPDATE/DELETE) ֵ δ * ý : ͺ̽ ڰ ִ CREATE USER ( ) DROP USER ( ) DROP ANY TABLE ( ̺ ) QUERY REWRITE (Լ ε ) BACKUP ANY TABLE (̺ ) * ý ڰ ڿ οϴ CREATE SESSION (ͺ̽ ) CREATE TABLE (̺ ) CREATE VIEW ( ) CREATE SEQUENCE ( ) CREATE PROCEDURE (Լ ) * ü : ü ִ - : ͺ̽ ִ ̵(̸) ȣ [] CREATE USER ̸ IDENTIFIED BY ȣ; [ǽ] -------------------------------------------------------------- 1. system α SQL> CONN system/ȣ 2. αε Ȯ SQL> SHOW USER 3. ο ȣ SQL> CREATE USER USER01 IDENTIFIED BY PASS01; 4. α SQL> CONN USER01/PASS01 -- ߻ : ڿ ο ʾұ . - οϱ : GRANT ɾ [] GRANT TO ̸ [WITH ADMIN OPTION]; * ̸ PUBLIC ϸ ڿ ش ý۱ ο [ǽ] α οϱ ----------------------------------------- 1. system SQL> GRANT CREATE SESSION TO USER01; 2. USER01 α SQL> CONN USER01/PASS01 SQL> SHOW USER [ǽ] ̺ οϱ ---------------------------------- 1. USER01 SQL> CREATE TABLE EMP01( ENO NUMBER(4), ENAME VARCHAR2(20), JOB VARCHAR2(10), DPTNO NUMBER(2)); -- ߻ 2. system α SQL> CONN system/ȣ SQL> SHOW USER 3. CREATE TABLE ο SQL> GRANT CREATE TABLE TO USER01; 4. USER01 α , ̺ ٽ SQL> CONN USER01/PASS01; SQL> SHOW USER SQL> CREATE TABLE EMP01( ENO NUMBER(4), ENAME VARCHAR2(20), JOB VARCHAR2(10), DPTNO NUMBER(2)); 5. CREATE TABLE ־µ ̺ => Ʈ ̺̽ USERS (QUOTA) ʾұ . - ̺̽(Tablespace) : ̺, , ͺ̽ ü Ǵ ũ Ŭ ġ scott ͸ ϱ USERS ̺̽ . [ǽ] USER01 ̺̽ ȮϷ 1. system ¿ SQL> CONN system/ȣ SQL> SHOW USER SQL> SELECT USERNAME, DEFAULT_TABLESPACE FROM DBA_USERS WHERE USERNAME = 'USER01'; -- ̺̽ USERS Ȯ. 2. ̺̽ Ҵ : USER01 ڰ ̺̽ Ҵ => QUOTA . ( 10M, 5M, UNLIMITED ) SQL> ALTER USER USER01 QUOTA 2M ON SYSTEM; 3. USER01 ٽ SQL> CONN USER01/PASS01 SQL> SHOW USER 4. ̺ SQL> CREATE TABLE EMP01( ENO NUMBER(4), ENAME VARCHAR2(20), JOB VARCHAR2(10), DPTNO NUMBER(2)); 5. ̺ Ȯ SQL> DESC EMP01; [] ---------------------------------------------------------------- ڸ : USER007 ȣ : PASS007 ̺̽ : 3M : DB , ̺ => Ȯ ------------------------------------------------------------------------ - WITH ADMIN OPTION : ڿ ý ο ο ڴ ٸ ڿ [] GRANT CREATE SESSION TO ڸ WITH ADMIN OPTION; - ü : ̺̳ , , Լ ü DML ִ ϴ [] GRANT [(÷)] | ALL ON ü | ROLE ̸ | PUBLIC TO ̸; * ü ALTER : TABLE, SEQUENCE DELETE : TABLE, VIEW EXECUTE : PROCEDURE INDEX : TABLE INSERT : TABLE, VIEW REFERENCES : TABLE SELECT : TABLE, VIEW, SEQUENCE UPDATE : TABLE, VIEW [ǽ] ----------------------------------------------------- : ٸ ڰ ̺ ȸϰ Ѵٸ 1. USER01 SQL> CONN USER01/PASS01 SQL> SHOW USER 2. USER007 ڰ USER01 EMP01 ̺ SELECT Ϸ SQL> GRANT SELECT ON EMP01 TO USER007; 3. USER007 α SQL> CONN USER007/PASS007 SQL> SHOW USER 4. ̺ Ȯ SQL> SELECT * FROM USER01.EMP01; - ڿ ο ȸϱ : Ѱ õ ųʸ - ڽſ ο ˰ * USER_TAB_PRIVS_RECD => SELECT * FROM USER_TAB_PRIVS_RECD; - ڰ ٸ ڿ ο * USER_TAB_PRIVS_MADE => SELECT * FROM USER_TAB_PRIVS_MADE; - öȸ : REVOKE ɾ [] REVOKE | ALL ON ü FROM [̸ | ROLE ̸ | PUBLIC]; [ǽ] ------------------------------------------------------------ 1. USER01 α 2. ش ڰ Ȯ SQL> SELECT * FROM USER_TAB_PRIVS_MADE; 3. SELECT SQL> REVOKE SELECT ON EMP01 FROM USER007; 4. ųʸ Ȯ SQL> SELECT * FROM USER_TAB_PRIVS_MADE; - WITH GRANT OPTION : ڰ ش ü ִ ο 鼭 ٸ ڿ ٽ ο [ǽ] ----------------------------------------------------------------- 1. USER01 SQL> GRANT SELECT ON USER01.EMP01 TO USER007 WITH GRANT OPTION; 2. USER007 α SQL> GRANT SELECT ON USER01.EMP01 TO STUDENT; -- ٸ ڿ ο ٽ ο Ȯ.
Python
UTF-8
727
3.796875
4
[ "BSD-3-Clause" ]
permissive
"""See want_play_again.__doc__.""" from out_of_range_error import out_of_range_error def want_play_again(): """Deduce whether the user wants to play again. Return: A boolean value, True if the user wants to play again, False if they do not. """ while True: try: user_input = int( input(""" Do you want to play again: 1) Yes 2) No [1-2]: """)) except ValueError: out_of_range_error(2) user_input = None if user_input in (1, 2): if user_input == 1: return True return False out_of_range_error(2) if __name__ == "__main__": print(want_play_again())
Markdown
UTF-8
3,563
2.890625
3
[]
no_license
+++ date = "2016-03-17T13:37:58+09:00" title = "Pythonで Neural Fitted Q Iteration を実装する" tags = ["Python", "NumPy", "機械学習"] +++ [前々回に実装した多層パーセプトロン](https://zaburo-ch.github.io/post/mlp/)と[前回実装した倒立振子のシミュレータ](https://zaburo-ch.github.io/post/inverted-pendulum/)を用いて、 [Neural Fitted Q Iteration](http://ml.informatik.uni-freiburg.de/_media/publications/rieecml05.pdf)(NFQ)の実験を行います。 NFQはQ学習の最適行動価値関数を多層パーセプトロンを用いて近似する手法の一つで、 学習中にはデータを追加せず、事前に集められたデータのみから学習を行います。 コードはこんな感じ。MLPはkerasで構築しました。 <script src="https://gist.github.com/zaburo-ch/f2f61a94ee722447d2d7.js"></script> mはepisodeの個数にあたる変数になっていて、 [50, 100, 150, 200, 300, 400]の各m対して、50回実験を行うようになっています。 実験の大まかな流れは、 1. make_episodes(m)でm個のepisodeを作る 2. 多層パーセプトロンを構築 3. Neural Fitted Q Iterationを実行 4. 倒立振子を立たせるタスクを実行 5. 停止するまでの時間を記録(t<299なら失敗、t==299なら成功) という感じです。肝心の3.では、 episodesの中からpattern_set_size個ずつepisodesを取り出し、 その中の各cycleから入力xと教師信号tを作成して、 多層パーセプトロンをこれにfitさせるのを繰り返すことで学習を行っています。 episodes1周だけではうまくタスクを成功させることができなかったので、 毎回取り出す順番をランダムに変えてepisodesを5周させるようにしています。 実験結果は次のようになりました。 | m | 成功した回数 | |-----|---------------| | 50 | 25 / 50 (50%) | | 100 | 41 / 50 (82%) | | 150 | 43 / 50 (86%) | | 200 | 43 / 50 (86%) | | 300 | 48 / 50 (96%) | | 400 | 46 / 50 (92%) | m = 50 の場合については論文とほぼ同程度成功できています。 しかし、それ以外の場合では論文の結果よりもやや悪い数字が出てしまっています。 特に m >= 200 では100%となるらしいのですが、100%は出ませんでした。 - Rpropを使うところをSGDでやったこと(sigmoid関数がフラットになる範囲で学習が停滞する) - episodesの周回数(5)やpattern_set_size(=m/10)をテキトーに決めたこと - fitの時のepoch数が1000で固定されていること あたりかなが原因なのかなと思っています。 この辺りをちゃんと設定すれば100%も出せると思うのですが、 まあそれほど悪くない結果が出ているのでひとまずこれで良いことにします。 倒立振子のアニメーションは以下のような感じ。 コスト関数が単純(倒れたら1、倒れないなら0)なため、 直立した状態でキープしようとするのではなく、 倒れそうになってから直そうとするので台車ごとすっ飛んで行きます。 ![m=50,失敗](/images/pendulum_m50_fail.gif) m = 50, 失敗 ![m=50,成功](/images/pendulum_m50_success.gif) m = 50, 成功(gifは10秒で打ち切り) ![m=400,失敗](/images/pendulum_m400_fail.gif) m = 400, 失敗 ![m=400,成功](/images/pendulum_m400_success.gif) m = 400, 成功(gifは10秒で打ち切り)
C++
UTF-8
2,710
3.953125
4
[]
no_license
/* You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end. The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall. Write a function: int solution(int H[], int N); that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it. For example, given array H containing N = 9 integers: H[0] = 8 H[1] = 8 H[2] = 5 H[3] = 7 H[4] = 9 H[5] = 8 H[6] = 7 H[7] = 4 H[8] = 8 the function should return 7. The figure shows one possible arrangement of seven blocks. https://app.codility.com/programmers/lessons/7-stacks_and_queues/stone_wall/ Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array H is an integer within the range [1..1,000,000,000]. */ #include<iostream> #include<vector> #include<algorithm> #include<stack> using namespace std; int solution(vector<int> &H){ stack<int> s; int count=0; int sum=0; for(int i =0; i < H.size(); ++i){ if(s.empty()){ count++; sum+= H[i]; s.push(H[i]); } else { if(H[i] == sum) // next value is same as stack value { continue; // nothing to do } else if(H[i] < sum) { if(s.size() == 1) { //have remove it s.pop(); s.push(H[i]); count++; sum = H[i]; } else { while(!s.empty() && sum > H[i]) { int v = s.top(); s.pop(); sum -= v; } if(s.empty()) { s.push(H[i]); count++; sum = H[i]; }else { int diff = H[i] - sum; if(diff != 0) { s.push(diff); count++; sum+= diff; } } } } else // H[i] > sum { int diff = H[i] - sum; s.push(diff); sum += diff; count++; } } } return count; } int main(int arg, char* argv[]) { vector<int> d = {8,8,5,7,9,8,7,4,8}; int res = solution(d); cout << "res=" << res << endl; return 0; }
C#
UTF-8
1,468
2.703125
3
[ "Apache-2.0" ]
permissive
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using DG.Tweening; namespace MissingComplete { public class Fader : MonoBehaviour { public delegate void OnFadeOutEvent(); public delegate void OnFadeInEvent(); public event OnFadeOutEvent fadeOutComplete; public event OnFadeInEvent fadeInComplete; private static Fader instance; public static Fader Instance { get { return instance; } } [SerializeField] Image fadeImage; [SerializeField] float fadeTime; public void FadeIn() { Debug.Log("Starting Fade In"); fadeImage.gameObject.SetActive(true); fadeImage.color = new Color(fadeImage.color.r, fadeImage.color.g, fadeImage.color.b, 1.0f); fadeImage.DOFade(0.0f, fadeTime).OnComplete(OnFadeInComplete).SetEase(Ease.Linear); } private void OnFadeInComplete() { Debug.Log("OnFadeInComplete"); fadeImage.gameObject.SetActive(false); if(fadeInComplete != null) { fadeInComplete(); } } public void FadeOut() { Debug.Log("Starting Fade Out"); fadeImage.gameObject.SetActive(true); fadeImage.color = new Color(fadeImage.color.r, fadeImage.color.g, fadeImage.color.b, 0.0f); fadeImage.DOFade(1.0f, fadeTime).OnComplete(OnFadeOutComplete).SetEase(Ease.Linear); } private void OnFadeOutComplete() { Debug.Log("OnFadeOutComplete"); if(fadeOutComplete != null) { fadeOutComplete(); } } private void Awake() { instance = this; } } }
C#
UTF-8
2,127
2.875
3
[]
no_license
using Application.Common.Interfaces; using MediatR; using System.Threading; using System.Threading.Tasks; namespace Application.V1.Users.Commands.CreateUser { public static class CreateUser { public record Query : IRequest<Response> { public string Username { get; init; } public string Email { get; init; } public string Password { get; init; } } public class Handler : IRequestHandler<Query, Response> { private readonly IIdentityService _identityService; public Handler(IIdentityService identityService) { _identityService = identityService; } public async Task<Response> Handle(Query request, CancellationToken cancellationToken) { var emailAvailable = await _identityService.EmailAvailableAsync(request.Email); if (emailAvailable == false) { return Response.Fail("Email not available."); } var result = await _identityService.CreateUserAsync( request.Username, request.Email, request.Password); if (result.IsSuccessful) { return Response.Success($"Your account has been successfully created, {request.Username}."); } return Response.Fail("Unable to create account."); } } public record Response { public string Description { get; private set; } public bool IsSuccessful { get; private set; } public static Response Success(string description) => new() { Description = description, IsSuccessful = true }; public static Response Fail(string description) => new() { Description = description, IsSuccessful = false }; } } }
Java
UTF-8
530
1.921875
2
[]
no_license
package kadai; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class kadai24_Uehara extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html;charset=ISO-2022-JP"); PrintWriter out = res.getWriter(); out.println("<html><head></head><body><center>"); out.println("service"); out.println("</center></body></html>"); out.close(); } }//http://localhost:8080/tomcat_test/kadai24.html
C#
UTF-8
3,203
2.546875
3
[]
no_license
#region 文件描述 /****************************************************************************** * 创建: Daoting * 摘要: * 日志: 2011-03-04 创建 ******************************************************************************/ #endregion #region 引用命名 #endregion namespace Dt.Base { /// <summary> /// phone模式一级菜单项显示状态 /// </summary> public enum VisibleInPhone { /// <summary> /// 只显示文字 /// </summary> ID, /// <summary> /// 只显示图标 /// </summary> Icon, /// <summary> /// 显示文字和图标 /// </summary> IconAndID, } /// <summary> /// 触发上下文菜单的事件种类 /// </summary> public enum TriggerEvent { /// <summary> /// 鼠标右键,触摸时长按 /// </summary> RightTapped, /// <summary> /// 鼠标左键,触摸时点击 /// </summary> LeftTapped, /// <summary> /// 自定义触发方式 /// </summary> Custom } /// <summary> /// 上下文菜单的显示位置,phone模式无固定位置显示功能 /// </summary> public enum MenuPosition { /// <summary> /// win模式在指定位置显示,phone模式为FromBottom /// </summary> Default, /// <summary> /// 左上对齐(对话框的左上角与目标元素的左上角重叠) /// </summary> TopLeft, /// <summary> /// 右上对齐(对话框的左上角与目标元素的右上角重叠) /// </summary> TopRight, /// <summary> /// 中心对齐(对话框的中心与目标元素的中心重叠) /// </summary> Center, /// <summary> /// 左下对齐(默认,对话框的左上角与目标元素的左下角重叠) /// </summary> BottomLeft, /// <summary> /// 右下对齐(对话框的左上角与目标元素的右下角重叠) /// </summary> BottomRight, /// <summary> /// 对话框的右上角与目标元素的左上角重叠 /// </summary> OuterLeftTop, /// <summary> /// 对话框的左下角与目标元素的左上角重叠 /// </summary> OuterTop } /// <summary> /// 菜单项使用范围 /// </summary> public enum MiScope { /// <summary> /// 始终显示 /// </summary> Both, /// <summary> /// 只在Phone模式显示 /// </summary> Phone, /// <summary> /// 只在Win模式显示 /// </summary> Windows } /// <summary> /// 菜单项状态 /// </summary> internal enum MenuItemState { /// <summary> /// 普遍状态 /// </summary> Normal, /// <summary> /// 移入状态 /// </summary> PointerOver, /// <summary> /// 点击状态 /// </summary> Pressed } }
PHP
UTF-8
1,117
2.671875
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; use PharIo\Manifest\Email; use App\User; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $users = [ [ 'name' => 'Francesco', 'email' => 'francesco@gmail.com', 'password' => 'ciaociaociao' ], [ 'name' => 'Giancarlo', 'email' => 'giancarlo@gmail.com', 'password' => 'ciaociaociao' ], [ 'name' => 'Giuseppe', 'email' => 'giuseppe@gmail.com', 'password' => 'ciaociaociao' ], [ 'name' => 'Amedeo', 'email' => 'amedeo@gmail.com', 'password' => 'ciaociaociao' ], ]; foreach ($users as $utente) { $user = new User(); $user->name = $utente['name']; $user->email = $utente['email']; $user->password = bcrypt($utente['password']); $user->save(); } } }
Java
UTF-8
791
3.734375
4
[]
no_license
public class StaticTestMain { public static void main(String[] args) { //클래스 내의 메소드를 호출하기 위해 객체를 생성 //StaticTest st = new StaticTest(); //st.prn(); // 멤버 변수에 static 키워드를 사용하면 클래스를 객체 생성하지 않고 사용 할 수 있다. // 클래스명.static멤버변수 //System.out.println( " num = " + StaticTest.num); //static 메서드 호출 // 클래스명.static메서드 //StaticTest.prn(); //static 멤버변수는 객체를 생성시 공통 변수로 사용된다. StaticTest st = new StaticTest(); StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); //값변경 st.num = 1234; st.name = "이순신"; st2.prn(); } }
Python
UTF-8
80
3.3125
3
[]
no_license
n=int(input('Enter the number')) a=n*1 b=n*2 c=n*3 d=n*4 e=n*5 print(a,b,c,d,e)
Markdown
UTF-8
27,949
2.65625
3
[ "Apache-2.0" ]
permissive
--- copyright: years: 2015, 2017 lastupdated: "2017-04-07" --- {:new_window: target="_blank"} {:shortdesc: .shortdesc} {:screen:.screen} {:codeblock:.codeblock} # 設定 Bluemix 環境 {: #patterns} 一個成功的專案,需要花時間計劃和設計您需要哪些資源,以及您的企業需求為何。為了協助您開始進行雲端專案,請考量下列問題: * 將要開發的應用程式數量及類型? * 應用程式需要存取哪些服務? * 哪些人會在開發過程中分工合作,以及他們將扮演什麼角色? * 專案的每一個階段所需的隔離程度為何? * 您的企業是否會提供基礎架構資源? * 貴公司的通訊方式? * 是否有可以實作的命名標準,以清楚識別組織和空間用量? {:shortdesc} 設計雲端解決方案時,也請思考帳戶安全,以及作業需求、國家/地區法規、市場指引和公司政策。為了滿足您的專案需求,{{site.data.keyword.Bluemix}} 提供三種類型的雲端環境。 * [{{site.data.keyword.Bluemix_notm}} 公用](/docs/overview/whatisbluemix.html "{{site.data.keyword.Bluemix_notm}} 公用"):由不同的公司及使用者共用的基礎架構資源。 * [{{site.data.keyword.Bluemix_notm}} 專用](/docs/dedicated/index.html#dedicated "{{site.data.keyword.Bluemix_notm}} 專用"):您使用自己專用的 SoftLayer 基礎架構,可以將其安全地連接至「{{site.data.keyword.Bluemix_notm}} 公用」雲端和您自己的網路。 * [{{site.data.keyword.Bluemix_notm}} 本端](/docs/local/index.html#local "{{site.data.keyword.Bluemix_notm}} 本端"):位於公司防火牆後面,可保護您最機密的工作負載,並可安全地連接至「{{site.data.keyword.Bluemix_notm}} 公用」和「{{site.data.keyword.Bluemix_notm}} 專用」雲端。 在決定您需要哪種類型的雲端環境時,就要計劃帳戶、組織、空間、資源和團隊成員的結構。 對大部分公司而言,單一 {{site.data.keyword.Bluemix_notm}} 帳戶即已足夠。如果是有多個業務領域的較大型公司,您可以針對每一個業務領域設定個別的 {{site.data.keyword.Bluemix_notm}} 帳戶。例如,在大型的銀行金融公司中,對於零售和商業部門,可能會有個別的帳戶。 下表提供部分重要元素的摘要。 | 元素 | 說明 | |---------------------------------------|--------------------------------------------------------------------------------------| | 帳戶 | 每一個帳戶各有一個帳戶擁有者。 | || 包含一個以上的組織。您必須有「隨收隨付制」帳戶,才能建立多個組織。 | | 帳戶擁有者 | 負責帳戶內累計的所有使用費用。 | || 只能擁有一個帳戶。 | || 可以新增一個以上的組織管理員來委派組織管理作業,其中包括組織的讀取和寫入權。 | || 可以是其他 {{site.data.keyword.Bluemix_notm}} 帳戶之組織和空間中的團隊成員。 | | 組織 | 包含一個以上的空間。 | || 包含一個以上的組織管理員。 | || 包含一個以上的團隊成員。每一個團隊成員可以被授與一個以上的角色。 | || 使用費用(由部署在空間中的應用程式所產生)是在組織層次提報。 | | 空間 | 包含一個以上的資源。 | || 包含一個以上的應用程式。 | || 包含一個以上的空間管理員。 | || 包含一個以上的團隊成員。每一個使用者都必須已經是擁有組織中的團隊成員。每一個團隊成員可以被授與一個以上的角色。 | | 團隊成員 | 可以新增至不同帳戶的一個以上組織和空間中。 | || 可以在相同的組織及/或空間內被賦予多個角色。 | {:caption="表 1. 重要元素的說明" caption-side="top"} ## 決定您的 {{site.data.keyword.Bluemix_notm}} 環境 {: #bpimplementation} 您可以實作讓開發人員和測試人員能夠與其他團隊成員分工合作的環境,而不是傳統嚴格定義的開發、測試和正式作業方法。在設計您要用來開發及交付應用程式的方法時,您可以建立 {{site.data.keyword.Bluemix_notm}} 空間來實踐該方法。您可以考慮從空間層次逐層向上設計 {{site.data.keyword.Bluemix_notm}} 環境,而不是從組織層次逐層向下設計環境。 考量您計劃要開發及部署之應用程式的規模和範圍。{{site.data.keyword.Bluemix_notm}} 空間可以用來作為緊密連接或定義的一個以上應用程式的開發環境。例如,除了開發空間之外,您可能還想要建立用於單元測試、效能測試和整合測試的空間。您也可以為建置、編譯打包和正式作業定義空間。您建立的每一個空間都可以與相同組織內的不同團隊成員共用。 若您有在不同業務領域工作的人員,而且他們的活動不會重疊,則可以建立個別的 {{site.data.keyword.Bluemix_notm}} 組織。如果有兩個完全獨立的群組,則針對每一個群組各建立一個組織,可以為團隊成員和資源的交付和管理定義清楚的界限。您可以定義 API,以在組織之間進行通訊。 您可以配合您工作的方式來建立 {{site.data.keyword.Bluemix_notm}} 組織,而不是配合公司的內部結構。一般而言,公司組織會變動,但無論如何,應用程式的開發及維護都會繼續。請針對應用程式的生命期限來設計您的 {{site.data.keyword.Bluemix_notm}} 環境,而不是依照公司組織結構來設計。 反覆運算式開發和部署可能會導致應用程式迅速擴充。您的交付程序設計必須能夠快速並輕鬆地擴增。您會想要以快速的部署速度持續開發。讓您的開發和正式作業空間在相同的 {{site.data.keyword.Bluemix_notm}} 組織中,可提供對相同資源的存取權。在單一組織內管理不同的空間,可以減少管理負擔。如果開發、測試和作業人員在相同的 {{site.data.keyword.Bluemix_notm}} 組織內工作,就可以輕鬆地分工合作。 實作命名標準,以清楚識別組織和空間用量。例如,您可以包含雲端類型、地理區域、用量類型(如開發、測試、正式作業)、應用程式名稱,以及版本或修訂號碼。如此就可以輕鬆地識別組織和空間,以方便管理及存取。 空間數會因為反覆運算式開發而快速倍增。您可以在組織內定義所需的空間數。如果您計劃要定義大量空間數,您可能會想要建立應用程式來協助管理空間。當空間數超過 60 時,您可能會想要考慮再定義另一個組織。 請某位人員來建立及管理組織、定義空間,以及授與團隊成員存取權。可以將相同的存取權授與第二位人員,在組織管理員沒有空時便能維護環境。 識別需要存取各空間和組織的所有人員。決定他們的角色。團隊成員的工作角色將決定其權限。例如,資深開發人員需要檢視及更新整個 {{site.data.keyword.Bluemix_notm}} 開發環境的權限。不過,對於資淺的開發人員,其可以檢視及更新的內容將會受限。 ## 決定您的組織架構 {: #orgstructure} 若要設計使用「{{site.data.keyword.Bluemix_notm}} 公用」、「{{site.data.keyword.Bluemix_notm}} 專用」、「{{site.data.keyword.Bluemix_notm}} 本端」或任何組合的雲端環境,您可以使用下列組織架構: * 單一組織:如果您需要同一組使用者存取組織中任何地方的可用資源,無論是在「{{site.data.keyword.Bluemix_notm}} 公用」、「{{site.data.keyword.Bluemix_notm}} 專用」或「{{site.data.keyword.Bluemix_notm}} 本端」中,可以考慮使用此架構。 * 多組織:如果您需要「{{site.data.keyword.Bluemix_notm}} 公用」、「{{site.data.keyword.Bluemix_notm}} 專用」或「{{site.data.keyword.Bluemix_notm}} 本端」中的不同環境各自獨立,可以考慮使用此架構。 ### 單一組織與多組織 {: #singleormulti} 在單一組織環境中,公司的不同領域會共用基礎架構資源。而在多組織環境中,不會共用基礎架構資源。 這兩種組織架構皆支援下列原則: * 應用程式及/或專案的界限強制執行。 * 依使用者角色授與的資源管理授權。 若要實作單一組織架構,請在「{{site.data.keyword.Bluemix_notm}} 公用」、「{{site.data.keyword.Bluemix_notm}} 專用」或「{{site.data.keyword.Bluemix_notm}} 本端」中建立帳戶,並定義一個組織。然後,您可以根據不同事業線 (LOB)、交付階段、特定專案、應用程式、使用者許可權或這些元件的組合,來定義多個空間。 若要實作多組織架構,請在「{{site.data.keyword.Bluemix_notm}} 公用」、「{{site.data.keyword.Bluemix_notm}} 專用」或「{{site.data.keyword.Bluemix_notm}} 本端」中建立帳戶。接下來,您可以定義對應於不同 LOB、交付階段、特定專案、使用者許可權或這些元件之組合的組織。然後,您可以根據公司中相同部門交付的應用程式或專案來定義多個空間。 **附註:**您必須具有計費的帳戶(例如「隨收隨付制」或「訂閱」),才能定義多個組織。 ### 組織考量 {: #orgconsiderations} 當您實作單一組織架構時,組織會包括您用來開發、管理及部署雲端應用程式的所有雲端資源、服務和應用程式。在「{{site.data.keyword.Bluemix_notm}} 公用」中,組織會隔離各帳戶,而所有地區都可以使用該組織。 ![此圖顯示 {{site.data.keyword.Bluemix_notm}} 中的單一組織架構](images/singleorg_example.svg "此圖顯示 {{site.data.keyword.Bluemix_notm}} 中的單一組織架構") 圖 1.「{{site.data.keyword.Bluemix_notm}} 公用」、「{{site.data.keyword.Bluemix_notm}} 專用」和「{{site.data.keyword.Bluemix_notm}} 本端」的單一組織架構範例 {: #bpfigure1} 當您實作多組織架構時,組織會提供第一層的界限強制執行和抽象化,您可用來控制及定義哪些人可以執行哪些作業。您可以根據不同 LOB、交付階段、使用者角色、特定專案或這些元件的組合,來設計每一個組織。 您需要的組織數目,取決於多個因素: * 您在組織內管理配額及控制成本時所需的精度等級。 * 您在不同環境中必須強制執行的安全等級。例如,如果您使用容器,則可能會想要將用於開發的容器映像檔與用於正式作業的容器映像檔隔離。 * 依組織、國家/地區和產業需求而設置的組織位置。例如,您可能會想要在位於您所在地理位置(地理)特定區域中的專用雲端上,執行您的所有應用程式。 當您為雲端結構定義不同的組織時,請考量下列指引: * 定義並強制執行命名慣例。例如,定義一個命名慣例,讓組織的名稱包括業務領域、雲端類型(「{{site.data.keyword.Bluemix_notm}} 公用」、「{{site.data.keyword.Bluemix_notm}} 本端」或「{{site.data.keyword.Bluemix_notm}} 專用」)和處理程序階段(開發、測試或正式作業)的相關資訊。對於位在「{{site.data.keyword.Bluemix_notm}} 公用」中的組織,您可能還會想要新增地區的相關資訊。 * 定義適用於組織的限制。例如,定義將在該組織中工作之團隊成員的角色。 * 識別組織的管理員。 * 識別配置給此組織的業務領域。 下列情境顯示當您定義雲端環境中的 {{site.data.keyword.Bluemix_notm}} 組織數目時,可以採用的不同方法: * **情境 1:依商業應用程式交付來隔離使用者群組** 說明:公司規則要求每一個 LOB 的應用程式都必須由各 LOB 的使用者來開發、管理及部署。必須強制執行安全保護措施,讓使用者只能存取與其業務部分相關的應用程式。因此,使用者會在不同的業務領域中工作,他們處理的應用程式需要存取不同的 {{site.data.keyword.Bluemix_notm}} 資源,而且沒有活動重疊。 解決方案:您可以為每一個商業應用程式交付程序各建立一個組織。例如,為零售銀行業務建立一個組織,為投資銀行業務建立另一個組織。 ![此圖顯示依商業應用程式交付隔離使用者](images/bank_example.svg "此圖顯示依商業應用程式交付隔離使用者") 圖 2. 配合 LOB 交付的多組織架構範例 {: #bpfigure2} * **情境 2:根據使用者類型(內部使用者、外部使用者)的隔離** 說明:您的公司與不同的合作夥伴共事,而您需要在內部與外部使用者之間有清楚的界限。 解決方案:您可以建立一個組織來交付在內部使用的應用程式。此外,您也可以為每一個外部合作夥伴各建立一個組織。 * **情境 3:依專案隔離** 說明:您的公司舉辦黑客松 (Hackathon) 來識別新服務。 解決方案:您可以根據每個黑客松 (Hackathon) 各定義一個組織,並使用該組織來進行沙盤推演。在舉辦黑客松 (Hackathon) 之後,您可以將沙盤推演組織提升成為帳戶中的額外組織。 * **情境 4:依交付階段隔離使用者** 說明:有一家公司想要讓開發、測試和正式作業使用者透過交付來分工合作,但其存取權是由使用者角色和工作經驗來控制。 解決方案:您可以建立單一組織,並且為每一個交付階段各定義一個空間。然後,視使用者角色和工作經驗而定,授與他們完成工作以及在組織內分工合作所需的讀取和寫入權。 ![此圖顯示依交付階段隔離使用者](images/user_groups_example.svg "此圖顯示依交付階段隔離使用者") 圖 3. 配合交付階段的單一組織架構範例 {: #bpfigure3} ### 組織命名、限制和管理 {: #orgadmin} 請考量下列組織指引: * 定義並強制執行命名慣例。例如,定義一個命名慣例,讓組織的名稱包括業務領域、雲端類型(「{{site.data.keyword.Bluemix_notm}} 公用」、「{{site.data.keyword.Bluemix_notm}} 本端」或「{{site.data.keyword.Bluemix_notm}} 專用」)和 IT 角色(開發、測試或正式作業)的相關資訊。對於位在「{{site.data.keyword.Bluemix_notm}} 公用」中的組織,您可能還會想要新增地區的相關資訊。您可以在建立組織名稱之後予以變更。如果組織名稱有所變更,請將變更資訊通知所有組織團隊成員。 * 定義適用於組織的限制。例如,定義每一個團隊成員的角色,以及他們在該組織中工作所需的許可權。 * 識別組織的管理員。您可能會想要將組織管理工作委派給多個人員。 * 識別配置給此組織的業務領域。在組織內每一個空間中產生的應用程式用量會累計,並且在組織層次提報。 ## 決定您的空間 {: #determinespaces} 在組織內,空間可提供額外的界限強制執行和抽象化層次。 空間是組織中的保留區域,使用者可在其中開發及執行應用程式和服務。您可以在組織中建立任何數量的空間,也可以控制有權存取空間的使用者。如需詳細資料,請參閱[空間](/docs/admin/orgs_spaces.html#spaceinfo "空間")。 如果您計劃要定義大量空間數,您可能會想要建立應用程式來協助管理空間。當空間數超過 60 時,您可能會想要考慮再定義另一個組織。 ### 單一組織與多組織的空間 {: #spaceconsiderations} 當您採用單一組織架構時,會依照您在組織內定義的空間來提供隔離和抽象化層次。在定義空間時,請考量下列指引: * 定義一個用來管理服務的空間,只需要在組織中佈建及配置一次。 * 根據交付生命週期來定義空間。例如,您可以為開發中的應用程式定義一個以上的空間、為測試階段中的應用程式定義一個以上的空間,並且為正式作業中的應用程式定義一個以上的空間。 * 如果足夠生命週期界限不足,您可以為每個 LOB 和足夠階段各定義一個以上的空間,以加強隔離。 * 識別您是否需要為不同的使用者群組強制執行界限。例如,開發人員無法開發應用程式並進行測試。您需要一組不同的使用者來測試應用程式。在此情境中,您可以建立兩個空間,一個供應用程式的開發人員使用,一個供應用程式的測試人員使用。然後,授與各組使用者正確空間的存取權。 當您實作多組織架構時,可以依 LOB 及/或交付生命週期來將各組織隔離。然後,您可以根據公司中相同部門交付的應用程式或專案數目來定義多個空間。在計劃組織中的空間時,請考量下列指引: * 定義一個用來管理服務的空間,只需要在組織中佈建及配置一次。 * 為每個應用程式、每個相關應用程式群組或一個特定專案定義一個空間。 * 如果您需要為不同的使用者強制執行界限,請為每一組使用者定義一個空間。當使用者被授與空間中的開發人員角色時,該使用者即具有完整的存取權,可以存取在該空間中佈建及執行的任何資源和 {{site.data.keyword.Bluemix_notm}} 服務。如果您需要強制執行更嚴密的安全措施,以防止使用者控制每項資源,請考慮定義不同的空間。您可以在這其中的任何空間內佈建 {{site.data.keyword.Bluemix_notm}} 服務,以供在該空間執行的應用程式使用。 ### 空間命名、限制及管理 {: #spaceadmin} 若要為雲端組織定義不同的空間,請考量下列指引: * 定義並強制執行命名慣例。例如,定義一個命名慣例,讓空間名稱包括組織所在位置以及雲端類型(「{{site.data.keyword.Bluemix_notm}} 公用」、「{{site.data.keyword.Bluemix_notm}} 專用」或「{{site.data.keyword.Bluemix_notm}} 本端」)的相關資訊。您可以在建立空間名稱之後予以變更。如果空間名稱有所變更,請將變更資訊通知所有空間團隊成員。 * 定義適用於空間的限制。例如,定義可以在每一個空間中開發、管理及部署的應用程式類型。 * 識別空間的管理員。您可能會想要將空間管理工作委派給多個人員。 ## 決定組織的配額 {: #determinequota} 當您在 {{site.data.keyword.Bluemix_notm}} 中建立組織時,會佈建基礎架構資源,其中包括例如記憶體、網際網路通訊協定 (IP)、伺服器和儲存空間等資源: * 若為「{{site.data.keyword.Bluemix_notm}} 公用」,IBM 會配置一組最基本的資源給組織。根據帳戶類型,您會有不同的資源配置。這些資源會定義 IBM 配置給組織的配額。 * 若為「{{site.data.keyword.Bluemix_notm}} 專用」,您可以向 IBM 要求一組資源,然後將其分配給「{{site.data.keyword.Bluemix_notm}} 專用」雲端環境中的不同組織。 * 若為「{{site.data.keyword.Bluemix_notm}} 本端」,則是由您提供資源,然後將其分配給「{{site.data.keyword.Bluemix_notm}} 本端」雲端環境中的不同組織。 若為「{{site.data.keyword.Bluemix_notm}} 公用」和「{{site.data.keyword.Bluemix_notm}} 專用」,您可以向 IBM 要求額外的資源。若為「{{site.data.keyword.Bluemix_notm}} 本端」,則由您負責提供在本端雲端中營運可能需要的任何資源。 配置給組織的配額,即代表組織內可用的資源。您可以管理配額,並決定如何將資源分配至整個組織。 ### 管理及監視配額 {: #managequota} 您可以依空間和依基礎架構來管理及監視帳戶的配額。佈建在空間中,然後由已部署應用程式使用的任何資源,都會耗用組織可用的一部分配額。 * 如需如何在「{{site.data.keyword.Bluemix_notm}} 公用」中檢視及管理組織配額的相關資訊,請參閱[管理配額](/docs/admin/manageorg.html#managequota "管理配額")。 * 如需如何在「{{site.data.keyword.Bluemix_notm}} 專用」或「{{site.data.keyword.Bluemix_notm}} 本端」中檢視及管理組織配額的相關資訊,請參閱[檢視用量及報告](/docs/admin/index.html?pos=2#oc_resource "檢視用量及報告")。 ## 指派角色 {: #roles} 您可以授與多個角色給 {{site.data.keyword.Bluemix_notm}} 帳戶中的團隊成員。這些角色定義了使用者用來管理帳戶和組織資源的許可權: * 您可以將[使用者角色](/docs/iam/users_roles.html#userrolesinfo "使用者角色")授與給組織的成員。這些角色定義在組織內的存取層次,並限制哪些人可以存取空間及其資源。例如,您可以授與使用者不同空間的不同許可權。 * 只有在「{{site.data.keyword.Bluemix_notm}} 專用」和「{{site.data.keyword.Bluemix_notm}} 本端」中,您才可以將[管理角色](/docs/admin/index.html#oc_useradmin "管理角色")授與給帳戶成員,以供其管理系統資訊、帳戶資源用量、報告和日誌、型錄服務、使用者,以及每個組織的資源用量。 ### 帳戶擁有者 {: #accountowner} 無論是設計多組織架構或單一組織架構,帳戶擁有者都是雲端環境的超級使用者。 帳戶擁有者的核心作業包括: * 管理廣域帳戶的資源。 * 建立組織。 * 新增團隊成員至帳戶。 若要新增團隊成員至帳戶,請利用使用者的電子郵件位址,或是電子郵件位址清單。在「{{site.data.keyword.Bluemix_notm}} 專用」和「{{site.data.keyword.Bluemix_notm}} 本端」中,您也可以使用公司 LDAP 來新增使用者及/或使用者群組。您也可以從檔案匯入使用者。如需相關資訊,請參閱[管理使用者及許可權](/docs/admin/index.html#oc_useradmin "管理使用者及許可權")。 帳戶擁有者也可以執行下列作業: * 指派**管理者**角色給一位以上使用者,以新增這些使用者作為組織的管理員。請考慮新增兩位使用者作為組織管理員。第一位使用者擔任組織的主要管理員。第二位使用者擔任代理管理員,以在主要管理員無法執行工作時代理其職務。 * 在「{{site.data.keyword.Bluemix_notm}} 公用」中(視[帳戶類型](/docs/pricing/index.html#pay-accounts "帳戶類型")而定),設定消費通知。首先,帳戶擁有者要定義當成本達到特定限制時,用來提出警示的臨界值。然後,[配置電子郵件通知](/docs/admin/account.html#notifications "配置電子郵件通知")。帳戶管理員可以使用電子郵件中的資訊作為警示通知,並可根據所提供的資訊來採取動作,例如升級帳戶。**附註:**帳戶擁有者是唯一可以接收消費通知電子郵件的人員。 * 指派**管理**角色給一位以上使用者,以新增這些使用者作為帳戶的管理者。請考慮至少新增兩位使用者。第一位使用者擔任帳戶的主要管理者。第二位使用者擔任代理管理者。 * 定義帳戶通知,以通知維護更新或重要突發事件警示的相關資訊。您可以配置這些通知,以傳送電子郵件或「簡訊服務」。 ### 使用者角色 {: #userroles} 使用者角色定義您可以指派給組織團隊成員的許可權,並定義團隊成員在組織和每一個空間內所擁有的存取層次。 在多組織架構或單一組織架構中定義團隊成員,以及每一位使用者完成工作所需的許可權: 1. 識別需要存取組織的一組使用者。 2. 為組織中以及組織空間中的每一個團隊成員定義許可權。 3. 選取可授與使用者所需許可權的角色。 * 組織管理員 * 組織審核員 * 組織帳單管理員 * 空間管理員 * 空間開發人員 * 空間審核員 #### 組織管理員 {: #bporgmgr} 組織管理員負責的作業包括建立空間、將配額分配給各空間、邀請團隊成員並選擇性地授與其特定角色,以及定義自訂網域。 #### 組織審核員 {: #bporgauditor} 具有組織**審核員**角色的團隊成員可以監視配額、資源用量,以及組織中所有空間的團隊成員。然後,審核員可以針對組織效率提出報告,並強調顯示任何潛在問題。 * 當您採用多組織架構時,可能會想要將審核員角色授與給帳戶中每個組織的相同團隊成員。然後,這些團隊成員就可以監視雲端環境中所有組織之間的配額,得到對帳戶的大局觀。 * 當您採用單一組織架構時,可以將審核員角色授與給負責監視組織配額用量和整體效率的團隊成員。 #### 組織帳單管理員 {: #bporgbillingmgr} 具有**帳單管理員**角色的團隊成員可以監視組織的成本。 * 當您採用多組織架構時,可能會想要將帳單角色授與給帳戶中每個組織的同一組團隊成員。然後,這些團隊成員就可以監視每一個組織的成本,得到對帳戶的大局觀。 * 在單一組織架構中,識別負責監視成本的使用者。 #### 空間管理員 {: #bpspacemgr} 空間**管理員**負責處理在其管理及控制的空間內執行的任何工作。空間管理員可以執行下列作業: * 監視配置給空間的配額。 * 向組織管理員要求額外資源。 * 通知組織管理員有不必要的資源。 * 將團隊成員新增至具有**開發人員**角色的空間。 * 可選擇將空間**管理員**角色指派給團隊成員,以在他們不在時擔任代理空間管理員。 #### 空間開發人員 {: #bpspacedev} 空間開發人員可以執行下列作業: * 管理 Cloud Foundry 應用程式。 * 佈建及配置 {{site.data.keyword.Bluemix_notm}} 服務。 * 建立網域與應用程式的關聯。 #### 空間審核員 {: #bpspaceauditor} 您可能會想要針對每個空間,將空間**審核員**角色授與給具有組織**審核員**角色的相同團隊成員。在您的企業中,可能必須將此角色授與給一組特定的使用者。 ### 專用及本端帳戶的管理角色 {: #adminroles} [管理角色](/docs/hybrid/index.html#oc_useradmin "管理使用者及許可權")定義您可以授與使用者以用來管理「{{site.data.keyword.Bluemix_notm}} 專用」或「{{site.data.keyword.Bluemix_notm}} 本端」帳戶的許可權。 您可以授與讀取或寫入權,讓使用者能夠檢視系統資訊、帳戶資源用量、報告和日誌、型錄服務、使用者,以及每個組織的資源用量。 在多組織架構或單一組織架構中,定義使用者以及每位使用者管理帳戶時所需的許可權。 1. 識別一組管理雲端團隊使用者,並授與其相關的管理許可權。將組織管理員包含為此團隊的成員。 2. 定義這些使用者在帳戶中的許可權。在團隊的使用者之間,分配管理型錄和報告的許可權。 3. 為每一位使用者選取一個以上角色,以符合管理帳戶所需的許可權: * 管理角色:使用者有權管理整個組織。 * 使用者角色:具有寫入權的組織管理員,可以將使用者新增至帳戶及其組織。具有讀取權的組織管理員,可以檢視帳戶中的成員清單。 * 型錄角色:具有寫入權的使用者可以定義及管理使用者可以在 {{site.data.keyword.Bluemix_notm}} 型錄中看到哪些 Bluemix 服務和入門範本。 * 報告角色:具有寫入權的使用者可以檢視及新增報告,而其他具有讀取權的使用者可以下載。將讀取權授與給管理團隊的所有成員。 * 登入角色:將此角色授與給管理團隊的所有成員。您也可以將此角色授與給帳戶中需要存取權的其他使用者,讓他們能夠檢視帳戶通知和系統資訊。
Python
UTF-8
8,501
2.765625
3
[]
no_license
import os import pandas as pd import zipfile import shutil from tqdm import tqdm import torch import numpy as np import torchvision as tv import matplotlib.pyplot as plt from torch.utils.data import dataloader from torchvision import models import random """ Предлагаем поучаствовать в соревновании на Kaggle "Dirty vs Cleaned V2" https://www.kaggle.com/c/platesv2 Чтобы получить за него баллы, отправьте свой submission.csv в форму этого задания. Мы начисляем от 0 до 20 баллов, в зависимости от accuracy: 80% даст 0 баллов, 100% - 20 баллов. """ class ImageFolderWithPaths(tv.datasets.ImageFolder): def __getitem__(self, index): original_tuple = super(ImageFolderWithPaths, self).__getitem__(index) path = self.imgs[index][0] tuple_with_path = (original_tuple + (path,)) return tuple_with_path def show_input(input_tensor, title=''): image = input_tensor.permute(1, 2, 0).numpy() image = std * image + mean plt.imshow(image.clip(0, 1)) plt.title(title) plt.show() plt.pause(0.001) def train_model(model, loss, optimizer, scheduler, num_epochs): for epoch in range(num_epochs): print('Epoch {}/{}:'.format(epoch, num_epochs - 1), flush=True) # У каждой эпохи есть этап обучения и валидации. for phase in ['train', 'val']: if phase == 'train': dataloader = train_dataloader # scheduler.step() model.train() # Установить модель в режим обучения else: dataloader = val_dataloader model.eval() # Установить модель в режим валидации running_loss = 0. running_acc = 0. # Перебираем данные. for inputs, labels in dataloader: inputs = inputs.to(device) labels = labels.to(device) optimizer.zero_grad() # forward and backward with torch.set_grad_enabled(phase == 'train'): preds = model(inputs) loss_value = loss(preds, labels) preds_class = preds.argmax(dim=1) # backward + оптимизировать, только если в фазе обучения if phase == 'train': loss_value.backward() optimizer.step() # статистика running_loss += loss_value.item() running_acc += (preds_class == labels.data).float().mean() epoch_loss = running_loss / len(dataloader) epoch_acc = running_acc / len(dataloader) print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc), flush=True) return model if __name__ == "__main__": seed = 51 random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) # torch.backends.cudnn.deterministic = True print(os.listdir("input")) with zipfile.ZipFile('input/plates.zip', 'r') as zip_obj: # Извлечь все содержимое zip-файла в текущий каталог zip_obj.extractall('kaggle/working/') print('After zip extraction:') print(os.listdir("kaggle/working/")) data_root = 'kaggle/working/plates/' print(os.listdir(data_root)) train_dir = 'train' val_dir = 'val' class_names = ['cleaned', 'dirty'] for dir_name in [train_dir, val_dir]: for class_name in class_names: os.makedirs(os.path.join(dir_name, class_name), exist_ok=True) for class_name in class_names: source_dir = os.path.join(data_root, 'train', class_name) for i, file_name in enumerate(tqdm(os.listdir(source_dir))): if i % 6 != 0: dest_dir = os.path.join(train_dir, class_name) else: dest_dir = os.path.join(val_dir, class_name) shutil.copy(os.path.join(source_dir, file_name), os.path.join(dest_dir, file_name)) train_transforms = tv.transforms.Compose([ tv.transforms.RandomApply([ tv.transforms.ColorJitter( brightness=0.4, contrast=0.4, saturation=0.4, hue=0.4 ) ]), tv.transforms.RandomResizedCrop(224), tv.transforms.ToTensor(), tv.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) val_transforms = tv.transforms.Compose([ tv.transforms.Resize((224, 224)), tv.transforms.ToTensor(), tv.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) train_dataset = tv.datasets.ImageFolder(train_dir, train_transforms) val_dataset = tv.datasets.ImageFolder(val_dir, val_transforms) batch_size = 8 train_dataloader = dataloader.DataLoader( train_dataset, batch_size=batch_size, shuffle=True, num_workers=1) val_dataloader = dataloader.DataLoader( val_dataset, batch_size=batch_size, shuffle=False, num_workers=1) print(len(train_dataloader), len(train_dataset)) X_batch, y_batch = next(iter(train_dataloader)) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) plt.imshow(X_batch[0].permute(1, 2, 0).numpy() * std + mean) plt.show() for x_item, y_item in zip(X_batch, y_batch): show_input(x_item, title=class_names[y_item]) # выбираем нейросеть # model = models.resnet50(pretrained=True) model = models.resnet152(pretrained=True) # model = torch.hub.load('pytorch/vision:v0.6.0', 'resnext50_32x4d', pretrained=True) # model = torch.hub.load('pytorch/vision:v0.6.0', 'resnext101_32x8d', pretrained=True) # model = torch.hub.load('pytorch/vision:v0.6.0', 'wide_resnet101_2', pretrained=True) # Замораживаем сеть, т.е. не обучаем все слои for param in model.parameters(): param.requires_grad = False # заменяем последний полносвязный слой с выходом два класса (нейрона) model.fc = torch.nn.Linear(model.fc.in_features, 2) # if torch.cuda.is_available() else "cpu" device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = model.to(device) loss = torch.nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=1.0e-3) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1) # Обучаем train_model(model, loss, optimizer, scheduler, num_epochs=5) test_dir = 'test' shutil.copytree(os.path.join(data_root, 'test'), os.path.join(test_dir, 'unknown')) test_dataset = ImageFolderWithPaths('test', val_transforms) test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=1) print(test_dataset) # Валидация model.eval() test_predictions = [] test_img_paths = [] for inputs, labels, paths in tqdm(test_dataloader): inputs = inputs.to(device) labels = labels.to(device) with torch.set_grad_enabled(False): preds = model(inputs) test_predictions.append( torch.nn.functional.softmax(preds, dim=1)[:, 1].data.cpu().numpy()) test_img_paths.extend(paths) test_predictions = np.concatenate(test_predictions) inputs, labels, paths = next(iter(test_dataloader)) for img, pred in zip(inputs, test_predictions): show_input(img, title=pred) plt.show() # Формируем 'submission.csv' submission_df = pd.DataFrame.from_dict({'id': test_img_paths, 'label': test_predictions}) submission_df['label'] = submission_df['label'].map(lambda pred: 'dirty' if pred > 0.5 else 'cleaned') submission_df['id'] = submission_df['id'].str.replace('.jpg', '', regex=True) submission_df['id'] = submission_df['id'].str[-4:] submission_df.set_index('id', inplace=True) submission_df.head(n=6) submission_df.to_csv('submission.csv') shutil.rmtree('train') shutil.rmtree('val') shutil.rmtree('test') shutil.rmtree('kaggle')
Java
UTF-8
7,592
2.015625
2
[]
no_license
package cash.xcl.api.dto; import cash.xcl.api.AllMessages; import cash.xcl.api.DtoParser; import cash.xcl.api.tcp.WritingAllMessages; import cash.xcl.api.util.RegionIntConverter; import net.openhft.chronicle.bytes.*; import net.openhft.chronicle.core.Jvm; import net.openhft.chronicle.core.io.IORuntimeException; import net.openhft.chronicle.wire.IntConversion; import net.openhft.chronicle.wire.Marshallable; import net.openhft.chronicle.wire.WireIn; import net.openhft.chronicle.wire.WireOut; import org.jetbrains.annotations.NotNull; public class TransactionBlockEvent extends SignedMessage { @IntConversion(RegionIntConverter.class) private int region; private int weekNumber; private long blockNumber; // unsigned int static public int MAX_16_BIT_NUMBER = 65536 - 1000; static int numberOfObjects = 0; private transient Bytes transactions; private transient int count; private transient DtoParser dtoParser; static public long _1_MB = 1 << 20; static public long _2_MB = 2 << 20; static public long _4_MB = 4 << 20; static public long _16_MB = 16 << 20; static public long _32_MB = 32 << 20; public TransactionBlockEvent() { this(0, false); } public TransactionBlockEvent(long capacity, boolean isFixedCapacity) { if (isFixedCapacity) { long start = System.nanoTime(); transactions = NativeBytesStore.lazyNativeBytesStoreWithFixedCapacity(capacity).bytesForWrite(); long time = System.nanoTime() - start; if (time > 100e3) System.out.printf("took %,d us to create %,d bytes%n", time / 1000, capacity); // if (Jvm.isDebugEnabled(getClass())) // System.out.printf("NEW TBE object - deep copying: %,d bytes%n", transactions.realCapacity()); } else { if (capacity > 0) { transactions = Bytes.allocateElasticDirect(capacity); if (Jvm.isDebugEnabled(getClass())) System.out.printf("NEW TBE object - explicit: %,d bytes%n", transactions.realCapacity()); } else { if (capacity == 0) { // 0 means use default transactions = Bytes.allocateElasticDirect(); // if (Jvm.isDebugEnabled(getClass())) // System.out.printf("NEW TBE object - default: %,d bytes%n", transactions.realCapacity()); } else { throw new IllegalArgumentException("bad capacity"); } } } numberOfObjects++; if (numberOfObjects % 1000 == 0) System.out.println("number of new TransactionBlockEvent objects: " + numberOfObjects); } public TransactionBlockEvent dtoParser(DtoParser dtoParser) { this.dtoParser = dtoParser; return this; } @Override public void reset() { super.reset(); transactions.clear(); count = 0; } public TransactionBlockEvent addTransaction(SignedMessage message) { count++; transactions.writeMarshallableLength16(message); //System.out.println("transactions writePosition " + transactions.writePosition() ); return this; } public void replay(AllMessages allMessages) { if (dtoParser == null) { dtoParser = new BaseDtoParser(); } transactions.readPosition(0); long limit = transactions.readLimit(); while (!transactions.isEmpty()) { try { int length = transactions.readUnsignedShort(); transactions.readLimit(transactions.readPosition() + length); dtoParser.parseOne(transactions, allMessages); } finally { transactions.readPosition(transactions.readLimit()); transactions.readLimit(limit); } } transactions.readPosition(0); } @Override protected void readMarshallable2(BytesIn<?> bytes) { region = bytes.readInt(); weekNumber = bytes.readUnsignedShort(); blockNumber = bytes.readUnsignedInt(); if (transactions == null) { transactions = Bytes.allocateElasticDirect(bytes.readRemaining()); } transactions.clear().write((BytesStore) bytes); } @Override protected void writeMarshallable2(BytesOut<?> bytes) { // System.out.println("Write " + this); bytes.writeInt(region); bytes.writeUnsignedShort(weekNumber); bytes.writeUnsignedInt(blockNumber); bytes.write(transactions); } @Override public void readMarshallable(@NotNull WireIn wire) throws IORuntimeException { reset(); super.readMarshallable(wire); wire.read("transactions").sequence(this, (tbe, in) -> { while (in.hasNextSequenceItem()) { tbe.addTransaction(in.object(SignedMessage.class)); } }); // System.out.println("Read " + this); } @NotNull @Override public <T> T deepCopy() { TransactionBlockEvent tbe = new TransactionBlockEvent(transactions.readRemaining(), true); this.copyTo(tbe); return (T) tbe; } @Override public <T extends Marshallable> T copyTo(@NotNull T t) { TransactionBlockEvent tbe = (TransactionBlockEvent) t; super.copyTo(t); tbe.region(region); tbe.weekNumber(weekNumber); tbe.blockNumber(blockNumber); tbe.transactions().ensureCapacity(transactions.readRemaining()); tbe.transactions() .clear() .write(transactions); return t; } @Override public void writeMarshallable(@NotNull WireOut wire) { super.writeMarshallable(wire); wire.write("transactions").sequence(out -> replay(new WritingAllMessages() { @Override public WritingAllMessages to(long addressOrRegion) { throw new UnsupportedOperationException(); } @Override public void write(SignedMessage message) { out.object(message); } @Override public void close() { throw new UnsupportedOperationException(); } })); } @Override public int messageType() { return MessageTypes.TRANSACTION_BLOCK_EVENT; } // to add helper methods. public Bytes transactions() { return transactions; } public int weekNumber() { return weekNumber; } public TransactionBlockEvent weekNumber(int weekNumber) { this.weekNumber = weekNumber; return this; } public long blockNumber() { return blockNumber; } public TransactionBlockEvent blockNumber(long blockNumber) { this.blockNumber = blockNumber; return this; } public int region() { return region; } public TransactionBlockEvent region(int region) { this.region = region; return this; } public TransactionBlockEvent region(String region) { this.region = RegionIntConverter.INSTANCE.parse(region); return this; } public int count() { return count; } public boolean isBufferFull() { return transactions.writePosition() > MAX_16_BIT_NUMBER; } static public void printNumberOfObjects() { System.out.println("Total number of new TransactionBlockEvent objects = " + numberOfObjects); } }
Python
UTF-8
230
3.890625
4
[]
no_license
X=int(input("Enter first number: ")) Y=int(input("Enter second number: ")) c=[] print("Even Numbers between ",X,"And ",Y," :") X=X+1 while (X<Y): if(X%2==0): c=c+[X] X=X+1 else: X=X+1 print(c)
Java
UTF-8
242
3.078125
3
[]
no_license
package br.usp.ime.mac321.lista04.ex1; public class Fibonacci { public static int fibonacci(int n) { if (n<0) return -1; else if (n==0) return 0; else if (n==1) return 1; else return fibonacci(n-1)+fibonacci(n-2); } }
Markdown
UTF-8
2,952
2.984375
3
[ "MIT" ]
permissive
# SAT-Maude SAT-Maude is a program written entirely in Maude to study and compare different techniques and heuristics in modern SAT solvers. This project contains 6 different strategies: 1. Classic DPLL 2. Modern DPLL 3. Watch literal DPLL 4. Watch literal DPLL with JW heuristic 5. Watch literal DPLL with VSIDS heuristic 6. Berkmin Solver More details in how these strategies work will be included in a near future. ## Installation ### 1. Download Core Maude 3.0 Download the source code from [Maude official site](http://maude.cs.illinois.edu/w/index.php/Maude_download_and_installation) Aditional requirements may be needed to run Maude. ## Run examples To execute SAT-Maude, run the following command inside the folder *code*: 1. Run an example from *examples* folder using Maude: ``` Maude-executable < ../examples/example.txt ``` For instance, if Maude executable is found in `../../Maude-3.0+yices2-linux/maude-Yices2.linux64` and we want to execute example `../examples/vsids-unsat.txt`, then we use the following command: ``` ../../Maude-3.0+yices2-linux/maude-Yices2.linux64 < ../examples/vsids-unsat.txt ``` ## Generate Maude instances You can generate your own instances to analyze in Maude using executable file in *parser* folder. These instances must follow [DIMACS CNF format](https://www.domagoj-babic.com/uploads/ResearchProjects/Spear/dimacs-cnf.pdf). This executable must be called with three arguments: file that contains the strategy, module that contains strategy call and name of strategy call. There are six different possibilities for these arguments: 1. *Classic DPLL system*: classic-dpll-strat CLASSIC-DPLL-STRATEGY classic-dpll-strat 2. *Basic DPLL system with learning*: basic-dpll-strat BASIC-DPLL-STRATEGY basic-dpll-strat 3. *Watch literal DPLL system*: watch-literal-dpll-strat WATCH-LITERAL-DPLL-STRATEGY watch-literal-dpll-strat 4. *Watch literal DPLL system with JW heuristic*: jw-heuristic-strat JW-HEURISTIC-STRATEGY jw-heuristic-strat 5. *Watch literal DPLL system with VSIDS heuristic*: vsids-heuristic-strat VSIDS-HEURISTIC-STRATEGY vsids-heuristic-strat 6. *Berkmin Solver*: berkmin-strat BERKMIN-STRATEGY berkmin-strat For instance, if we want to generate the Maude file `../examples/berkmin-20-01.txt` from instance `../instances/sat/uf20-01.cnf` using *Berkmin Solver* strategy, we use the following command in folder *tools*: ``` ./parser berkmin-strat BERKMIN-STRATEGY berkmin-strat < ../instances/sat/uf20-01.cnf > ../examples/berkmin-20-01.txt ``` Instances in *instances* folder represent 3-SAT random formulas that have been taken directly from [SATLIB](https://www.cs.ubc.ca/~hoos/SATLIB/benchm.html). ## Scripts A script has been included to analyze all files in a folder using the same strategy and store the results in another folder. This script has been included in folder *scripts* and it needs Maude path and the path of folder where results are stored.
Go
UTF-8
1,024
2.828125
3
[]
no_license
package main import ( "encoding/json" "fmt" "io/ioutil" ) const ( //max = 6 //min = 4 //min = 2 ) /* var data = map[string][][]byte{ "bmp": [][]byte{[]byte{0x42, 0x4D}}, "jpg": [][]byte{[]byte{0xFF, 0xD8}}, //"jpg": [][]byte{[]byte{0xFF, 0xD8, 0xDD, 0xE0}, []byte{0xFF, 0xD8, 0xFF, 0xFE}}, "png": [][]byte{[]byte{0x89, 0x50, 0x4E, 0x47}}, "gif": [][]byte{[]byte{0x47, 0x49, 0x46, 0x38, 0x39, 0x61}, []byte{0x47, 0x49, 0x46, 0x38, 0x37, 0x61}}, } */ var min, max int var data map[string][][]byte func loadMagic(filePath string) (err error) { var bb []byte bb, err = ioutil.ReadFile(filePath) if err != nil { return } err = json.Unmarshal(bb, &data) if err != nil { return } for _, pp := range data { for _, p := range pp { l := len(p) if l == 0 { err = fmt.Errorf("abnormal magic") return } if l > max { max = l } if min == 0 { min = l } else { if l < min { min = l } } } } return }
Java
UTF-8
6,314
2.234375
2
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.android; import static com.google.errorprone.BugPattern.LinkType.NONE; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.enclosingClass; import static com.google.errorprone.matchers.Matchers.enclosingMethod; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.methodInvocation; import static com.google.errorprone.matchers.Matchers.methodIsNamed; import com.google.auto.service.AutoService; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; /** * Parcelable data can be transported in many ways (some of which can be very * inefficient) so this checker guides developers towards using high-performance * best-practices. */ @AutoService(BugChecker.class) @BugPattern( name = "AndroidFrameworkEfficientParcelable", summary = "Verifies Parcelable performance best-practices", linkType = NONE, severity = WARNING) public final class EfficientParcelableChecker extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<Tree> INSIDE_WRITE_TO_PARCEL = allOf( enclosingClass(isSubtypeOf("android.os.Parcelable")), enclosingMethod(methodIsNamed("writeToParcel"))); private static final Matcher<ExpressionTree> WRITE_STRING = methodInvocation( instanceMethod().onExactClass("android.os.Parcel").named("writeString")); private static final Matcher<ExpressionTree> WRITE_STRING_ARRAY = methodInvocation( instanceMethod().onExactClass("android.os.Parcel").named("writeStringArray")); private static final Matcher<ExpressionTree> WRITE_VALUE = methodInvocation( instanceMethod().onExactClass("android.os.Parcel").named("writeValue")); private static final Matcher<ExpressionTree> WRITE_PARCELABLE = methodInvocation( instanceMethod().onExactClass("android.os.Parcel").named("writeParcelable")); private static final Matcher<ExpressionTree> WRITE_LIST = methodInvocation( instanceMethod().onExactClass("android.os.Parcel").named("writeList")); private static final Matcher<ExpressionTree> WRITE_PARCELABLE_LIST = methodInvocation( instanceMethod().onExactClass("android.os.Parcel").named("writeParcelableList")); private static final Matcher<ExpressionTree> WRITE_PARCELABLE_ARRAY = methodInvocation( instanceMethod().onExactClass("android.os.Parcel").named("writeParcelableArray")); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (INSIDE_WRITE_TO_PARCEL.matches(tree, state)) { if (WRITE_STRING.matches(tree, state)) { return buildDescription(tree) .setMessage("Recommended to use 'writeString8()' to improve " + "efficiency; sending as UTF-8 can double throughput") .build(); } if (WRITE_STRING_ARRAY.matches(tree, state)) { return buildDescription(tree) .setMessage("Recommended to use 'writeString8Array()' to improve " + "efficiency; sending as UTF-8 can double throughput") .build(); } if (WRITE_VALUE.matches(tree, state)) { return buildDescription(tree) .setMessage("Recommended to use strongly-typed methods to improve " + "efficiency; saves 4 bytes for type and overhead of " + "Parcelable class name") .build(); } if (WRITE_PARCELABLE.matches(tree, state)) { return buildDescription(tree) .setMessage("Recommended to use 'item.writeToParcel()' to improve " + "efficiency; saves overhead of Parcelable class name") .build(); } if (WRITE_LIST.matches(tree, state)) { return buildDescription(tree) .setMessage("Recommended to use 'writeTypedList()' to improve " + "efficiency; saves overhead of repeated Parcelable class name") .build(); } if (WRITE_PARCELABLE_LIST.matches(tree, state)) { return buildDescription(tree) .setMessage("Recommended to use 'writeTypedList()' to improve " + "efficiency; saves overhead of repeated Parcelable class name") .build(); } if (WRITE_PARCELABLE_ARRAY.matches(tree, state)) { return buildDescription(tree) .setMessage("Recommended to use 'writeTypedArray()' to improve " + "efficiency; saves overhead of repeated Parcelable class name") .build(); } } return Description.NO_MATCH; } }
Python
UTF-8
868
3.0625
3
[]
no_license
import os, sys from PIL import Image size = 600, 600 def image_scale(file): a,b = os.path.splitext(file) if b in [".jpeg", ".jpg", ".png"]: outfile = a + "_standard" + b try: im = Image.open(file) im.thumbnail(size) im.save(outfile, im.format) except IOError: print "cannot create thumbnail for '%s'" % file def test(root_dir): list_dirs = os.walk(root_dir) for root, dirs, files in list_dirs: for f in files: image_scale(os.path.join(root, f)) def main(): length = len(sys.argv) if length <= 1: print "need root directory parameter" exit() elif length > 2: print "only one root directory parameter needed" exit() else: argv = sys.argv[1] test(argv) if __name__ == '__main__': main()
TypeScript
UTF-8
2,268
3.78125
4
[]
no_license
// Reference - https://blog.bitsrc.io/solid-principles-every-developer-should-know-b3bfa96bb688 // Pending - Dependency Inversion Principle /** * Single Responsibility Principle - A class/component/microService should be responsible for only one thing. * If a class has more than one responsibility, it becomes coupled. * A change to one responsibility results to modification of the other responsibility. */ // Example class Animal { name; constructor(name: string){ this.name = name || '' } getAnimalName() { return this.name; } makeSound() { return 'mute'; } legCount():any { return 'no legs'; }; } class AnimalDB { getAnimal(a: Animal) { } saveAnimal(a: Animal) { } } /** * Open-Closed Principle - Software entities(Classes, modules, functions) should be open for extension, not modification. * Liskov Substitution Principle - A sub-class must be substitutable for its super-class */ // Eaxmple class Lion extends Animal { makeSound() { return 'roar'; } legCount() { return 4; } } class Squirrel extends Animal { makeSound() { return 'squeak'; } legCount() { return 4; } } class Snake extends Animal { makeSound() { return 'hiss'; } } const animals: Array<Animal> = [ new Lion('lion'), new Squirrel('mouse'), new Snake('snake'), new Animal('Human') ] for(let animal of animals) { console.log(`Animal ${animal.getAnimalName()} makes ${animal.makeSound()}! sound and has ${animal.legCount()} legs`); } /** * Interface Segregation Principle - Make fine grained interfaces that are client specific Clients should not be forced to depend upon interfaces that they do not use. */ interface IShape { draw(); } class Circle implements IShape { radius; constructor(radius) { this.radius = radius || 0; } draw(){ return `Drawing circle with radius ${this.radius}`; } } class Triangle implements IShape { side constructor(side) { this.side = side || 0; } draw(){ return `Drawing triangle with side ${this.side}`; } } const shapes: Array<IShape> = [ new Circle(5), new Triangle(20), ]
JavaScript
UTF-8
2,608
2.75
3
[]
no_license
import React, { Component } from "react"; import "./App.css"; import employees from "./employees.json"; import EmployeeRow from "./components/employeeRow"; import Wrapper from "./components/Wrapper"; import Title from "./components/Title"; import BasicTextField from "./components/field/Field.js"; class App extends Component { state = { employees, SortCategory: "", textFieldValue: "", //additional state for filter }; handleTextFieldChange = (e) => { this.setState({ textFieldValue: e.target.value }); this.filterList(); }; filterList = () => { const currentList = [...this.state.employees]; const filteredList = currentList.filter((el) => { return el.name.includes(this.state.textFieldValue); }); console.log(filteredList); this.setState({ employees: filteredList }); }; handleChange = (event) => { // setCategory(event.target.value); this.setState({ SortCategory: event.target.value }); }; handleList = (event) => { // handle the sort from array of employees, sort by category. Have a default sort //handle the filter, later // const sorted = // }; handleTableSort = (colName) => { const currentList = [...this.state.employees]; currentList.sort((employeeA, employeeB) => { if (employeeA[colName] < employeeB[colName]) { return -1; } }); console.log(currentList); this.setState({ employees: currentList, }); }; render() { return ( <div> <Title>Employee List</Title> <div> <BasicTextField handleTextFieldChange={this.handleTextFieldChange} /> </div> <Wrapper> <table> <thead> <tr> <td onClick={() => this.handleTableSort("name")}>name</td> <td onClick={() => this.handleTableSort("occupation")}> occupation </td> <td onClick={() => this.handleTableSort("location")}> location </td> </tr> </thead> <tbody> {this.state.employees.map((employee) => ( <EmployeeRow id={employee.id} key={employee.id} name={employee.name} occupation={employee.occupation} location={employee.location} /> ))} </tbody> </table> {/* <DropDown handleChange={this.handleChange} /> */} </Wrapper> </div> ); } } export default App;
SQL
UTF-8
1,034
2.984375
3
[]
no_license
-- Table: public.transactions -- DROP TABLE public.transactions; CREATE TABLE public.transactions ( code character varying COLLATE pg_catalog."default", load_date date, date_index bigint, market_open numeric, market_previous_close numeric, market_day_high numeric, market_day_low numeric, market_price numeric, market_volume numeric, target_low_price numeric, target_high_price numeric, target_median_price numeric, target_mean_price numeric, number_of_analyst numeric, recommendation_mean numeric, tailing_pe numeric, forward_pe numeric, average_volume numeric, ask numeric, ask_size numeric, bid numeric, bid_size numeric, enterprise_revenue numeric, profit_margins numeric, enterprise_ebitda numeric, quarterly_earning_growth numeric, short_position bigint, total_in_issue bigint, reported_position numeric ) WITH ( OIDS = FALSE ) TABLESPACE pg_default; ALTER TABLE public.transactions OWNER to postgres;
C++
UTF-8
12,989
2.703125
3
[]
no_license
#include<GL/glut.h> #include<math.h> #include<stdio.h> #define c 3.14/180 #define PI 3.14 #define TWO_PI 2.0 * PI #define RAD_TO_DEG 180.0 / PI //Coordinates for the chassis of the car float p[]={5.5,-2.5,1},q[]={5.5,-7.5,1},r[]={10.7,-7.5,1},s[]={10.7,-2.5,1}; float p1[]={10.7,-9,3},s1[]={12.7,-9,3},q1[]={10.7,-1,3},r1[]={12.7,-1,3}; float p2[]={0.5,-1,1},s2[]={5.5,-1,1},q2[]={0.5,-9,1},r2[]={5.5,-9,1}; float p3[]={-15,-6.5,1},q3[]={-15,-3.5,1},r3[]={0.5,-2.5,1},s3[]={0.5,-7.5,1}; float p4[]={-13,-6.5,1},q4[]={-13,-6.5,2.5},r4[]={0.5,-7.5,3.5},s4[]={0.5,-7.5,1}; float p5[]={-13,-3.5,1},q5[]={-13,-3.5,2.5},r5[]={0.5,-2.5,3.5},s5[]={0.5,-2.5,1}; float p6[]={5.5,-2.5,1},q6[]={5.5,-2.5,3.5},r6[]={10.7,-2.5,3.5},s6[]={10.7,-2.5,1}; float p7[]={5.5,-7.5,1},q7[]={5.5,-7.5,3.5},r7[]={10.7,-7.5,3.5},s7[]={10.7,-7.5,1}; float p8[]={5.5,-7.5,3.5},q8[]={10.7,-7.5,3.5},r8[]={10.7,-6,3.5},s8[]={5.5,-6,3.5}; float p9[]={5.5,-2.5,3.5},q9[]={5.5,-4,3.5},r9[]={10.7,-4,3.5},s9[]={10.7,-2.5,3.5}; float p10[]={5.5,-4,3.5},q10[]={10.7,-4,3.5},r10[]={10.7,-5,4.5},s10[]={5.5,-5,5.5}; float p11[]={5.5,-6,3.5},q11[]={10.7,-6,3.5},r11[]={10.7,-5,4.5},s11[]={5.5,-5,5.5}; float p12[]={10.7,-9,2},q12[]={10.7,-9,4},r12[]={12.7,-9,4},s12[]={12.7,-9,2}; float p13[]={10.7,-1,2},q13[]={10.7,-1,4},r13[]={12.7,-1,4},s13[]={12.7,-1,2}; float p14[]={0.5,-1,1},q14[]={0.5,-1,3},r14[]={5.5,-1,3},s14[]={5.5,-1,1}; float p15[]={0.5,-9,1},q15[]={0.5,-9,3},r15[]={5.5,-9,3},s15[]={5.5,-9,1}; float p16[]={0.5,-1,1},q16[]={0.5,-1,3},r16[]={0.5,-2.5,3.5},s16[]={0.5,-2.5,1}; float p17[]={0.5,-7.5,1},q17[]={0.5,-7.5,3.5},r17[]={0.5,-9,3},s17[]={0.5,-9,1}; float p18[]={5.5,-1,1},q18[]={5.5,-1,3},r18[]={5.5,-2.5,3.5},s18[]={5.5,-2.5,1}; float p19[]={5.5,-7.5,1},q19[]={5.5,-7.5,3.5},r19[]={5.5,-9,3},s19[]={5.5,-9,1}; float p20[]={10.7,-7.5,1},q20[]={10.7,-7.5,3.5},r20[]={10.7,-2.5,3.5}, s20[]={10.7,-2.5,1}; float p21[]={4,-2.5,3.5},q21[]={5.5,-2.5,3.5},r21[]={5.5,-7.5,3.5},s21[]={4,-7.5,3.5}; enum { // Constants for different views HELICOPTER,FRONT,SIDE,BACK } viewpoint = BACK; int MID=570; //Distance of the car on the track from the centre of the track int start=0; char KEY; //Variable that stores key pressed by user float angle; //Rotation angle for car float carx=0,cary=570; //Variables that specify position of the car int rot=0; //rotation angle for the wheels //Function to generate a cone void cone() { float i,x,y,r=10; glColor3f(0.0,0.7,0.2); glBegin(GL_TRIANGLE_FAN); glVertex3f(0,0,20); for(i=0;i<=361;i+=2) { x= r * cos(i*c); y= r * sin(i*c); glVertex3f(x,y,0); } glEnd(); } //Fuction to draw the track void track(float R1,float R2) { float X,Y,Z; int y; glBegin(GL_QUAD_STRIP); for( y=0;y<=361;y+=1) { X=R1*cos(c*y); Y=R1*sin(c*y); Z=-1; glVertex3f(X,Y,Z); X=R2*cos(c*y); Y=R2*sin(c*y); Z=-1; glVertex3f(X,Y,Z); } glEnd(); } //Function that generates a cylinder void cylinder(float r,float l) { float x,y,z; int d; glBegin(GL_QUAD_STRIP); for( d=0;d<=362;d+=1) { x=r*cos(c*d); z=r*sin(c*d); y=0; glVertex3f(x,y,z); y=l; glVertex3f(x,y,z); } glEnd(); } //Function that generates tree with cone shaped tree top void tree(float a,float b) { //Tree trunk glColor3f(0.9,0.3,0); glPushMatrix(); glTranslatef(a,b,-1); glRotatef(90,1,0,0); cylinder(3,15); glPopMatrix(); //Cone shaped tree top glPushMatrix(); glTranslatef(a,b,8); cone(); glPopMatrix(); } //Functin that generates tree with sphere shaped tree top void tree2(float a,float b) { //Tree trunk glColor3f(1,0.2,0); glPushMatrix(); glTranslatef(a,b,-1); glRotatef(90,1,0,0); cylinder(6,25); glPopMatrix(); //Sphere shaped tree top glColor3f(0,1,0.3); glPushMatrix(); glTranslatef(a,b,45); glutSolidSphere(30,10,10); glPopMatrix(); } //Function to generate the sides of the tyres void alloy(float R1,float R2) { float X,Y,Z;int y; glColor3f(0,0,0); glBegin(GL_QUAD_STRIP); for(y=0;y<=361;y+=1) { X=R1*cos(c*y); Z=R1*sin(c*y); Y=0; glVertex3f(X,Y,Z); X=R2*cos(c*y); Z=R2*sin(c*y); Y=0; glVertex3f(X,Y,Z); } glEnd(); } //Function to draw the spokes of the wheel void actall(float R1,float R2) { float X,Y,Z; int i; glBegin(GL_QUADS); for(i=0;i<=361;i+=120) { glColor3f(0,0.5,0.5); X=R1*cos(c*i); Y=0; Z=R1*sin(c*i); glVertex3f(X,Y,Z); X=R1*cos(c*(i+30)); Y=0; Z=R1*sin(c*(i+30)); glVertex3f(X,Y,Z); X=R2*cos(c*(i+30)); Y=0; Z=R2*sin(c*(i+30)); glVertex3f(X,Y,Z); X=R2*cos(c*i); Y=0; Z=R2*sin(c*i); glVertex3f(X,Y,Z); } glEnd(); } //Function to draw a circle void circle(float R) { float X,Y,Z;int i; glBegin(GL_POLYGON); for(i=0;i<=360;i++) { X=R*cos(c*i); Z=R*sin(c*i); Y=0; glVertex3f(X,Y,Z); } glEnd(); } //Function to draw a quadrilateral void rect(float p[],float q[],float r[],float s[]) { glBegin(GL_POLYGON); glVertex3fv(p); glVertex3fv(q); glVertex3fv(r); glVertex3fv(s); glEnd(); } //Function to generate car driver void driver() { glColor3f(0.5,0.2,0.8); //Legs glPushMatrix(); glTranslatef(3,-3.5,1.5); glRotatef(90,0,0,1); cylinder(0.4,3); glPopMatrix(); glPushMatrix(); glTranslatef(3,-6.5,1.5); glRotatef(90,0,0,1); cylinder(0.4,3); glPopMatrix(); //Hands glPushMatrix(); glTranslatef(3,-3.5,2.5); glRotatef(90,0,0,1); cylinder(0.4,3); glPopMatrix(); glPushMatrix(); glTranslatef(3,-6.5,2.5); glRotatef(90,0,0,1); cylinder(0.4,3); glPopMatrix(); //Head glPushMatrix(); glTranslatef(3,-5,4); glutSolidSphere (1.0, 20, 16); glPopMatrix(); //Body glPushMatrix(); glTranslatef(3,-5,1); glRotatef(90,1,0,0); cylinder(1,2); glPopMatrix(); //Circle glPushMatrix(); glTranslatef(3,-5,3); glRotatef(90,1,0,0); circle(1); glPopMatrix(); } //Function generating scenery using functions track( ),tree( ),tree2( ) void scenery() { float x,y; int p; //Background glColor3f(0.4,0.9,0.9); glPushMatrix(); glRotatef(90,1,0,0); cylinder(1000,1000); glPopMatrix(); //Ground glColor3f(0,1,0); glPushMatrix(); glTranslatef(0,0,-1.1); glRotatef(90,1,0,0); circle(1100); glPopMatrix(); //Track glColor3f(0.3,0.3,0.6); track(600,540); //Cone shaped trees for(p=0;p<=360;p+=30) { x=700*cos(c*p); y=700*sin(c*p); tree(x,y); } //Sphere shaped trees for( p=100;p<=460;p+=30) { x=800*cos(c*p); y=800*sin(c*p); tree2(x,y); } } //Function to draw triangles void tri(float a[],float b[],float z[]) { glBegin(GL_TRIANGLES); glVertex3fv(a); glVertex3fv(b); glVertex3fv(z); glEnd(); } //Function that has calls to other functions to generate wheels along with axle void wheels() { //axle glColor3f(0,0.5,0.3); cylinder(0.4,9); //1st Wheel glColor3f(0,0,0); cylinder(2,2); alloy(2,1.4); actall(1.4,0.8); glColor3f(0,0.5,0.4); circle(0.8); glPushMatrix(); glTranslatef(0,2,0); alloy(2,1.4); actall(1.4,0.8); glColor3f(0,0.5,0.4); circle(0.8); glPopMatrix(); //2nd Wheel glPushMatrix(); glTranslatef(0,8,0); glColor3f(0,0,0); cylinder(2,2); alloy(2,1.4); actall(1.4,0.8); glColor3f(0,0.5,0.4); circle(0.8); glPopMatrix(); glPushMatrix(); glTranslatef(0,10,0); actall(1.4,0.8); alloy(2,1.4); glColor3f(0,0.5,0.4); circle(0.8); glPopMatrix(); } //Function that generates the chassis of the car void chassis() { //Parameters For glMaterialfv() function GLfloat specular[] = { 0.7, 0.7, 0.7, 1.0 }; GLfloat ambient[]={1,1,1,1},diffuse[]={0.7,0.7,0.7,1}; GLfloat full_shininess[]={100.0}; //Material Properties glMaterialfv(GL_FRONT,GL_AMBIENT,ambient); glMaterialfv(GL_FRONT,GL_SPECULAR,specular); glMaterialfv(GL_FRONT,GL_DIFFUSE,diffuse); glMaterialfv(GL_FRONT,GL_SHININESS, full_shininess); glColor3f(0,0.2,0.9); rect(p,q,r,s); rect(p2,q2,r2,s2); rect(p3,q3,r3,s3); rect(p4,q4,r4,s4); rect(p5,q5,r5,s5); rect(q5,q4,r4,r5); rect(p6,q6,r6,s6); rect(p7,q7,r7,s7); rect(p8,q8,r8,s8); rect(p9,q9,r9,s9); glColor3f(1,0.6,0); rect(p1,q1,r1,s1); rect(q5,q4,p3,q3); tri(p4,q4,p3); tri(p5,q5,q3); rect(p10,q10,r10,s10); rect(p11,q11,r11,s11); rect(r16,r18,q18,q16); rect(q17,q19,r19,r17); rect(p21,q21,r21,s21); glColor3f(0,0.2,0.9); rect(p12,q12,r12,s12); rect(p13,q13,r13,s13); rect(p14,q14,r14,s14); rect(p15,q15,r15,s15); rect(p16,q16,r16,s16); rect(p17,q17,r17,s17); rect(p18,q18,r18,s18); rect(p19,q19,r19,s19); rect(r18,q19,p19,s18); rect(p20,q20,r20,s20); } //Function that that has function calls to chassis(),tyrea(), //tyreb(),driver() to generate the car with wheels rotating void car() { glPushMatrix(); glRotatef(180,0,0,1); chassis(); glPushMatrix(); glTranslatef(8,-10,1); glRotatef(rot,0,1,0); wheels(); glPopMatrix(); glPushMatrix(); glTranslatef(-12,-10,1); glRotatef(rot,0,1,0); wheels(); glPopMatrix(); driver(); rot+=90; if(rot>360) rot-=360; glPopMatrix(); } //Keyboard Callback Function void keys(unsigned char key,int x,int y) { KEY=key; if(key=='E' || key=='e') { start=0; } if(key=='G' || key=='g') { start=1; } } //Function that generates a particular view of scene depending on view selected by //user void view() { float pos[]={1000,1000,2000,1};//Position of the light source switch(viewpoint) { case HELICOPTER: glLightfv(GL_LIGHT0, GL_POSITION, pos); gluLookAt(200,0,700,0,0,0,0,0,1); scenery(); glPushMatrix(); glTranslatef(carx,cary,0); glRotatef(angle*RAD_TO_DEG,0,0,-1); car(); glPopMatrix(); break; case SIDE: gluLookAt(-20.0,-20.0,15,0.0,0.0,2.0,0.0, 0.0,1.0); car(); glPushMatrix(); glRotatef(angle*RAD_TO_DEG, 0.0,0.0,1.0); glTranslatef(-carx,-cary,0); glLightfv(GL_LIGHT0, GL_POSITION, pos); scenery(); glPopMatrix(); break; case FRONT: gluLookAt(15.0,5.0,20,0.0,0.0,4.0,0.0,0.0,1.0); car(); glPushMatrix(); glRotatef(angle*RAD_TO_DEG, 0.0,0.0,1.0); glTranslatef(-carx,-cary,0); glLightfv(GL_LIGHT0, GL_POSITION, pos); scenery(); glPopMatrix(); break; case BACK: gluLookAt(-12.0,6.0,13,15.0,6.0,2.0,0.0,0.0,1.0); car(); glPushMatrix(); glRotatef(RAD_TO_DEG * angle, 0.0, 0.0, 1.0); glTranslatef(-carx,-cary,0); glLightfv(GL_LIGHT0, GL_POSITION, pos); scenery(); glPopMatrix(); break; } } //Idle Callback Function void idle() { if(start==1) { angle+=0.05; if(angle==TWO_PI) { angle-=TWO_PI; } carx=MID*sin(angle); cary=MID*cos(angle); switch(KEY) { case 'H': case 'h':viewpoint=HELICOPTER;break; case 'S': case 's':viewpoint=SIDE;break; case 'F': case 'f':viewpoint=FRONT;break; case 'B': case 'b':viewpoint=BACK;break; } glutPostRedisplay(); } } void init() { GLfloat amb[]={1,1,1,1},diff[]={1,1,1,1},spec[]={1,1,1,1}; glLoadIdentity(); glLightfv(GL_LIGHT0, GL_AMBIENT, amb); glLightfv(GL_LIGHT0, GL_DIFFUSE, diff); glLightfv(GL_LIGHT0, GL_SPECULAR, spec); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glClearColor(1,1,1,1); } //Display Callback Function void display() { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); view(); glutSwapBuffers(); } //Reshape Function void reshape(int w, int h) { glViewport (0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective(100, (GLfloat) w/(GLfloat) h, 1, 2000.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } //Main Fuction int main(int argc,char **argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH); printf("\t\t**********RACING CAR IN A RACE TRACK***********\n"); printf("\n\tPRESS:\n"); printf("\n\tG or g:To Start or Continue\n"); printf("\n\tE or e:To Stop\n"); printf("\n\tH or h :Helicopter View\n"); printf("\n\tB or b :Back View\n"); printf("\n\tS or s :Side View\n"); printf("\n\tF or f :Front View\n"); glutInitWindowPosition(500,500); glutInitWindowSize(500,500); glutCreateWindow("Computer Graphics"); glutDisplayFunc(display); glutIdleFunc(idle); glutKeyboardFunc(keys); glutReshapeFunc(reshape); init(); glutMainLoop(); }