language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C#
UTF-8
1,266
3.265625
3
[]
no_license
using System; using System.Runtime.Serialization; using Xunit; namespace Pandemonium.Test.Extensions.Object { public class CloneTests { [Fact] public void Should_Clone_Object_Values_To_New_Reference() { Sample value = new Sample { Anything = "anything" }; Sample newObject = value.Clone(); Assert.False(value.Equals(newObject)); Assert.Equal(value.Anything, newObject.Anything); value.Anything = "another"; Assert.NotEqual(value.Anything, newObject.Anything); } [Fact] public void Should_Throw_SerializationException_Try_Serialize_Non_Serializeble_Class() { object value = new { Anything = "anything" }; Assert.Throws<SerializationException>(() => value.Clone()); } } [Serializable] internal class Sample { public string Anything { get; set; } public override bool Equals(object obj) { if (!ReferenceEquals(this, obj)) { return false; } return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } }
Markdown
UTF-8
12,919
3.15625
3
[]
no_license
###### tags: `單元測試的藝術` # Chapter 8 好的單元測試的支柱 ### 8.2 撰寫可維護的測試 隨著時間推移,測試會變得難以理解及維護。所以可維護性是大多數開發人員撰寫單元測試的核心問題之一。 > 系統每一個**微小的改變**,即使沒有bug,都會使**測試失效**,而導致需要花時間修正測試 本節介紹 3 個技巧來讓測試**更好維護** - [ ] **1. 只考慮測試公開契約** - [ ] **2. 刪除重覆的測試** - [ ] **3. 測試隔離的實踐** ## 8.2.1 測試私有或保護的方法 + **只考慮測試公開契約** - 因爲私有方法不會獨立存在,必定被其他公開方法呼叫 - 私有方法通常是大工作單元的一部分,在原本重構的過程中被抽取成私有方法 - 如果是私有方法值得被測試,那應該考慮以下作法,並撰寫測試 - [ ] **把方法改成公開方法 (public)** - [ ] **把方法改成靜態方法 (static)** - [ ] **把方法抽取到新類別中** - [ ] **把方法改成內部方法 (internal)** + 工作單元會有 3 種結果 - 回傳值 - 系統狀態改變 - 第三方的互動。 ### 把方法改成公開方法 如果你覺得某個私有方法具有被測試的價值,且這方法也可能在其他呼叫端使用,那可以考慮將這個方法改成公開的,代表正式將契約對外開放。 ### 把方法改成靜態方法 如果一個方法沒有用到執行物件的任何變數跟狀態,那你可以考慮把它改為靜態方法,同時這也表示了這個方法為某種輔助方法。 ### 把方法抽取到新類別中 如果一個方法中包含了很多獨立職責的邏輯,或是類別的某些狀態只和這個方法有關,把這個方法抽取到另外一個具有特定功能的類別會更好,也符合單一職責原則。 ### 把方法改成內部方法 如果上述的方法都行不通,你也可以考慮將方法設置為 internal ,並且在測試中設定 ```[InternalsVisibleTo("Test- Assembly")]``` ,讓測試專案也可以呼叫到該方法。 ### Demo + [計算機類別(修改前)](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.Core/Services/Ch8/8.2.1/CalculatorOriginal.cs) + [計算機類別(修改後)](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.Core/Services/Ch8/8.2.1/Calculator.cs) - [單元測試](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.UnitTests/Ch8/8.2.1/CalculatorTest.cs) - 加法:只測試公開方法 - 減法:把方法改成公開方法 - 乘法:把方法抽取到新類別中 - 除法:把方法改成內部方法 - 四捨五入:把方法改成靜態方法 ## 8.2.2 去除重複的程式碼 DRY (Don't Repeat Yourself) 原則也同樣適用於測試程式碼,需要適時的去除重複的測試程式碼 ### Demo + [LogAnalyzer](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.Core/Services/Ch8/8.2.2/LogAnalyzer.cs) + [UnitTest](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.UnitTests/Ch8/8.2.2/LogAnalyzerTest.cs) 如果當今天 ```LogAnalyzer``` 的使用方式發生變化,例如說新增```initialize()```方法。之前寫的測試會壞掉,每個測試方法都得進行調整,這樣維護的工作量會變大。 這時候有兩種策略可以使用 - [ ] 1. 使用輔助方法 - [ ] 2. 使用 ```SetUp``` 方法 ### 使用輔助方法來去除重複的程式碼 我們將創造 ```LogAnalyzer``` 及 ```initialize()``` 的過程封裝為一個工廠方法,並讓所有的測試都去呼叫這個工廠方法來拿取 ```LogAnalyzer``` ### 使用 ```SetUp``` 方法來去除重複的程式碼 使用 ```SetUp``` ,不需要在每個測試中都包含一行建立 ```LogAnalyzer``` 的語句,在執行每個測試之前 ```SetUp``` 都會執行。 使用 ```SetUp``` 來去除重複程式碼不是一個好的方式,其原因下一節會做討論。 ### Demo + [LogAnalyzerInit](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.Core/Services/Ch8/8.2.2/LogAnalyzerInit.cs) + UnitTest + [UnitTest(修改前)](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.UnitTests/Ch8/8.2.2/LogAnalyzerInitTest.cs) + [UnitTest(輔助方法)](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.UnitTests/Ch8/8.2.2/LogAnalyzerInitTestVersion1.cs) + [UnitTest(SetUp)](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.UnitTests/Ch8/8.2.2/LogAnalyzerInitTestVersion2.cs) ## 8.2.3 具可維護性的設計來使用 ```SetUp``` 方法 ```SetUp``` 用起來很容易,但存在侷限性: - 只用於需要進行初始化的工作時 - 不一定是去除重複程式碼的最佳方式,有時候重複程式碼的目的並不是初始化 - 沒有參數或者回傳值,也就無法當作物件生成的工廠方法使用 - 只包含適用於所有測試方法中的程式碼,否則會使測試更加難以理解 基於以上,開發者通常會用以下的方式去濫用 ```SetUp``` 方法 - [ ] 1. ```SetUp``` 方法內初始化只有某些測試方法會用到的物件 - [ ] 2. ```SetUp``` 方法內的程式碼冗長難懂 - [ ] 3. ```SetUp``` 方法內準備模擬物件及假物件 ### 初始化只在某些測試會使用到的物件 我們來看一個[例子](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.UnitTests/Ch8/8.2.3/LogAnalyzerTest.cs) 上述測試程式碼為什麼不好維護呢?因為我們在維護的時候大概會經過以下的過程 1. 讀一遍 SetUp 方法,理解初始化了什麼 2. 假設所有的測試都會用到 SetUp 方法 3. 在維護的過程發現自己的假設錯誤,進而花時間去找誰沒有使用到 SetUp 方法的內容 4. 花更多時間來理解測試的意圖跟內容 ### 冗長難懂的 ```SetUp``` 方法 + 開發者往往會在 ```SetUp``` 方法中初始化很多東西,導致程式可讀性變差。 + 要解決這個問題,可以把初始化的過程都提取整輔助方法,並用方法名稱去做語意化的命名,讓人容易去理解初始化的過程。 ### 在 ```SetUp``` 方法中準備模擬物件或假物件 + 在 ```SetUp``` 方法中準備模擬物件或假物件會使可讀性變差,也不好維護。 + 可以把假物件的生成寫成輔助方法配合語意化的命名,這樣在呼叫的時候也能夠確切知道發生什麼事情。 **請使用輔助方法或工廠方法取代 ```SetUp``` 方法** [例子](https://github.com/YNCBearz/CodingKaoshiungArtOfUnitTesting/blob/main/C%23/CKUT/CKUT.UnitTests/Ch8/8.2.3/LogAnalyzerTestVersion1.cs) ## 8.2.4 實作測試隔離 如果沒有將測試隔離,他們就會互相影響,當出現問題時,往往需要花費更大量的時間去定位真正的問題所在。如果你的測試執行起來有下面這些跡象,很有可能表示你的測試有隔離上的問題。 - [ ] 強制的測試順序:測試需要以某種特定的順序去執行 - [ ] 存在呼叫其他測試的隱藏動作:在測試中呼叫其他的測試 - [ ] 共享狀態損毀:測試共享記憶體裡面的某個狀態,卻沒有將它重置 - [ ] 外部共享狀態損毀:整合測試共享資源,卻沒有重置資源 底下我們來討論這幾種反模式 ### 強制的測試順序:單元測試必須依照特定順序執行 大多數的測試平台,並不能夠保證測試按某種特定的順序執行,因此很有可能這次會過的測試,在下一次執行的時候因為順序不同就變成不通過的,進而產生許多問題。==所有的單元測試不管以什麼順序執行都應正常運作== #### 解決方式: - 流程測試或整合測試 - 不要在單元測試撰寫流程相關的測試。 - 可以考慮使用整合測試框架去處理流程測試。 - 開發人員因為偷懶,而沒有將測試會異動的狀態回復初始值 - 建議您不要繼續從事程式開發工作 ### 隱藏的測試呼叫:測試呼叫其他測試 測試直接呼叫同類測試或者是其他測試的測試方法,造成測試之間互相依賴,這種依賴會產生許多問題。 #### 解決方式: - 試圖避免撰寫相同的程式碼 - 你應該把重複的程式碼移動到新的方法,並讓兩個測試去共用這個新方法 - 開發人員因為偷懶,而懶得分隔測試 - 把手頭上的測試當作系統中唯一的測試,~~不然建議您不要繼續從事程式開發工作~~ ### 共享狀態損毀、外部共享狀態損毀:測試共享資源,卻沒有重置 這種反模式主要有兩種情況,且這兩種情況通常獨立存在 1. 測試共享資源(如:記憶體、資料庫、檔案系統),但沒有清理或者復原成乾淨的狀態 2. 測試開始前沒有設定測試所需的初始狀態 #### 解決方式: - 在每個測試執行前設定狀態 - 可使用```SetUp``` 或者輔助方法來設定初始狀態 - 不使用共享狀態 - 每個測試都使用獨立狀態 - 測試使用了靜態的物件執行個體 - 在 ```SetUp``` 或 ```TearDown``` 重置狀態。若是測試單例(Singleton)物件,可以為它新增一個方法來協助重置為乾淨物件。 ## 8.2.5 避免對不同的關注點進行多次驗證 ```csharp= [Test] public void Result_Should_Higher_Than_1000() { Assert.AreEqual(3, Sum(1001, 1, 2)); Assert.AreEqual(3, Sum(1, 1001, 2)); Assert.AreEqual(3, Sum(1, 2, 1001)); } ``` 這個測試方法中含有多個測試,若第一個 assert 錯誤,這個測試就會直接被宣告為失敗,這是我們不期望看到的,我們希望可以單獨觀察每一個案例的執行結果,**這樣更能看到 bug 的全貌**。 #### 解決方式 - 每個驗證建立一個單獨的測試:會有重複程式碼問題 - 使用參數化測試:==最推薦== - 把驗證碼放在一個 try-catch 區塊中:可讀性比參數化測試差 ### 參數化測試 ```csharp= [TestCase(1001, 1, 2, 3)] [TestCase(1, 1001, 2, 3)] [TestCase(1, 2, 1001, 3)] public void Result_Should_Higher_Than_1000(int x, int y, int z, int expected) { Assert.AreEqual(expected, Sum(x, y, z)); } ``` ## 8.2.6 物件比較 有時一個測試方式的多個驗證,指的不是測試案例,而是一個狀態的多個方面 #### 修改前 ```csharp= [Test] public void Result_Should_Higher_Than_1000() { LogAnalyzer log = new LogAnalyzer(); AnalyzedOutput output = log.Analyze("10:05\tOpen\tRoy"); Assert.AreEqual("10:05", output.Time); Assert.AreEqual("Open", output.Status); Assert.AreEqual("Roy", output.Name); } ``` #### 修改後 ```csharp= [Test] public void Result_Should_Higher_Than_1000() { LogAnalyzer log = new LogAnalyzer(); AnalyzedOutput output = log.Analyze("10:05\tOpen\tRoy"); output.Should().BeEquivalentTo(new AnalyzedOutput() { Time: "10:05", Status: "Open", Name: "Roy" }); } ``` ## 8.2.7 避免過度指定 過度指定的測試代表單元測試對內部行為進行了假設,而不是只驗證最終行為的正確性 單元測試中過度指定主要有以下幾種情況 - 測試對於被測試物件的純內部狀態進行驗證 - 測試中使用了多個模擬物件 - 測試在需要虛設常式時,使用模擬物件 - 測試在不必要的狀況下,指定了順序或是使用了精準的參數匹配器 ### 驗證被測試物件的純內部行為 單元測試應該只測試物件的公開契約和公開功能,驗證最終行為的正確性 ```csharp= [Test] public void LogAnalyzerTest() { var log = new LogAnalyzer(); log.Initialize(); Assert.IsTrue(log.initialized); //過度指定 var valid = logan.IsValid("1234567"); Assert.IsTrue(valid); } ``` ### 在需要虛設常式時,使用模擬物件 測試目標是最終行為的正確性,那就不應該再去關注內部方法呼叫, ```csharp= [Test] public void LogAnalyzerTest() { var userId = 123; var fakeData = Substitute.For<IData>(); fakeData.GetUserById(userId).Returns(null); var login = new LoginManager(fakeData); var result = login.IsUserExists(userId); Assert.IsTrue(result); fakeData.Received(1).GetUserById(123); //過度指定 } ``` ### 不必要的順序,或過於精準的參數匹配器 對於測試的回傳值,我們常常想要很精準地去比對是否完全一致,但實際上可能只需要去驗證字串是否有被包含即可。又例如 Array、Collection 之類的集合,我們可能只需要驗證是否含有包含指定元素即可
Java
UTF-8
1,813
3.9375
4
[]
no_license
public class ResizeableTest { public static void main(String[] args) { Shape[] shapes = new Shape[3]; shapes[0] = new Circle(5); shapes[1] = new Rectangle(5.2, 3.2); shapes[2] = new Square(3.3); for (Shape shape : shapes) { if (shape instanceof Circle) { Circle circle = (Circle) shape; System.out.println(circle); } else if (shape instanceof Rectangle) { Rectangle rectangle = (Rectangle) shape; System.out.println(rectangle); } if (shape instanceof Square) { Square square = (Square) shape; System.out.println(square); } } for (Shape shape : shapes) { if (shape instanceof Circle) { Circle circle = (Circle) shape; circle.resize(200); System.out.println(circle.getRadius()); } else if (shape instanceof Rectangle && !(shape instanceof Square)) { Rectangle rectangle = (Rectangle) shape; rectangle.resize(500); } if(shape instanceof Square) { Square square = (Square) shape; square.resize(400); } } System.out.println(); for (Shape shape : shapes) { if (shape instanceof Circle) { Circle circle = (Circle) shape; System.out.println(circle); } else if (shape instanceof Rectangle) { Rectangle rectangle = (Rectangle) shape; System.out.println(rectangle); } if (shape instanceof Square) { Square square = (Square) shape; System.out.println(square.getSide()); } } } }
C++
UTF-8
4,734
2.6875
3
[]
no_license
#ifndef SPACE_INFO_H #define SPACE_INFO_H #include <memory> #include <cmath> #include <Cube.h> // Tao's occupancy mask //#include <volume.h> // Tao's volume struct #include "Volume3DScalar.h" #include "commondefs.h" using std::shared_ptr; //struct SpaceInfo3D //{ // point //}; struct SpaceConverter { // voxel corner offset w.r.t. the center static const point vox_corner_offset[8]; // return the voxel space coordinate of the requested corner static inline point getVoxelCorner( const ivec3& _vox, int _ix, int _iy, int _iz ) { auto cidx = ( _ix << 2 ) | ( _iy << 1 ) | _iz; const auto& o = vox_corner_offset[ cidx ]; return point( _vox[ 0 ] + o[ 0 ], _vox[ 1 ] + o[ 1 ], _vox[ 2 ] + o[ 2 ] ); } // return whether specified voxel in the given volume is tagged as "inside" static bool voxTaggedAsInside( const ivec3& _vox, const shared_ptr<Volume3DScalar> _vol) { return ( !SpaceConverter::outOfVolBounds( _vox, _vol ) ) && ( get_occupancy_at_vox( _vox, _vol ) == 1 ); } // conversion from/to voxel space (continuous) to/from 3d model space (continuous) // (where both voxel and 3d geometry points are floating numbers) static inline void fromVoxToModel( const point& _v, point& _p, const xform& _vox2model ) { //_p = _v + point( 0.5f ); _p = _v; _p = _vox2model * _p; //std::swap( _p[ 1 ], _p[ 0 ] ); } static inline void fromModelToVox( const point& _p, point& _q, const xform& _model2vox ) { // convert to voxel space _q = _model2vox * _p; //std::swap( _q[ 1 ], _q[ 0 ] ); //_q = _q - point( 0.5f ); } // conversion from/to voxel space (continuous) to/from 3d model space (continuous) // (where the source point is floating numbers, but target is always snapped to nearest integers) static inline void fromVoxToModel( const point& _v, ivec3& _p, const xform& _vox2model ) { //auto p = _v + point( 0.5f ); point p; p = _vox2model * _v; _p[ 0 ] = (int)p[ 0 ]; _p[ 1 ] = (int)p[ 1 ]; _p[ 2 ] = (int)p[ 2 ]; //std::swap( _p[ 0 ], _p[ 1 ] ); } static inline void fromModelToVox( const point& _p, ivec3& _v, const xform& _model2vox ) { // convert to voxel space auto q = _model2vox * _p; //q = q - point( 0.5f ); // snap to nearest integer (i.e. the voxel coord.s) _v[ 0 ] = int( std::round( q[ 0 ] ) ); _v[ 1 ] = int( std::round( q[ 1 ] ) ); _v[ 2 ] = int( std::round( q[ 2 ] ) ); // finally don't forget to swap x, y //std::swap( _v[ 1 ], _v[ 0 ] ); } // test whether the given voxel is within volume bounds static inline bool outOfVolBounds( const ivec3& _v, const Volume3DScalar* _vol ) { return ( _v[ 0 ] >= _vol->getSizeX() || _v[ 0 ] < 0 || _v[ 1 ] >= _vol->getSizeY() || _v[ 1 ] < 0 || _v[ 2 ] >= _vol->getSizeZ() || _v[ 2 ] < 0 ); } static inline bool outOfVolBounds( const ivec3& _v, const shared_ptr<Volume3DScalar>& _vol ) { return outOfVolBounds( _v, _vol.get() ); } // return the value at the given voxel. return 0 if out of bound static inline int get_occupancy_at_vox( const ivec3& _v, const Volume3DScalar* _vol ) { auto val = SpaceConverter::outOfVolBounds( _v, _vol ) ? 0 : _vol->getDataAt( _v[ 0 ], _v[ 1 ], _v[ 2 ] ) > 0.0 ? 1 : 0; return val; } static inline int get_occupancy_at_vox( const ivec3& _v, const shared_ptr<Volume3DScalar>& _vol ) { return get_occupancy_at_vox( _v, _vol.get() ); } // return the list of 8 nb voxels' coords, given a point in the voxel space // Note: the returned voxels are computed using constants defined in Tao's geomcommon.h file static inline void getNbVoxelCoords( const point& _p, ivec3* _nb_vx_coords ) { point v; // locate the given point into a voxel with lowest possible coords point p((int)_p[0], (int)_p[1], (int)_p[2]); // the eight neighbor voxels will be the offset voxels based on that one for ( int i = 0; i < 8; ++i ) { v = p + point(coordmap[i]); _nb_vx_coords[ i ][ 0 ] = (int)v[ 0 ]; _nb_vx_coords[ i ][ 1 ] = (int)v[ 1 ]; _nb_vx_coords[ i ][ 2 ] = (int)v[ 2 ]; } } // return whether the nb 8 voxels of the given point are all inside the volume static inline bool allNbVoxelsInside( const point& _p, const shared_ptr<Volume3DScalar>& _vol ) { ivec3 v; // locate the given point into a voxel with lowest possible coords point p( (int)_p[ 0 ], (int)_p[ 1 ], (int)_p[ 2 ] ); // the eight neighbor voxels will be the offset voxels based on that one int inside_cnt = 0; for ( int i = 0; i < 8; ++i ) { v[ 0 ] = p[ 0 ] + coordmap[ i ][ 0 ]; v[ 1 ] = p[ 1 ] + coordmap[ i ][ 1 ]; v[ 2 ] = p[ 2 ] + coordmap[ i ][ 2 ]; inside_cnt += (int)get_occupancy_at_vox( v, _vol ); } return inside_cnt == 8; } private: // constants }; #endif // !SPACE_CONVERT_H
C++
UTF-8
2,853
3.015625
3
[]
no_license
#include "tablecheck.h" #include "modprod.h" #include <fstream> #include <iostream> using namespace std; // This table contains a random permutation of the values from 00 through ff, inclusive. // (Need to compute the inverse transform in code.) bool checkS(string line) { if (line.size() != 2 + 256 * 2) { cerr << "S line in invalid!\n"; return false; } char array[line.size() + 1]; //as 1 char space for null is also required strcpy(array, line.c_str()); if (array[0] != 'S' || array[1] != '=') { cerr << "S line is in incorrect format!\n"; return false; } int decimalArray[256]; for (int i = 0; i < 256; i++) { decimalArray[i] = -1; } for (unsigned int i = 2; i < line.size(); i = i + 2) { int dec = getDecimalValueOfHex(array, 2, i); if (decimalArray[dec] != -1) { cerr << "S line is in incorrect format, the hex at " << i << " " << array[i] << array[i + 1] << " appears more than one time!\n"; return false; } else { decimalArray[dec] = 1; } } return true; } // This table contains a hexstring of length 8 which corresponds to 4 byte of binary values. // Each byte is a coefficient of the a(x) polynomial in the MixColumns() transformation. // The first two hex digits correspond to the coefficient for x3, the next two hex digits // correspond to the coefficient for x2, etc. // This table contains a hexstring of length 8 which corresponds to 4 byte of binary values. // Each byte is a coefficient of the a-1(x) polynomial in the InvMixColumns() transformation. // The first two hex digits correspond to the coefficient for x3, the next two hex digits correspond // to the coefficient for x2, etc. bool checkPnINVP(string line1, string line2) { // cout << line1 << endl; // cout << line2 << endl; char* a = (char*) line1.c_str(); char* b = (char*) line2.c_str(); return modprod(a, b, false) == 1; } // Check the integrity of table file bool tableCheck(std::ifstream& file) { std::string line; int count = 0; char *P, *INVP, *S; while (std::getline(file, line)) { count++; if (count == 1) { S = strdup(line.substr(2, strlen(line.c_str()) - 2).c_str()); if (strlen(S) != 512) { cerr << "Invalid S-box, wrong number of entries!\n"; return false; } bool arr[256]; for (int i = 0; i < 256; i++) { arr[i] = false; } for (int i = 0; i < 256; i++) { int value = getDecimalValueOfHex(S, 2, 2 * i); if (arr[value] == true) { cerr << "Invalid S-box,!\n"; return false; } arr[value] = true; } } if (count == 2) { P = strdup(line.substr(2, strlen(line.c_str()) - 2).c_str()); } else if (count == 3) { INVP = strdup(line.substr(5, strlen(line.c_str()) - 5).c_str()); return checkPnINVP(P, INVP); } } if (count != 3) { cerr << "The input file should have 3 lines!\n"; } file.close(); return false; }
Python
UTF-8
2,489
2.8125
3
[]
no_license
import numpy as np import sys import csv from sklearn.cluster import AffinityPropagation from sklearn import metrics # Text proc from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer import codecs def read_text_file(inpFile,delim): f = open(inpFile, "r") ylabels = [] tsvData = [] for s in f: try: u = s.encode('utf-8') label,line = u.split(delim) ylabels.append(label) tsvData.append(line) except: pass return tsvData,ylabels ############################################################################## # Generate sample data X,labels = read_text_file(sys.argv[1],"\t") vectorizer = CountVectorizer() transformer = TfidfTransformer() X = vectorizer.fit_transform(X) # Arra-ize X = X.toarray() #y = np.array(labels) print "Affinity Clustering..." print X ############################################################################## # Compute Affinity Propagation af = AffinityPropagation().fit(X) cluster_centers_indices = af.cluster_centers_indices_ labels = af.labels_ n_clusters_ = len(cluster_centers_indices) print('Estimated number of clusters: %d' % n_clusters_) print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels)) print("Completeness: %0.3f" % metrics.completeness_score(labels_true, labels)) print("V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels)) print("Adjusted Rand Index: %0.3f" % metrics.adjusted_rand_score(labels_true, labels)) print("Adjusted Mutual Information: %0.3f" % metrics.adjusted_mutual_info_score(labels_true, labels)) print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X, labels, metric='sqeuclidean')) ############################################################################## # Plot result import pylab as pl from itertools import cycle pl.close('all') pl.figure(1) pl.clf() colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') for k, col in zip(range(n_clusters_), colors): class_members = labels == k cluster_center = X[cluster_centers_indices[k]] pl.plot(X[class_members, 0], X[class_members, 1], col + '.') pl.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=14) for x in X[class_members]: pl.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col) pl.title('Estimated number of clusters: %d' % n_clusters_) pl.show()
Java
UTF-8
800
2.390625
2
[]
no_license
package iVotas.Action; import org.apache.struts2.interceptor.SessionAware; import java.util.ArrayList; public class VotarEleicoesAction extends Action implements SessionAware{ private String listaeleicoes = ""; @Override public String execute() throws Exception { ArrayList<String> auxeleicoes; auxeleicoes = this.getiVotasBean().getEleicoes(); if (!auxeleicoes.isEmpty()){ for (String ele : auxeleicoes) listaeleicoes += ele +"\n"; } else listaeleicoes = "*Sem eleições para votar*"; return SUCCESS; } public String getListaeleicoes() { return listaeleicoes; } public void setListaeleicoes(String listaeleicoes) { this.listaeleicoes = listaeleicoes; } }
C++
UTF-8
264
2.53125
3
[]
no_license
#include<stdio.h> int main() { int n, arr[20], sumFirstLast; sumFirstLast = 0; scanf("%d", &n); for(int i = 0; i < n; i++){ scanf("%d", &arr[i]); } sumFirstLast= arr[0] + arr[n- 1]; printf("%d", sumFirstLast); return 0; }
Shell
UTF-8
513
3.046875
3
[]
no_license
#!/bin/bash #---VladVons@gmail.com source ./const.sh source $DIR_ADMIN/conf/script/service.sh TestEx() # ------------------------ { Test echo rsync localhost:: } Init() # ------------------------ { Log "$0->$FUNCNAME" touch $cLog1 chmod 600 $cLog1 chown root:wheel $cLog1 } Info() { Log "$0->$FUNCNAME" MultiCall ManPrint $Man $gDirMan/$cApp } # ------------------------ clear case $1 in Exec|e) Exec $2 ;; Init) $1 $2 ;; Install) $1 $2 ;; Info) $1 $2 ;; *) TestEx ;; esac
Java
UTF-8
3,860
2.265625
2
[]
no_license
package entity; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import java.util.Date; @Entity public class PostInfo { private int postid; private String rightname; private String posttitle; private Date posttime; private String postinfo; private String pic; private int postcollected; private int postfabulous; private int poststate; @Id @Column(name = "postid") public int getPostid() { return postid; } public void setPostid(int postid) { this.postid = postid; } @Basic @Column(name = "rightname") public String getRightname() { return rightname; } public void setRightname(String rightname) { this.rightname = rightname; } @Basic @Column(name = "posttitle") public String getPosttitle() { return posttitle; } public void setPosttitle(String posttitle) { this.posttitle = posttitle; } @Basic @Column(name = "posttime") public Date getPosttime() { return posttime; } public void setPosttime(Date posttime) { this.posttime = posttime; } @Basic @Column(name = "postinfo") public String getPostinfo() { return postinfo; } public void setPostinfo(String postinfo) { this.postinfo = postinfo; } @Basic @Column(name = "pic") public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } @Basic @Column(name = "postcollected") public int getPostcollected() { return postcollected; } public void setPostcollected(int postcollected) { this.postcollected = postcollected; } @Basic @Column(name = "postfabulous") public int getPostfabulous() { return postfabulous; } public void setPostfabulous(int postfabulous) { this.postfabulous = postfabulous; } @Basic @Column(name = "poststate") public int getPoststate() { return poststate; } public void setPoststate(int poststate) { this.poststate = poststate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PostInfo postinfo1 = (PostInfo) o; if (postid != postinfo1.postid) return false; if (postcollected != postinfo1.postcollected) return false; if (postfabulous != postinfo1.postfabulous) return false; if (poststate != postinfo1.poststate) return false; if (rightname != null ? !rightname.equals(postinfo1.rightname) : postinfo1.rightname != null) return false; if (posttitle != null ? !posttitle.equals(postinfo1.posttitle) : postinfo1.posttitle != null) return false; if (posttime != null ? !posttime.equals(postinfo1.posttime) : postinfo1.posttime != null) return false; if (postinfo != null ? !postinfo.equals(postinfo1.postinfo) : postinfo1.postinfo != null) return false; if (pic != null ? !pic.equals(postinfo1.pic) : postinfo1.pic != null) return false; return true; } @Override public int hashCode() { int result = postid; result = 31 * result + (rightname != null ? rightname.hashCode() : 0); result = 31 * result + (posttitle != null ? posttitle.hashCode() : 0); result = 31 * result + (posttime != null ? posttime.hashCode() : 0); result = 31 * result + (postinfo != null ? postinfo.hashCode() : 0); result = 31 * result + (pic != null ? pic.hashCode() : 0); result = 31 * result + postcollected; result = 31 * result + postfabulous; result = 31 * result + poststate; return result; } }
Java
UTF-8
3,183
2.484375
2
[]
no_license
package kirgiz.stockandsalesmanagement.app.service; import kirgiz.stockandsalesmanagement.app.domain.Usr; import kirgiz.stockandsalesmanagement.app.repository.UsrRepository; import kirgiz.stockandsalesmanagement.app.repository.search.UsrSearchRepository; import kirgiz.stockandsalesmanagement.app.service.dto.UsrDTO; import kirgiz.stockandsalesmanagement.app.service.mapper.UsrMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import static org.elasticsearch.index.query.QueryBuilders.*; /** * Service Implementation for managing Usr. */ @Service @Transactional public class UsrService { private final Logger log = LoggerFactory.getLogger(UsrService.class); private final UsrRepository usrRepository; private final UsrMapper usrMapper; private final UsrSearchRepository usrSearchRepository; public UsrService(UsrRepository usrRepository, UsrMapper usrMapper, UsrSearchRepository usrSearchRepository) { this.usrRepository = usrRepository; this.usrMapper = usrMapper; this.usrSearchRepository = usrSearchRepository; } /** * Save a usr. * * @param usrDTO the entity to save * @return the persisted entity */ public UsrDTO save(UsrDTO usrDTO) { log.debug("Request to save Usr : {}", usrDTO); Usr usr = usrMapper.toEntity(usrDTO); usr = usrRepository.save(usr); UsrDTO result = usrMapper.toDto(usr); usrSearchRepository.save(usr); return result; } /** * Get all the usrs. * * @param pageable the pagination information * @return the list of entities */ @Transactional(readOnly = true) public Page<UsrDTO> findAll(Pageable pageable) { log.debug("Request to get all Usrs"); return usrRepository.findAll(pageable) .map(usrMapper::toDto); } /** * Get one usr by id. * * @param id the id of the entity * @return the entity */ @Transactional(readOnly = true) public UsrDTO findOne(Long id) { log.debug("Request to get Usr : {}", id); Usr usr = usrRepository.findOne(id); return usrMapper.toDto(usr); } /** * Delete the usr by id. * * @param id the id of the entity */ public void delete(Long id) { log.debug("Request to delete Usr : {}", id); usrRepository.delete(id); usrSearchRepository.delete(id); } /** * Search for the usr corresponding to the query. * * @param query the query of the search * @param pageable the pagination information * @return the list of entities */ @Transactional(readOnly = true) public Page<UsrDTO> search(String query, Pageable pageable) { log.debug("Request to search for a page of Usrs for query {}", query); Page<Usr> result = usrSearchRepository.search(queryStringQuery(query), pageable); return result.map(usrMapper::toDto); } }
Markdown
UTF-8
40,432
3.3125
3
[ "MIT" ]
permissive
--- layout: post title: "前端笔记" date: 2017-06-08 excerpt: "" tag: - js基础 comments: true --- 2.z-index配合position使用,只在定位元素上奏效 4.获取鼠标位置: ```js //获取鼠标相对文档开头的位置 function getMousePosition(evt){ var e = evt || window.evt; //Chrome下用document.body;IE下document.documentElement var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; //FireFox原生支持pageX和pageY var x = e.pageX||e.clientX+scrollX; var y = e.pageY||e.clientY+scrollY; return {'x':x,'y':y}; } ``` 5.0.5px border 实现 ``` /*linear-gradient第一个参数是渐变方向,0(to top,从下到上),90deg(to right,从左到右),180deg(to bottom,从上到下),270deg(-90deg,to left,从右到左),后面的参数是渐变颜色及起止,至少两个;linear-gradient()之后是background-position(eg:top left,第二个参数默认是center);'/'之后是background-size*/ .border {background: linear-gradient(180deg, black 50%, transparent 50%) top/ 100% 10px no-repeat, linear-gradient(90deg, black 50%, transparent 50%) left/ 10px 100% no-repeat, linear-gradient(0, black 50%, transparent 50%) bottom / 100% 10px no-repeat, linear-gradient(-90deg, black 50%, transparent 50%) right/ 10px 100% no-repeat; } ``` 7.visibility:hidden;元素不可见 但会占据空间; display:none;//不可见 不占据空间 visibility:collapse;//用于普通元素类似hidden;用于表格元素,IE11以下不起作用,仍然显示;FF下hidden,不占据空间;Chrome下hidden,但仍然占据空间。 animation和transition区别:transition关注的是css属性的变化,属性值和时间的关系是三次贝塞尔曲线;animation作用于元素本身而不是样式属性,可以使用关键帧概念。 8.浏览器解析css选择器是 从右往左的。 9.内部元素的宽高设置百分比,分别相对于父元素的宽高;但是padding margin 的百分比均相对于父元素的宽度; 10.js创建对象 ```js //工厂模式 无法知道对象类型 function Person(name,age){ var o = new Object(); o.name = name; o.age = age; o.sayName = function(){console.log(this.name);} return o; } var person = Person("qq",12); //构造函数模式 方法不能共享 function Person(name,age){ this.name = name; this.age = age; this.sayName = function(){console.log(this.name);} } var person = new Person("qq",12); //原型模式 实例共享导致问题 function Person(){} Person.prototype.name = "qq"; Person.prototype.age = 12; Person.prototype.sayName = function(){console.log(this.name);} var person = new Person(); //组合使用构造函数模式和原型模式 function Person(name,age){ this.name = name; this.age = age; } Person.prototype= { //必须重新指定构造函数 constructor:Person, sayName:function(){console.log(this.name);} } var person = new Person("qq",12); //动态原型模式,避免原型方法的重复定义 function Person(name,age){ this.name = name; this.age = age; if(typeof this.sayName != "function"){ Person.prototype.sayName = function(){console.log(this.name);} } } var person = new Person("qq",12); //稳妥构造函数模式 ``` 11.js继承 ```js //原型链继承 function superType(){this.superValue = true;} superType.prototype.getSuperValue = function(){console.log(this.superValue);} function subType(){this.subValue = false;} //此处不是subType的原型的constructor属性被修改了,而是因为subType原型指向了另一个对象--superType的原型,而这个原型对象的constructor属性指向的是superType subType.prototype = new superType(); subType.prototype.getSubType = function(){console.log(this.subValue);} var ins = new subType(); //借用构造函数 function superType(){this.color = "red";} function subType(){superType.call(this);} var ins = new subType(); ins.color;//"red" //组合式继承 function superType(name){ this.name = name; } superType.prototype.sayName = function(){console.log(this.name)} function subType(name){ superType.call(this,name); } subType.prototype = new superType(); subType.prototype.constructor = subType; var ins = new subType("qq"); ins.sayName();//"qq" //原型式继承 //可以用Object.create()方法替代 function Object(o){ function F(){} F.prototype = o; return new F(); } var Person = { name:"qq", age :123 } var person = Object(Person); person.name;//"qq" //寄生式继承 function createAnother(origin){ var clone = Object(origin); clone.sayHi = function (){console.log("Hi")} return clone; } var Person = { name:"qq", age :123 } var another = createAnother(Person); another.sayHi();//"Hi" //寄生组合式继承,为了防止两次调用超类型构造函数 function inheritPrototype(subType,superType){ var prototype = Object(superType.prototype);//创建对象,是超类型原型的一个副本 prototype.constructor = subType;//增强对象 subType.prototype = prototype; } function superType(name){ this.name = name; } superType.prototype.sayName = function(){console.log(this.name)} function subType(name){ superType.call(this,name); } inheritPrototype(subType,superType); ``` 12.数组随机排序 ```js var arr = [1,2,3,4,5,6,7,8,9]; //比较函数的参数,v1-v2升序,v2-v1降序 arr.sort(function(){ return Math.random()-0.5; }); //sort接受一个比较函数作为参数,比较函数会接收两个参数,若第一个参数位于第二个参数之前返回一个负数,第一个参数位于第二个参数之后返回一个正数;Math.random()生成[0-1)的随机数,减去0.5可能正可能负; ``` 13.This对象的理解 this指向函数的直接调用者;如果有new,this指向new出来的对象;在事件中,this指向事件的触发对象,IE的attachEvent中的this总是指向全局对象window。 14.通用的事件侦听器 ```js var EventUtil = { addEvent:function(element,type,handler){ if(element.addEventListener){ element.addEventListener(type,handler,false); }else if(element.attachEvent){ element.attachEvent('on'+type,handler); }else{ element['on'+type] = handler; } }, removEvent:function(element,type,handler){ if(element.removeEventListener){ element.removeEventListener(type,handler,false); }else if(element.detachEvent){ element.detachEvent('on'+type,handler); }else{ element['on'+type] = null; } }, getEvent: function(e){ return e||window.e; }, getTarget: function(e){ return e.target||e.srcElement; }, //阻止事件冒泡,IE不支持捕获 stoPropagation: function(e){ if(e.stoPropagation){ e.stoPropogation(); }else{ e.cancelBubble = true; } }, preventDefault: function(e){ if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue = false; } } }; ``` 15.['1','2','3'].map(parseInt);//[1,NaN,NaN],map的参数是function(value,index,array){},parseInt方法最多接受两个参数,第一个是要解析的数字,第二个是要解析的数字的基数(2-36),所以实际传给parseInt的参数是'1'-'0','2'-'1','3'-'2';基数‘0’会被当成‘10’来解析,'2'的基数‘1’不在基数范围之内,'3'超过了基数‘2’的值,所以后两个返回NaN. 17.ajax原生实现: ```js var createXHR = (function(){ if(typeof XMLHttpRequest != 'undefined'){ return function(){ return new XMLHttpRequest(); }; }else if(typeof ActiveXObject != 'undefined'){ return function(){ if(typeof arguments.callee.activeXString != 'String'){ var versions = ['MSXML2.XMLHttp.6.0','MSXML2.XMLHttp.3.0','MSXML2.XMLHttp'], var len = versions.length; for(var i = 0;i<len;i++){ try{ new ActiveXObject(versions[i]); arguments.callee.activeXString = versions[i]; break; }catch{ ... } } } rerurn new ActiveXObject(arguments.callee.activeXString); }; }else{ return function(){ throw new Error('No XHR object avaliable') }; } })(); var xhr = createXHR(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status >=200 && xhr.status < 300 || xhr.status == 304){ //dosomeThing(); }else{ alert('Request was unsuccessfull'); } } }; xhr.open('get/post','example.php',false); xhr.send(); ``` ajax清除缓存,jquery使用{catch:false};原生可以调用setRequestHeader()设置请求头; ```js xhr.setRequestHeader('If-Modified-Since','0'); xhr.setRequestHeader('Carch-Control','no-catch'); //或者在url上加随机版本号或时间戳"fresh=" + Math.random();"nowtime=" + new Date().getTime();。 ``` 18.js实现事件模型 ```js function EventTarget(){ this.handlers = {}; } EventTarget.prototype={ constructor:EventTarget, //绑定事件 addHandler:function(type,handler){ if(typeof this.handlers[type] == 'undefined'){ this.handlers[type] = []; } this.handlers[type].push(handler); }, //触发事件 fire:function(type){ var args = Array.prototype.slice.call(arguments,1), handler = this.handlers[type]; if(!Array.isArray(handler)) return; handler.forEach(function(callback){ try{ //args是参数数组,需要apply解析 callback.apply(this,args); }catch(e){ console.log(e); } }); }, //解绑事件 removeHandler:function(type,handler){ if(this.handlers[type] instanceof Array){ var handlers = this.handlers[type], len = handlers.length; for(var i = 0;i<len;i++){ if(handlers[i] === handler){ break; } } handlers.splice(i,1) } } }; var et = new EventTarget(); var handler = function(a,b){ console.log(a+b); } et.addHandler('sum',handler); et.fire('sum',1,2);//3 et.removeHandler('sum',handler); et.fire('sum',1,2);//undefined ``` 20.hasOwnProperty(propertyName)查找的是当前对象的实例是否含有给定属性,不会查找原型链。 21.当new 构造函数时发生了什么? new foo(...)执行时,1.一个新对象被创建,它继承自foo.prototype;2.构造函数foo被执行,执行的时候,相应的传参会被传入,同时上下文(this)会被指定为这个新实例。new foo等同于new foo(),只能用在不传递任何参数的情况下。3. 如果构造函数返回了一个“对象”,这个对象会取代整个new出来的结果,如果构造函数没有返回对象,那么new出来的结果就是步骤1创建的对象。返回数组也会覆盖,因为数组也是对象。 22.直接在对象上定义属性与使用Object.defineProperty()方法定义的区别? ECMAScript中有两种属性:数据属性和访问器属性。 数据属性包含一个数据值的位置,有4个描述其行为的特性: [[Configurable]]:表示能否通过delete删除属性从而重新定义属性,能否修改属性的特性,或者能否把属性修改为访问器属性。 [[Enumerable]]:表示能否通过for-in循环返回属性。 [[Writable]]:表示能否修改属性值。 [[Value]]:包含这个属性的数据值。默认值是undefined. 直接在对象上定义属性,[[Configurable]]、[[Enumerable]]、[[Writable]]默认为true,[[Value]]被设为指定值。 使用Object.defineProperty()方法时,如果不指定的话,[[Configurable]]、[[Enumerable]]、[[Writable]]默认为false。 23.http 301 302 304的区别 301:是永久重定向; 302:临时重定向。 302会存在URL规范化和网址劫持的问题。 302重定向和网址劫持(URL hijacking)有什么关系呢?这要从搜索引擎如何处理302转向说起。从定义来说,从网址A做一个302重定向到网址B时,主机服务器的隐含意思是网址A随时有可能改主意,重新显示本身的内容或转向其他的地方。大部分的搜索引擎在大部分情况下,当收到302重定向时,一般只要去抓取目标网址就可以了,也就是说网址B。 实际上如果搜索引擎在遇到302转向时,百分之百的都抓取目标网址B的话,就不用担心网址URL劫持了。问题就在于,有的时候搜索引擎,尤其是Google,并不能总是抓取目标网址。为什么呢?比如说,有的时候A网址很短,但是它做了一个302重定向到B网址,而B网址是一个很长的乱七八糟的URL网址,甚至还有可能包含一些问号之类的参数。很自然的,A网址更加用户友好,而B网址既难看,又不用户友好。这时Google很有可能会仍然显示网址A。 由于搜索引擎排名算法只是程序而不是人,在遇到302重定向的时候,并不能像人一样的去准确判定哪一个网址更适当,这就造成了网址URL劫持的可能性。也就是说,一个不道德的人在他自己的网址A做一个302重定向到你的网址B,出于某种原因, Google搜索结果所显示的仍然是网址A,但是所用的网页内容却是你的网址B上的内容,这种情况就叫做网址URL劫持。你辛辛苦苦所写的内容就这样被别人偷走了。 当网页A用301重定向转到网页B时,搜索引擎可以肯定网页A永久的改变位置,或者说实际上不存在了,搜索引擎就会把网页B当作唯一有效目标。 301的好处是: 第一, 没有网址规范化问题。 第二, 也很重要的,网页A的PR网页级别会传到网页B。 24.实现自适应的正方形 ```js <!-- vw方法,不是很正方形 css3新增属性,vw:相对于视口宽度百分比的单位;1vw=1% viewport width; vh:相对于视口高度百分比的单位;1vh = 1% viewport height; vmin:相对于视口宽高中较小的一个百分比单位; vmax:相对于视口宽高中较大的一个百分比单位; --> <!-- <!DOCTYPE html> <html> <head> <style> #father{ display: flex; align-items: center; justify-content: center; height:600px; background:#f00; } #center{ width:50%; height: 50vw; background:#ff0; } </style> </head> <body> <div id="father"> <div id="center">正方形</div> </div> </body> </html> --> <!-- 设置垂直方向的padding撑开容器,margin,padding的百分比是相对于父元素的宽度计算的;如果center内部有文字,会撑开center的高度,所以要把center设为height=0, 但是这样的话max-height就不起作用,因为max-height是基于height使用的--> <!-- <!DOCTYPE html> <html> <head> <style> #father{ height:600px; background:#f00; } #center{ position:relative; top:50%; left:50%; width:50%; height:0; padding-bottom: 50%; background:#ff0; transform: translate(-50%,-50%); } </style> </head> <body> <div id="father"> <div id="center">正方形</div> </div> </body> </html> --> <!-- 利用伪元素的margin-top撑开元素,伪元素可理解为当前元素的子元素,所以百分比是相对于center的宽度--> <!DOCTYPE html> <html> <head> <style> #father{ height:600px; background:#f00; } #center{ position:relative; top:50%; left:50%; width:50%; overflow: hidden; background:#ff0; transform: translate(-50%,-50%); } #center:after{ content:''; display: block; margin-top: 100%; } </style> </head> <body> <div id="father"> <div id="center"></div> </div> </body> </html> ``` 25.事件循环 JavaScript所有任务可以分为同步任务和异步任务,同步任务指在主线程上排队执行的任务,前一个任务执行完毕才能执行后一个任务,异步任务指不进入主线程而进入任务队列的任务,只有任务队列通知主线程,某个异步任务可以执行了,该任务才会进入主线程执行。 异步任务运行机制:1.所有同步任务在主线程上执行,形成一个执行栈; 2.主线程之外还存在一个任务队列,只要异步任务有了运行结果,就在任务队列中放置一个事件。 3.一旦执行栈中的所有同步任务执行完毕,系统就会读取任务队列,看看里面有哪些事件,那些对应的异步任务,就会结束等待状态,进入执行栈开始执行。 4.主线程从任务队列中读取事件的过程是不断循环的,所以整个的运行机制称为Event Loop。 26.跨域如何发送cookie? 在open XMLHttpRequest之后,设置xhr.withCredentials为true,服务器端设置Access-Control-Allow-Credentials响应头为true.另外要求Access-Control-Allow-Origin不能使用通配符,并且只能使用单一域名。 27.AMD CMD CommonJs AMD和CMD均是异步加载模块,但AMD依赖前置(代表:require.js),提前执行;CMD推崇就近依赖(代表:sea.js),延迟执行。 CommonJS模块的特点如下:加载模块是同步的 所有代码都运行在模块作用域,不会污染全局作用域。 模块可以多次加载,但是只会在第一次加载时运行一次,然后运行结果就被缓存了,以后再加载,就直接读取缓存结果。要想让模块再次运行,必须清除缓存。 模块加载的顺序,按照其在代码中出现的顺序。 CommonJS模块的加载机制是,输入的是被输出的值的拷贝。也就是说,一旦输出一个值,模块内部的变化就影响不到这个值。 25.js 轮播图 ```js <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>js轮播图</title> </head> <body> <style type="text/css"> * { margin: 0; padding: 0; text-decoration: none; } body { padding: 20px; } #container { position: relative; width: 600px; height: 400px; border: 3px solid #333; overflow: hidden; } #list { position: absolute; z-index: 1; width: 3000px; height: 400px; } #list img { float: left; width: 600px; height: 400px; } #buttons { position: absolute; left: 250px; bottom: 20px; z-index: 2; height: 10px; width: 100px; } #buttons span { float: left; margin-right: 5px; width: 10px; height: 10px; border: 1px solid #fff; border-radius: 50%; background: #333; cursor: pointer; } #buttons .on { background: orangered; } .arrow { position: absolute; top: 180px; z-index: 2; display: none; width: 40px; height: 40px; font-size: 36px; font-weight: bold; line-height: 39px; text-align: center; color: #fff; background-color: RGBA(0, 0, 0, .3); cursor: pointer; } .arrow:hover { background-color: RGBA(0, 0, 0, .7); } #container:hover .arrow { display: block; } #prev { left: 20px; } #next { right: 20px; } </style> <div id="container"> <div id="list" style="left: 0"> <img src="img/1.jpg" alt="1"/> <img src="img/2.jpg" alt="2"/> <img src="img/3.jpg" alt="3"/> <img src="img/4.jpg" alt="4"/> <img src="img/5.jpg" alt="5"/> </div> <div id="buttons"> <span index="1" class="on"></span> <span index="2"></span> <span index="3"></span> <span index="4"></span> <span index="5"></span> </div> <a href="javascript:;" id="prev" class="arrow">&lt;</a> <a href="javascript:;" id="next" class="arrow">&gt;</a> </div> </body> <script type="text/javascript"> /* 知识点: */ /* this用法 */ /* DOM事件 */ /* 定时器 */ window.onload = function () { var container = document.getElementById('container'); var list = document.getElementById('list'); var buttons = document.getElementById('buttons').getElementsByTagName('span'); var prev = document.getElementById('prev'); var next = document.getElementById('next'); var index = 1; var timer; function animate(offset) { //获取的是style.left,是相对左边获取距离,所以第一张图后style.left都为负值, //且style.left获取的是字符串,需要用parseInt()取整转化为数字。 var newLeft = parseInt(list.style.left) + offset; list.style.left = newLeft + 'px'; //无限滚动判断 if (newLeft > 0) { list.style.left = -2400 + 'px'; } if (newLeft < -2400) { list.style.left = 0; } } function play() { //重复执行的定时器 timer = setInterval(function () { next.onclick(); }, 2000) } function stop() { clearInterval(timer); } function buttonsShow() { //将之前的小圆点的样式清除 for (var i = 0; i < buttons.length; i++) { if (buttons[i].className == "on") { buttons[i].className = ""; } } //数组从0开始,故index需要-1 buttons[index - 1].className = "on"; } prev.onclick = function () { index -= 1; if (index < 1) { index = 5 } buttonsShow(); animate(600); }; next.onclick = function () { //由于上边定时器的作用,index会一直递增下去,我们只有5个小圆点,所以需要做出判断 index += 1; if (index > 5) { index = 1 } animate(-600); buttonsShow(); }; for (var i = 0; i < buttons.length; i++) { (function (i) { buttons[i].onclick = function () { /* 这里获得鼠标移动到小圆点的位置,用this把index绑定到对象buttons[i]上,去谷歌this的用法 */ /* 由于这里的index是自定义属性,需要用到getAttribute()这个DOM2级方法,去获取自定义index的属性*/ var clickIndex = parseInt(this.getAttribute('index')); var offset = 600 * (index - clickIndex); //这个index是当前图片停留时的index animate(offset); index = clickIndex; //存放鼠标点击后的位置,用于小圆点的正常显示 buttonsShow(); } })(i) } container.onmouseover = stop; container.onmouseout = play; play(); } </script> </html> ``` 26.js上拉加载和下拉刷新 ```js //上拉加载 //获取滚动条当前的位置 function getScrollTop() { var scrollTop = 0; if (document.documentElement && document.documentElement.scrollTop) { scrollTop = document.documentElement.scrollTop; } else if (document.body) { scrollTop = document.body.scrollTop; } return scrollTop; } //获取当前可视范围的高度 function getClientHeight() { var clientHeight = 0; if (document.body.clientHeight && document.documentElement.clientHeight) { clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight); } else { clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight); } return clientHeight; } //获取文档完整的高度 function getScrollHeight() { return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); } window.onscroll = function () { if (getScrollTop() + getClientHeight() == getScrollHeight()){ //请求数据 } } ``` ```js //下拉刷新 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <title>下拉刷新</title> <style type="text/css"> #slideDown{margin-top: 0;width: 100%;} #slideDown1,#slideDown2{width: 100%;height: 70px;;background: #e9f4f7;display: none;} #slideDown1{height: 20px;} #slideDown1>p,#slideDown2>p{margin: 20px auto;text-align:center;font-size: 14px;color: #37bbf5;} </style> <div id="content"> <div id="slideDown"> <div id="slideDown1"> <p>松开刷新</p> </div> <div id="slideDown2"> <p>正在刷新 ...</p> </div> </div> <div class="myContent"> <ul> <li>item1 -- item1 -- item1</li> <li>item2 -- item2 -- item2</li> <li>item3 -- item3 -- item3</li> <li>item4 -- item4 -- item4</li> <li>item5 -- item5 -- item5</li> <li>item6 -- item6 -- item6</li> <li>item7 -- item7 -- item7</li> </ul> </div> </div> <body> <script type="text/javascript"> //第一步:下拉过程 function slideDownStep1(dist){ // dist 下滑的距离,用以拉长背景模拟拉伸效果 var slideDown1 = document.getElementById("slideDown1"), slideDown2 = document.getElementById("slideDown2"); slideDown2.style.display = "none"; slideDown1.style.display = "block"; slideDown1.style.height = (- dist) + "px"; } //第二步:下拉,然后松开, function slideDownStep2(){ var slideDown1 = document.getElementById("slideDown1"), slideDown2 = document.getElementById("slideDown2"); slideDown1.style.display = "none"; slideDown1.style.height = "20px"; slideDown2.style.display = "block"; //刷新数据 //location.reload(); } //第三步:刷新完成,回归之前状态 function slideDownStep3(){ var slideDown1 = document.getElementById("slideDown1"), slideDown2 = document.getElementById("slideDown2"); slideDown1.style.display = "none"; slideDown2.style.display = "none"; } //下滑刷新调用 k_touch("content","y"); //contentId表示对其进行事件绑定,way==>x表示水平方向的操作,y表示竖直方向的操作 function k_touch(contentId,way){ var _start = 0, _end = 0, _content = document.getElementById(contentId); _content.addEventListener("touchstart",touchStart,false); _content.addEventListener("touchmove",touchMove,false); _content.addEventListener("touchend",touchEnd,false); function touchStart(event){ //var touch = event.touches[0]; //这种获取也可以,但已不推荐使用 var touch = event.targetTouches[0]; if(way == "x"){ _start = touch.pageX; }else{ _start = touch.pageY; } } function touchMove(event){ var touch = event.targetTouches[0]; console.log(event); if(way == "x"){ _end = (_start - touch.pageX); }else{ _end = (_start - touch.pageY); //下滑才执行操作 if(_end < 0){ slideDownStep1(_end); } } } function touchEnd(event){ if(_end >0){ console.log("左滑或上滑 "+_end); }else{ console.log("右滑或下滑"+_end); slideDownStep2(); //刷新成功则 //模拟刷新成功进入第三步 setTimeout(function(){ slideDownStep3(); },1500); } } } </script> </html> ``` 27.jQuery 源码 1.jQuery.fn.init.prototype = jQuery.fn;//关键代码 ```js //源码部分 var jQuery = function( selector, context ) { return new jQuery.fn.init( selector, context, rootjQuery ); }, class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function(selector, context, rootjQuery){ } } jQuery.fn.init.prototype = jQuery.fn; ``` 28.vue ng双向绑定的实现:AngularJS使用$scope.$watch(视图到模型)以及$scope.$apply(模型到视图)来实现这个功能。 ng:脏检查,涉及到scope下面的三个方法:$watch,$digest,$apply $digest和$apply差异:最直接的差异是,$apply可以带参数,它可以接受一个函数,然后在应用数据之后,调用这个函数。所以,一般在集成非Angular框架的代码时,可以把代码写在这个里面调用。在简单的数据模型中,这两者没有本质差别,但是当有层次结构的时候,就不一样了。考虑到有两层作用域,我们可以在父作用域上调用这两个函数,也可以在子作用域上调用,这个时候就能看到差别了。对于$digest来说,在父作用域和子作用域上调用是有差别的,但是,对于$apply来说,这两者一样。当调用$digest的时候,只触发当前作用域和它的子作用域上的监控,但是当调用$apply的时候,会触发作用域树上的所有监控。因此,从性能上讲,如果能确定自己作的这个数据变更所造成的影响范围,应当尽量调用$digest,只有当无法精确知道数据变更造成的影响范围时,才去用$apply,很暴力地遍历整个作用域树,调用其中所有的监控。 我们按下按钮=> 浏览器接收到一个事件,进入angular context(后面会解释为什么)=> $digest循环开始执行,查询每个$watch是否变化=> 由于监视$scope.name的$watch报告了变化,它会强制再执行一次$digest循环=> 新的$digest循环没有检测到变化=> 浏览器拿回控制权,更新与$scope.name新值相应部分的DOM。 谁决定什么事件进入angular context,而哪些又不进入呢?$apply! 如果当事件触发时,你调用apply,它会进入angularcontext,如果没有调用就不会进入。现在你可能会问:刚才的例子里我也没有调用apply,为什么?Angular为你做了!因此你点击带有ng-click的元素时,事件就会被封装到一个apply调用。如果你有一个ng−model="foo"的输入框,然后你敲一个f,事件就会这样调用apply("foo = 'f';")。 Angular什么时候不会自动为我们apply呢?这是Angular新手共同的痛处。为什么我的jQuery不会更新我绑定的东西呢?因为jQuery没有调用apply,事件没有进入angular context,$digest循环永远没有执行。 ng什么时候进行脏检查: 其实,ng只有在指定事件触发后,才进入$digest cycle: 1.DOM事件,譬如用户输入文本,点击按钮等。(ng-click) 2.XHR响应事件 ($http) 3.浏览器Location变更事件 ($location) 4.Timer事件($timeout, $interval) 5.执行$digest()或$apply() vue数据双向绑定是通过数据劫持(Object.defineProperty)结合发布者-订阅者模式的方式来实现的.实现步骤: 1.实现一个监听器Observer,用来劫持并监听所有属性,如果有变动的,就通知订阅者。 2.实现一个订阅者Watcher,可以收到属性的变化通知并执行相应的函数,从而更新视图。 3.实现一个解析器Compile,可以扫描和解析每个节点的相关指令,并根据初始化模板数据以及初始化相应的订阅器。 29.cookie和localStorage、sessionStorage区别 cookie:一般由服务器生成,可设置失效时间。如果在浏览器端生成Cookie,默认是关闭浏览器后失效;4k左右;每次都会携带在HTTP头中,如果使用cookie保存过多数据会带来性能问题; localStorage:除非被清除,否则永久保存;5M左右;仅在客户端(即浏览器)中保存,不参与和服务器的通信 sessionStorage:仅在当前会话下有效,关闭页面或浏览器后被清除;同上 30.node的核心模块 process:全局变量,描述Node.js的进程状态,提供了一个操作系统的简单接口; util:核心模块 events:事件驱动,只提供一个对象events.EventEmitter fs:文件系统 31.git pull fetch 区别 git pull == git fetch +git merge 32.重排和重绘 "重绘"不一定需要"重排",比如改变某个网页元素的颜色,就只会触发"重绘",不会触发"position属性为absolute或fixed的元素,重排的开销会比较小,因为不用考虑它对其他元素的影响。 重排",因为布局没有改变。但是,"重排"必然导致"重绘",比如改变一个网页元素的位置,就会同时触发"重排"和"重绘",因为布局改变了。 提高性能的几个技巧: 1.DOM 的多个读操作(或多个写操作),应该放在一起。不要两个读操作之间,加入一个写操作。 2.如果某个样式是通过重排得到的,那么最好缓存结果。避免下一次用到的时候,浏览器又要重排。 3.不要一条条地改变样式,而要通过改变class,或者csstext属性,一次性地改变样式。 4.尽量使用离线DOM,而不是真实的网面DOM,来改变元素样式。比如,操作Document Fragment对象,完成后再把这个对象加入DOM。再比如,使用 cloneNode() 方法,在克隆的节点上进行操作,然后再用克隆的节点替换原始节点。 5.先将元素设为display: none(需要1次重排和重绘),然后对这个节点进行100次操作,最后再恢复显示(需要1次重排和重绘)。这样一来,你就用两次重新渲染,取代了可能高达100次的重新渲染。 6.position属性为absolute或fixed的元素,重排的开销会比较小,因为不用考虑它对其他元素的影响。 7.只在必要的时候,才将元素的display属性为可见,因为不可见的元素不影响重排和重绘。另外,visibility : hidden的元素只对重绘有影响,不影响重排。 8.window.requestAnimationFrame() 方法 39.js排序算法: ```js //选择排序 4.276ms /*const selectionSort = (arr) => { let len = arr.length; let minIndex = 0; for(let i=0;i<len-1;i++){ minIndex = i; for(let j=i+1;j<len;j++){ if(arr[minIndex]>arr[j]){ minIndex = j; } } let tmp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = tmp; } return arr; } */ //插入排序 4.346ms /*const insertionSort = (arr) => { let len = arr.length; for(let i=1;i<len;i++){ let key = arr[i]; let j=i-1; while(j>=0&&arr[j]>key){ arr[j+1] = arr[j]; j--; } arr[j+1] = key; } return arr; }*/ //二分插入排序 4.557ms /*const binaryinsertionSort = (arr) => { let len = arr.length; for (let i = 1; i < len; i++) { let key = arr[i]; let left = 0; let right = i-1; while(left<=right){ let middle = parseInt((left+right)/2); if(key<arr[middle]){ right = middle - 1; }else{ left = middle+1; } } for(let j = i-1;j>=left;j--){ arr[j+1] = arr[j]; } arr[left] = key; } return arr; }*/ //希尔排序 什么玩意儿~~ //归并排序,循环调用 对子序列分别归并排序 /*const mergeSort = (arr) => { let len = arr.length; //如果len大于2,mergeSort方法最终返回的是merge函数运行后的结果, //即排序过的子数组;len<2是用来取子序列用的 if(len<2){ return arr; } let middle = parseInt(len/2); let left = arr.slice(0,middle); let right = arr.slice(middle); return merge(mergeSort(left),mergeSort(right)); } const merge = (left,right) => { let result = []; while(left.length&&right.length){ if(left[0]<=right[0]){ result.push(left.shift()); }else{ result.push(right.shift()); } } //console.log('剩余',left,right); //剩下的是排好序的比较大的数值,依次push进result即可 能用concat但是不优雅 //if(left.length){ // result = result.concat(left); //} //if(right.length){ // result = result.concat(right); //} while(left.length) result.push(left.shift()); while(right.length) result.push(right.shift()); return result; }*/ //快速排序 4.317ms /*const quickSort = (arr) => { let len = arr.length; if(len < 2) return arr; let pivotIndex = Math.floor(len/2); let pivot = arr.splice(pivotIndex,1)[0]; let left = []; let right = []; //此时arr的长度已改变 for(let i=0;i<arr.length;i++){ if(arr[i]<pivot){ left.push(arr[i]); }else{ right.push(arr[i]); } } return quickSort(left).concat(pivot,quickSort(right)); }*/ //堆排序,利用最大堆或最小堆的概念 4.112ms //最大堆中的最大元素值出现在根结点(堆顶) //堆中每个父节点的元素值都大于等于其孩子结点(如果存在) /*const heapSort = (arr) => { let heapSize = arr.length,tmp; for(let i = Math.floor(heapSize/2)-1;i>=0;i--){ heapify(arr,i,heapSize); } for(let j = heapSize-1;j>=1;j--){ tmp = arr[0]; arr[0] = arr[j]; arr[j] = tmp; heapify(arr,0,--heapSize); } return arr; } const heapify = (arr,x,len) => { let l = 2*x+1,r=2*(x+1),largest = x,tmp; if(l<len&&arr[l]>arr[largest]){ largest = l; } if(r<len&&arr[r]>arr[largest]){ largest = r; } if(largest != x){ tmp = arr[x]; arr[x] = arr[largest]; arr[largest] = tmp; heapify(arr,largest,len) } } */ /*let arr = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]; console.time('耗时'); console.log(heapSort(arr)); console.timeEnd('耗时');*/ ``` http://www.qcyoung.com/2016/12/18/JavaScript%20%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95%E6%B1%87%E6%80%BB/ ng: 所有的供应商都只被实例化一次,也就说他们都是单例的 除了constant,所有的供应商都可以被装饰器(decorator)装饰 value就是一个简单的可注入的值 service是一个可注入的构造器 factory是一个可注入的方法 decorator可以修改或封装其他的供应商,当然除了constant provider是一个可配置的factory
Java
UTF-8
3,262
2.671875
3
[]
no_license
package dsp.hadoop.examples; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; class Call implements WritableComparable<Call> { long caller; long recipient; int year; Call() { this.caller = -1; this.recipient = -1; this.year = -1; } Call(long caller, long recipient, int year) { this.caller = caller; this.recipient = recipient; this.year = year; } public void readFields(DataInput in) throws IOException { this.caller = in.readLong(); this.recipient = in.readLong(); this.year = in.readInt(); } public void write(DataOutput out) throws IOException { out.writeLong(caller); out.writeLong(recipient); out.writeInt(year); } public int compareTo(Call other) { int ret = (int) (caller - other.caller); if (ret == 0) ret = (int) (recipient - other.recipient); if (ret == 0) ret = year - other.year; return ret; } public long getCaller() { return caller; } public long getRecipient() { return recipient; } public int getYear() { return year; } } public class DistributePhoneCallsPerYear { public static class MapperClass extends Mapper<User,UserAction,Call,IntWritable> { @Override public void map(User user, UserAction userAction, Context context) throws IOException, InterruptedException { if (userAction.getAction().getType() == Action.ActionType.CALL) { Calendar cal = Calendar.getInstance(); cal.setTime(userAction.getDate()); context.write( new Call( user.getPhoneNumber(), Long.parseLong(userAction.getAction().desc), cal.get(Calendar.YEAR)), new IntWritable(1)); } } } public static class ReducerClass extends Reducer<Call,IntWritable,Call,IntWritable> { @Override public void reduce(Call call, Iterable<IntWritable> counts, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable count : counts) sum += count.get(); context.write(call, new IntWritable(sum)); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "DistributePhoneCallsPerYear"); job.setJarByClass(DistributePhoneCallsPerYear.class); job.setMapperClass(MapperClass.class); job.setReducerClass(ReducerClass.class); job.setMapOutputKeyClass(Call.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(Call.class); job.setOutputValueClass(IntWritable.class); job.setInputFormatClass(CellcomUserActionInputFormat .class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
Python
UTF-8
1,569
3.984375
4
[]
no_license
### Clases en Python ### Seguramente te has fijado ya que cuando necesitamos utilizar algunas ### funciones especiales, tenemos que "importar" una biblioteca. ### A lo largo de las sesiones hemos utilizado las bibliotecas "os" y ### "random". ### Estas bibliotecas son compendios que contienen clases ### y funciones que alguien más ya codificó y las puso a disposición ### de la comunidad Python. ### Nosotros también podemos hacer lo mismo con los scripts que usamos ### regularmente. Después de todo: si ya lo codificaste una vez, ¿para qué ### hacerlo otra vez? ### Las clases son estructuras de datos, tal como lo son las listas, ### los diccionarios, las funciones, pero son una estructura de datos especial: ### las clases son la plantilla en la que se crean los objetos. ### Hasta ahora hemos hablado mucho de objetos,¿pero qué son los objetos? ### Simple y llano: son encapsulaciones de variables y funciones. ### Las "clases" son los planos con los que esos objetos son construidos. ### Por ejemplo, supongamos que tenemos un pequeño almacén de ### reactivos químicos en los que tenemos: NaCl, NaOH y Na2SO4. ### Vamos a representar la estructura de nuestro almacén con una clase: class almacen(object): def __init__(self, compuestos): self.compuestos = compuestos def reporte(self): nombres = '' for x in compuestos: print(x) nombres += str(x['cantidad']) + ' gramos de ' + x['formula'] + '\n' return print('El almacén cuenta con los siguientes compuestos:\n' + nombres)
Java
UTF-8
1,861
2.4375
2
[]
no_license
package com.example.logic_university; import android.os.AsyncTask; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /* Android code is 95 % done by Li Zhengyi,with the help of teammate Sriram and Emma in some errors' debugging and fixing */ public class AsyncTaskGET extends AsyncTask<Command3,Void, JSONObject> { JSONObject jsonObject=null; AsyncTaskGET.IServerResponse3 callback; String JSON_STRING; @Override protected JSONObject doInBackground(Command3...commands ) { Command3 cmd = commands[0]; this.callback = cmd.callback; HttpURLConnection conn=null; try { URL url1=new URL(cmd.url); conn=(HttpURLConnection)url1.openConnection(); InputStream inputStream=new BufferedInputStream(conn.getInputStream()); BufferedReader r=new BufferedReader(new InputStreamReader(inputStream)); StringBuilder response = new StringBuilder(); while((JSON_STRING=r.readLine())!=null){ response.append(JSON_STRING+"\n"); } r.close(); inputStream.close(); try{ jsonObject=new JSONObject(response.toString().trim()); } catch (Exception e) { e.printStackTrace(); } } catch (Exception ex) { return jsonObject; } finally { if (conn != null) { conn.disconnect(); } } return jsonObject ; } @Override protected void onPostExecute(JSONObject jo){ super.onPostExecute(jo); this.callback.onServerResponse(jo); } public interface IServerResponse3{ void onServerResponse(JSONObject jsonObject); } }
C#
UTF-8
1,321
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace PZ1_Mahno_.Сlass_library { public class Owner { public string owner_name { get; set; } public long owner_phone { get; set; } public DateTime owner_date_buy { get; set; } public Owner(string owner_name, long owner_phone, DateTime owner_date_buy) { this.owner_name = owner_name; this.owner_phone = owner_phone; this.owner_date_buy = owner_date_buy; } public override string ToString() { return owner_name + Convert.ToString(owner_phone)+ Convert.ToString(owner_date_buy); } public static List<Owner> GetOwner() { List<Owner> owner_list = new List<Owner>() { new Owner("Ivan", 380937172521, new DateTime(2015, 7, 20, 18, 30, 25)), new Owner("Evhen", 38022222222, new DateTime(2017, 6, 14, 18, 30, 25)), new Owner("Liza", 380664432666, new DateTime(2018, 3, 10, 18, 30, 25)), new Owner("Liza2", 380664432666, new DateTime(2018, 3, 10, 18, 30, 25)) }; return owner_list; } } }
Python
UTF-8
1,052
2.578125
3
[ "MIT" ]
permissive
import time class TestRoomTemp: url = "/home_api/room_temp" def test_post(self, client): res = client.post(self.url) assert res.status_code != 200 # This should fail data = {"name": "pytest", "value": -1} res = client.post(self.url, json=data) assert res.status_code == 200 data = {"name": "pytest"} res = client.post(self.url, json=data) assert res.status_code != 200 # This should fail def test_get_simple(self, client): res = client.get(self.url) assert res.status_code == 200 def test_get_with_name(self, client): res = client.get(self.url + "?name=pytest") assert res.status_code == 200 assert "result" in res.json def test_get_with_time(self, client): res = client.get(self.url + "?begin={}".format(time.time() + 1000)) assert res.status_code == 200 assert len(res.json["result"]) == 0 res = client.get(self.url + "?end={}".format(0)) assert len(res.json["result"]) == 0
Java
UTF-8
188
1.539063
2
[]
no_license
package com.riotdata.demo.domain.riotChamp; import org.springframework.data.jpa.repository.JpaRepository; public interface ChampionRepository extends JpaRepository<Champion, String> { }
C++
UTF-8
4,602
2.875
3
[]
no_license
#include "TreeNodes.h" // #include "NameValueTypeVisitor.h" // #include "NameValueTypeActions.h" // the order of static vars initialization is always respected for each translation unit const char* NameValueNode::_arrayIndex[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; const unsigned int NameValueNode::_arrayIndexSize = (sizeof((NameValueNode::_arrayIndex))/sizeof(*(NameValueNode::_arrayIndex))); const char* NameValueNode::_arrayElementObject = "arrayElement"; const clang::QualType QualTypeNode::_defaultType = clang::QualType(); const clang::FunctionDecl* const FunctionDeclNode::_defaultType = nullptr; NameValueNode::NameValueNode(const NameValueNode& other) : _name(other._name) , _value(other._value) { } NameValueNode::NameValueNode(const char *name, const char *value) : _name(name) , _value(value) {} bool NameValueNode::_isNameInteger(void) const { if(_name.empty()) { return false; } char* p; strtol(_name.c_str(), &p, DECIMAL_BASE); return (*p == '\0'); } NameValueNode* NameValueNode::createValue(const char *name, const char *value) { return new NameValueNode(name, value); } NameValueNode* NameValueNode::createObject(const char *name) { return new NameValueNode(name, "object"); } NameValueNode* NameValueNode::createArray(const char *name) { return new NameValueNode(name, "array"); } NameValueNode* NameValueNode::createArrayElement(unsigned int index, const char* val) { if ( val == nullptr ) { val = NameValueNode::_arrayElementObject; } return new NameValueNode( std::to_string(index).c_str(), val ); } NameValueNode* NameValueNode::clone(const char * value) const { if (value == "") { return new NameValueNode(*this); } else { // clone but with different value return new NameValueNode( this->_name.c_str(), value); } } int NameValueNode::getIndex(void) const { if ( isArrayElement() ) { if(_isNameInteger()){ return stoi(_name); } else { throw std::logic_error(std::string("Error getIndexAsString: name is not an index\n")); } } else { return -1; } } void NameValueNode::addChild(NameValueNode* child) { _children[child->_name] = std::unique_ptr<NameValueNode>(child); } const NameValueNode* NameValueNode::getChild(const char *name) const { auto iter = _children.find(name); if (iter == _children.end()) { std::cout << "ERROR: node " << _name << " has no child named '" << name << "'" << std::endl; return nullptr; } return iter->second.get(); } QualTypeNode::QualTypeNode(const QualTypeNode& other) : NameValueNode(other) , _type(other._type) {} QualTypeNode::QualTypeNode(const char *name, const clang::QualType& type, const char *value) : NameValueNode(name, value) , _type(type) {} QualTypeNode* QualTypeNode::clone(const char * value) const { if (value == "") { return new QualTypeNode(*this); } else { // clone but with different value return new QualTypeNode( this->getName().c_str(), this->_type, value); } } FunctionDeclNode::FunctionDeclNode(const FunctionDeclNode& other) : NameValueNode(other) , _type(other._type) {} FunctionDeclNode::FunctionDeclNode(const char *name, const clang::FunctionDecl* type, const char *value) : NameValueNode(name, value ) , _type(type) {} FunctionDeclNode* FunctionDeclNode::create(const char *name, const clang::FunctionDecl* type, const char *value) { return new FunctionDeclNode(name, type, value); } FunctionDeclNode* FunctionDeclNode::clone(const char * value) const { if (value == "") { return new FunctionDeclNode(*this); } else { return new FunctionDeclNode( this->getName().c_str(), this->_type, value); } } QualTypeNode* QualTypeNode::create(const char* name, const clang::QualType& qualType, const char* value ) { QualTypeNode* node = nullptr; const clang::RecordType *structType = qualType->getAsStructureType(); if (structType != nullptr) { // not useful , value can be "" for struct const std::string structName = qualType.getAsString(); node = new QualTypeNode(name, qualType, structName.c_str() ); const clang::RecordDecl *structDecl = structType->getDecl(); for (const auto field : structDecl->fields()) { auto* child = QualTypeNode::create(field->getNameAsString().c_str(), field->getType(), ""); node->addChild(child); } } else { node = new QualTypeNode(name, qualType, value ); } return node; }
Java
UTF-8
2,203
2.1875
2
[]
no_license
package com.sinco.carnation.goods.tools; import net.weedfs.client.WeedFSClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.sinco.carnation.goods.service.GoodsService; import com.sinco.carnation.sys.service.AccessoryServiceImpl; import com.sinco.carnation.sys.service.SysConfigService; /** * * <p> * Title: GoodsTools.java * </p> * * <p> * Description:商品管理工具 * </p> * * <p> * Copyright: Copyright (c) 2015 * </p> * * <p> * Company: 新科聚合 thinker.vc * </p> * * @author thinker * * @date 2014-12-10 * * @version 1.0.1 */ @Component public class GoodsTools { @Autowired private SysConfigService configService; @Autowired private GoodsService goodsService; @Autowired private AccessoryServiceImpl accessoryService; @Autowired private WeedFSClient fsClient; /** * 异步生成商品二维码,使用@Async,有时session、商品主图片获取不到 * * @param request * @param goods_id */ // @Async // public void createGoodsQRAsync(HttpServletRequest request, String goods_id, String goodsMainImgPath, String goodsUrl) { // String path = create(request, goods_id, goodsMainImgPath, goodsUrl); // Goods updateGoods = new Goods(); // updateGoods.setId(Long.parseLong(goods_id)); // updateGoods.setQrImgPath(path); // goodsService.update(updateGoods); // } // public String createGoodsQRSync(HttpServletRequest request, String goods_id, String goodsMainImgPath, String goodsUrl) { // return create(request, goods_id, goodsMainImgPath, goodsUrl); // } // private String create(HttpServletRequest request, String goods_id, String goodsMainImgPath, String goodsUrl) // { // try { // BufferedImage image = ThinkerQRCodeUtil.createImage(goodsUrl, goodsMainImgPath, true); // // ByteArrayOutputStream os = new ByteArrayOutputStream(); // ImageIO.write(image, "jpg", os); // InputStream is = new ByteArrayInputStream(os.toByteArray()); // RequestResult result = fsClient.upload(is, goodsMainImgPath, goodsMainImgPath); // return result.getUrl(); // } catch (Exception e) { // e.printStackTrace(); // } // return null; // } }
Markdown
UTF-8
2,757
2.5625
3
[ "MIT" ]
permissive
# Safari Cookbook [![Cookbook Version](http://img.shields.io/cookbook/v/safari.svg?style=flat-square)][cookbook] [![Build Status](http://img.shields.io/travis/dhoer/chef-safari.svg?style=flat-square)][travis] [cookbook]: https://supermarket.chef.io/cookbooks/safari [travis]: https://travis-ci.org/dhoer/chef-safari This cookbook provides a `safari_version` library method to retrieve Safari version installed, and a `safari_extension` resource to install Safari extensions. ## Requirements - Safari 7 only (Safari 8 or higher no longer allows for automation) - User must be logged into GUI before calling safari_extension (see [macosx_gui_login](https://supermarket.chef.io/cookbooks/macosx_gui_login) cookbook) - Chef 11.14 or higher (sensitive attribute introduced) ### Platforms - Mac OS X ## Usage Include the safari as a dependency to make library method and extension resource available. ### safari_version The safari_version retrieves CFBundleShortVersionString by default: ```ruby version = safari_version # => 7.0.6 ``` You can return other version types by passing the name (e.g. BuildVersion, CFBundleVersion, ProjectName or SourceVersion) ```ruby bundle_version = safari_version('CFBundleVersion') # => 10600.4.10.7 ``` **Tip:** use allow_any_instance_of to stub safari_version method when testing with rspec: ```ruby allow_any_instance_of(Chef::Recipe).to receive(:safari_version).and_return('7.0.6') ``` ### safari_extension Installs Safari extensions. User must be logged into GUI before calling safari_extension (see [macosx_gui_login](https://supermarket.chef.io/cookbooks/macosx_gui_login) cookbook). #### Attribute - `safariextz` (required) - Path to Safari extension to install. Defaults to the name of the resource block. #### Example Install a Safari extension: ```ruby safari_extension 'a safari extension' do safariextz '/path/to/a.safariextz' action :install end ``` ## ChefSpec Matchers This cookbook includes a custom [ChefSpec](https://github.com/sethvargo/chefspec) matcher you can use to test your own cookbooks. Example Matcher Usage ```ruby expect(chef_run).to install_safari_extension('a safari extension').with( safariextz: '/path/to/a.safariextz') ``` Cookbook Matcher - install_safari_extension(safariextz) ## Getting Help - Ask specific questions on [Stack Overflow](http://stackoverflow.com/questions/tagged/chef-safari). - Report bugs and discuss potential features in [Github issues](https://github.com/dhoer/chef-safari/issues). ## Contributing Please refer to [CONTRIBUTING](https://github.com/dhoer/chef-safari/blob/master/CONTRIBUTING.md). ## License MIT - see the accompanying [LICENSE](https://github.com/dhoer/chef-safari/blob/master/LICENSE.md) file for details.
Python
UTF-8
7,665
2.578125
3
[]
no_license
import operator, os, stat def extract_input(): global input_str, orig_burst with open("MP04 Checker.txt", "r", encoding="utf-8") as f: file_input = f.read().split("\n") process_amt = int(file_input[0]) init_arrival_times = file_input[1].split() init_burst_times = file_input[2].split() init_priorities = file_input[3].split() init_classification = file_input[4].split() fp_algo = int(file_input[5]) bg_algo = int(file_input[6]) process_names = ["P" + str(i) for i in range(1, process_amt + 1)] arrival_times = [int(val) for val in init_arrival_times] burst_times = [int(val) for val in init_burst_times] priorities = [int(val) for val in init_priorities] classifications= [int(val) for val in init_classification] input_str += "Enter no. of processes: {} \n".format(process_amt) input_str += "Arrival Time: \n" for i in range(1, process_amt + 1): input_str += " P{}: {} \n".format(i, arrival_times[i - 1]) input_str += "\nBurst Time: \n" for i in range(1, process_amt + 1): input_str += " P{}: {} \n".format(i, burst_times[i - 1]) input_str += "\nPriority: \n" for i in range(1, process_amt + 1): input_str += " P{}: {} \n".format(i, priorities[i - 1]) input_str += "\nClassification(1-FP/2-BP):\n" for i in range(1, process_amt + 1): input_str += " P{}: {} \n".format(i, classifications[i - 1]) input_str += """\nAlgorithm Choices: 1. FCFS 2. SJF-P 3. SJF-NP 4. P-P 5. P-NP 6. RR\n""" input_str += "\nForeground Process: " + str(fp_algo) + "\n" input_str += "Background Process: " + str(bg_algo) + "\n" for i in range(process_amt): orig_burst[process_names[i]] = burst_times[i] processes = [list(a) for a in zip(process_names, arrival_times, burst_times, priorities, classifications)] return processes[:process_amt] def multilevel_queue(processes): global gantt_str, gantt_borders, lbl_str, orig_burst counter = 0 completed = 0 previous = None streak = 0 output_dict = {} fg_processes = [p for p in processes if p[4] == 1] bg_processes = [p for p in processes if p[4] == 2] while completed != len(processes): # process name, arrival, burst, priority, classification current = get_process(fg_processes, counter, 3) if not current: current = get_process(bg_processes, counter, 2) if current[4] == 1: previous, streak, current, counter = priority_preemptive(previous, streak, current, counter) if current[4] == 2: previous, streak, current, counter = sjf_np(previous, streak, current, counter) if current[2] == 0: output_dict[current[0]] = (counter - current[1], (counter - current[1]) - orig_burst[current[0]]) completed += 1 gantt_update(previous, streak, counter, True) # gantt_borders = gantt_borders[:-1] gantt_str = '┌' + gantt_borders.replace('*', '┬') + '┐\n' + gantt_str + '\n└' + gantt_borders.replace('*', '┴') + '┘\n' + lbl_str + '\n' return output_dict def priority_preemptive(previous, streak, current, counter): if previous != current[0]: if streak != 0: gantt_update(previous, streak, counter, False) previous = current[0] streak = 0 current[2] -= 1 streak += 1 counter += 1 return previous, streak, current, counter def sjf_np(previous, streak, current, counter): # process name, arrival, burst, priority, classification if previous != current[0]: if streak != 0: gantt_update(previous, streak, counter, False) previous = current[0] streak = 0 current[2] -= 1 streak += 1 counter += 1 return previous, streak, current, counter def gantt_update(previous, streak, counter, end): global gantt_str, gantt_borders, lbl_str gantt_str += "{prev:^{spacing}}│".format(prev = previous, spacing = streak if streak > 1 else streak + 1) gantt_borders += ("─" * streak) if streak > 1 else ("─" * (streak + 1)) lbl_str += "{ctr:>{spacing}}│".format(ctr = counter, spacing = streak if streak > 1 else streak + 1) if not end: gantt_borders += '*' def get_process(processes, arrival_ctr, classification): # process name, arrival, burst, priority eligible = [job for job in processes if arrival_ctr >= job[1] and job[2] != 0] return sorted(eligible, key=operator.itemgetter(classification, 0))[0] if eligible else None def tabulate(output_dict): global table_str border_str = '{}*{}*{}'.format('─' * 7, '─' * 15, '─' * 12) table_skeleton = '│{process:^7}│{turnaround:^15}│{waiting:^12}│ \n' table_str += table_skeleton.format(process = 'PROCESS', turnaround = 'TURNAROUND TIME', waiting = 'WAITING TIME') table_str += '├' + border_str.replace('*', '┼') + '┤\n' for i in range(1, len(output_dict) + 1): table_str += table_skeleton.format(process = "P" + str(i), turnaround = output_dict["P" + str(i)][0], waiting = output_dict["P" + str(i)][1]) table_str += '├' + border_str.replace('*', '┼') + '┤\n' total_turnaround = sum([val[0] for key, val in output_dict.items()]) total_waiting = sum([val[1] for key, val in output_dict.items()]) table_str += table_skeleton.format(process = "TOTAL", turnaround = total_turnaround, waiting = total_waiting) table_str += '├' + border_str.replace('*', '┼') + '┤\n' table_str += table_skeleton.format(process = "AVERAGE", turnaround = total_turnaround / len(output_dict), waiting = total_waiting / len(output_dict)) table_str = '┌' + border_str.replace('*', '┬') + '┐\n' + table_str + '└' + border_str.replace('*', '┴') + '┘\n' def append_to_file(): global input_str, gantt_str, table_str # os.chmod(resource_path("MP02 Checker.txt"), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) try: with open("MP04 Checker.txt", "a", encoding="utf-8") as f: f.write('\n') f.write(input_str) f.write(gantt_str) f.write(table_str) except Exception as e: print(e) print("If the error is permission denied, please disable your antivirus") checker = input("Press any key to continue") def main(): while True: # main program global input_str, orig_burst, gantt_str, gantt_borders, lbl_str, table_str input_str = "Programmed by: Danielle Samonte \nMP04 - MULTILEVEL QUEUE ALGORITHM\n" orig_burst = {} gantt_str = '│' gantt_borders = '' lbl_str = '0' table_str = '' processes = extract_input() output = multilevel_queue(processes) tabulate(output) gantt_str = "\nGantt Chart\n" + gantt_str table_str = "\nTable\n" + table_str print(input_str) print(gantt_str) print(table_str) while True: answer = str(input('Do you want to run again [y/n]: ')).lower() if answer in ('y', 'n'): break if answer == 'y': continue else: append_to_file() break main()
Python
UTF-8
1,994
2.6875
3
[]
no_license
''' This class runs on an xyz file (taken as the second argument). ''' from parse_xyz import Trajectory from process_coord import Coordinate #from lattice import Lattice import numpy as np import sys params = (1, 1, .11268, 1.1051, .96, 1.00547, .05153) #sigma, epsilon, alpha, r_a, a_g, sig_g, r_g unred_params = (340, 58.6, 758789.8) #epsilon, sigma, mass #parse file, store trajectory data in numpy array in_file = sys.argv[1] pos = Trajectory(in_file, unred_params) num_ts = pos.parse_file() num_particles = pos.get_num_particles() area_data = pos.get_area_data() #area is unreduced, in nm^2 pos_data = pos.get_pos_data() #positions are reduced print("Timesteps: " + str(num_ts)) print("Particles: " + str(num_particles)) #start analyzing coordinate date (z-positions, position graphs) coord = Coordinate(num_particles, num_ts, area_data, pos_data, unred_params) #coord.cluster_kde(1041, True, 'kde_graph_1041.png') ''' coord.graph_particle_path(300, 40, 780, 'particle_300_path.png') coord.graph_particle_path(400, 40, 780, 'particle_400_path.png') coord.graph_particle_path(600, 40, 780, 'particle_600_path.png') coord.graph_particle_path(700, 40, 780, 'particle_700_path.png') ''' #test functions here: get_threshold_value, check_layer, graph_pos_dist #graph coordinate data here #coord.graph_pos_dist(441, 'plot_441.png') coord.graph_2D(300, 200, 250, 600, False, 'graph_test_300.png') coord.graph_2D(400, 200, 250, 600, False, 'graph_test_400.png') coord.graph_2D(500, 200, 250, 600, False, 'graph_test_500.png') coord.graph_2D(600, 200, 250, 600, False, 'graph_test_600.png') coord.graph_2D(700, 200, 250, 600, False, 'graph_test_700.png') coord.graph_2D(800, 200, 250, 600, False, 'graph_test_800.png') coord.graph_2D(900, 200, 250, 600, False, 'graph_test_900.png') coord.graph_2D(950, 200, 250, 600, False, 'graph_test_950.png') coord.graph_2D(1000, 200, 250, 600, False, 'graph_test_1000.png') coord.graph_2D(1040, 200, 250, 600, False, 'graph_test_1040.png')
Java
UTF-8
1,423
2.0625
2
[]
no_license
package com.jalarbee.aleef.account.api; import akka.Done; import akka.NotUsed; import com.jalarbee.aleef.account.api.model.Account; import com.lightbend.lagom.javadsl.api.Descriptor; import com.lightbend.lagom.javadsl.api.Service; import com.lightbend.lagom.javadsl.api.ServiceCall; import com.lightbend.lagom.javadsl.api.broker.Topic; import static com.lightbend.lagom.javadsl.api.Service.*; /** * @author Abdoulaye Diallo */ public interface AccountService extends Service { ServiceCall<Account, Account> register(); Topic<AccountEvent> accountEvents(); ServiceCall<NotUsed, Account> getAccount(String accountId); ServiceCall<Long, Done> suspend(String accountId); ServiceCall<NotUsed, Done> liftSuspension(String accountId); ServiceCall<NotUsed, Done> delete(String accountId); @Override default Descriptor descriptor() { // @formatter:off return named("accountService").withCalls( pathCall("/api/accounts", this::register), pathCall("/api/account/:id/suspend", this::suspend), pathCall("/api/account/:id/delete", this::delete), pathCall("/api/account/:id/unsuspend", this::liftSuspension), pathCall("/api/account/:id", this::getAccount) ).publishing( topic("account-AccountEvent", this::accountEvents) ).withAutoAcl(true); // @formatter:on } }
Markdown
UTF-8
772
2.59375
3
[ "MIT" ]
permissive
# Material UI > styling component framework for React ```bash npm install @material-ui/core ``` ## Styles > CSS-in-JS styling solution ```bash npm i @material-ui/styles ``` ### Theming ```js export const arc = createMuiTheme({ palette: { common: {}, primary: { main: '', }, secondary: { main: '', }, }, typography: { h3: {}, }, }); ``` ### Menu ```js <Menu id={label} anchorEl={anchorEl} open={Boolean(anchorEl)} MenuListProps={{ /* handlers */ onMouseLeave: handleClose }} > ``` ### Responsive ```js styled.div` ${{ ...theme.mixins.toolbar }}; margin-bottom: 3em; ${theme.breakpoints.down('md')} { margin-bottom: 2em; } ${theme.breakpoints.down('xs')} { margin-bottom: 1.25em; } `; ```
Java
UTF-8
20,312
2.609375
3
[]
no_license
package com.mifan.article.article; import com.mifan.article.AbstractTests; import com.mifan.article.domain.TopicsClassification; import com.mifan.article.domain.TopicsClustering; import org.junit.Test; import org.moonframework.amqp.Data; import org.moonframework.amqp.Resource; import org.moonframework.core.amqp.Message; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.support.CorrelationData; import org.springframework.beans.factory.annotation.Autowired; import java.time.LocalDateTime; import java.util.*; /** * Created by LiuKai on 2017/7/7. */ public class SendAndReceiveTest extends AbstractTests { @Autowired private Message message; @Autowired private RabbitTemplate template; //过滤emoji表情 @Test public void testMessage() { Map<String, String> meta = new HashMap<>(); Map<String, Object> data = new HashMap<>(); Map<String, Set<Long>> relationships = new HashMap<>(); meta.put("name", "test"); meta.put("origin", "http://test.shiwuTest11.com"); meta.put("className", "com.mifan.article.domain.TopicsDocument"); data.put("forumId", 3); data.put("title", "shiwuTest11"); data.put("author", "lkshiwuTest"); data.put("brand", "dddshiwuTest"); data.put("description", "descriptionshiwuTest"); data.put("content", "<img src=\"http://static.budee.com/yyren/image/205/29/1953106.jpg\" alt=\"RoRo Diamante looking at the camera\" width=\"760\" height=\"350\"> \n" + "<strong><em>RoRo (Rochelle) Diamante is a leading light on YouTube who has penned and produced her own solo album.</em></strong> \n" + "<em>She explains how she learned to listen to heart and her voice and ended up with studio magic.</em> \n" + "<strong>What advice would you have for emerging artists who want to make a record?</strong>\n" + "<br> Just do it! We can always make excuses or put a bunch of obstacles in our way that make us think we can’t do that one thing we want to do. I created this album from scratch all by myself with no knowledge of production whatsoever! I knew how to write music but I didn’t know how to produce. But it was what I needed to do. \n" + "<strong>Describe the process behind your debut album? </strong>\n" + "<br> It took me about 10 months to create “Release”. Just me, myself and I in my little home studio! This album came about at a time when I was fresh out of a management contract and record deal so I wanted some time to be by myself and listen to my heart. There were just magical moments when I knew that a song was “the one” for the album and I just followed those moments. \n" + "<strong>How was your experience recording and listening back to your voice?</strong>\n" + "<br> Just myself in my home studio… I was WAY more critical of my vocals than when I’m collaborating with another producer. I’ve been in recording booths since I was 10 years old so it’s something that’s always been exciting for me. \n" + "<strong>How challenging is it to replicate studio vibes live on stage?</strong>\n" + "<br> It’s two completely different vibes. For me personally, I’m very relaxed and comfy in a recording booth. But on stage, I’m excited and in this performance zone. It’s like I’ve entered another dimension. I love them both. \n" + "<strong>What role does social media play in your career?</strong>\n" + "<br> Social media not only lets people know when I’m doing something new but it lets them come along for the journey so that they were a part of it as well. \n" + "<strong>How important is branding for recording artists?</strong>\n" + "<br> People need to know who you are and what you’re all about so they know what they’re getting into. When it’s clear who you are, you can create super fans who are dedicated to your brand. \n" + "<strong>How about videos?</strong>\n" + "<br> Videos make it easy to spread the word about upcoming things in your career. And you have opportunities to attract new fans through your video’s content. For example, when I do covers of popular music, I get new fans that were simply searching for that specific song. Now I can inform them about my own original music as well. \n" + "<blockquote cite=\"https://www.facebook.com/roroofficial7/videos/1380545541987341/\"> \n" + " <p><a href=\"https://www.facebook.com/roroofficial7/videos/1380545541987341/\"></a></p> \n" + " <p>This is a fun video for you guys to enjoy and hear one of my FAV songs \"1,2,3\" off of my new album \"Release\"! Go check out the album! You'll love it because it was made with love…and sparkles…and unicorns\uD83D\uDE03 (Made with Vidial Video App) #TCHelicon #truetoyourself #roroofficial #ReleaseAlbum #AvailableNow #songwriter #producer #popmusic</p> \n" + " <p>Opslået af <a href=\"https://www.facebook.com/roroofficial7/\">RoRo</a> på 18. januar 2017</p> \n" + "</blockquote> \n" + "<em>This video was created using the new TC-Helicon app ‘VIDIAL’</em> \n" + "<strong>What big lessons have you learned about the recording process so far?</strong>\n" + "<br> I have learned that it’s really personal. Being in that vocal booth and closing your eyes and pouring your heart out on a microphone is a one in a million feeling. \n" + "<strong>What have you found is the best platform for selling music?</strong>\n" + "<br> iTunes seems to be one of the most used platforms for buying new music. Every time I have a new release, I’m always asked by my fans if it will be on iTunes. For hard copies, Amazon is really simple to go through. \n" + "<strong>Any plans to perform the album live?</strong>\n" + "<br> This coming march, I am excited to say that I will be flying down to Orlando, FL to perform at a charity event where I will be performing songs such as “Angel in Blue” and “Queen Bee” to name a few. I am booking a lot more gigs to take the album out for a spin. \n" + "<em>Create your own professional looking videos with the brand new app, Vidial. Find out more here:&nbsp;<a href=\"http://www.vidial.com/\">www.vidial.com</a></em> \n" + "<img src=\"http://static.budee.com/yyren/image/205/29/1953107.jpg\" alt=\"\" width=\"150\" height=\"150\">\n" + "<em><strong>RoRo</strong>&nbsp;(Rochelle Diamante) is a singer/songwriter who has accomplished an impressive amount for her age. She regularly posts videos on her YouTube Channel. Her debut album ‘Release’ is out now.</em> \n" + "<a href=\"http://www.youtube.com/roroofficial7\">YouTube</a>&nbsp;|&nbsp;\n" + "<a href=\"https://www.facebook.com/roroofficial7/\">Facebook</a>&nbsp;|&nbsp;\n" + "<a href=\"https://twitter.com/roroofficial7\">Twitter</a>"); data.put("parentId", 0l); data.put("seedId", 2l); data.put("origin", meta.get("origin")); data.put("originHash", 111L); //data.put("parentId",0L); data.put("creator", 0l); Set<Long> longSet = new HashSet<>(); longSet.add(999999999L); longSet.add(1111111111L); longSet.add(111122L); longSet.add(111122222L); relationships.put("images", longSet); message.sendAndReceive(meta, data, relationships); } @Test public void testMessageAttachment() { Map<String, String> meta = new HashMap<>(); Map<String, Object> data = new HashMap<>(); meta.put("name", "images"); System.out.println("1111"); meta.put("origin", "http://img0.imgtn.bdimg.com/it/u=2607522353,2439730680&fm=214&gp=0.jpg"); meta.put("className", "com.mifan.article.domain.Attachments"); data.put("origin", "http://img0.imgtn.bdimg.com/it/u=2607522353,2439730680&fm=214&gp=0.jpg"); data.put("title", "test007"); data.put("enabled", 0); data.put("mime", "image/jpeg"); data.put("filename", "http://ddddd.com"); message.sendAndReceive(meta, data, null); } //发送一个消息给线上,进行分类使用 @Test public void sendMessage() { String exchange = "server.data.direct.exchange3"; String routingKey = "server.data.direct.queue3"; String id = "1"; String type = "com.mifan.article.domain.Topics"; Data data = new Data(id, type); Map<String, Object> map = new HashMap<>(); map.put("moderated", 0); map.put("docId", 1); map.put("modifier", 0); map.put("title", "Virus TI2 Desktop"); map.put("enabled", 1); map.put("imageSingle", false); Map<String, Object> postMap = new HashMap<>(); postMap.put("creator", 0); postMap.put("postType", "CRAWLER"); postMap.put("created", new Date()); postMap.put("modifier", 0); postMap.put("description", "Analog Modeling Desktop Synthesizer and 24-bit/192kHz Audio/MIDI Interface"); postMap.put("postTypeValue", "爬取"); postMap.put("priority", 0); postMap.put("title", "Virus TI2 Desktop"); postMap.put("content", "<div> \n" + " <h2>Access Steps Up The Renowned Virus!</h2> \n" + " <p>The Access Virus TI2 Desktop synthesizer takes the revered Virus TI to the next level, boasting 25% more calculating power, a more robust onboard effects section, a lighter weight, and a completely redesigned housing. At the heart of the Virus TI2 Desktop is the new OS3 which comes with new effects - Frequency Shifter, Tape Delay, new Distortions, and Character. What's more, it now includes the enhanced Virus Control 5 plug-in, giving you even deeper control of the synthesizer and your many presets. Already a known Ferrari of a synth, expect even more from the Access Virus TI2 Desktop.</p> \n" + " <p></p> \n" + " <p></p> \n" + " <strong>Access Virus TI2 Desktop Synthesizer at a Glance:</strong> \n" + " <ul> \n" + " <li>The \"Ferrari\" Just Got Better </li> \n" + " <li>Robust effects section, with new TI2 effects </li> \n" + " <li>Total Integration - enhanced Virus Control 3.0 plug-in </li> \n" + " <li>3 main oscillators and one sub-oscillator per voice </li> \n" + " <li>Two fully independent filters and 2-dimensional modulation matrix </li> \n" + " <li>Robust effects section, with new TI2 effects </li> \n" + " <li>Each patch contains its own arpeggiator pattern </li> \n" + " <li>Premium redesigned enclosure, lighter in weight</li> \n" + " </ul> \n" + " <strong>The \"Ferrari\" Just Got Better</strong> \n" + " <p> Access somehow managed to improve on the revered Virus TI system, taking the \"Ferrari\" to the next level of performance - and TI computer integration. With a lighter, redesigned enclosure, a bolstered effects section, and an enhanced Virus Control 3.0 plug-in - plus all the staples that made the Virus the famous powerhouse - the Virus TI2 Desktop is truly the culmination of Access's 12-year triathlon of sound research, distillation of user input, and their simple desire to create an exceptional instrument.</p> \n" + " <strong>Robust effects section, with new TI2 effects</strong> \n" + " <p> The new Access Virus TI2 Desktop features an even more powerful effects section, bringing studio-favorite effects to the live performance realm. In addition to phaser, chorus/flanger, ring modulator/shifter, EQ, and a global vocoder, onboard are a new Tape Delay effect, a Frequency Shifter, and new Distortions. There's also a new Character effect, which lets you shape the timbre of the Virus's sound and its fit in the mix, using Analog Boost, Vintage 1/2/3, Pad Opener, Lead Enhancer, Bass Enhancer, or Stereo Widener \"Characters.\"</p> \n" + " <strong>Total Integration - enhanced Virus Control 5 plug-in</strong> \n" + " <p> The TI in the Virus TI2 Desktop stands for Total Integration with your DAW - and Access has heightened that integration, with the Access Virus TI2 line. With the new Virus Control 5 plug-in, you have enhanced control over your Virus TI2, right inside your DAW. There's also an even more robust presets manager, so you can organize, sort, search, and tweak - as quickly as you want to work.</p> \n" + " <strong>3 main oscillators and one suboscillator per voice</strong> \n" + " <p> The Access Virus TI2 Desktop features three main oscillators and one sub-oscillator per voice. Each main oscillator can be made up of various oscillator types, including Hyper Saw (a multi saw-tooth oscillator with up to 9 stacked oscillators, 9 sub oscillators, and a sync oscillator at the same time), Classic Virtual Analog oscillators (saw, variable pulse, sine, triangle, 62 spectral waves with several FM modes), Graintable, Wavetable (with 100 multi-index wavetables), and Format oscillators</p> \n" + " <strong>Two fully independent filters and 2-dimensional modulation matrix</strong> \n" + " <p> You can use two fully independent filters with the Access Virus TI2 Desktop - lowpass, highpass, bandpass, and bandstop) while using an optional saturation module between both filter blocks. The saturation module can add one of several distortions and lo-fi effects, or an additional low/highpass filter. There's also optional self-resonating Moog cascade filter simulation, with circuit overload and 1-4 poles. What's more, the Access Virus TI2 Desktop offers a 2-dimensional modulation matrix, with 6 slots (1 source and 3 modulation targets each), and you can modulate parameters in real-time. </p> \n" + " <strong>Each patch contains its own arpeggiator pattern</strong> \n" + " <p> Every patch onboard the Access Virus TI2 keyboard features its own arpeggiator pattern with 32 programmable steps (length and velocity can be adjusted per step) and a global control for swing/shuffle timing and for note lengths. You can control all of this using the modulation matrix.</p> \n" + " <strong>Premium redesigned enclosure, lighter in weight</strong> \n" + " <p> The new Access Virus TI2 Desktop retains is classy look - all designed, engineered, and built in Germany. It also features a lighter weight, so the Virus TI2 Desktop is even more prepared for the stage.</p> \n" + " <strong>Access Virus TI2 Desktop Synthesizer Features:</strong> \n" + " <ul> \n" + " <li>New Effects, including Tape Delay, Frequency Shifter, new Distortions, and Character </li> \n" + " <li>25% more calculating power than Virus TI, and completely redesigned housing </li> \n" + " <li>Dual DSP system with over 80 stereo voices under average load. (Load depends on which oscillator / filter model has been chosen). </li> \n" + " <li>Virus Control 5 VST and Apple Audio Unit Plug-for Mac OS X and Windows. The remote seamlessly integrates the Virus TI into your sequencer, making it feel just like a plug-in. </li> \n" + " <li>The Virus TI's Audio and MIDI inputs and outputs can be used by the sequencer application as an audio and MIDI interface. </li> \n" + " <li>The Virus TI is the first hardware synthesizer with sample-accurate timing and delay-compensated connection to your sequencer. </li> \n" + " <li>WaveTable Oscillators for a completely new array of sounds. WaveTable and conventional Virus oscillators and filters can be mixed. </li> \n" + " <li>HyperSaw oscillators with up to 9 sawtooths - each with parallel sub oscillator per voice (that's over 1800 stereo oscillators @ 100 voices!). </li> \n" + " <li>Independent delay and reverb for all 16 multi mode slots. </li> \n" + " <li>129 parallel effects. There is reverb and delay, chorus, phaser, ring modulator, distortion, 3 band EQ and the Analog Boost bass enhancer. </li> \n" + " <li>2 multi-mode filters (HP, LP, BP, BS) and the Analog Filter (modeled after the MiniMoog cascade filter with 6-24dB Slope and self-oscillation). </li> \n" + " <li>Dedicated remote mode turns the Virus TI into an universal remote control for VST / AU plug-ins and external synthesizers. </li> \n" + " <li>6 balanced outputs with +4dB level and switchable soft limiting algorithm. Studio grade 192kHz D/A converters with S/PDIF digital I/O. 2x24 bit inputs. Surround sound capabilities </li> \n" + " <li>Tap tempo button. The algorithm is based on Access' Sync Xtreme technology. </li> \n" + " <li>Programmable arpeggiator pattern for every patch. </li> \n" + " <li>Knob quantize for creating stepped controller movements. The stepping automatically syncs to the Virus clock or an incoming MIDI clock. </li> \n" + " <li>3 LFOs with 68 waveforms to choose from. </li> \n" + " <li>2 super fast ADSTR envelopes. </li> \n" + " <li>Extended memory: 512 RAM patches and 2048 ROM patches (rewritable). </li> \n" + " <li>Adaptive control smoothing for jitter-free modulations on all important parameters. </li> \n" + " <li>Multi mode with embedded patches. </li> \n" + " <li>Compatible with USB 2.0 specifications, USB and High-Speed USB devices. </li> \n" + " <li>2 pedal inputs.</li> \n" + " </ul> \n" + " <span>The Access Virus TI2 Desktop takes the renowned Virus TI synthesizer to the next level!</span> \n" + "</div>"); postMap.put("enabled", 1); postMap.put("parentId", 0); Map<Integer, Object> tagsMap = new HashMap<>(); tagsMap.put(0, "VirusTI2Desk"); postMap.put("tags", tagsMap); List featuresList = new ArrayList<>(); Map<String, String> featuresList1 = new HashMap<>(); featuresList1.put("_name", "Sound Engine Type(s)"); featuresList1.put("_value", "Analog Modeling"); featuresList.add(featuresList1); postMap.put("features", featuresList); postMap.put("topicId", 1L); postMap.put("modified", new Date()); postMap.put("id", 1L); Map<Integer, Object> categoriesMap = new HashMap<>(); categoriesMap.put(0, "Keyboards & MIDI"); categoriesMap.put(1, "Synths / Modules"); postMap.put("categories", categoriesMap); map.put("post", postMap); map.put("reviews", 0); map.put("userLike", false); map.put("modified", new Date()); Map<String, Object> fromMap = new HashMap<>(); fromMap.put("topicId", 1L); fromMap.put("reviews", 0); fromMap.put("origin", "http://www.sweetwater.com/store/detail/VirusTI2Desk"); fromMap.put("seedId", 2L); fromMap.put("rating", 0.9); fromMap.put("id", 1L); fromMap.put("originHash", -6949920113737340651L); map.put("from", fromMap); map.put("id", 1L); map.put("locked", 0); map.put("creator", 0); data.setAttributes(map); Map<String, Object> meta = new HashMap<>(); meta.put(Resource.META_DATETIME, LocalDateTime.now()); meta.put("target_classification", TopicsClassification.class.getName()); meta.put("method", Resource.Method.PATCH); meta.put("target_cluster", TopicsClustering.class.getName()); template.convertAndSend(exchange, routingKey, new Resource(meta, data), new CorrelationData(id)); } }
JavaScript
UTF-8
885
2.578125
3
[]
no_license
import Subject from "../models/subject.js"; export const getSubjects = async (req, res) => { const {classId} = req.query; const filter = classId ? {class: classId} : {}; try { const subjects = await Subject.find(filter); res.status(200).json(subjects); } catch (error) { console.log(error) res.json({ message: error.message }); } }; export const addSubject = async (req, res) => { const subject = req.body; const subjectId = subject.name.toLocaleLowerCase().split(" ").join("-"); const newSubject = new Subject({ ...subject, subjectId, addedAt: new Date().getTime(), }); try { await newSubject.save(); res.status(201).json(newSubject); } catch (error) { console.log(error.message); res.status(409).json({ message: error.message }); } };
Java
UTF-8
2,839
2.15625
2
[]
no_license
package com.huntor.demo.entity; import javax.persistence.*; import java.util.Date; /** * Created by liuyang on 2017/8/16. */ @Entity @Table( name = "tag_life_cycle_statistics" ) public class TagLifeCycleStatistics { private Integer id; private Integer lastLifeCycleId; private String lastLifeCycleName; private Integer lifeCycleId; private String lifeCycleName; private Integer transCount; private Date createdAt; private Date updatedAt; private String createdBy; private String updatedBy; private Date inputDate; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name = "last_life_cycle_id") public Integer getLastLifeCycleId() { return lastLifeCycleId; } public void setLastLifeCycleId(Integer lastLifeCycleId) { this.lastLifeCycleId = lastLifeCycleId; } @Column(name = "last_life_cycle_name") public String getLastLifeCycleName() { return lastLifeCycleName; } public void setLastLifeCycleName(String lastLifeCycleName) { this.lastLifeCycleName = lastLifeCycleName; } @Column(name = "life_cycle_id") public Integer getLifeCycleId() { return lifeCycleId; } public void setLifeCycleId(Integer lifeCycleId) { this.lifeCycleId = lifeCycleId; } @Column(name = "life_cycle_name") public String getLifeCycleName() { return lifeCycleName; } public void setLifeCycleName(String lifeCycleName) { this.lifeCycleName = lifeCycleName; } @Column(name = "trans_count") public Integer getTransCount() { return transCount; } public void setTransCount(Integer transCount) { this.transCount = transCount; } @Column(name = "created_at") public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } @Column(name = "updated_at") public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } @Column(name = "created_by") public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } @Column(name = "updated_by") public String getUpdatedBy() { return updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } @Column(name = "input_date") public Date getInputDate() { return inputDate; } public void setInputDate(Date inputDate) { this.inputDate = inputDate; } }
Java
UTF-8
1,009
3.25
3
[]
no_license
package leetcode.unique_paths; class Solution { final static int[][] memoization = new int[101][101]; public int uniquePaths(int m, int n) { if (m == 1 || n == 1) { return 1; } else { final int firstCall = memoization[m - 1][n] == 0 ? uniquePaths(m - 1, n) : memoization[m - 1][n]; final int secondCall = memoization[m][n - 1] == 0 ? uniquePaths(m, n - 1) : memoization[m][n - 1]; final int result = firstCall + secondCall; memoization[m][n] = result; return result; } } public int iterativeUniquePaths(int m, int n) { for(int i = 1; i <= m; i++) { for( int j = 1; j <= n; j++) { memoization[i][j] = 1; } } for(int i = 2; i <= m; i++) { for( int j = 2; j <= n; j++) { memoization[i][j] = memoization[i-1][j] + memoization[i][j-1]; } } return memoization[m][n]; } }
C++
GB18030
1,720
3.859375
4
[]
no_license
// operatorTree.cpp // IJ #include <iostream> #include <cstdio> // ʾ typedef struct BiTNode { int data; struct BiTNode *lchild, *rchild; }BiTNode, *BiTree; // Ҷӽ int sum1 = 0; void countLeafNum1(BiTNode *T) { if (T == NULL) { return; } if (T->lchild == NULL && T->rchild == NULL) { sum1++; } countLeafNum1(T->lchild); countLeafNum1(T->rchild); } // 1ݹ麯ȫֱתɺ // 2ıǿ // ·ֻͬǼҶӽʱͬ void countLeafNum2(BiTNode *T, int *sum) { if (T == NULL) { return; } if (T->lchild == NULL && T->rchild == NULL) { (*sum)++; } countLeafNum2(T->lchild, sum); countLeafNum2(T->rchild, sum); } void countLeafNum3(BiTNode *T, int *sum) { if (T == NULL) { return; } countLeafNum3(T->lchild, sum); countLeafNum3(T->rchild, sum); if (T->lchild == NULL && T->rchild == NULL) { (*sum)++; } } void countLeaf() { BiTNode nodeA, nodeB, nodeC, nodeD, nodeE; memset(&nodeA, 0, sizeof(BiTNode)); memset(&nodeB, 0, sizeof(BiTNode)); memset(&nodeC, 0, sizeof(BiTNode)); memset(&nodeD, 0, sizeof(BiTNode)); memset(&nodeE, 0, sizeof(BiTNode)); nodeA.data = 1; nodeB.data = 2; nodeC.data = 3; nodeD.data = 4; nodeE.data = 5; nodeA.lchild = &nodeB; nodeA.rchild = &nodeC; nodeB.lchild = &nodeD; nodeC.lchild = &nodeE; countLeafNum1(&nodeA); printf("sum1: %d\n", sum1); // sum1: 2 int sum2 = 0; countLeafNum2(&nodeA, &sum2); printf("sum2: %d\n", sum2); // sum2: 2 int sum3 = 0; countLeafNum3(&nodeA, &sum3); printf("sum3: %d\n", sum3); // sum3: 2 } int main() { countLeaf(); return 0; }
Java
UTF-8
970
3.125
3
[ "MIT" ]
permissive
package chapter04; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import org.hamcrest.core.Is; import org.junit.Assert; import org.junit.Test; public class ImmutableCollectionsExamplesTest { @Test public void testImmutableListMultiMapBuilder() { Multimap<Integer, String> map = new ImmutableListMultimap.Builder<Integer, String>() .put(1, "Foo") .putAll(2, "Foo", "Bar", "Baz") .putAll(4, "Huey", "Duey", "Luey") .put(3, "Single") .build(); Assert.assertThat(map.get(1), Is.is(Lists.newArrayList("Foo"))); Assert.assertThat(map.get(2), Is.is(Lists.newArrayList("Foo", "Bar", "Baz"))); Assert.assertThat(map.get(4), Is.is(Lists.newArrayList("Huey", "Duey", "Luey"))); Assert.assertThat(map.get(3), Is.is(Lists.newArrayList("Single"))); } }
Java
UTF-8
2,087
2.90625
3
[]
no_license
package topc.easy; import java.util.*; import java.io.*; // SRM 272 Division II Level Three - 1000 // brute force, geometry // statement: http://community.topcoder.com/stat?c=problem_statement&pm=5885&rd=8069 // editorial: http://www.topcoder.com/tc?module=Static&d1=match_editorials&d2=srm272 public class VectorPolygon { double best; int[] dx; int[] dy; public double maxArea(int[] dx, int[] dy) { this.best = 0; this.dx = dx; this.dy = dy; Point[] pts = new Point[dx.length + 1]; pts[0] = new Point(0, 0); search(pts, 0, 0); return best; } private double area(Point[] pts, int last) { int area = 0; int n = last + 1; for (int i = 1; i < n - 1; i++) { int x1 = pts[i].x - pts[0].x; int y1 = pts[i].y - pts[0].y; int x2 = pts[i + 1].x - pts[0].x; int y2 = pts[i + 1].y - pts[0].y; int cross = x1 * y2 - x2 * y1; area += cross; } return Math.abs(area / 2.0); } private void search(Point[] pts, int last, int used) { if (pts[last].x == 0 && pts[last].y == 0 && Integer.bitCount(used) > 0) { best = Math.max(best, area(pts, last)); } else { for (int i = 0; i < dx.length; i++) { if (off(used, i)) { Point p = new Point(pts[last].x + dx[i], pts[last].y + dy[i]); pts[last + 1] = p; search(pts, last + 1, used | (1 << i)); } } } } private boolean off(int mask, int k) { return ((mask >> k) & 1) == 0; } private void debug(Object... os) { System.out.println(Arrays.deepToString(os)); } public class Point { public final int x; public final int y; public Point(int x, int y) { this.x = x; this.y = y; } public String toString() { return String.format("%s:%s", x, y); } } }
JavaScript
UTF-8
196
3.09375
3
[]
no_license
export default class NumericHelper { constructor(number) { this.number = number; } isEven() { return this.number % 2 === 0; } isOdd() { return this.number % 2 === 1; } }
C++
UTF-8
337
2.515625
3
[]
no_license
// // Created by Niv Swisa on 23/08/2020. // #include "../controller/Display.h" void Display::execute(vector<string> para) { if(para.size()>2){ cout<<"You must insert less parameters"<<endl; return; } Maze2d maze; maze = _model->display(para[1]); _view->getOut() << maze; //cout<<_model<<endl; }
Rust
UTF-8
7,482
2.546875
3
[ "Apache-2.0" ]
permissive
// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com> // // 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. //! Generic API bits for implementing new services. use std::rc::Rc; use std::vec; use fallible_iterator::FallibleIterator; use super::super::{Error, ErrorKind, Result}; use super::super::session::Session; use super::super::utils::Query; use super::{ListResources, ResourceId}; /// Generic implementation of a `FallibleIterator` over resources. #[derive(Debug, Clone)] pub struct ResourceIterator<T> { session: Rc<Session>, query: Query, cache: Option<vec::IntoIter<T>>, marker: Option<String>, can_paginate: Option<bool>, } impl<T> ResourceIterator<T> { #[allow(dead_code)] // unused with --no-default-features pub(crate) fn new(session: Rc<Session>, query: Query) -> ResourceIterator<T> { let can_paginate = query.0.iter().all(|pair| { pair.0 != "limit" && pair.0 != "marker" }); ResourceIterator { session: session, query: query, cache: None, marker: None, can_paginate: if can_paginate { None // ask the service later } else { Some(false) } } } } impl<T> ResourceIterator<T> where T: ListResources + ResourceId { /// Assert that only one item is left and fetch it. /// /// Fails with `ResourceNotFound` if no items are left and with /// `TooManyItems` if there is more than one item left. pub fn one(mut self) -> Result<T> { match self.next()? { Some(result) => if self.next()?.is_some() { Err(Error::new(ErrorKind::TooManyItems, "Query returned more than one result")) } else { Ok(result) }, None => Err(Error::new(ErrorKind::ResourceNotFound, "Query returned no results")) } } } impl<T> FallibleIterator for ResourceIterator<T> where T: ListResources + ResourceId { type Item = T; type Error = Error; fn next(&mut self) -> Result<Option<T>> { if self.can_paginate.is_none() { self.can_paginate = Some(T::can_paginate(&self.session)?); } let maybe_next = self.cache.as_mut().and_then(|cache| cache.next()); Ok(if maybe_next.is_some() { maybe_next } else { if self.cache.is_some() && self.can_paginate == Some(false) { // We have exhausted the results and pagination is not possible None } else { let mut query = self.query.clone(); if self.can_paginate == Some(true) { // can_paginate=true implies no limit was provided query.push("limit", T::DEFAULT_LIMIT); if let Some(marker) = self.marker.take() { query.push_str("marker", marker); } } let mut servers_iter = T::list_resources(self.session.clone(), &query.0)? .into_iter(); let maybe_next = servers_iter.next(); self.cache = Some(servers_iter); maybe_next } }.map(|next| { self.marker = Some(next.resource_id()); next })) } } #[cfg(test)] mod test { use std::rc::Rc; use fallible_iterator::FallibleIterator; use serde_json::{self, Value}; use super::super::super::Result; use super::super::super::session::Session; use super::super::super::utils::{self, Query}; use super::super::{ListResources, ResourceId}; use super::ResourceIterator; #[derive(Debug, PartialEq, Eq)] struct Test(u8); impl ResourceId for Test { fn resource_id(&self) -> String { self.0.to_string() } } fn array_to_map(value: Vec<Value>) -> serde_json::Map<String, Value> { value.into_iter().map(|arr| { match arr { Value::Array(v) => match v[0] { Value::String(ref s) => (s.clone(), v[1].clone()), ref y => panic!("unexpected query key {:?}", y) }, x => panic!("unexpected query component {:?}", x) } }).collect() } impl ListResources for Test { const DEFAULT_LIMIT: usize = 2; fn list_resources<Q>(_session: Rc<Session>, query: Q) -> Result<Vec<Self>> where Q: ::serde::Serialize + ::std::fmt::Debug { let map = match serde_json::to_value(query).unwrap() { Value::Array(arr) => array_to_map(arr), x => panic!("unexpected query {:?}", x) }; assert_eq!(*map.get("limit").unwrap(), Value::String("2".into())); Ok(match map.get("marker") { Some(&Value::String(ref s)) if s == "1" => vec![Test(2), Test(3)], Some(&Value::String(ref s)) if s == "3" => Vec::new(), None => vec![Test(0), Test(1)], Some(ref x) => panic!("unexpected marker {:?}", x) }) } } #[derive(Debug, PartialEq, Eq)] struct NoPagination(u8); impl ListResources for NoPagination { const DEFAULT_LIMIT: usize = 2; fn can_paginate(_session: &Session) -> Result<bool> { Ok(false) } fn list_resources<Q>(_session: Rc<Session>, query: Q) -> Result<Vec<Self>> where Q: ::serde::Serialize + ::std::fmt::Debug { let map = match serde_json::to_value(query).unwrap() { Value::Array(arr) => array_to_map(arr), x => panic!("unexpected query {:?}", x) }; assert!(map.get("limit").is_none()); assert!(map.get("marker").is_none()); Ok(vec![NoPagination(0), NoPagination(1), NoPagination(2)]) } } impl ResourceId for NoPagination { fn resource_id(&self) -> String { self.0.to_string() } } #[test] fn test_resource_iterator() { let s = utils::test::new_session(utils::test::URL); let it: ResourceIterator<Test> = ResourceIterator::new(Rc::new(s), Query::new()); assert_eq!(it.collect::<Vec<Test>>().unwrap(), vec![Test(0), Test(1), Test(2), Test(3)]); } #[test] fn test_resource_iterator_no_pagination() { let s = utils::test::new_session(utils::test::URL); let it: ResourceIterator<NoPagination> = ResourceIterator::new(Rc::new(s), Query::new()); assert_eq!(it.collect::<Vec<NoPagination>>().unwrap(), vec![NoPagination(0), NoPagination(1), NoPagination(2)]); } }
Java
UTF-8
2,060
3.984375
4
[]
no_license
package DynamicProgramming; /** * This method is used to find the subset of an array which sums up to a certain number. * * @author ankit * */ public class SubsetSum { public static void main(String[] args) { int set[] = {3, 34, 4, 12, 5, 2}; System.out.println(isSubsetSum(9, set)); System.out.print("Using Naive recursive method : "); System.out.println(recurIsSubsetSum(9,6,set)); } /** * This is the naive recursive approach. * @param sum * @param n * @param a * @return */ static boolean recurIsSubsetSum(int sum, int n, int a[]){ if(sum == 0) return true; if(n == 0) return false; // If last element is greater than sum, then ignore it if(a[n-1] > sum) return recurIsSubsetSum(sum, n-1, a); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return recurIsSubsetSum(sum, n-1,a) || recurIsSubsetSum( sum-a[n-1], n-1,a); } /** * This is a dynamic programming based solution * @param sum * @param a * @return */ static boolean isSubsetSum(int sum, int a[]){ int n = a.length; //the table subset[i][j] implies that the sum of a[0...j] = i boolean subsetSum[][] = new boolean[sum+1][n+1]; //if sum =0, then the subset exist for(int i=0; i <= n; i++) subsetSum[0][i] = true; //if sum is not 0 and the number of elements =0 then the subset doesn't exist for(int i=1; i <= sum; i++) subsetSum[i][0] = false; for(int i = 1; i <= sum; i++){ for(int j =1; j<= n; j++){ subsetSum[i][j] = subsetSum[i][j-1]; if(i >= a[j-1]){ //Here we check the sum including the last element and excluding the last element similar to the naive recursion process // In the statement below the first part of the OR operation checks the sum including the last element // the second part checks the sum excluding the last element subsetSum[i][j] = subsetSum[i][j] || subsetSum[i - a[j-1]][j-1]; } } } return subsetSum[sum][n]; } }
Markdown
UTF-8
5,654
2.703125
3
[]
no_license
一九 “兄台,我们错了认错,是惊鸿剑客坚持要追你出口怨气。”许纯芳胆量大些,也显得俏皮活泼,羞笑着接口,“你扮猪吃老虎,也不是什么好德行呀!兄台,救命大恩,不敢或忘,可否将贵姓大名赐告?” “你们可以去查呀!专管闲事的行道女英雄,应该有查的本钱。” “我年轻少见识,你应该宽宏大量……” “少废话!快走吧!他们快要搜回来了。”他挥手赶人,“不要妄想惊鸿剑客两个人回来救你们,他们从西面落荒逃走的,我敢打赌,他们已经逃回州城了。” “他会带了摩云神手的人回来救我们的。”霸剑奇花讪讪地说,仍然不敢抬头,羞态可掬,武林女英雌的气概消失无踪。 “是吗?摩云神手那几手鬼画符武功,比惊鸿剑客差了十万八千里,他敢面对一群比惊鸿剑客更高明的人?他算老几?” “有你在,我不怕。”许纯芳居然像男人一样,拍拍她那诱人犯罪的美妙酥胸,“兄台,让我见识你斗凶魔的绝世奇功,好不好?刚才我没看到,你是怎么样把老道妖妇制住的。” “他们还有六个人,最先遭殃的一定是你们,果真是年轻少见识不知利害,快走!”他指指先前红衣女郎所坐处,树下堆放着三女的剑、囊、皮护腰。“别忘了佩剑,以免回程碰上仇家。你们的剑术很好,但太过倚赖剑,早晚会遭殃的。” “你也有剑。” “我的剑是唬人的。” “我听说过妙观音这位妖妇。”许纯芳抬回自己的物品,从容不迫佩带,没有走的意思。 “她是你们这些江湖新秀的前辈,是个妙人儿,江湖朋友耳熟能详,又妙又阴损可怕而且可爱。” “你要她……” “我喜欢她,所以要她呀!” “你……” “她是个很够味的女人,哈哈哈……”他大笑,向东一指,“算算他们也该来了,这次我一定可以把她弄到手,一定。” 身形乍起,进入树林冉冉而去。 “他比那些妖魔更坏。”霸剑奇花跺着小脚鄙夷地说,“居然要强抢一个可耻的荡妇,不像话。” “申姐,人各有所好,他与惊鸿剑客是完全不同的两种人。”许纯芳笑吟吟地说,“惊鸿剑客是能说会道,很会讨好我们的大好人。但是,我总觉某些地方不时,似乎有必要时刻提防,他倜傥潇洒的气质背面,所隐藏的另一种令我不安的面目。” “胡说八道。”霸剑奇花笑嗔,“刻意讨好人也没有错呀!至少不会惹人讨厌不快。许姐,你希望喜欢你的人,像这个坏蛋一样,惦着剑追逐你?” 三女人在一起,说起敏感的话题百无禁忌。二个男人在一起,更是言不及义。 “好了好了。”吕飞琼制止两人争论,“你们不打算走?再被什么魔香弄翻,恐怕就福无双至,没有人会救得了我们哪!” “不会再上当了。”霸剑奇花咬牙,“今后与任何人交手,都是留意风向,不击则已,击即必得,哼!我要等夜游鹰。” “为人谋岂能不忠?申姐,我既然开始就自告奋勇拔剑相助,当然有始有终,我陪你等。”吕飞琼慨然说,“就算福无双至,我认了。” “我们同心协力在先,不结束是不会各行其是的。申姐,我只希望今后行事,你能自有主见,不受其他事故所左右。”许纯芳显得有点懒散,“我们根本没有必要追这个救了我们的人,惊鸿剑客一坚持,结果,几乎万劫不复。而坚持追的惊鸿剑客主仆,……啧啧啧……” “也不能怪他,许姐。”霸剑奇花叹了一口气,“毕竟是初交,他有权为保全自己而采取有利行动,其实,我也是有意追赶的。” 她不便说出有意追赶的原因,被杨一元在大腿上摸了一把的事怎好启齿? 惊鸿剑客追赶杨一元的原因非常单纯。一个名号响亮的人物,被一个默默无闻的人,在大街上击败,这羞辱委实难以忍受,把杨一元恨入骨髓,报复的念头极为迫切。 输不起的人,就会有这种激烈反应。 “我们先躲起来。”吕飞琼不想谈论惊鸿剑客的事,她对惊鸿剑客追求霸剑奇花的事,并无成见。在江湖遨游,有不少才子向她们献殷勤,也有许多不三不四的人追逐裙下,对这种窈窕淑女,君子好述的事司空见惯,习以为常,感情涉入还没深,任何一方都有权为了自己的利益,而采取有利的行动。 三女略一商量,以留下的七匹坐骑作目标,这些人早晚会来取坐骑的,守住坐骑有耐心等候,决定以速战速决的凌厉攻击,对付这些威震江湖的妖魔鬼怪,她们有向高手名宿叫阵挑战的本钱。 已经知道这些凶魔的来历,凶险便减少了一半。 枯等了半个时辰,等得心中冒烟。 北面五里地,路旁有座三家村。 妙观音藏好坐骑,藏身在村口的大树后,眼巴巴向南眺望,也等得心中焦躁。 最先到达的人是无上散仙,穿了一袭村夫的肮脏直裰衫,不再赤条条,大概是抢来的衣裤。 这位夸称是散仙的妖道,输得最惨,不折不扣的输得精光,杨一元羞辱的手段也的确缺德。 许久许久,百绝头陀六个男女终于赶到了。八人一商量,落荒而走折返州城。
Shell
UTF-8
129
3.15625
3
[]
no_license
#! /bin/sh for file in $(find . -name "*.tig"); do content=$(cat $file) if [ -z "$content" ]; then echo $file fi done
Java
ISO-8859-3
2,653
2.546875
3
[]
no_license
package tests; import java.sql.SQLException; import java.sql.Statement; import java.util.GregorianCalendar; import com.microsoft.sqlserver.jdbc.SQLServerException; import clases.basicas.ConfiguracionImpl; import clases.basicas.CuentaImpl; import clases.basicas.VotacionImpl; import clases.gestion.ConexionSQL; import clases.gestion.GestionConfiguracion; import clases.gestion.GestionCuenta; import clases.gestion.GestionVotacion; public class GestionVotacionTest { public static void main(String[] args) { ConexionSQL SQL = new ConexionSQL("jdbc:sqlserver://localhost;" + "database=Coches;" + "user=usuarioCoches;" + "password=123;"); SQL.abrirConexion(); GestionVotacion gestionVotacion = new GestionVotacion(SQL.getConexion()); GestionConfiguracion gestionConfiguracion = new GestionConfiguracion(SQL.getConexion()); GestionCuenta gestionCuenta = new GestionCuenta(SQL.getConexion()); ConfiguracionImpl configuracionTest = gestionConfiguracion.obtenerConfiguracion("A6221DF6-D42D-4F2C-84C6-CC153AF80EFE"); CuentaImpl cuentaTest = gestionCuenta.obtenerCuenta("testuser"); System.out.println("obtenerVotaciones(configuracionTest)"); for(VotacionImpl votacion:gestionVotacion.obtenerVotaciones(configuracionTest)) { System.out.println(votacion.getFecha().getTime() + " - calificacion: " + votacion.getCalificacion()); } System.out.println(); System.out.println("obtenerVotaciones(cuentaTest)"); for(VotacionImpl votacion:gestionVotacion.obtenerVotaciones(cuentaTest)) { System.out.println(votacion.getFecha().getTime() + " - calificacion: " + votacion.getCalificacion()); } System.out.println(); System.out.println("insertarVotacion(new VotacionImpl(\"5813a7ac-84d2-40bf-87ca-9f8dd35183af\", new GregorianCalendar(), 7)"); try { Statement statement = SQL.getConexion().createStatement(); statement.execute("BEGIN TRANSACTION"); //Se realiza una transaccin para que no se guarden los cambios. VotacionImpl votacionTest = new VotacionImpl("5813a7ac-84d2-40bf-87ca-9f8dd35183af", new GregorianCalendar(), 7); votacionTest.establecerConfiguracion(configuracionTest); votacionTest.establecerCuenta(cuentaTest); boolean insertada = gestionVotacion.insertarVotacion(votacionTest); if(insertada) System.out.println("Votacion insertada."); else System.out.println("No se insert la votacin."); statement.execute("ROLLBACK"); //No se guardarn los cambios } catch(SQLServerException e) { System.out.println(e.getMessage()); } catch (SQLException e) { e.printStackTrace(); } } }
Markdown
UTF-8
14,379
2.59375
3
[]
no_license
--- group: cloud-guide title: Configuration management for store settings functional_areas: - Cloud - Deploy --- Configuration management in {{site.data.var.ece}} provides a new way to deploy across your environments with minimal downtime. The process extracts all configuration settings from your Magento implementation into a single file. With this file, you can add it to your Git commit and push it across all of your environments to keep consistent settings and reduce downtime. It provides the following benefits: * Better way to [manage and synchronize](#cloud-confman-over) the configuration across your Integration, Staging, and Production environments. * Less time required to [build](#cloud-confman-scd-over) and deploy your project by moving static file deployment from the deploy to the build phase. Your site is in maintenance mode until deployment completes. For details, see [Deployment Process]({{ page.baseurl }}/cloud/reference/discover-deploy.html). * Sensitive data is automatically added into an environment variables file (`/app/etc/env.php`). You can also manually add sensitive environment variables using the Project Web Interface, the CLI, or directly in the Magento Admin. For example, payment processor passwords and API keys. {:.bs-callout .bs-callout-info} These new methods are optional but strongly recommended. The process ensures faster deployments and consistent configurations across your environments. ## Feature availability {#release} To complete these configuration management tasks, you must have at a minimum a project reader role with [environment administrator]({{ page.baseurl }}/cloud/project/user-admin.html#cloud-role-env) privileges. ## How it works {#cloud-confman-over} Magento's store configurations are stored in the database. When updating configurations in development/Integration, Staging, and Production environments, you would need to make those changes in the Magento Admin per environment. By using these commands, you generate a file, exporting all Magento configuration settings into a single text file: `app/etc/config.local.php`. After configuring your environment, generate the file using one of the following commands: * `php bin/magento magento-cloud:scd-dump`: **Recommended**. Exports only modified configuration settings * `php ./vendor/bin/ece-tools config:dump`: Exports every configuration setting, including modified and default settings {:.bs-callout .bs-callout-warning} For {{site.data.var.ece}}, we **do not recommend** `app:config:dump` as this command pulls and locks all values as read-only. This will affect Fastly and other important modules. Specifically, this affects customizing your extensions across environments. Any data that exports to the file becomes locked. The corresponding field in the Magento Admin becomes read-only. This ensures consistent configurations as you push the file across all environments. By using the `scd-dump` command, you can configure only the settings you want copied across all environments. After you merge the code, you can configure additional settings in Staging and Production. For sensitive configurations, you can also add those settings to environment variables. For example, you may want to add different PayPal merchant account credentials for Staging (sandbox) and Production (live). If sensitive data is found in your configurations, it is generated as environment variables to `env.php`. This file remains in the environment and should not be added to your Git environment. ### Switching between commands {#commands} Can you switch between using `php bin/magento magento-cloud:scd-dump` and `php ./vendor/bin/ece-tools config:dump`? Yes, you can. For 2.1.4 and later (not 2.2.X), you can always delete the `config.local.php` file and regenerate it with either command. Remember, `scd-dump` only pulls configured values (not defaults) and `config:dump` captures all values (default and modified). ### Configuration data {#data} System settings refer to the configurations in the Magento Admin in **Stores** > **Settings** > **Configuration**. Depending on the command used, all or just modified system configurations save to the file. This file can include all system configuration settings for stores, sites, extensions, and static file optimization settings. System values related to static content deployment (for example, static file optimization) are also stored in `app/etc/config.local.php`. _Static file optimization_ means merging and minifying JavaScript and Cascading Style Sheets, and minifying HTML templates. Sensitive values are _not_ stored in `app/etc/config.local.php`. Any sensitive configurations should export to `app/etc/config.php` during the `scd-dump` process. You should create environment variables using CLI commands or the Project Web Interface. {:.bs-callout .bs-callout-info} You can set _any_ value using environment variables, but we recommend using environment variables for sensitive values. For a list of configurable settings, see [Configuration settings you can change](#cloud-clp-settings) and [System settings reference]({{ page.baseurl }}/config-guide/prod/config-reference-var-name.html). ### Static content deployment performance {#cloud-confman-scd-over} Depending on the size of your store, you may have a large amount of static content files to deploy. Normally, static content deploys during the [deploy phase]({{ page.baseurl }}/cloud/reference/discover-deploy.html#cloud-deploy-over-phases-hook), which is in Maintenance mode. To move the deployment of static content to the [build phase]({{ page.baseurl }}/cloud/reference/discover-deploy.html#cloud-deploy-over-phases-build), generate the configuration file. If you generate `config.local.php`, the build and deploy hooks identify the file and deploy all static files during the build phase. This helps reduce the time spent in Maintenance mode during the deploy phase. {:.bs-callout .bs-callout-info} Before deploying static files, the build and deploy phases compress static content using `gzip`. Compressing static files reduces server loads and increases site performance. Refer to [Magento build options]({{ site.baseurl }}/guides/v2.2/cloud/env/variables-build.html) to learn about customizing or disabling file compression. ## Configuration selection flow All system configurations are set during deployment according to the following override scheme: 1. If an environment variable exists, use the custom configuration and ignore the default configuration. 1. If an environment variable does not exist, use the configuration from a `MAGENTO_CLOUD_RELATIONSHIPS` name-value pair in the `.magento.app.yaml` file. Ignore the default configuration. 1. If an environment variable does not exist and `MAGENTO_CLOUD_RELATIONSHIPS` does not contain a name-value pair, remove all customized configuration and use the values from the default configuration. ## Configuration settings you can change {#cloud-clp-settings} The following table shows the configuration settings affected by the `bin/magento magento-cloud:scd-dump` command. These are the configuration settings that you can manage in Git. If you use `php ./vendor/bin/ece-tools config:dump`, all settings are exported. The `config.local.php` file includes the following settings and configuration values: <table> <tbody> <tr> <th style="width:250px;">Description</th> <th>Path in Magento Admin: Stores > Settings > Configuration > ...</th> </tr> <tr> <td>Store locale</td> <td>General > General, Locale Options > Locale</td> </tr> <tr> <td>Static asset signing</td> <td>Advanced > Developer, Static Files Settings > Static Files Signing</td> </tr> <tr> <td>Server-side or client-side LESS compilation</td> <td>Advanced > Developer, Frontend Developer Workflow > Workflow type</td> </tr> <tr> <td>HTML minification</td> <td>Advanced > Developer, Template Settings > Minify Html</td> </tr> <tr> <td>JavaScript minification</td> <td>Advanced > Developer, JavaScript Settings > (several options)</td> </tr> <tr> <td>CSS minification</td> <td>Advanced > Developer, CSS Settings > Merge CSS Files and Minify CSS Files</td> </tr> <tr> <td>Disable modules output</td> <td>Advanced > Advanced > Disable Modules Output</td> </tr> </tbody> </table> ## Recommended procedure to manage your settings {#cloud-config-specific-recomm} Managing store configuration is a complex task mostly up to you. What locales do you want to use? What custom themes do you need? Instead of making these changes in every environment, you can use the `config.local.php` file, which contains a number of configuration properties that you can adjust as needed. We **strongly recommend** using the `scd-dump` command to generate a `config.local.php` file. This file includes only the settings you configure without locking the default values. It also ensures that all extensions used in the Staging and Production environments do not break due to read-only configurations, especially Fastly. To fully understand the process, see [our extensive example]({{ page.baseurl }}/cloud/live/sens-data-initial.html). The **Starter plan** environment high-level overview of this process: ![Overview of Starter configuration management]({{ site.baseurl }}/common/images/cloud_configmgmt-starter-2-1.png) The **Pro plan** environment high-level overview of this process: ![Overview of Pro configuration management]({{ site.baseurl }}/common/images/cloud_configmgmt-pro-2-1.png) ### Step 1: Configure your store {#config-store} Complete all configurations for your stores in the Admin console: 1. Log in to the Magento Admin for one of the environments: * Starter: An active development branch * Pro: Integration branch 2. Create and configure all store settings. These configurations do not include the actual products unless you plan on dumping the database from this environment to Staging and Production. Typically development databases do not include your full store data. 3. Open a terminal on your local and use an SSH command to generate `/app/etc/config.local.php` on the environment: `ssh <SSH URL> "<Command>"` For example, for Pro on the Integration branch: ssh itnu84v4m4e5k-master-ouhx5wq@ssh.us.magentosite.cloud "php bin/magento magento-cloud:scd-dump" ### Step 2: Transfer and add the file to Git {#transfer-file} Push `config.local.php` to Git. To push this file to the `master` Git branch, you need to complete a few extra steps because this environment is read-only. 1. Transfer `config.local.php` to your local system using `rsync` or `scp`. You can only add this file to the Git branch through your local. `rsync <SSH URL>:app/etc/config.local.php ./app/etc/config.local.php` 2. Add and push `config.local.php` to the Git master branch. `git add app/etc/config.local.php && git commit -m "Add system-specific configuration" && git push origin master` ### Step 3 & 4: Push Git branch to Staging and Production {#push-git} Log in to the Magento Admin in those environments to verify the settings. If you used `scd-dump`, only configured settings display. You can continue configuring the environment if needed. For Starter, when you push, the updated code pushes to the active environment. Merge the branch to Staging and finally `master` for Production. Complete any additional configurations in Staging and Production as needed. For Pro, when you push to the Git branch, the Integration environment updates. Deploy this branch to Staging and Production. Complete any additional configurations in Staging and Production as needed. ## Update configurations If you need to change any configuration settings in the `config.local.php` file, repeat the process with an extra step. For Starter, complete the changes in an active, development environment. For Pro, use the Integration environment. If you need to make a small change, you can edit the `config.local.php` file in a local development branch and redeploy across environments. To complete extensive changes: 1. Delete the `config.local.php`file in your Integration branch. You must delete the file to change settings. All configurations exist in the database, displaying as editable in your Magento Admin panel. Remember, the stored configurations in the file are blocked from editing in the Admin console until you delete the file. For example, if you want to change a store name, you can not edit the name until this file is removed. 2. Make configuration changes in the Admin on the Integration environment. 3. Repeat the process to re-create `config.local.php` and deploy. You do not need to make additional configurations in Staging and Production unless you need to. Recreating this file should not affect those environment specific settings. ## Change locales You can change your store locales without following a complex configuration import and export process, _if_ you have [SCD_ON_DEMAND]({{ page.baseurl }}/cloud/env/variables-global.html#scd_on_demand) enabled. You can update the locales using the Admin panel. You can add another locale to the Staging or Production environment by enabling `SCD_ON_DEMAND` in an Integration branch, generate an updated `config.local.php` file with the new locale information, and copy the configuration file to the target environment. {: .bs-callout .bs-callout-warning} This process **overwrites** the store configuration; only do the following if the environments contain the same stores. 1. From your Integration environment, enable the `SCD_ON_DEMAND` variable. 1. Add the necessary locales using your Admin panel. 1. Generate the `app/etc/config.local.php` file containing all locales. ```bash php ./vendor/bin/ece-tools config:dump ``` 1. Copy the new configuration file from your Integration environment to your local Staging environment directory. ```bash rsync <SSH URL>:app/etc/config.local.php ./app/etc/config.local.php ``` 1. Push code changes to the remote. {:.bs-callout .bs-callout-warning} While you can manually edit the `config.local.php` file in the Staging and Production environments, we do not recommend it. The file helps to keep all configurations consistent across all environments. Never delete the `config.local.php` file to rebuild it. Deleting the file can remove specific configurations and settings required for build and deploy processes.
Ruby
UTF-8
559
2.59375
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'pug' class MockClient < Pug::Interfaces::Client attr_accessor :message_queue, :sent_messages def initialize @sent_messages = [] @message_queue = [] end # Overrides def listen queue = @message_queue yield queue.shift until queue.empty? end def send_message(message) @sent_messages.push(message) end # Helpers def enqueue_message(message) @message_queue.push(message) end def last_sent_message return nil if @sent_messages.empty? @sent_messages.pop end end
Java
UTF-8
733
1.976563
2
[]
no_license
/* * Copyright 2005-2017 ptnetwork.net. All rights reserved. * Support: http://www.ptnetwork.net * License: http://www.ptnetwork.net/license */ package net.ptnetwork.dao; import net.ptnetwork.Page; import net.ptnetwork.Pageable; import net.ptnetwork.entity.Member; import net.ptnetwork.entity.MemberDepositLog; /** * Dao - 会员预存款记录 * * @author PTNETWORK Team * @version 5.0 */ public interface MemberDepositLogDao extends BaseDao<MemberDepositLog, Long> { /** * 查找会员预存款记录分页 * * @param member * 会员 * @param pageable * 分页信息 * @return 会员预存款记录分页 */ Page<MemberDepositLog> findPage(Member member, Pageable pageable); }
JavaScript
UTF-8
940
4.03125
4
[]
no_license
// Ecrivez une fonction qui étant donné un tableau de n nombres // tous identiques sauf un // retourne le seul nombre qui n’est pas identique aux autres. function nbOccur(val, myArray) { const occurTab = myArray.filter(function(num) { return num === val; }); return occurTab.length; } const numbers = [1, 2, 1, 1, 1, 1]; const nbUnique = numbers.find(function(x) { return nbOccur(x, numbers) === 1; }); console.log(nbUnique); // Ecrivez une fonction qui étant donné un tableau de n nombres // tous identiques sauf un // retourne le seul nombre qui n’est pas identique aux autres. const numbers = [1, 2, 1, 1, 1, 1]; const cache = {}; const nbNumInArray = (num, numArray) => { if (cache[num]) { return cache[num]; } cache[num] = numArray.filter(val => val === num).length; return cache[num]; }; const isUnique = numbers.find(x => nbNumInArray(x, numbers) === 1); console.log(isUnique); // mise en cache
Go
UTF-8
10,585
2.828125
3
[]
no_license
// !可修改点权的 Link-Cut Tree // https://ei1333.github.io/library/structure/lct/link-cut-tree-lazy-path.hpp // https://hitonanode.github.io/cplib-cpp/data_structure/link_cut_tree.hpp // LinkCutTreeLazy(rev,id,op,mapping,composition): コンストラクタ. // rev は要素を反転する演算を指す. // id は作用素の単位元を指す. // op は 2 つの要素の値をマージする二項演算, // mapping は要素と作用素をマージする二項演算, // composition は作用素同士をマージする二項演算, // Build(vs): 各要素の値を vs[i] としたノードを生成し, その配列を返す. // Evert(t): t を根に変更する. // LinkEdge(child, parent): child の親を parent にする.如果已经连通则不进行操作。 // CutEdge(u,v) : u と v の間の辺を切り離す.如果边不存在则不进行操作。 // QueryToRoot(u): u から根までのパス上の頂点の値を二項演算でまとめた結果を返す. // QueryPath(u, v): u から v までのパス上の頂点の値を二項演算でまとめた結果を返す. // QeuryKthAncestor(x, k): x から根までのパスに出現するノードを並べたとき, 0-indexed で k 番目のノードを返す. // QueryLCA(u, v): u と v の lca を返す. u と v が異なる連結成分なら nullptr を返す. // !上記の操作は根を勝手に変えるため、根を固定したい場合は Evert で根を固定してから操作する. // IsConnected(u, v): u と v が同じ連結成分に属する場合は true, そうでなければ false を返す. // Alloc(v): 要素の値を v としたノードを生成する. // UpdateToRoot(t, lazy): t から根までのパス上の頂点に作用素 lazy を加える. // Update(u, v, lazy): u から v までのパス上の頂点に作用素 lazy を加える. // Set(t, v): t の値を v に変更する. // Get(t): t の値を返す. // GetRoot(t): t の根を返す. // expose(t): t と根をつなげて, t を splay Tree の根にする. package main import ( "bufio" "fmt" "os" ) func main() { // https://judge.yosupo.jp/problem/dynamic_tree_vertex_add_path_sum // 0 u v w x 删除 u-v 边, 添加 w-x 边 // 1 p x 将 p 节点的值加上 x // 2 u v 输出 u-v 路径上所有点的值的和(包含端点) // n,q=2e5 in := bufio.NewReader(os.Stdin) out := bufio.NewWriter(os.Stdout) defer out.Flush() var n, q int fmt.Fscan(in, &n, &q) nums := make([]int, n) for i := 0; i < n; i++ { fmt.Fscan(in, &nums[i]) } lct := NewLinkCutTreeLazy(true) vs := lct.Build(nums) for i := 0; i < n-1; i++ { // 连接树边 var v1, v2 int fmt.Fscan(in, &v1, &v2) // lct.Evert(vs[v1]) // lct.Link(vs[v1], vs[v2]) lct.LinkEdge(vs[v1], vs[v2]) } for i := 0; i < q; i++ { var op int fmt.Fscan(in, &op) if op == 0 { var u, v, w, x int fmt.Fscan(in, &u, &v, &w, &x) // lct.Evert(vs[u]) // lct.Cut(vs[v]) lct.CutEdge(vs[u], vs[v]) // lct.Evert(vs[w]) // lct.Link(vs[w], vs[x]) lct.LinkEdge(vs[w], vs[x]) } else if op == 1 { var p, x int fmt.Fscan(in, &p, &x) // lct.Set(vs[p], vs[p].key+x) lct.UpdatePath(vs[p], vs[p], x) } else { var u, v int fmt.Fscan(in, &u, &v) fmt.Fprintln(out, lct.QueryPath(vs[u], vs[v])) } } } type E = int type Id = int // 区间反转 func (*LinkCutTreeLazy) rev(e E) E { return e } func (*LinkCutTreeLazy) id() Id { return 0 } func (*LinkCutTreeLazy) op(a, b E) E { return a + b } func (*LinkCutTreeLazy) mapping(lazy Id, data E) E { return data + lazy } func (*LinkCutTreeLazy) composition(parentLazy, childLazy Id) Id { return parentLazy + childLazy } type LinkCutTreeLazy struct { nodeId int edges map[struct{ u, v int }]struct{} check bool } // check: AddEdge/RemoveEdge で辺の存在チェックを行うかどうか. func NewLinkCutTreeLazy(check bool) *LinkCutTreeLazy { return &LinkCutTreeLazy{edges: make(map[struct{ u, v int }]struct{}), check: check} } // 各要素の値を vs[i] としたノードを生成し, その配列を返す. func (lct *LinkCutTreeLazy) Build(vs []E) []*treeNode { nodes := make([]*treeNode, len(vs)) for i, v := range vs { nodes[i] = lct.Alloc(v) } return nodes } // 要素の値を v としたノードを生成する. func (lct *LinkCutTreeLazy) Alloc(e E) *treeNode { res := newTreeNode(e, lct.id(), lct.nodeId) lct.nodeId++ return res } // t を根に変更する. func (lct *LinkCutTreeLazy) Evert(t *treeNode) { lct.expose(t) lct.toggle(t) lct.push(t) } // 存在していない辺 uv を新たに張る. // すでに存在している辺 uv に対しては何もしない. func (lct *LinkCutTreeLazy) LinkEdge(child, parent *treeNode) (ok bool) { if lct.check { if lct.IsConnected(child, parent) { return } id1, id2 := child.id, parent.id if id1 > id2 { id1, id2 = id2, id1 } tuple := struct{ u, v int }{id1, id2} lct.edges[tuple] = struct{}{} } lct.Evert(child) lct.expose(parent) child.p = parent parent.r = child lct.update(parent) return true } // 存在している辺を切り離す. // 存在していない辺に対しては何もしない. func (lct *LinkCutTreeLazy) CutEdge(u, v *treeNode) (ok bool) { if lct.check { id1, id2 := u.id, v.id if id1 > id2 { id1, id2 = id2, id1 } tuple := struct{ u, v int }{id1, id2} if _, has := lct.edges[tuple]; !has { return } delete(lct.edges, tuple) } lct.Evert(u) lct.expose(v) parent := v.l v.l = nil lct.update(v) parent.p = nil return true } // u と v の lca を返す. // u と v が異なる連結成分なら nullptr を返す. // !上記の操作は根を勝手に変えるため, 事前に Evert する必要があるかも. func (lct *LinkCutTreeLazy) QueryLCA(u, v *treeNode) *treeNode { if !lct.IsConnected(u, v) { return nil } lct.expose(u) return lct.expose(v) } func (lct *LinkCutTreeLazy) QueryKthAncestor(x *treeNode, k int) *treeNode { lct.expose(x) for x != nil { lct.push(x) if x.r != nil && x.r.sz > k { x = x.r } else { if x.r != nil { k -= x.r.sz } if k == 0 { return x } k-- x = x.l } } return nil } // u から根までのパス上の頂点の値を二項演算でまとめた結果を返す. func (lct *LinkCutTreeLazy) QueryToRoot(u *treeNode) E { lct.expose(u) return u.sum } // u から v までのパス上の頂点の値を二項演算でまとめた結果を返す. func (lct *LinkCutTreeLazy) QueryPath(u, v *treeNode) E { lct.Evert(u) return lct.QueryToRoot(v) } // t から根までのパス上の頂点に作用素 lazy を加える. func (lct *LinkCutTreeLazy) UpdateToRoot(t *treeNode, lazy Id) { lct.expose(t) lct.propagate(t, lazy) lct.push(t) } // u から v までのパス上の頂点に作用素 lazy を加える. func (lct *LinkCutTreeLazy) UpdatePath(u, v *treeNode, lazy Id) { lct.Evert(u) lct.UpdateToRoot(v, lazy) } // t の値を v に変更する. func (lct *LinkCutTreeLazy) Set(t *treeNode, v E) { lct.expose(t) t.key = v lct.update(t) } // t の値を返す. func (lct *LinkCutTreeLazy) Get(t *treeNode) E { return t.key } func (lct *LinkCutTreeLazy) GetRoot(t *treeNode) *treeNode { lct.expose(t) for t.l != nil { lct.push(t) t = t.l } return t } // u と v が同じ連結成分に属する場合は true, そうでなければ false を返す. func (lct *LinkCutTreeLazy) IsConnected(u, v *treeNode) bool { return u == v || lct.GetRoot(u) == lct.GetRoot(v) } func (lct *LinkCutTreeLazy) expose(t *treeNode) *treeNode { rp := (*treeNode)(nil) for cur := t; cur != nil; cur = cur.p { lct.splay(cur) cur.r = rp lct.update(cur) rp = cur } lct.splay(t) return rp } func (lct *LinkCutTreeLazy) update(t *treeNode) *treeNode { t.sz = 1 t.sum = t.key if t.l != nil { t.sz += t.l.sz t.sum = lct.op(t.l.sum, t.sum) } if t.r != nil { t.sz += t.r.sz t.sum = lct.op(t.sum, t.r.sum) } return t } func (lct *LinkCutTreeLazy) rotr(t *treeNode) { x := t.p y := x.p x.l = t.r if t.r != nil { t.r.p = x } t.r = x x.p = t lct.update(x) lct.update(t) t.p = y if y != nil { if y.l == x { y.l = t } if y.r == x { y.r = t } lct.update(y) } } func (lct *LinkCutTreeLazy) rotl(t *treeNode) { x := t.p y := x.p x.r = t.l if t.l != nil { t.l.p = x } t.l = x x.p = t lct.update(x) lct.update(t) t.p = y if y != nil { if y.l == x { y.l = t } if y.r == x { y.r = t } lct.update(y) } } func (lct *LinkCutTreeLazy) toggle(t *treeNode) { t.l, t.r = t.r, t.l t.sum = lct.rev(t.sum) t.rev = !t.rev } func (lct *LinkCutTreeLazy) propagate(t *treeNode, lazy Id) { t.lazy = lct.composition(lazy, t.lazy) t.key = lct.mapping(lazy, t.key) t.sum = lct.mapping(lazy, t.sum) } func (lct *LinkCutTreeLazy) push(t *treeNode) { if t.lazy != lct.id() { if t.l != nil { lct.propagate(t.l, t.lazy) } if t.r != nil { lct.propagate(t.r, t.lazy) } t.lazy = lct.id() } if t.rev { if t.l != nil { lct.toggle(t.l) } if t.r != nil { lct.toggle(t.r) } t.rev = false } } func (lct *LinkCutTreeLazy) splay(t *treeNode) { lct.push(t) for !t.IsRoot() { q := t.p if q.IsRoot() { lct.push(q) lct.push(t) if q.l == t { lct.rotr(t) } else { lct.rotl(t) } } else { r := q.p lct.push(r) lct.push(q) lct.push(t) if r.l == q { if q.l == t { lct.rotr(q) lct.rotr(t) } else { lct.rotl(t) lct.rotr(t) } } else { if q.r == t { lct.rotl(q) lct.rotl(t) } else { lct.rotr(t) lct.rotl(t) } } } } } type treeNode struct { l, r, p *treeNode key, sum E lazy Id rev bool sz int id int } func newTreeNode(v E, lazy Id, id int) *treeNode { return &treeNode{key: v, sum: v, lazy: lazy, sz: 1, id: id} } func (n *treeNode) IsRoot() bool { return n.p == nil || (n.p.l != n && n.p.r != n) } func (n *treeNode) String() string { return fmt.Sprintf("key: %v, sum: %v, sz: %v, rev: %v", n.key, n.sum, n.sz, n.rev) }
Python
UTF-8
1,475
3.390625
3
[]
no_license
######################### # ColorfulLED # ######################### # @Author: Aaron Earl # # 5/25/19 # # # # From Freenove RPi # # tutorials # # Ch.5 RGBLED # # # # Task: Use PWM and # # SW PWM to change # # RGBLED Colors # ######################### import RPi.GPIO as GPIO import time import random pins = {'pin_R':11, 'pin_G':12, 'pin_B':13} #pins as a dict def setup(): global p_R, p_G,p_B print('Program is starting...') GPIO.setmode(GPIO.BOARD) # Number the pins by physical loc for i in pins: GPIO.setup(pins[i], GPIO.OUT) # Set pins' mode to output GPIO.output(pins[i], GPIO.HIGH) # Set pins to high(+3.3V) to off LED p_R = GPIO.PWM(pins['pin_R'], 2000) # Set frequency to 2KHz p_G = GPIO.PWM(pins['pin_G'], 2000) p_B = GPIO.PWM(pins['pin_B'], 2000) p_R.start(0) # Initial duty cycle = 0 p_G.start(0) p_B.start(0) def setColor(r_val, g_val, b_val): p_R.ChangeDutyCycle(r_val) # Change duty cycle p_G.ChangeDutyCycle(g_val) p_B.ChangeDutyCycle(b_val) def loop(): while True: r = random.randint(0, 100) # Get a random integer from 0-100 g = random.randint(0, 100) b = random.randint(0, 100) setColor(r, g, b) # Set Random as duty cycle value print('r = %d, g = %d, b = %d' %(r, g, b)) time.sleep(0.3) def destroy(): p_R.stop() p_G.stop() p_B.stop() GPIO.cleanup() if __name__ == "__main__": setup() try: loop() except KeyboardInterrupt: # When Ctrl+C is pressed destroy() destroy()
Markdown
UTF-8
4,993
3.28125
3
[]
no_license
# Ch1. Meet Python: *Everyone Loves Lists* - summarized by 전승일(2014/9/14) - source code: http://www.headfirstlabs.com/books/hfpython/ - support site: http://python.itcarlow.ie ## What’s to like about Python? (python의 매력) * PC, 맥, 휴대기기, 휴대폰, 웹, 대형서버에서 빠르고 쉽게 코드 작성, GUI 생성 가능 * Programming Languages Ranking: http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html ## Install Python 3 * www.python.org에서 download 및 설치 python3 -V # for OS-X, Linux c:\Python31\python.exe -V # for Windows ## Use IDLE to help learn Python * IDLE은 python 구문 및 내장함수를 알고 보기쉽게 표시 해 줌 * __BIF__(내장함수) : built-in function dir(__builtins__) help(input) ## Work effectively with IDLE * 탭 완성, 코드 문장 기억, 이전 문장 불러와서 편집하기, IDLE 환경 설정 바꾸기 * __Eclipse__ + __PyDev__ 사용하는 방법도 있음 1. www.eclipse.org/downloads 에서 Standard version 선택 2. 압축 풀고 eclipse 실행 3. http://pydev.org/manual_101_install.html 참고하여 pydev 추가 * Help > Install New Software * Location: http://pydev.org/updates * PyDev 선태 후 화면에 따라 진행 * 환경설정: General > Editors > Text Editors : Tab을 space로 변경, Tab = 4 PyDev > Interpreters > Python Interpreter : Advanced Auto-Config ## Deal with complex data * 영화광 데이터 영화제목 및 개요 주연배우 조연배우 * list 사용하여 관리 ## Create simple Python lists * __list__ : 데이터의 집합체로 콤마로 구분하고 대괄호로 시작과 끝을 둘러 싼다 movies = ["The Holy Grail", "The Life of Brian", "The Meaning of Life"] ## Lists are like arrays * list는 항목으로 서로다른 유형의 데이터를 포함할 수 있지만, array는 동일한 유형의 데이터만 포함할 수 있음 movies = ["The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91] ## Add more data to your list cast = ["Cleese", 'Palin', 'Jones', "Idle"] len(cast) cast.append("Gilliam") cast.pop() cast.extend(["Gilliam", "Chapman"]) cast.remove("Chapman") cast.insert(0, "Chapman") ## Work with your list data movies = ["The Holy Grail", "The Life of Brian"] print(movies[0]) print(movies[1]) * list의 항목이 늘어나면? 코드도 늘어나야... ## For loops work with lists of any size movies = ["The Holy Grail", "The Life of Brian"] for each_item in movies: print(each_item) 또는 count = 0 while count < len(movie): print(movies[count]) count = count + 1 * list의 크기에 무관하게 코드가 늘어나지 않음 ## Store lists within lists * 배우 데이터를 저장하기 위해 list 사용, 조연 배우를 위해 또 다른 list 사용: __nested list__ movies = ["The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91, ["Graham Chapman", ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]] for each_item in movies: print(each_item) ## Check a list for a list * data가 list인지 아닌지 확인하는 function isinstance(data, list) ## Complex data is hard to process for each_item in movies: if isinstance(each_item, list): for nested_item in each_item: print(nested_item) else: print(each_item) ## Handle many levels of nested lists for each_item in movies: if isinstance(each_item, list): for nested_item in each_item: if isinstance(nested_item, list): for deeper_item in nested_item: print(deeper_item) else: print(nested_item) else: print(each_item) ## Don’t repeat code; create a function * code가 반복되면 function을 만든다 ## Create a function in Python def function_name(arguments): code_suites ## Recursion to the rescue! * define a recursive function def print_lol(the_list): for each_item in the_list: if isinstance(each_item, list): print_lol(each_item) else: print(each_item) print_lol(movies) ## Additional Information * 파이썬 2.7 vs 파이썬 3 차이 (added by 좌승룡) https://wikidocs.net/743 * Install Python3 using brew on Mac (added by 표준영) http://brew.sh/ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew install python3
PHP
UTF-8
2,384
2.9375
3
[ "Apache-2.0" ]
permissive
<?php namespace jR\I\Cache; use jR\I\Cache; /** * Redis缓存驱动 * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis */ class Redis extends Cache { /** * 架构函数 * @param array $options 缓存参数 * @access public */ public function __construct($options=array()) { if ( !extension_loaded('redis') ) { err('系统不支持:redis'); } $this->options = $options; $func = $options['redis']['persistent'] ? 'pconnect' : 'connect'; $this->handler = new \Redis; $options['redis']['timeout'] === false ? $this->handler->$func($options['redis']['host'], $options['redis']['port']) : $this->handler->$func($options['redis']['host'], $options['redis']['port'], $options['redis']['timeout']); } /** * 读取缓存 * @access public * @param string $name 缓存变量名 * @return mixed */ public function get($name) { $value = $this->handler->get($this->options['prefix'].$name); $jsonData = json_decode( $value, true ); return ($jsonData === NULL) ? $value : $jsonData; //检测是否为JSON数据 true 返回JSON解析数组, false返回源数据 } /** * 写入缓存 * @access public * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param integer $expire 有效时间(秒) * @return boolean */ public function set($name, $value, $expire = null) { if(is_null($expire)) { $expire = $this->options['expire']; } $name = $this->options['prefix'].$name; $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value; if(is_int($expire) && $expire) { $result = $this->handler->setex($name, $expire, $value); }else{ $result = $this->handler->set($name, $value); } return $result; } /** * 删除缓存 * @access public * @param string $name 缓存变量名 * @return boolean */ public function rm($name) { return $this->handler->delete($this->options['prefix'].$name); } /** * 清除缓存 * @access public * @return boolean */ public function clear() { return $this->handler->flushDB(); } }
C++
UTF-8
3,774
3.515625
4
[]
no_license
// 11 - CountSemiprimes.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <assert.h> #include <vector> using namespace std; /// Find smallest prime divisor for each number vector<int> sieveOfEratosthenes(int N) { vector<int> sieve(N+1, 0); // +1 zero indexed sieve[0] = 0; // number 2 is a prime int i = 2; while (i*i <= N) { if (sieve[i] == 0) { int k = i*i; while (k <= N) { if (sieve[k] == 0) { sieve[k] = i; } k += i; } } i += 1; } return sieve; } bool isPrime(int N, const vector<int>& sieve) { return (N > 1) && (sieve[N] == 0); } bool isSemiprime(int N, const vector<int>& sieve) { int smallestPrimeDivisor = sieve[N]; if (smallestPrimeDivisor == 0) { return false; } return isPrime(smallestPrimeDivisor, sieve) && isPrime(N / smallestPrimeDivisor, sieve); } vector<int> solution(int N, vector<int> &P, vector<int> &Q) { vector<int> sieve = sieveOfEratosthenes(N+1); // Precalc number of semiprimes up to the index (modification of prefix-sums) vector<int> numberOfSemiprimes(N+1, 0); numberOfSemiprimes[0] = 0; for (int i = 1; i < N+1; ++i) { numberOfSemiprimes[i] = numberOfSemiprimes[i - 1]; if (isSemiprime(i, sieve)) { numberOfSemiprimes[i]++; } } // Go through the queries and store the answer vector<int> answers(P.size(), 0); for (int i = 0; i < P.size(); ++i) { int p = P[i]; int q = Q[i]; answers[i] = numberOfSemiprimes[q] - numberOfSemiprimes[p-1]; } return answers; } int main() { // Test sieve assert(vector<int>({0,0,0,0,2,0,2,0,2,3,2,0,2,0,2,3,2,0,2,0,2}) == sieveOfEratosthenes(20)); // Test isPrime vector<int> sieve = sieveOfEratosthenes(26); assert(!isPrime(0, sieve)); assert(!isPrime(1, sieve)); assert(isPrime(2, sieve)); assert(isPrime(3, sieve)); assert(!isPrime(4, sieve)); assert(isPrime(5, sieve)); assert(!isPrime(6, sieve)); assert(isPrime(7, sieve)); assert(!isPrime(8, sieve)); assert(!isPrime(9, sieve)); assert(!isPrime(10, sieve)); assert(isPrime(11, sieve)); assert(!isPrime(12, sieve)); assert(isPrime(13, sieve)); assert(!isPrime(14, sieve)); assert(!isPrime(15, sieve)); assert(!isPrime(16, sieve)); assert(isPrime(17, sieve)); assert(!isPrime(18, sieve)); assert(isPrime(19, sieve)); // Test isSemiprime assert(!isSemiprime(0, sieve)); assert(!isSemiprime(1, sieve)); assert(!isSemiprime(2, sieve)); assert(!isSemiprime(3, sieve)); assert(isSemiprime(4, sieve)); assert(!isSemiprime(5, sieve)); assert(isSemiprime(6, sieve)); assert(!isSemiprime(7, sieve)); assert(!isSemiprime(8, sieve)); assert(isSemiprime(9, sieve)); assert(isSemiprime(10, sieve)); assert(!isSemiprime(11, sieve)); assert(!isSemiprime(12, sieve)); assert(!isSemiprime(13, sieve)); assert(isSemiprime(14, sieve)); assert(isSemiprime(15, sieve)); assert(!isSemiprime(16, sieve)); assert(!isSemiprime(17, sieve)); assert(!isSemiprime(18, sieve)); assert(!isSemiprime(19, sieve)); assert(!isSemiprime(20, sieve)); assert(isSemiprime(21, sieve)); assert(isSemiprime(22, sieve)); assert(!isSemiprime(23, sieve)); assert(!isSemiprime(24, sieve)); assert(isSemiprime(25, sieve)); assert(isSemiprime(26, sieve)); // Test solution assert(vector<int>({ 10,4,0 }) == solution(26, vector<int>({ 1,4,16 }), vector<int>({ 26,10,20 }))); return 0; }
Python
UTF-8
1,002
2.59375
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- from sys import argv import os import re outfile = argv[2] if len(argv) > 2 else argv[1] fout = open(outfile, "w") title = { "实验目标" : "##", "实验内容" : "##", "实验步骤" : "##", "实验检查" : "##", "思考题" : "##" } index = [0] def indexstr(): return ".".join(map(lambda x: str(x), index)) for line in open(argv[1]): for k in title: if k in line: index = [index[0] + 1] line = title[k] + " " + indexstr() + " " + k line += "\n" if re.match(r"[0-9]*(\.|\\\.) .*", line): index = [index[0], 1 if len(index) == 1 else index[1] + 1 ] line = "###" + " " + indexstr() + " "+ " ".join(line.split(" ")[1:]) line += "\n" if re.match(r"[ ]*<!--[ ]*-->[ ]*", line): line = "" if re.match(r" *图-[0-9].*", line) or re.match(r" *表-[0-9].*", line): line = "<center>" + line + "</center>" fout.write(line)
Shell
UTF-8
462
2.921875
3
[]
no_license
#!/bin/bash # script that compiles NAS applications with different register allocation algorithms. # You can find each executable file under ./llvm/APP/app.$class.regalloc.o # 25.2.2016 Created by Mohammad cd ./llvm for result in */ ; do echo $result cd ${result} app=${PWD##*/} echo $app for classDir in */ ; do echo $classDir cd ${classDir} class=${PWD##*/} echo $class sudo rm -R -f * cd .. done cd .. done
Python
UTF-8
367
3.5625
4
[]
no_license
class Ejemplo: __atributo_privado = "Soy un atributo inalcanzable desde afuera" def __metodo_privado(self): print("Soy un método inalcanzable desde afuera") def metodo_publico(self): self.__metodo_privado() def getAtributoPrivado(self): print(self.__atributo_privado) e = Ejemplo() e.metodo_publico() e.getAtributoPrivado()
TypeScript
UTF-8
2,962
2.671875
3
[ "MIT" ]
permissive
import { standardize, createPredictionResult, createTeamNameLookup, getOneHotEncoding } from "./index"; import * as tf from "@tensorflow/tfjs"; import { numAllTimeTeams } from "@gvhinks/epl-constants"; describe("test utils", (): void => { const arsenal = getOneHotEncoding("Arsenal") const villa = getOneHotEncoding("Aston Villa"); describe("standandize", (): void => { test("standardise expect binary 1,0,0", (): void => { const testPrediction: number[] = [ 0.9, 0.8, 0.7]; const result: number[] = standardize(testPrediction); expect(result[0]).toEqual(1); expect(result[1]).toEqual(0); expect(result[2]).toEqual(0); }); test("standardise expect binary 0,1,0", (): void => { const testPrediction: number[] = [ 0.05, 0.95, 0.7]; const result: number[] = standardize(testPrediction); expect(result[0]).toEqual(0); expect(result[1]).toEqual(1); expect(result[2]).toEqual(0); }); test("standardise expect binary 0,0,1", (): void => { const testPrediction: number[] = [ 0.05, 0.10,0.85]; const result: number[] = standardize(testPrediction); expect(result[0]).toEqual(0); expect(result[1]).toEqual(0); expect(result[2]).toEqual(1); }); }); describe("createPredictionResult", (): void => { const hotEncodedFeatureArr: number[] = [...arsenal, ...villa, 19]; const teamNames: Map<string, string> = new Map([[`${arsenal}`, "arsenal"], [`${villa}`, "villa"]]); const mockModel = { predict: (): object => ({ data: async (): Promise<number[]> => Promise.resolve([0.1, 0.2, 0.3]) }) }; const testLabelValues = [0,0,1]; test("expect a prediction result", async (): Promise<void> => { // eslint-disable-next-line @typescript-eslint/consistent-type-assertions const mockSeq: tf.Sequential = <tf.Sequential><unknown>mockModel; const result = await createPredictionResult(mockSeq, hotEncodedFeatureArr, teamNames, testLabelValues); expect(result.standardizedResult[0]).toEqual(0); expect(result.standardizedResult[1]).toEqual(0); expect(result.standardizedResult[2]).toEqual(1); }); }); describe("Team name reverse lookup", (): void => { test("arsenal", (): void => { const teams = createTeamNameLookup(); const name = teams.get(`${arsenal}`); expect(name).toEqual("Arsenal"); }); test("villa", (): void => { const teams = createTeamNameLookup(); const name = teams.get(`${villa}`); expect(name).toEqual("Aston Villa"); }); }); describe("One hot encoded team name", (): void => { test("Arsenal", (): void => { const oneHotEncoded = getOneHotEncoding("Arsenal"); expect(oneHotEncoded.length).toBe(numAllTimeTeams); expect(oneHotEncoded[0]).toBe(1); const sum: number = oneHotEncoded.reduce((a, v): number => { return a + v; }, 0); expect(sum).toEqual(1); }) }) });
Markdown
UTF-8
1,370
2.578125
3
[]
no_license
--- layout: post title: 连番激战II:都输给了时间 date: 2014-10-27 22:28 author: alvachien comments: true tags: [Real Madrid, 皇家马德里, 皇马] categories: [五洲足坛] --- 红蓝输球了,虽然比分并不是悬殊的大比分,而是相对让双方都能接受的一个“1:3”,但,下半场白衣军团完全在场面上和气势上压制住了红蓝军团。作为白衣拥趸的我,在这个场景下,却始终开心不起来。好吧,我无次数想过在伯纳乌能够还给巴萨一个5:0,也曾经再次期待让巴萨在伯纳乌列队欢迎冠军皇马,但是看到红蓝队中,金毛狮王普约尔已经离开了巴萨,守门员不再是那个熟悉的黄油手,而世界最佳中场组合——哈维和伊内斯塔——已然步履蹒跚。而与他们对位的是,22岁的伊斯科,24岁的克鲁斯和23岁的J罗。 真应了谁说过的那句话,“没有哪支球队能天下无敌,迟早时间会击败他们”。这句话验证在了五连冠时代的无敌皇马,也验证在英超赛场不败夺冠的枪手,如今也再一次验证在叱咤天下的梦二和梦三。这是竞技体育的残酷,却又是那么顺其自然。 人生如同长跑,或早或晚,我们都将输给时间——哪怕相对论已经证明光速才能改变时间。 是为之记。 Alva Chien 2014.10.27
C++
UTF-8
12,512
2.75
3
[ "MIT" ]
permissive
#include "ahi.hpp" #include <iostream> #include <sstream> uintptr_t AHI::base_addr = 0x0; std::map<LPVOID, BYTE[JMP_OPCODE_SIZE]> AHI::func_backups; std::map<std::pair<LPVOID, LPVOID>, BYTE *> AHI::opcode_backups; void AHI::init(void) { base_addr = (uintptr_t)GetModuleHandle(nullptr); } LPVOID AHI::hook_func(uintptr_t func_addr, LPVOID dst_func_addr, bool silent) { func_addr = func_addr + base_addr; if (func_backups.find((LPVOID)func_addr) != func_backups.end()) { std::cerr << __FUNCTION__ << ": " << (LPVOID)func_addr << " is already hooked!" << std::endl; return 0; } for (auto const &opcode_backup : opcode_backups) { LPVOID backup_start_addr = opcode_backup.first.first; LPVOID backup_end_addr = opcode_backup.first.second; if ((LPVOID)func_addr >= backup_start_addr && (LPVOID)func_addr <= backup_end_addr) { std::cerr << __FUNCTION__ << ": Target is located inside function injection range [" << backup_start_addr << ", " << backup_end_addr << "]!" << std::endl; return 0; } } HANDLE process_handle = GetCurrentProcess(); if (!process_handle) { std::cerr << __FUNCTION__ << ": GetCurrentProcess error: " << GetLastError() << std::endl; return 0; } if (!ReadProcessMemory(process_handle, (LPVOID)func_addr, func_backups[(LPVOID)func_addr], JMP_OPCODE_SIZE, 0)) { std::cerr << __FUNCTION__ << ": ReadProcessMemory error: " << GetLastError() << std::endl; func_backups.erase((LPVOID)func_addr); return 0; } LPVOID dst_func_relative_addr = (LPVOID)((uintptr_t)dst_func_addr - func_addr - JMP_OPCODE_SIZE); DWORD previous_protection; VirtualProtect((LPVOID)func_addr, JMP_OPCODE_SIZE, PAGE_EXECUTE_READWRITE, &previous_protection); BYTE jmp_opcode[JMP_OPCODE_SIZE] = {JMP_OPCODE_BYTES}; memcpy(&jmp_opcode[1], &dst_func_relative_addr, ADDR_SIZE); if (!WriteProcessMemory(process_handle, (LPVOID)func_addr, jmp_opcode, JMP_OPCODE_SIZE, 0)) { std::cerr << __FUNCTION__ << ": WriteProcessMemory error: " << GetLastError() << std::endl; func_backups.erase((LPVOID)func_addr); return 0; } if (!VirtualProtect((LPVOID)func_addr, JMP_OPCODE_SIZE, previous_protection, &previous_protection)) { std::cerr << __FUNCTION__ << ": VirtualProtect error: " << GetLastError() << std::endl; func_backups.erase((LPVOID)func_addr); return 0; } if (!FlushInstructionCache(process_handle, 0, 0)) { std::cerr << __FUNCTION__ << ": FlushInstructionCache error: " << GetLastError() << std::endl; func_backups.erase((LPVOID)func_addr); return 0; } if (!silent) { std::cout << "Hooked " << dst_func_relative_addr << " to " << (LPVOID)func_addr << std::endl; } return (LPVOID)func_addr; } LPVOID AHI::unhook_func(uintptr_t func_addr, bool silent) { func_addr = func_addr + base_addr; if (func_backups.find((LPVOID)func_addr) == func_backups.end()) { std::cerr << __FUNCTION__ << ": " << func_addr << " is not hooked!" << std::endl; return 0; } HANDLE process_handle = GetCurrentProcess(); if (!process_handle) { std::cerr << __FUNCTION__ << ": GetCurrentProcess error: " << GetLastError() << std::endl; return 0; } if (!WriteProcessMemory(process_handle, (LPVOID)func_addr, func_backups[(LPVOID)func_addr], JMP_OPCODE_SIZE, 0)) { std::cerr << __FUNCTION__ << ": WriteProcessMemory error: " << GetLastError() << std::endl; return 0; } if (!FlushInstructionCache(process_handle, 0, 0)) { std::cerr << __FUNCTION__ << ": FlushInstructionCache error: " << GetLastError() << std::endl; return 0; } if (!silent) { std::cout << "Unhooked function from " << (LPVOID)func_addr << std::endl; } func_backups.erase((LPVOID)func_addr); return (LPVOID)func_addr; } LPVOID AHI::hook_dll_func(std::string dll, std::string func_name, LPVOID dst_func_addr, bool silent) { HMODULE module_handle = GetModuleHandle(dll.c_str()); if (!module_handle) { std::cerr << __FUNCTION__ << ": GetModuleHandle error: " << GetLastError() << std::endl; return 0; } LPVOID func_addr = (LPVOID)GetProcAddress(module_handle, func_name.c_str()); if (!func_addr) { std::cerr << __FUNCTION__ << ": GetProcAddress error: " << GetLastError() << std::endl; return 0; } if (!silent) { std::cout << dll << "." << func_name << ": "; } // Pointer arithmetic required because hook_func doesn't expect absolute // address. return hook_func((uintptr_t)func_addr - base_addr, dst_func_addr, silent); } LPVOID AHI::unhook_dll_func(std::string dll, std::string func_name, bool silent) { HMODULE module_handle = GetModuleHandle(dll.c_str()); if (!module_handle) { std::cerr << __FUNCTION__ << ": GetModuleHandle error: " << GetLastError() << std::endl; return 0; } LPVOID func_addr = (LPVOID)GetProcAddress(module_handle, func_name.c_str()); if (!func_addr) { std::cerr << __FUNCTION__ << ": GetProcAddress error: " << GetLastError() << std::endl; return 0; } if (!silent) { std::cout << dll << "." << func_name << ": "; } // Pointer arithmetic required because unhook_func doesn't expect absolute // address. return unhook_func((uintptr_t)func_addr - base_addr, silent); } LPVOID AHI::inject_func(uintptr_t start_addr, uintptr_t end_addr, LPVOID func_addr) { start_addr = start_addr + base_addr; end_addr = end_addr + base_addr; if (end_addr - start_addr < CALL_OPCODE_SIZE) { std::cerr << __FUNCTION__ << ": Not enough space to inject call instruction!" << std::endl; return 0; } for (auto const &opcode_backup : opcode_backups) { LPVOID backup_start_addr = opcode_backup.first.first; LPVOID backup_end_addr = opcode_backup.first.second; if ((LPVOID)start_addr < backup_start_addr && (LPVOID)end_addr <= backup_start_addr || (LPVOID)start_addr >= backup_end_addr && (LPVOID)end_addr > backup_end_addr) { continue; } else { std::cerr << __FUNCTION__ << ": Injection conflicts with another in range [" << backup_start_addr << ", " << backup_end_addr << "]!" << std::endl; return 0; } } if (func_backups.find((LPVOID)start_addr) != func_backups.end() || func_backups.find((LPVOID)end_addr) != func_backups.end()) { std::cerr << __FUNCTION__ << ": " << "Injection at " << (LPVOID)start_addr << " conflicts with function hook!" << std::endl; return 0; } HANDLE process_handle = GetCurrentProcess(); if (!process_handle) { std::cerr << __FUNCTION__ << ": GetCurrentProcess error: " << GetLastError() << std::endl; return 0; } uintptr_t size = end_addr - start_addr; BYTE * backup = new BYTE[size]; if (!ReadProcessMemory(process_handle, (LPVOID)start_addr, backup, size, 0)) { std::cerr << __FUNCTION__ << ": ReadProcessMemory error: " << GetLastError() << std::endl; return 0; } LPVOID dst_func_relative_addr = (LPVOID)((uintptr_t)func_addr - start_addr - CALL_OPCODE_SIZE); DWORD previous_protection; VirtualProtect((LPVOID)func_addr, size, PAGE_EXECUTE_READWRITE, &previous_protection); BYTE *nops = new BYTE[size]; for (int i = 0; i < size; ++i) { nops[i] = NOP_OPCODE; } if (!WriteProcessMemory(process_handle, (LPVOID)start_addr, nops, size, 0)) { std::cerr << __FUNCTION__ << ": 1st WriteProcessMemory error: " << GetLastError() << std::endl; return 0; } delete[] nops; BYTE call_opcode[CALL_OPCODE_SIZE] = {CALL_OPCODE_BYTES}; memcpy(&call_opcode[1], &dst_func_relative_addr, ADDR_SIZE); if (!WriteProcessMemory(process_handle, (LPVOID)start_addr, call_opcode, CALL_OPCODE_SIZE, 0)) { std::cerr << __FUNCTION__ << ": 2nd WriteProcessMemory error: " << GetLastError() << std::endl; return 0; } if (!VirtualProtect((LPVOID)func_addr, size, previous_protection, &previous_protection)) { std::cerr << __FUNCTION__ << ": VirtualProtect error: " << GetLastError() << std::endl; return 0; } if (!FlushInstructionCache(process_handle, 0, 0)) { std::cerr << __FUNCTION__ << ": FlushInstructionCache error: " << GetLastError() << std::endl; return 0; } std::cout << "Injected " << func_addr << " into [" << (LPVOID)start_addr << ", " << (LPVOID)end_addr << ")" << std::endl; opcode_backups[std::pair<LPVOID, LPVOID>((LPVOID)start_addr, (LPVOID)end_addr)] = backup; return (LPVOID)start_addr; } LPVOID AHI::eject_func(uintptr_t start_addr) { start_addr = start_addr + base_addr; for (auto const &opcode_backup : opcode_backups) { LPVOID backup_start_addr = opcode_backup.first.first; LPVOID backup_end_addr = opcode_backup.first.second; if ((LPVOID)start_addr == backup_start_addr) { HANDLE process_handle = GetCurrentProcess(); if (!process_handle) { std::cerr << __FUNCTION__ << ": GetCurrentProcess error: " << GetLastError() << std::endl; return 0; } uintptr_t size = (uintptr_t)backup_end_addr - (uintptr_t)backup_start_addr; if (!WriteProcessMemory(process_handle, (LPVOID)start_addr, opcode_backup.second, size, 0)) { std::cerr << __FUNCTION__ << ": WriteProcessMemory error: " << GetLastError() << std::endl; return 0; } if (!FlushInstructionCache(process_handle, 0, 0)) { std::cerr << __FUNCTION__ << ": FlushInstructionCache error: " << GetLastError() << std::endl; return 0; } std::cout << "Ejected function from [" << backup_start_addr << ", " << backup_end_addr << ")" << std::endl; delete[] opcode_backup.second; opcode_backups.erase(opcode_backup.first); return backup_start_addr; } } std::cerr << __FUNCTION__ << ": No function injected at " << (LPVOID)start_addr << "!" << std::endl; return 0; } uintptr_t AHI::get_base_addr(){ return base_addr; } uintptr_t AHI::get_offset(uintptr_t image_base, uintptr_t rva){ return rva - image_base; } uintptr_t AHI::get_abs_addr(uintptr_t image_base, uintptr_t rva) { return (rva - image_base) + base_addr; } std::string AHI::stringify(char *buf, long len){ std::stringstream sstream; for(int i = 0; i < len; ++i){ if(buf[i] >= READABLE_RANGE_START && buf[i] <= READABLE_RANGE_END){ sstream << buf[i]; } else { sstream << UNREADABLE_CHAR_PLACEHOLDER; } } return sstream.str(); }
Python
UTF-8
21,767
3.234375
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "Python-2.0" ]
permissive
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) import unittest from collections import OrderedDict, defaultdict, deque, namedtuple class OrderedDictTests(unittest.TestCase): def test_dunder_repr(self): d = OrderedDict({5: 1, 6: 0}) actual = str(d) self.assertEqual(actual, "OrderedDict([(5, 1), (6, 0)])") def test_move_to_end(self): d = OrderedDict({"d": 2, "b": 1, "z": 0}) d.move_to_end("b") k, v = d.popitem() self.assertEqual((k, v), ("b", 1)) class DefaultdictTests(unittest.TestCase): def test_dunder_init_returns_dict_subclass(self): result = defaultdict() self.assertIsInstance(result, dict) self.assertIsInstance(result, defaultdict) self.assertIsNone(result.default_factory) def test_dunder_init_with_non_callable_raises_type_error(self): with self.assertRaises(TypeError) as context: defaultdict(5) self.assertIn("must be callable or None", str(context.exception)) def test_dunder_init_sets_default_factory(self): def foo(): pass result = defaultdict(foo) self.assertIs(result.default_factory, foo) def test_dunder_getitem_calls_dunder_missing(self): def foo(): return "value" result = defaultdict(foo) self.assertEqual(len(result), 0) self.assertEqual(result["hello"], "value") self.assertEqual(result[5], "value") self.assertEqual(len(result), 2) def test_dunder_missing_with_none_default_factory_raises_key_error(self): result = defaultdict() with self.assertRaises(KeyError) as context: result.__missing__("hello") self.assertEqual(context.exception.args, ("hello",)) def test_dunder_missing_calls_default_factory_function(self): def foo(): raise UserWarning("foo") result = defaultdict(foo) with self.assertRaises(UserWarning) as context: result.__missing__("hello") self.assertEqual(context.exception.args, ("foo",)) def test_dunder_missing_calls_default_factory_callable(self): class A: def __call__(self): raise UserWarning("foo") result = defaultdict(A()) with self.assertRaises(UserWarning) as context: result.__missing__("hello") self.assertEqual(context.exception.args, ("foo",)) def test_dunder_missing_sets_value_returned_from_default_factory(self): def foo(): return 5 result = defaultdict(foo) self.assertEqual(result, {}) self.assertEqual(result.__missing__("hello"), 5) self.assertEqual(result, {"hello": 5}) def test_dunder_repr_with_no_default_factory(self): empty = defaultdict() self.assertEqual(empty.__repr__(), "defaultdict(None, {})") def test_dunder_repr_with_default_factory_calls_factory_repr(self): class A: def __call__(self): pass def __repr__(self): return "foo" def __str__(self): return "bar" empty = defaultdict(A()) self.assertEqual(empty.__repr__(), "defaultdict(foo, {})") def test_dunder_repr_stringifies_elements(self): result = defaultdict() result["a"] = "b" self.assertEqual(result.__repr__(), "defaultdict(None, {'a': 'b'})") def test_clear_removes_elements(self): def foo(): pass result = defaultdict(foo) result["a"] = "b" self.assertEqual(len(result), 1) self.assertIsNone(result.clear()) self.assertIs(result.default_factory, foo) self.assertEqual(len(result), 0) class DequeTests(unittest.TestCase): def test_dunder_bool_with_empty_returns_false(self): result = deque() self.assertEqual(result.__bool__(), False) def test_dunder_bool_with_non_empty_returns_true(self): result = deque([1, 2, 3]) self.assertEqual(result.__bool__(), True) def test_dunder_contains_with_empty_returns_false(self): result = deque() self.assertEqual(result.__contains__(1), False) def test_dunder_contains_with_non_empty_returns_true(self): result = deque([1, 2, 3]) self.assertEqual(result.__contains__(2), True) def test_dunder_contains_checks_identity(self): class C: def __eq__(self, other): return False c = C() result = deque([1, c, 3]) self.assertEqual(result.__contains__(c), True) def test_dunder_new_calls_super_dunder_new(self): class C(deque): def __new__(cls): raise UserWarning("foo") with self.assertRaises(UserWarning): C() def test_dunder_new_does_not_call_super_clear(self): class C(deque): def clear(self): raise UserWarning("foo") C() def test_dunder_init_with_negative_maxlen_raises_value_error(self): with self.assertRaises(ValueError) as context: deque(maxlen=-1) self.assertEqual(str(context.exception), "maxlen must be non-negative") def test_dunder_init_with_non_int_maxlen_raises_type_error(self): with self.assertRaises(TypeError): deque(maxlen="hello") def test_dunder_init_sets_maxlen(self): result = deque(maxlen=5) self.assertEqual(result.maxlen, 5) def test_dunder_init_calls_dunder_iter_on_iterable(self): class C: def __iter__(self): raise UserWarning("foo") iterable = C() with self.assertRaises(UserWarning): deque(iterable=iterable) def test_dunder_init_adds_elements_from_iterable(self): result = deque(iterable=[1, 2, 3]) self.assertEqual(len(result), 3) self.assertIn(1, result) self.assertIn(2, result) self.assertIn(3, result) def test_dunder_copy_with_non_deque_raises_type_error(self): self.assertRaises(TypeError, deque.__copy__, None) with self.assertRaises(TypeError): deque.__copy__(None) def test_dunder_copy_returns_copy(self): orig = deque([1, 2, 3]) copy = orig.__copy__() self.assertEqual(orig, copy) self.assertIsNot(orig, copy) def test_dunder_delitem_with_int_subclass_does_not_call_dunder_index(self): class C(int): def __index__(self): raise ValueError("foo") result = deque([1, 2, 3]) deque.__delitem__(result, C(0)) self.assertEqual(list(result), [2, 3]) def test_dunder_delitem_with_raising_descriptor_propagates_exception(self): class Desc: def __get__(self, obj, type): raise AttributeError("foo") class C: __index__ = Desc() result = deque([1, 2, 3]) with self.assertRaises(AttributeError) as context: result.__delitem__(C()) self.assertEqual(str(context.exception), "foo") def test_dunder_delitem_with_non_int_raises_type_error(self): result = deque([1, 2, 3]) with self.assertRaises(TypeError): result.__delitem__("3") def test_dunder_delitem_with_dunder_index_calls_dunder_index(self): class C: def __index__(self): return 2 result = deque([1, 2, 3]) result.__delitem__(C()) self.assertEqual(list(result), [1, 2]) def test_dunder_delitem_index_too_small_raises_index_error(self): result = deque() with self.assertRaises(IndexError) as context: result.__delitem__(-1) self.assertEqual(str(context.exception), "deque index out of range") def test_dunder_delitem_index_too_large_raises_index_error(self): result = deque([1, 2, 3]) with self.assertRaises(IndexError) as context: result.__delitem__(3) self.assertEqual(str(context.exception), "deque index out of range") def test_dunder_delitem_negative_index_relative_to_end(self): result = deque([1, 2, 3]) result.__delitem__(-3) self.assertEqual(list(result), [2, 3]) def test_dunder_delitem_with_slice_raises_type_error(self): result = deque([1, 2, 3, 4, 5]) self.assertRaises(TypeError, result.__delitem__, slice(0, 1)) def test_dunder_eq_with_different_length_returns_false(self): left = deque([1, 2, 3]) right = deque([1, 2, 3, 4]) self.assertFalse(left.__eq__(right)) def test_dunder_eq_with_non_deque_returns_not_implemented(self): left = deque([1, 2, 3]) right = 5 self.assertIs(left.__eq__(right), NotImplemented) def test_dunder_eq_with_identity_equal_but_inequal_elements_returns_true(self): nan = float("nan") left = deque([1, nan, 3]) right = deque([1, nan, 3]) self.assertTrue(left.__eq__(right)) def test_dunder_eq_compares_item_equality_dunder_eq(self): class C: def __eq__(self, other): return True left = deque([1, 2, 3]) right = deque([1, C(), 3]) self.assertTrue(left.__eq__(right)) def test_dunder_eq_compares_item_equality(self): left = deque([1, 2, 3]) right = deque([1, 2, 3]) self.assertTrue(left.__eq__(right)) def test_dunder_iadd_calls_dunder_iter_on_rhs(self): class C: def __iter__(self): return [4, 5, 6].__iter__() left = deque([1, 2, 3]) right = C() result = left.__iadd__(right) self.assertIs(result, left) self.assertEqual(list(left), [1, 2, 3, 4, 5, 6]) def test_dunder_iadd_returns_left(self): left = deque([1, 2, 3]) right = [4] result = left.__iadd__(right) self.assertIs(result, left) self.assertEqual(list(left), [1, 2, 3, 4]) self.assertEqual(list(right), [4]) def test_dunder_getitem_with_int_subclass_does_not_call_dunder_index(self): class C(int): def __index__(self): raise ValueError("foo") result = deque([1, 2, 3]) self.assertEqual(deque.__getitem__(result, C(0)), 1) def test_dunder_getitem_with_raising_descriptor_propagates_exception(self): class Desc: def __get__(self, obj, type): raise AttributeError("foo") class C: __index__ = Desc() result = deque([1, 2, 3]) with self.assertRaises(AttributeError) as context: result.__getitem__(C()) self.assertEqual(str(context.exception), "foo") def test_dunder_getitem_with_non_int_raises_type_error(self): result = deque([1, 2, 3]) with self.assertRaises(TypeError): result.__getitem__("3") def test_dunder_getitem_with_dunder_index_calls_dunder_index(self): class C: def __index__(self): return 2 result = deque([1, 2, 3]) self.assertEqual(result.__getitem__(C()), 3) def test_dunder_getitem_index_too_small_raises_index_error(self): result = deque() with self.assertRaises(IndexError) as context: result.__getitem__(-1) self.assertEqual(str(context.exception), "deque index out of range") def test_dunder_getitem_index_too_large_raises_index_error(self): result = deque([1, 2, 3]) with self.assertRaises(IndexError) as context: result.__getitem__(3) self.assertEqual(str(context.exception), "deque index out of range") def test_dunder_getitem_negative_index_relative_to_end(self): result = deque([1, 2, 3]) self.assertEqual(result.__getitem__(-3), 1) def test_dunder_getitem_with_slice_raises_type_error(self): result = deque([1, 2, 3, 4, 5]) self.assertRaises(TypeError, result.__getitem__, slice(2, -1)) def test_dunder_hash_is_none(self): self.assertIsNone(deque.__hash__) def test_dunder_len_returns_length(self): result = deque([1, 2, 3]) self.assertEqual(result.__len__(), 3) def test_dunder_repr(self): result = deque([1, "foo", 3]) self.assertEqual(result.__repr__(), "deque([1, 'foo', 3])") def test_dunder_repr_recursive(self): result = deque([1, "foo", 3]) result.append(result) self.assertEqual(result.__repr__(), "deque([1, 'foo', 3, [...]])") def test_dunder_repr_with_maxlen(self): result = deque([1, 2, 3], maxlen=4) self.assertEqual(result.__repr__(), "deque([1, 2, 3], maxlen=4)") # TODO(T69992771): Add deque.__setitem__ tests def test_append_adds_elements(self): result = deque() self.assertEqual(len(result), 0) result.append(1) result.append(2) result.append(3) self.assertEqual(len(result), 3) self.assertEqual(list(result), [1, 2, 3]) def test_append_over_maxlen_removes_element_from_left(self): result = deque([1, 2, 3, 4, 5], maxlen=5) result.append("foo") self.assertEqual(list(result), [2, 3, 4, 5, "foo"]) def test_append_over_zero_maxlen_does_nothing(self): result = deque(maxlen=0) result.append(1) self.assertEqual(len(result), 0) def test_appendleft_adds_elements_to_left(self): result = deque() self.assertEqual(len(result), 0) result.appendleft(1) result.appendleft(2) result.appendleft(3) self.assertEqual(len(result), 3) self.assertEqual(list(result), [3, 2, 1]) def test_appendleft_over_maxlen_removes_element_from_right(self): result = deque([1, 2, 3], maxlen=3) result.appendleft("foo") self.assertEqual(list(result), ["foo", 1, 2]) def test_appendleft_over_zero_maxlen_does_nothing(self): result = deque(maxlen=0) result.appendleft(1) self.assertEqual(len(result), 0) def test_clear_removes_elements(self): result = deque(iterable=[1, 2, 3]) self.assertEqual(len(result), 3) result.clear() self.assertEqual(len(result), 0) self.assertNotIn(1, result) self.assertNotIn(2, result) self.assertNotIn(3, result) def test_extend_calls_dunder_iter_on_iterable(self): class C: def __iter__(self): raise UserWarning("foo") iterable = C() result = deque() with self.assertRaises(UserWarning): result.extend(iterable) def test_extend_with_self_copies_deque(self): result = deque([1, 2, 3]) result.extend(result) self.assertEqual(list(result), [1, 2, 3, 1, 2, 3]) def test_extend_adds_elements_from_iterable(self): class C: def __iter__(self): return [1, 2, 3].__iter__() result = deque() result.extend(C()) self.assertEqual(list(result), [1, 2, 3]) def test_extend_over_maxlen_removes_elements_from_right(self): result = deque([1, 2, 3], maxlen=3) result.extend([4]) self.assertEqual(list(result), [2, 3, 4]) def test_extendleft_calls_dunder_iter_on_iterable(self): class C: def __iter__(self): raise UserWarning("foo") iterable = C() result = deque() with self.assertRaises(UserWarning): result.extendleft(iterable) def test_extendleft_with_self_copies_deque(self): result = deque([1, 2, 3]) result.extendleft(result) self.assertEqual(list(result), [3, 2, 1, 1, 2, 3]) def test_extendleft_adds_elements_from_iterable(self): class C: def __iter__(self): return [1, 2, 3].__iter__() result = deque() result.extendleft(C()) self.assertEqual(list(result), [3, 2, 1]) def test_extendleft_over_maxlen_removes_elements_from_left(self): result = deque([1, 2, 3], maxlen=3) result.extendleft([4]) self.assertEqual(list(result), [4, 1, 2]) def test_pop_from_empty_deque_raises_index_error(self): result = deque() self.assertRaises(IndexError, result.pop) def test_pop_removes_element_from_right(self): result = deque([1, 2, 3]) result.pop() self.assertEqual(list(result), [1, 2]) def test_popleft_from_empty_deque_raises_index_error(self): result = deque() self.assertRaises(IndexError, result.popleft) def test_popleft_removes_element_from_left(self): result = deque([1, 2, 3]) result.popleft() self.assertEqual(list(result), [2, 3]) def test_count_counts_number_of_occurrences_with_dunder_eq(self): class C: def __eq__(self, other): return True result = deque([1, 2, 3]) self.assertEqual(result.count(C()), 3) def test_count_counts_number_of_occurrences(self): result = deque([1, 2, 3, 2, 1]) self.assertEqual(result.count(2), 2) def test_count_checks_identity(self): nan = float("nan") result = deque([1, nan, 3, nan]) self.assertEqual(result.count(nan), 2) def test_remove_with_element_not_in_deque_raises_value_error(self): result = deque() self.assertRaises(ValueError, result.remove, 4) def test_remove_with_checks_identity(self): nan = float("nan") result = deque([1, nan, 3]) result.remove(nan) self.assertEqual(list(result), [1, 3]) def test_remove_removes_first_occurrence_of_element_from_left(self): result = deque([1, 2, 3, 2, 1]) result.remove(2) self.assertEqual(list(result), [1, 3, 2, 1]) def test_rotate_rotates_elements_right_by_one(self): result = deque([1, 2, 3]) result.rotate() self.assertEqual(list(result), [3, 1, 2]) def test_rotate_with_non_int_raises_type_error(self): result = deque() self.assertRaises(TypeError, result.rotate, "x") def test_rotate_rotates_elements_right_by_given_amount(self): result = deque([1, 2, 3, 4, 5]) result.rotate(3) self.assertEqual(list(result), [3, 4, 5, 1, 2]) # TODO(T70064130): Implement deque.reverse class NamedtupleTests(unittest.TestCase): def test_create_with_space_separated_field_names_splits_string(self): self.assertEqual(namedtuple("Foo", "a b")._fields, ("a", "b")) def test_create_with_rename_renames_bad_fields(self): result = namedtuple("Foo", ["a", "5", "b", "1"], rename=True)._fields self.assertEqual(result, ("a", "_1", "b", "_3")) def test_create_with_rename_renames_fields_starting_with_underscore(self): result = namedtuple("Foo", ["a", "5", "_b", "1"], rename=True)._fields self.assertEqual(result, ("a", "_1", "_2", "_3")) def test_repr_formats_fields(self): Foo = namedtuple("Foo", "a b") self.assertEqual(Foo(1, 2).__repr__(), "Foo(a=1, b=2)") def test_repr_formats_fields_with_different_str_repr(self): Foo = namedtuple("Foo", "a b") self.assertEqual(Foo(1, "bar").__repr__(), "Foo(a=1, b='bar')") def test_dunder_getattr_with_namedtuple_class_returns_descriptor(self): Foo = namedtuple("Foo", "a b") self.assertTrue(hasattr(Foo, "a")) self.assertTrue(hasattr(Foo.a, "__get__")) self.assertTrue(hasattr(Foo, "b")) self.assertTrue(hasattr(Foo.b, "__get__")) def test_with_non_identifier_type_name_raises_value_error(self): with self.assertRaisesRegex( ValueError, "Type names and field names must be valid identifiers: '5'" ): namedtuple("5", ["a", "b"]) def test_with_keyword_raises_value_error(self): with self.assertRaisesRegex( ValueError, "Type names and field names cannot be a keyword: 'from'" ): namedtuple("from", ["a", "b"]) def test_with_field_starting_with_underscore_raises_value_error(self): with self.assertRaisesRegex( ValueError, "Field names cannot start with an underscore: '_a'" ): namedtuple("Foo", ["_a", "b"]) def test_with_duplicate_field_name_raises_value_error(self): with self.assertRaisesRegex( ValueError, "Encountered duplicate field name: 'a'" ): namedtuple("Foo", ["a", "a"]) def test_with_too_few_args_raises_type_error(self): Foo = namedtuple("Foo", ["a", "b"]) with self.assertRaisesRegex(TypeError, "Expected 2 arguments, got 1"): Foo._make([1]) def test_under_make_returns_new_instance(self): Foo = namedtuple("Foo", ["a", "b"]) inst = Foo._make([1, 3]) self.assertEqual(inst.a, 1) self.assertEqual(inst.b, 3) self.assertEqual(len(inst), 2) self.assertEqual(inst[0], 1) self.assertEqual(inst[1], 3) def test_under_replace_with_nonexistet_field_name_raises_value_error(self): Foo = namedtuple("Foo", ["a", "b"]) with self.assertRaisesRegex(ValueError, "Got unexpected field names.*'x'.*"): Foo(1, 2)._replace(x=4) def test_under_replace_replaces_value_at_name(self): Foo = namedtuple("Foo", ["a", "b"]) inst = Foo(1, 2) self.assertIs(inst.a, 1) self.assertIs(inst.b, 2) self.assertIs(inst[1], 2) inst = inst._replace(b=3) self.assertIs(inst.a, 1) self.assertIs(inst.b, 3) self.assertIs(inst[1], 3) if __name__ == "__main__": unittest.main()
Swift
UTF-8
1,269
2.875
3
[ "MIT" ]
permissive
// // ImageResizer.swift // OperationComparison // // Created by Ellen Shapiro on 10/10/18. // Copyright © 2018 Bakken & Baeck. All rights reserved. // import UIKit class ImageResizer: NSObject { enum Error: Swift.Error { case imageDidNotResize } static func resizeImage(_ image: UIImage, to size: CGSize, fakingDelay delay: TimeInterval = 1, completion: @escaping (Swift.Result<UIImage, Swift.Error>) -> Void) { DispatchQueue.global(qos: .userInitiated).async { UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) image.draw(in: CGRect(origin: .zero, size: size)) var result: Result<UIImage, Swift.Error> defer { UIGraphicsEndImageContext() DispatchQueue.main.asyncAfter(deadline: .now() + delay) { completion(result) } } guard let resized = UIGraphicsGetImageFromCurrentImageContext() else { result = .failure(Error.imageDidNotResize) return } result = .success(resized) } } }
Python
UTF-8
3,475
3.6875
4
[]
no_license
#desafio1 programa que tenha uma tupla totalmente preenchida de 0 a 20 e receba um valor de 0 a 20 e mostrar por extenso #desafio2 tupla como os 20 primeiros colocados da tabela do brasileiro e mostre os 5 primeiros colocados, os ultimos 4, lista com ordem alfabetica e posição do sport #desafio3 programa que gere cinco numeros aleatorios e guardar em uma tupla e mostrar o menor e o maior valor na tupla #desafio4 ler programa que guarde 4 valores no teclado e guarde em uma tupla, quantas vezees apareceu o 9, em que posição apareceu o 3 e quais os numeros pares #desafio5 programa com uma tupla unica com nomes de produtos e seus respectivos preços na sequencia no final mostre os dados em uma forma tabular #desafio6 programa que tenha um a tupla com varias palavras e mostrar as vogais de cada palavra #RESOLUÇÃO #1) ''' intervalo=(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) valor=0 extenso=('zero', 'um', 'dois', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze','treze', 'catorze', 'quinze', 'dezesseis', 'dezessete', 'dezeoito', 'dezenove', 'vinte') while True: valor=int(input('INFORME O VALOR: ')) if valor>=0 and valor<=20: print(extenso[valor]) break if(valor<0 or valor>20): print('DIGITOU UM VALO INVALIDO. DIGITE ENTRE 0 E 20') ''' #2) ''' tabela=('palmeiras', 'flamengo', 'internacional', 'gremio', 'sao paulo', 'atletico MG', 'atletico PR', 'cruzeiro', 'botafogo', 'santos','bahia', 'fluminense', 'corinthians', 'chapecoense', 'ceara','vasco', 'sport', 'america', 'vitoria', 'parana') c=0 for c in range(0, len(tabela)): if(c<5): print(f'{c+1}º colocado----{str(tabela[c]).upper()}') if(c>=16): print(f'{c+1}º colocado---{str(tabela[c]).upper()}') if(tabela[c]=='sport'): print('SPORT ESTÁ NA POSIÇÃO {}'.format(c+1)) print(sorted(tabela)) ''' #3) ''' import random var1=random.randint(0,10) var2=random.randint(0,10) var3=random.randint(0,10) var4=random.randint(0,10) var5=random.randint(0,10) array=(var1, var2, var3, var4, var5) valormenor=valormaior=0 valormenor=var1 for c in array: if(c>valormaior): valormaior=c if(c<valormenor): valormenor=c print(array) print(f'O valor maior é {valormaior}\nO valor menor é {valormenor}') ''' #4) ''' tres=x=0 num1=int(input('INFORME UM VALOR: ')) num2 = int(input('INFORME UM VALOR: ')) num3 = int(input('INFORME UM VALOR: ')) num4 = int(input('INFORME UM VALOR: ')) dupla=(num1, num2, num3, num4) for x in range(0, len(dupla)): if(dupla[x]==9): print(f'{x}º posição apareceu o 9') x=0 for x in range(0, len(dupla)): if (dupla[x] == 3): tres+=1 print(f'APARECERAM {tres} na dupla') x=0 for x in range(0, len(dupla)): if (dupla[x]%2 == 0): print(f'{dupla[x]}') ''' #5) #lista_de_compras=('feijão', '3.5', 'arroz', '3.2', 'macarrão', '2.0', 'carne', '16.69', 'leite', '3.70', 'fubá', '1.50', 'biscoito', '2.80') #print('\t\t\t****************\n\t\t\tLISTA DE COMPRAS\n\t\t\t****************') #for c in (0, len(lista_de_compras)/2): # print(f'\t\t\t{str(lista_de_compras[c]).upper()}--------{str(lista_de_compras[c+1])}') #6) ''' palavras=('CASA', 'CARRO', 'CANETA', 'COMPUTADOR', 'TECLADO', 'ESTOJO', 'MOUSE', 'LAMPADA', 'LAPIS', 'DEDO', 'BRAÇO', 'MAO') for palavra in palavras: print('\n',palavra,'--->', end=' ') for x in palavra: if x.lower() in 'aeiou': print(x, end=' ') '''
SQL
UTF-8
2,446
3.078125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.4.15.9 -- https://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Apr 22, 2018 at 11:50 AM -- Server version: 5.6.37 -- PHP Version: 7.0.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `filter` -- -- -------------------------------------------------------- -- -- Table structure for table `flt_products` -- CREATE TABLE IF NOT EXISTS `flt_products` ( `product_ID` int(11) NOT NULL, `product_name` text NOT NULL, `brand_name` char(50) NOT NULL, `category_name` char(50) NOT NULL, `product_price` float NOT NULL, `product_image` varchar(255) NOT NULL, `created_at` datetime NOT NULL ) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `flt_products` -- INSERT INTO `flt_products` (`product_ID`, `product_name`, `brand_name`, `category_name`, `product_price`, `product_image`, `created_at`) VALUES (1, 'Galaxy 5s', 'Samsung', 'Electronics', 15000, '343d87f33f1901cde6e4e301795dc9f8.jpg', '2018-04-21 12:33:59'), (2, 'Shirt', 'Manyawar', 'Man', 799, '9c30bb407d3186bf437f4f2e3385020f.jpg', '2018-04-21 13:02:00'), (3, 'Black Perl', 'Titan', 'Watch', 1599, 'd79d073d19b59c5f6591c295fe4732e4.jpg', '2018-04-21 13:18:15'), (4, 'Red Wine', 'Red Chief', 'Shoes', 2500, 'f6934607d53dd1503dd5b5ac18171310.jpg', '2018-04-21 15:06:56'), (5, 'Kurta', 'Manyawar', 'Man', 5999, '2c51ea7937e189b358348ffa4b9a4907.jpg', '2018-04-21 15:30:56'), (6, 'Legies', 'Addidas', 'Woman', 649, '3fc2cdfba34a788ebaa9299fe97d7c37.jpg', '2018-04-21 15:53:56'), (7, 'Best Cooler', 'Symphony', 'Electronics', 5299, '37d8abf0476757a7b937dfe122c87726.jpg', '2018-04-22 08:19:34'); -- -- Indexes for dumped tables -- -- -- Indexes for table `flt_products` -- ALTER TABLE `flt_products` ADD PRIMARY KEY (`product_ID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `flt_products` -- ALTER TABLE `flt_products` MODIFY `product_ID` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=8; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Shell
UTF-8
2,185
4.21875
4
[]
no_license
#!/bin/bash # Script to check for host response to ICMP Timestamp # Timestamp will be converted to current time of day & compared # Output to stdout will display time in ms & H:M:S # # Edit local_tz variable below to adjust time offset to your locale # # Author: Jason Ashton # Created: 08/24/2015 # # Timezone offset - unsigned local_tz=4 # Argument check & usage sname=`basename "$0"` if [ $# -ne 1 ]; then echo echo "Usage: $sname <ip_addr>" echo exit 1 fi # Format Check if ! [[ $1 =~ ^[0-9]{,3}\.[0-9]{,3}\.[0-9]{,3}\.[0-9]{,3}$ ]]; then echo echo "$1 Does Not Contain a Valid IP Address" >&2 echo exit 1 else : fi # Valid IP Address Check addr=( $(echo $1 | tr \. " ") ) if [[ (${addr[0]} -eq 0 || ${addr[0]} -gt 255) || ${addr[1]} -gt 255 \ || ${addr[2]} -gt 255 || ${addr[3]} -gt 255 ]]; then echo echo "$1 Does Not Contain a Valid IP Address" >&2 echo exit else : fi # Ping host for timestamp reply #ip_addr=$1 nping --icmp-type timestamp $1 > ts_tmp.txt # Use Receive Time on count 5 time_ms=$(cat ts_tmp.txt | grep seq=5 | grep RCVD | cut -d" " -f13 | tr \= " " | awk '{print $2}') # Check for Reply if [[ $time_ms -eq 0 ]]; then echo echo "No Reply From Host" echo rm ts_tmp.txt exit 1 else : fi # Subract Local TZ from UTC local_time=$(( $time_ms - ($local_tz * 3600000) )) # Convert ms to s time_s=$(echo "$local_time / 1000" | bc -l) # Convert Hours hours=$(echo "$time_s / 3600" | bc -l | cut -d"." -f1 | awk '{printf ("%02d\n", $1)}') # Convert Minutes hours_rem=$(echo "$time_s / 3600" | bc -l | cut -d"." -f2 | awk '{printf "."$1}') mins=$(echo "$hours_rem * 60" | bc -l | cut -d"." -f1 | awk '{printf ("%02d\n", $1)}') # Convert Seconds mins_rem=$(echo "$hours_rem * 60" | bc -l | cut -d"." -f2 | awk '{printf "."$1}') secs=$(echo "$mins_rem * 60" | bc -l | cut -d"." -f1 | awk '{printf ("%02d\n", $1)}') # Assemble Time in H:M:S time_hms=$(echo "$hours $mins $secs" | awk '{printf $1":"$2":"$3}') time_now=$(date +"%T") echo echo "Host Reply Time in ms = $time_ms" echo "Host Reply Time in H:M:S = $time_hms EDT" echo "Current Time of Day = $time_now" echo rm ts_tmp.txt
C#
UTF-8
1,155
2.9375
3
[]
no_license
using System; namespace SrtTranslator.Core { public class Subtitle { public SubtitleId Id { get; private set; } public SubtitleTimestamps Timestamps { get; private set; } public SubtitleText Text { get; private set; } public Subtitle( SubtitleId id, SubtitleTimestamps timestamps, SubtitleText text) { if (id == null) throw new ArgumentNullException(nameof(id)); if (timestamps == null) throw new ArgumentNullException(nameof(timestamps)); if (text == null) throw new ArgumentNullException(nameof(text)); Id = id; Timestamps = timestamps; Text = text; } public override bool Equals(object obj) { return obj is Subtitle @object && Id.Equals(@object.Id) && Timestamps.Equals(@object.Timestamps) && Text.Equals(@object.Text); } public override int GetHashCode() { return HashCode.Combine(Timestamps, Text); } } }
Java
UTF-8
6,121
1.890625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2023 Google LLC * * 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.cloud.teleport.v2.templates.sinks; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutureCallback; import com.google.api.core.ApiFutures; import com.google.api.gax.batching.BatchingSettings; import com.google.api.gax.retrying.RetrySettings; import com.google.cloud.pubsub.v1.Publisher; import com.google.cloud.teleport.v2.templates.common.TrimmedDataChangeRecord; import com.google.cloud.teleport.v2.templates.constants.Constants; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.ByteString; import com.google.pubsub.v1.PubsubMessage; import com.google.pubsub.v1.TopicName; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.threeten.bp.Duration; /** Class to store connection info and write methods for PubSub. */ public class PubSubSink implements DataSink, Serializable { private static final Logger LOG = LoggerFactory.getLogger(PubSubSink.class); private PubSubConnectionProfile pubSubConn; private Publisher publisher; public PubSubSink(String dataTopicId, String errorTopicId, String endpoint) { this.pubSubConn = new PubSubConnectionProfile(dataTopicId, errorTopicId, endpoint); } public void createClient() throws IOException { long requestBytesThreshold = 100000L; long messageCountBatchSize = 100L; Duration publishDelayThreshold = Duration.ofMillis(100); // Set batching settings. BatchingSettings batchingSettings = BatchingSettings.newBuilder() .setElementCountThreshold(messageCountBatchSize) .setRequestByteThreshold(requestBytesThreshold) .setDelayThreshold(publishDelayThreshold) .build(); // Set retry settings. Duration initialRetryDelay = Duration.ofMillis(100); // default: 100 ms double retryDelayMultiplier = 2.0; // back off for repeated failures, default: 1.3 Duration maxRetryDelay = Duration.ofSeconds(60); // default : 60 seconds Duration initialRpcTimeout = Duration.ofSeconds(2); double rpcTimeoutMultiplier = 1.0; Duration maxRpcTimeout = Duration.ofSeconds(600); // default: 600 seconds Duration totalTimeout = Duration.ofSeconds(600); // default: 600 seconds RetrySettings retrySettings = RetrySettings.newBuilder() .setInitialRetryDelay(initialRetryDelay) .setRetryDelayMultiplier(retryDelayMultiplier) .setMaxRetryDelay(maxRetryDelay) .setInitialRpcTimeout(initialRpcTimeout) .setRpcTimeoutMultiplier(rpcTimeoutMultiplier) .setMaxRpcTimeout(maxRpcTimeout) .setTotalTimeout(totalTimeout) .build(); TopicName topicName = TopicName.of(pubSubConn.getProjectId(), pubSubConn.getDataTopicId()); // Create a publisher and set message ordering to true. this.publisher = Publisher.newBuilder(topicName) // Sending messages to the same region ensures they are received in order // even when multiple publishers are used. .setEndpoint(pubSubConn.getEndpoint()) .setBatchingSettings(batchingSettings) .setRetrySettings(retrySettings) .setEnableMessageOrdering(true) .build(); } public void write(String shardId, List<TrimmedDataChangeRecord> recordsToOutput) throws IOException, IllegalArgumentException, InterruptedException, ExecutionException { List<ApiFuture<String>> messageIdFutures = new ArrayList<>(); List<String> errors = new ArrayList<String>(); try { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); for (TrimmedDataChangeRecord rec : recordsToOutput) { ByteString data = ByteString.copyFromUtf8(ow.writeValueAsString(rec)); PubsubMessage pubsubMessage = PubsubMessage.newBuilder() .setData(data) .putAllAttributes(ImmutableMap.of(Constants.PUB_SUB_SHARD_ID_ATTRIBUTE, shardId)) .setOrderingKey(shardId) .build(); ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage); messageIdFutures.add(messageIdFuture); ApiFutures.addCallback( messageIdFuture, new ApiFutureCallback<String>() { @Override public void onFailure(Throwable throwable) { errors.add(throwable.getMessage()); } @Override public void onSuccess(String messageId) {} }, MoreExecutors.directExecutor()); } } catch (IOException e) { throw new IOException("error during json processing: " + e); } finally { // Wait on any pending publish requests. List<String> messageIds = ApiFutures.allAsList(messageIdFutures).get(); if (publisher != null) { // When finished with the publisher, shutdown to free up resources. publisher.shutdown(); publisher.awaitTermination(1, TimeUnit.MINUTES); } } if (errors.size() != 0) { throw new IllegalStateException( "Could not write batch to sink. Found error(s): " + errors.toString()); } } }
Markdown
UTF-8
6,775
2.796875
3
[]
no_license
## 鸡腿保卫战-EOS概念入门文章 --- ### **百科登场** 简介 > *EOS,可以理解为Enterprise Operation System,即为商用分布式应用设计的一款区块链操作系统。EOS是引入的一种新的区块链架构,旨在实现分布式应用的性能扩展。注意,它并不是像比特币和以太坊那样的货币,而是基于EOS软件项目之上发布的代币,被称为区块链3.0。* 特点 >*1. EOS有点类似于微软的windows平台,通过创建一个对开发者友好的区块链底层平台,支持多个应用同时运行,为开发dAPP提供底层的模板。* >*2. EOS通过并行链和DPOS的方式解决了延迟和数据吞吐量的难题,EOS是每秒可以上千级别的处理量,而比特币每秒7笔左右,以太坊是每秒30-40笔;* >*3. EOS是没有手续费的,普通受众群体更广泛。EOS上开发dApp,需要用到的网络和计算资源是按照开发者拥有的EOS的比例分配的。当你拥有了EOS的话,就相当于拥有了计算机资源,随着DAPP的开发,你可以将手里的EOS租赁给别人使用,单从这一点来说EOS也具有广泛的价值。简单来说,就是你拥有了EOS,就相当于拥有了一套房租给别人收房租,或者说拥有了一块地租给别人建房。* --- ### **EOS中文社区的wiki列表(有点老了,但啃起来还是香)** <li><a class="page" href="/wiki/api-serializer">EOSFans API 数据类型</a></li> <li><a class="page" href="/wiki/api-index">EOSFans API 目录</a></li> <li><a class="page" href="/wiki/api">EOSFans API 快速开始</a></li> <li><a class="page" href="/wiki/index">EOS技术开发资料汇总</a></li> <li><a class="page" href="/wiki/development-tools">EOS效率工具</a></li> <li><a class="page" href="/wiki/eos-releases">EOS版本计划</a></li> <li><a class="page" href="/wiki/tutorials">EOS开发新手教程</a></li> <li><a class="page" href="/wiki/glossary">EOS词汇表</a></li> <li><a class="page" href="/wiki/hello-word-contracts">EOS Hello Word 智能合约</a></li> <li><a class="page" href="/wiki/eosio-token-contract">Eosio.token,Exchange和Eosio.msig合约</a></li> <li><a class="page" href="/wiki/introduction-to-eosio-smart-contract">EOS智能合约入门</a></li> <li><a class="page" href="/wiki/smart-contracts">EOS智能合约</a></li> <li><a class="page" href="/wiki/persistence-api">EOS持久化API</a></li> <li><a class="page" href="/wiki/cli-wallet">EOS命令行钱包</a></li> <li><a class="page" href="/wiki/programs-tools">程序和工具</a></li> <li><a class="page" href="/wiki/local-environment">设置本地环境</a></li> <li><a class="page" href="/wiki/account-permission">EOS账户权限</a></li> <li><a class="page" href="/wiki/cleos-command-reference">Cleos命令使用指南</a></li> <li><a class="page" href="/wiki/eosiodb">EOSIO 3.0 数据库使用指南</a></li> <li><a class="page" href="/wiki/contributors">EOS中文社区贡献者名单</a></li> <li><a class="page" href="/wiki/eos-party-testnet">EOS Party 测试网络</a></li> <li><a class="page" href="/wiki/eos3-smart-contract">EOS3.0-智能合约</a></li> <li><a class="page" href="/wiki/emergency">应急方案</a></li> <li><a class="page" href="/wiki/contact">联系我们</a></li> <li><a class="page" href="/wiki/about">关于我们</a></li> --- ### **EOS系列导航** <p><a href="https://github.com/EOSIO/eos">Github</a> <a href="https://github.com/EOSIO/Documentation/blob/master/TechnicalWhitePaper.md">白皮书</a> <a href="https://github.com/EOSIO/eos/releases">版本列表</a></p> <p><span id="more-2"></span></p> <p><strong>#开发文档</strong></p> <p><a href="https://developers.eos.io/">EOS Developer</a> <a href="https://github.com/superoneio/awesome-eos">Awesome-EOS</a> <a href="https://developers.eos.io/eosio-nodeos/reference">HTTP API</a> <a href="https://github.com/slowmist/eos-smart-contract-security-best-practices">慢雾安全指南</a></p> <p><!--more--></p> <p><strong>#测试网</strong></p> <p><a href="http://blog.eosdata.io/index.php/2018/11/05/jungle-eos-testnet/">Jungle 测试网</a> <a href="http://blog.eosdata.io/index.php/2018/09/25/cryptokylin-eos-testnet/">麒麟测试网</a> <a href="http://blog.eosdata.io/index.php/2020/01/17/eosio-guan-fang-testnet/">官方Testnet</a></p> <p><!--more--></p> <p><strong>#环境配置</strong></p> <p><a href="https://github.com/eoshackathon/eos_dapp_development_cn">开发配置(中文)</a> <a href="https://dev4eos.com/#/">部署工具Dev4eos</a> <a href="https://beosin.com/EOS-IDE/index.html#/">部署工具Beosin</a> <a href="http://app.eosstudio.io/">部署工具EOSstudio</a> <a href="https://validate.eosnation.io/mainnet/reports/endpoints.html">RPC Endpoint</a></p> <p><!--more--></p> <p><strong>#Scatter 接口开发</strong></p> <p><a href="https://github.com/MediShares/scatter-eos-sample">ScatterSample</a> <a href="https://github.com/eoshackathon/eos_dapp_development_cn/blob/master/docs/eosjs_manual.md">eosjs 说明文档</a> <a href="https://www.youtube.com/playlist?list=PLyM_BB-jMJPrj79ykPNQPgJ5kinwLi8W_">EOS应用开发视频教程</a></p> <p><!--more--></p> <p><strong>#ÐApps 排行</strong></p> <p><a href="https://dapp.review/explore/eos">DAppReview</a> <a href="https://dappradar.com/eos-dapps">DAppRadar</a> <a href="https://www.spider.store/">SpiderStore</a></p> <p><!--more--></p> <p><strong>#区块浏览器</strong></p> <p><a href="http://eosflare.io">EOS Flare</a> <a href="https://www.myeoskit.com/">MyEOSKit</a> <a href="https://eospark.com/">EOSPark</a> <a href="https://www.bloks.io/">Bloks</a></p> <p><!--more--></p> <p><strong>#开发社区</strong></p> <p><a href="https://steemit.com/trending/eosdev">Steem EOS频道</a> <a href="http://blog.eosdata.io/index.php/xiaomq/">EOS开发微信群</a> <a href="https://eoshackathon.io/">EOSHackathon</a> <a href="https://eosio.stackexchange.com/">Stack Exchange</a></p> <p><!--more--></p> <p><strong>#侧链</strong></p> <p><a href="https://www.eosforce.io/">EOS原力</a> <a href="https://boscore.io/">BOS</a> <a href="https://enumivo.org/">ENU</a> <a href="https://telosfoundation.io/">Telos</a> <a href="https://worbli.io/">Worbli</a> <a href="https://meet.one">MEETONE</a></p> <p><!--more--></p> <p>#其它相关网站</p> <p><a href="https://eos.io/">EOS.io</a> <a href="https://medium.com/eosio">EOS Blog</a> <a href="http://block.one/">BlockONE</a> <a href="https://ecaf.io/">ECAF</a></p> <p><a href="https://steemit.com/@dan">Dan@Steem</a> <a href="https://medium.com/@bytemaster">Dan@Medium</a> <a href="https://github.com/bytemaster">ByteMaster</a> <a href="https://www.reddit.com/r/eos/">Reddit</a></p> </div>
C#
UTF-8
1,507
2.921875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Configuration; namespace SafeConnectCore { public class Logger { private const string LOG_ENABLED_KEY = "LogEnabled"; private static readonly string LOG_DIRECTORY = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SafeConnect"); private static readonly string LOG_FILE_NANE = "SafeConnectLog.txt"; private static readonly string LOG_PATH = Path.Combine(LOG_DIRECTORY, LOG_FILE_NANE); private static readonly long MAX_FILE_SIZE = 1024 * 20; public static void Log(string message) { bool logEnabled = Boolean.Parse(ConfigurationManager.AppSettings[LOG_ENABLED_KEY]); if (logEnabled) { if (!Directory.Exists(LOG_DIRECTORY)) { Directory.CreateDirectory(LOG_DIRECTORY); } FileInfo logFileInfo = new FileInfo(LOG_PATH); if (logFileInfo.Exists && logFileInfo.Length > MAX_FILE_SIZE) { logFileInfo.Delete(); } using (StreamWriter logfile = new StreamWriter(LOG_PATH, true)) { logfile.WriteLine(System.DateTime.Now.ToString("M/d/yy h:mm:ss") + " - " + message); logfile.Close(); } } } } }
Java
UTF-8
20,086
2.15625
2
[]
no_license
package com.kaplanteam.cathy.dangerparty.Level3; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Color; import android.os.Bundle; import android.os.CountDownTimer; import android.support.annotation.Nullable; import android.support.constraint.ConstraintLayout; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.kaplanteam.cathy.dangerparty.EndGameActivity; import com.kaplanteam.cathy.dangerparty.R; /** * Created by Cole on 4/1/18. */ public class FragmentLevel3A extends Fragment implements View.OnClickListener { private Button moistyTequila, backtrack; private ImageView sapphire, ruby, diamond, emerald, amethyst, topaz, left_cave, right_cave, flashlight, bat1, bat2, bat3, bat4, bat5, sglow, rglow, dglow, eglow, aglow, tglow; private ConstraintLayout background; private boolean lightOn; private View timerView; private final int MILLIS_IN_FUTURE = 7000; private final int COUNT_DOWN_INTERVAL = 100; private final float SCREEN_WIDTH = Resources.getSystem().getDisplayMetrics().widthPixels; private CountDownTimer t; private final int NUMBER_OF_STRINGS = 11; private String[] strings; private final int NUMBER_OF_STRINGS_DARK = 12; private String[] stringsDark; private TextView text; private boolean popS, popM, popL; private int swirl; private int successScore; private int failScore; private final int MOVE_ON_SUCCESSES = 10; private final int END_GAME_FAILURES = 5; private ImageView liveOne, liveTwo, liveThree, liveFour, liveFive; private ImageView[] img; private Fragment currentFragment; private boolean firstTime; private SharedPreferences counter; private SharedPreferences.Editor editor; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View rootView = inflater.inflate(R.layout.level3a, container, false); counter = getActivity().getSharedPreferences("HELLO", Context.MODE_PRIVATE); editor = counter.edit(); //wire any widgets -- must use rootView.findViewById lightOn = true; firstTime = true; wireWidgets(rootView); setListeners(); img = new ImageView[5]; img[0] = liveFive; img[1] = liveFour; img[2] = liveThree; img[3] = liveTwo; img[4] = liveOne; strings = new String[NUMBER_OF_STRINGS]; strings[0] = "Snatch the sapphire"; strings[1] = "Rub the ruby"; strings[2] = "Abduct the diamond"; strings[3] = "Extract the emerald"; strings[4] = "Palpate the amethyst"; strings[5] = "Tap the topaz"; strings[6] = "Moisty Tequila"; strings[7] = "Take the left fork of the cave path"; strings[8] = "Take the right fork of the cave path"; strings[9] = "Backtrack"; strings[10] = "Turn off the light"; stringsDark = new String[NUMBER_OF_STRINGS_DARK]; stringsDark[0] = "Snatch the sapphire"; stringsDark[1] = "Rub the ruby"; stringsDark[2] = "Abduct the diamond"; stringsDark[3] = "Extract the emerald"; stringsDark[4] = "Palpate the amethyst"; stringsDark[5] = "Tap the topaz"; stringsDark[6] = "Moisty Tequila"; stringsDark[7] = "Take the left fork of the cave path"; stringsDark[8] = "Take the right fork of the cave path"; stringsDark[9] = "Backtrack"; stringsDark[10] = "Turn on the light"; stringsDark[11] = "Put the bats to sleep"; text.setText("Level 3: Cave of Nightmares");// could make ready set go or other animation type thing //get any other initial set up done t = new CountDownTimer(MILLIS_IN_FUTURE, COUNT_DOWN_INTERVAL) { @Override public void onTick(long l) { timerView.setX(l / (float) MILLIS_IN_FUTURE * SCREEN_WIDTH - SCREEN_WIDTH); } @Override public void onFinish() { if(firstTime){ text.setText(strings[(int)(Math.random()*NUMBER_OF_STRINGS)]); t.start(); firstTime = false; } else{ timerView.setX(0 - SCREEN_WIDTH); //closer to death failScore++; if(failScore >= END_GAME_FAILURES){ //End Game editor.putInt("score", successScore*100); editor.commit(); Intent i = new Intent(getActivity(), EndGameActivity.class); startActivity(i); } else{ img[END_GAME_FAILURES - failScore].setVisibility(View.INVISIBLE); text.setText(strings[(int)(Math.random()*NUMBER_OF_STRINGS)]); t.start(); } } } }.start(); //return the view that we inflated return rootView; } private void wireWidgets(View rootView) { moistyTequila = rootView.findViewById(R.id.button_moisty_tequila); backtrack = rootView.findViewById(R.id.button_backtrack); sapphire = rootView.findViewById(R.id.imageView_sapphire); ruby = rootView.findViewById(R.id.imageView_ruby); diamond = rootView.findViewById(R.id.imageView_diamond); emerald = rootView.findViewById(R.id.imageView_emerald); amethyst = rootView.findViewById(R.id.imageView_amethyst); topaz = rootView.findViewById(R.id.imageView_topaz); left_cave = rootView.findViewById(R.id.imageView_left_cave); right_cave = rootView.findViewById(R.id.imageView_right_cave); flashlight = rootView.findViewById(R.id.imageView_flashlight); background = rootView.findViewById(R.id.level3a_background); bat1 = rootView.findViewById(R.id.imageView_bat1); bat2 = rootView.findViewById(R.id.imageView_bat2); bat3 = rootView.findViewById(R.id.imageView_bat3); bat4 = rootView.findViewById(R.id.imageView_bat4); bat5 = rootView.findViewById(R.id.imageView_bat5); sglow = rootView.findViewById(R.id.imageView_sapp_glow); rglow = rootView.findViewById(R.id.imageView_ruby_glow); dglow = rootView.findViewById(R.id.imageView_dia_glow); eglow = rootView.findViewById(R.id.imageView_emer_glow); tglow = rootView.findViewById(R.id.imageView_top_glow); aglow = rootView.findViewById(R.id.imageView_ame_glow); timerView = rootView.findViewById(R.id.timer); text = rootView.findViewById(R.id.textView); liveOne = rootView.findViewById(R.id.imageView_live_one); liveTwo = rootView.findViewById(R.id.imageView_live_two); liveThree = rootView.findViewById(R.id.imageView_live_three); liveFour = rootView.findViewById(R.id.imageView_live_four); liveFive = rootView.findViewById(R.id.imageView_live_five); } private void setListeners() { moistyTequila.setOnClickListener(this); backtrack.setOnClickListener(this); sapphire.setOnClickListener(this); ruby.setOnClickListener(this); diamond.setOnClickListener(this); emerald.setOnClickListener(this); amethyst.setOnClickListener(this); topaz.setOnClickListener(this); left_cave.setOnClickListener(this); right_cave.setOnClickListener(this); flashlight.setOnClickListener(this); bat1.setOnClickListener(this); bat2.setOnClickListener(this); bat3.setOnClickListener(this); bat4.setOnClickListener(this); bat5.setOnClickListener(this); } @Override public void onClick(View view) { switch(view.getId()){ case R.id.imageView_flashlight: if(lightOn){ lightOn = false; flashlight.setImageResource(R.drawable.light_off); background.setBackgroundColor(Color.BLACK); bat1.setVisibility(View.VISIBLE); bat2.setVisibility(View.VISIBLE); bat3.setVisibility(View.VISIBLE); bat4.setVisibility(View.VISIBLE); bat5.setVisibility(View.VISIBLE); ruby.setImageResource(R.drawable.ruby_dark); sapphire.setImageResource(R.drawable.sapp_dark); emerald.setImageResource(R.drawable.emer_dark); diamond.setImageResource(R.drawable.dia_dark); topaz.setImageResource(R.drawable.top_dark); amethyst.setImageResource(R.drawable.ame_dark); sglow.setVisibility(View.VISIBLE); rglow.setVisibility(View.VISIBLE); eglow.setVisibility(View.VISIBLE); dglow.setVisibility(View.VISIBLE); tglow.setVisibility(View.VISIBLE); aglow.setVisibility(View.VISIBLE); if(text.getText().equals("Turn off the light")){ success(); } else{ successScore--; } } else{ lightOn = true; flashlight.setImageResource(R.drawable.light_on); background.setBackgroundColor(Color.WHITE); bat1.setVisibility(View.INVISIBLE); bat2.setVisibility(View.INVISIBLE); bat3.setVisibility(View.INVISIBLE); bat4.setVisibility(View.INVISIBLE); bat5.setVisibility(View.INVISIBLE); ruby.setImageResource(R.drawable.ruby); sapphire.setImageResource(R.drawable.sapphire); emerald.setImageResource(R.drawable.emerald); diamond.setImageResource(R.drawable.diamond); topaz.setImageResource(R.drawable.topaz); amethyst.setImageResource(R.drawable.amethyst); sglow.setVisibility(View.INVISIBLE); rglow.setVisibility(View.INVISIBLE); eglow.setVisibility(View.INVISIBLE); dglow.setVisibility(View.INVISIBLE); tglow.setVisibility(View.INVISIBLE); aglow.setVisibility(View.INVISIBLE); if(text.getText().equals("Turn on the light")){ success(); } else{ successScore--; } } break; case R.id.imageView_sapphire: if(text.getText().equals(strings[0])){ success(); } else { successScore--; } break; case R.id.imageView_ruby: if(text.getText().equals(strings[1])){ success(); } else { successScore--; } break; case R.id.imageView_diamond: if(text.getText().equals(strings[2])){ success(); } else { successScore--; } break; case R.id.imageView_emerald: if(text.getText().equals(strings[3])){ success(); } else { successScore--; } break; case R.id.imageView_amethyst: if(text.getText().equals(strings[4])){ success(); } else { successScore--; } break; case R.id.imageView_topaz: if(text.getText().equals(strings[5])){ success(); } else { successScore--; } break; case R.id.button_moisty_tequila: if(text.getText().equals(strings[6])){ success(); } else { successScore--; } break; case R.id.imageView_left_cave: if(text.getText().equals(strings[7])){ success(); } else { successScore--; } break; case R.id.imageView_right_cave: if(text.getText().equals(strings[8])){ success(); } else { successScore--; } break; case R.id.button_backtrack: if(text.getText().equals(strings[9])){ success(); } else { successScore--; } break; case R.id.imageView_bat1: if(text.getText().equals(stringsDark[11]) && bat2.getVisibility() == View.INVISIBLE && bat3.getVisibility() == View.INVISIBLE && bat4.getVisibility() == View.INVISIBLE && bat5.getVisibility() == View.INVISIBLE){ // will need to change later for 2 people ----------------------------------------------- success(); } else if (!text.getText().equals(stringsDark[11])){ successScore--; } bat1.setVisibility(View.INVISIBLE); CountDownTimer timers1 = new CountDownTimer(6000, 2000) { @Override public void onTick(long l) { } @Override public void onFinish() { if(!lightOn){ bat1.setVisibility(View.VISIBLE); } } }.start(); break; case R.id.imageView_bat2: if(text.getText().equals(stringsDark[11]) && bat1.getVisibility() == View.INVISIBLE && bat3.getVisibility() == View.INVISIBLE && bat4.getVisibility() == View.INVISIBLE && bat5.getVisibility() == View.INVISIBLE){ // will need to change later for 2 people ----------------------------------------------- success(); } else if (!text.getText().equals(stringsDark[11])){ successScore--; } bat2.setVisibility(View.INVISIBLE); CountDownTimer timers2 = new CountDownTimer(6000, 2000) { @Override public void onTick(long l) { } @Override public void onFinish() { if(!lightOn){ bat2.setVisibility(View.VISIBLE); } } }.start(); break; case R.id.imageView_bat3: if(text.getText().equals(stringsDark[11]) && bat2.getVisibility() == View.INVISIBLE && bat1.getVisibility() == View.INVISIBLE && bat4.getVisibility() == View.INVISIBLE && bat5.getVisibility() == View.INVISIBLE){ // will need to change later for 2 people ----------------------------------------------- success(); } else if (!text.getText().equals(stringsDark[11])){ successScore--; } bat3.setVisibility(View.INVISIBLE); CountDownTimer timers3 = new CountDownTimer(6000, 2000) { @Override public void onTick(long l) { } @Override public void onFinish() { if(!lightOn){ bat3.setVisibility(View.VISIBLE); } } }.start(); break; case R.id.imageView_bat4: if(text.getText().equals(stringsDark[11]) && bat2.getVisibility() == View.INVISIBLE && bat3.getVisibility() == View.INVISIBLE && bat1.getVisibility() == View.INVISIBLE && bat5.getVisibility() == View.INVISIBLE){ // will need to change later for 2 people ----------------------------------------------- success(); } else if (!text.getText().equals(stringsDark[11])){ successScore--; } bat4.setVisibility(View.INVISIBLE); CountDownTimer timers4 = new CountDownTimer(6000, 2000) { @Override public void onTick(long l) { } @Override public void onFinish() { if(!lightOn){ bat4.setVisibility(View.VISIBLE); } } }.start(); break; case R.id.imageView_bat5: if(text.getText().equals(stringsDark[11]) && bat2.getVisibility() == View.INVISIBLE && bat3.getVisibility() == View.INVISIBLE && bat4.getVisibility() == View.INVISIBLE && bat1.getVisibility() == View.INVISIBLE){ // will need to change later for 2 people ----------------------------------------------- success(); } else if (!text.getText().equals(stringsDark[11])){ successScore--; } bat5.setVisibility(View.INVISIBLE); CountDownTimer timers5 = new CountDownTimer(6000, 2000) { @Override public void onTick(long l) { } @Override public void onFinish() { if(!lightOn){ bat5.setVisibility(View.VISIBLE); } } }.start(); break; } } private void success(){ t.cancel(); successScore++; if(successScore >= MOVE_ON_SUCCESSES){ //move to next level editor.putInt("score", successScore*100); editor.commit(); Intent i = new Intent(getActivity(), EndGameActivity.class); startActivity(i); } else{ if(lightOn){ text.setText(strings[(int)(Math.random()*NUMBER_OF_STRINGS)]); t.start(); } else{ text.setText(stringsDark[(int)(Math.random()*NUMBER_OF_STRINGS_DARK)]); t.start(); } } } @Override public void onPause() { super.onPause(); t.cancel(); } }
Java
UTF-8
1,274
3.609375
4
[]
no_license
import java.util.ArrayList; import java.util.stream.*; public class StreamReview{ public static void main(String[] args){ ArrayList<String> list1 = new ArrayList<>(); list1.add("test"); list1.add("string"); list1.add("hello"); list1.stream() .filter((t) -> t.length() <= 5) .forEach((t) -> System.out.println(t)); ArrayList<Integer> list2 = new ArrayList<>(); list2.add(1); list2.add(3); list2.add(4); list2.add(5); long count = list2.stream() .filter((t) -> t%2 == 1) .count(); System.out.println(count); ArrayList<Double> list3 = new ArrayList<>(); list3.add(3.4); list3.add(3.7); list3.add(5.5); Stream<Double> str = list3.stream(); str.map((t) -> Math.round(t)).forEach((t) -> System.out.println(t)); ArrayList<Students> list4 = new ArrayList<>(); list4.add(new Students("Hunter", "McDonaldson")); list4.add(new Students("John" , "Doe")); list4.add(new Students("James", "Doe")); list4.stream() .map((t) -> t.getLastName()) .distinct() .forEach((t) -> System.out.println(t)); list1.stream() .map((t) -> t.hashCode()) .forEach((t) -> System.out.println(t)); list1.stream() .distinct() .map((t) -> t.length()) .sorted() .forEach((t) -> System.out.println(t)); } }
C#
UTF-8
1,434
2.796875
3
[]
no_license
using System.Net; using System.Net.Mail; using System.Text; using System.Threading.Tasks; using Application.Interfaces; using Microsoft.Extensions.Options; namespace Infrastructure.Email { public class EmailSender : IEmailSender { private readonly SMTPConfigModel _smtpConfig; public EmailSender(IOptions<SMTPConfigModel> smtpConfig) { _smtpConfig = smtpConfig.Value; } public async Task SendEmailAsync(string userEmail, string emailSubject, string msg) { MailMessage mail = new MailMessage { Subject = emailSubject, Body = msg, From = new MailAddress(_smtpConfig.SenderAddress, _smtpConfig.SenderDisplayName), IsBodyHtml = _smtpConfig.IsBodyHTML }; mail.To.Add(userEmail); NetworkCredential networkCredential = new NetworkCredential(_smtpConfig.UserName, _smtpConfig.Password); SmtpClient smtpClient = new SmtpClient { Host = _smtpConfig.Host, Port = _smtpConfig.Port, EnableSsl = _smtpConfig.EnableSSL, UseDefaultCredentials = _smtpConfig.UseDefaultCredentials, Credentials = networkCredential }; mail.BodyEncoding = Encoding.Default; await smtpClient.SendMailAsync(mail); } } }
Python
UTF-8
155
3.078125
3
[ "MIT" ]
permissive
class AlarmError(Exception): @classmethod def NoMatchingAlarm(cls, name: str): return cls(f'Unable to find alarm matching name: {name}.')
Java
UTF-8
1,103
3.71875
4
[]
no_license
package day51; import java.util.Stack; public class MinStack { //create 2 stack one normal stack private Stack<Integer> stackData; //one stack only stores min number in every step see push private Stack<Integer> stackMin; public MinStack() { this.stackData = new Stack<Integer>(); this.stackMin = new Stack<Integer>(); } public void push(int x) { if(this.stackMin.isEmpty()) this.stackMin.push(x); else if(x <= this.getMin()) this.stackMin.push(x); this.stackData.push(x); } public void pop() { if(this.stackData.isEmpty()){ throw new RuntimeException("Your stack is empty"); } if(this.stackData.peek() == this.stackData.peek()){ this.stackMin.pop(); } this.stackData.pop(); } public int top() { return this.stackData.peek(); } public int getMin() { if(this.stackMin.isEmpty()) throw new RuntimeException("Your stack is empty"); return stackMin.peek(); } public void main(String[] args) { } }
Markdown
UTF-8
587
2.9375
3
[]
no_license
# 第1回 Pythonの基本的な関数の使い方とデバッグ方法 ここでは,Pythonの基本的な関数の使い方とデバッグ方法について勉強しましょう. まずは説明を読んで,練習問題に取り組みましょう. - [説明:Pythonの基本的な関数の使い方とデバッグ方法](https://github.com/Shimamura-Lab-SU/Sharing-Knowledge-Database/blob/master/python_exercise/01_basic/description.md) - [練習問題1](https://github.com/Shimamura-Lab-SU/Sharing-Knowledge-Database/blob/master/python_exercise/01_basic/exercise.md)
Java
UTF-8
792
2.078125
2
[]
no_license
package activities; import java.util.Map; import entities.Comment; public class CommentEnviar extends Comment { private Map hora; public CommentEnviar(Map hora) { this.hora = hora; } public CommentEnviar() { } public CommentEnviar(String comment, String nombre, String urlFoto, String fotoPerfil, String type_message, Map hora) { super(comment, nombre, urlFoto, fotoPerfil, type_message); this.hora = hora; } public CommentEnviar(String comment, String nombre, String fotoPerfil, String type_message, Map hora) { super(comment, nombre, fotoPerfil, type_message); this.hora = hora; } public Map getHora() { return hora; } public void setHora(Map hora) { this.hora = hora; } }
Java
UTF-8
1,177
2.9375
3
[]
no_license
package com.nelliott.noahcollegeapp; public class Guardian extends FamilyMember{ String mLastName; String mFirstName; String mOccupation; String mObjectId; @Override public String getFirstName() { return mFirstName; } @Override public void setFirstName(String firstName) { mFirstName = firstName; } @Override public String getLastName() { return mLastName; } @Override public void setLastName(String lastName) { mLastName = lastName; } public Guardian(String firstName, String lastName){ super(firstName, lastName); mOccupation = "unknown"; } public Guardian(){ super(); mOccupation = "unknown"; } public Guardian(String firstName, String lastName, String occupation){ mFirstName = firstName; mLastName = lastName; mOccupation = occupation; } @Override public String toString(){ return("Guardian: " + mFirstName + " " + mLastName + "\n Occupation: " + mOccupation); } public void setObjectId(String objectId) { mObjectId = objectId; } public String getObjectId() { return mObjectId; } }
Java
UTF-8
464
1.765625
2
[]
no_license
package my.study.dataprepare.bean; import lombok.Data; import java.io.Serializable; import java.sql.Timestamp; @Data public class ForexTrade implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String deal; private String login; private String type; private String symbol; private Double volume; private Timestamp opentime; private Timestamp closetime; private Double profit; }
Java
UTF-8
578
2.515625
3
[]
no_license
package com.eomcs.util; // 클라이언트의 요청 정보를 다루는 역할 public class CommandRequest01 { private String commandPath; private String remoteAddr; private int remotePort; public CommandRequest01(String commandPath, String remoteAddr, int remotePort) { this.commandPath = commandPath; this.remoteAddr = remoteAddr; this.remotePort = remotePort; } public String getCommandPath() { return commandPath; } public String getRemoteAddr() { return remoteAddr; } public int getRemotePort() { return remotePort; } }
Java
UTF-8
964
3.15625
3
[]
no_license
package StepDefinitions; public class _01_LoginFunction { // // @Given("^Navigate to the website$") // public void navigate_to_the_website() { // System.out.println("Navigate to website"); // } // // @When("^User enters valid username and password$") // public void user_enters_valid_username_and_password() { // System.out.println("Enter username and password"); // } // // @Then("^User should be able to login their account$") // public void user_should_be_able_to_login_their_account() { // System.out.println("Login successful"); // } // // @When("User enters invalid username and password") // public void user_enters_invalid_username_and_password() { // System.out.println("Enter invalid username and password"); // } // // @Then("User should not login to their account") // public void user_should_not_login_to_their_account() { // System.out.println("Login failed"); // } }
Java
UTF-8
1,984
2.34375
2
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/** * Tencent is pleased to support the open source community by making Tseer available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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.qq.seer.common.log; import java.io.PrintWriter; import java.io.StringWriter; /** * 日志处理 * */ public class LogUtils { public static void localLogInfo(long logId, String info) { long tid = Thread.currentThread().getId(); String logInfo = "[" + logId + "][" + tid + "]" + info; System.out.println(logInfo); } public static void localLogError(long logId, String error, Throwable th) { long tid = Thread.currentThread().getId(); String logError = "[" + logId + "][" + tid + "]" + error; System.out.println(logError); StringWriter sw = new StringWriter(); th.printStackTrace(new PrintWriter(sw, true)); String rtnValue = sw.toString(); System.out.println(rtnValue); } public static void localLogError(long logId, String error) { long tid = Thread.currentThread().getId(); String logError = "[" + logId + "][" + tid + "]" + error; System.out.println(logError); } public static void localLogInfo(String info) { long logId = 0; localLogInfo(logId, info); } public static void localLogError(String error, Throwable th) { long logId = 0; localLogError(logId, error, th); } public static void localLogError(String error) { long logId = 0; localLogError(logId, error); } }
Python
UTF-8
2,375
2.71875
3
[]
no_license
from json_reader import get_tweets, get_contains, get_most_common import nltk from nltk.collocations import * from nltk import ngrams #removes all words before the word for (inc) def clean_awards(awards): new = [] for i in awards: if i.find(" rt ") != -1 or i.find(" rt") != -1 or i[0:3] == "rt ": continue in1 = i.find(" golden globe for best") in2 = i.find(" nominated for best") if (in1 != -1): new.append(i[in1 + 18:]) else: new.append(i[in2 + 15:]) return new def remove_banned(awards, banned): for i in range(len(awards)-2, -1, -1): for j in banned: if (awards[i].find(j) != -1): awards.pop(i) def filter_noise(awards): new = [] stop_signal = [".", "#", ",","?", "for", "!", ":", "goes to", "should", "at", "@", "like"] for i in range(len(awards)): lowest = 100 for j in stop_signal: temp = awards[i].find(j) if (temp < lowest and temp != -1): lowest = temp new.append(awards[i][:lowest]) return new def is_in(word1, word2): split1 = word1.split() for i in split1: if (not (i in word2)): return False return True def is_similar(word, word_list): out = word_list.copy() for i in range(len(word_list)): east = is_in(word_list[i], word) west = is_in(word, word_list[i]) if (east): out[i] = word return out elif (west): return out out.append(word) return out def longest_discrete(awards): finalized = [] for i in awards: finalized = is_similar(i, finalized) finalized = compress(finalized) finalized.sort(key=sizeify) return finalized[-26:] def sizeify(word): return len(word) def compress(a): seen = set() result = [] for item in a: if item not in seen: seen.add(item) result.append(item) return result def awards_get(tweets): awards = [] relevant = get_contains(tweets," golden globe for best", "goldenglobes") awards.extend(relevant) relevant = get_contains(tweets," nominated for best", "goldenglobes") awards.extend(relevant) awards = clean_awards(awards) banned = ["something", "anything", "everything", "oscar", "golden globe", "academy award", "academyaward", "emmy", "awards"] remove_banned(awards, banned) awards = filter_noise(awards) final = longest_discrete(awards) return final
Python
UTF-8
57
2.546875
3
[]
no_license
print("hello world") x = 2 if(x == 2): print("test")
C
UTF-8
1,470
2.703125
3
[]
no_license
/* * cachelab.h - Prototypes for Cache Lab helper functions */ #ifndef CACHELAB_TOOLS_H #define CACHELAB_TOOLS_H #define MAX_TRANS_FUNCS 100 typedef struct trans_func{ void (*func_ptr)(int M,int N,int[N][M],int[M][N]); char* description; char correct; unsigned int num_hits; unsigned int num_misses; unsigned int num_evictions; } trans_func_t; typedef long long unsigned int address_t; typedef struct lineStruct Line; typedef struct setStruct Set; typedef struct cacheStruct Cache; struct lineStruct { unsigned long long int tag_index; Line *next; Line *prev; int valid; int tag; }; struct setStruct { Line *head; Line *tail; int count; }; struct cacheStruct { Set *cacheSets; int m; int s; int E; int b; int verbose; }; /* * printSummary - This function provides a standard way for your cache * simulator * to display its final hit and miss statistics */ void printSummary(int hits, /* number of hits */ int misses, /* number of misses */ int evictions); /* number of evictions */ /* Fill the matrix with data */ void initMatrix(int M, int N, int A[N][M], int B[M][N]); /* The baseline trans function that produces correct results. */ void correctTrans(int M, int N, int A[N][M], int B[M][N]); /* Add the given function to the function list */ void registerTransFunction( void (*trans)(int M,int N,int[N][M],int[M][N]), char* desc); #endif /* CACHELAB_TOOLS_H */
JavaScript
UTF-8
3,070
3.078125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// This example requires the Places library. Include the libraries=places // parameter when you first load the API. For example: // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: 20.593684, lng: 78.96288000000004}, zoom: 6 }); var card = document.getElementById('pac-card'); var input = document.getElementById('pac-input'); var latitude = document.getElementById('latitude'); var longitude = document.getElementById('longitude'); var google_place_name = document.getElementById('google_place_name'); var google_place_address = document.getElementById('google_place_address'); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card); var autocomplete = new google.maps.places.Autocomplete(input); // Bind the map's bounds (viewport) property to the autocomplete object, // so that the autocomplete requests use the current map bounds for the // bounds option in the request. autocomplete.bindTo('bounds', map); var infowindow = new google.maps.InfoWindow(); var infowindowContent = document.getElementById('infowindow-content'); infowindow.setContent(infowindowContent); var marker = new google.maps.Marker({ map: map, anchorPoint: new google.maps.Point(0, -29) }); // prevent page refresh on clicking enter for google place selections $('form').keypress(function(e) { return e.keyCode != 13; }); // call when address exists after form invalidates if(latitude.value !== "" && longitude.value !== "") { setLocation(); } // call event when user types a new location autocomplete.addListener('place_changed', function() { infowindow.close(); marker.setVisible(false); var place = autocomplete.getPlace(); if (!place.geometry) { // User entered the name of a Place that was not suggested and // pressed the Enter key, or the Place Details request failed. return; } latitude.value = place.geometry.location.lat(); longitude.value = place.geometry.location.lng(); var address = ''; if (place.address_components) { address = [ (place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '') ].join(' '); } google_place_name.value = place.name; google_place_address.value = address; setLocation(); }); function setLocation() { var location = new google.maps.LatLng(latitude.value, longitude.value); map.setCenter(location); map.setZoom(17); setMarker(location); setInfoWindow(google_place_name.value, google_place_address.value); } function setMarker(location) { marker.setPosition(location); marker.setVisible(true); } function setInfoWindow(name, address) { infowindowContent.children['place-name'].textContent = name; infowindowContent.children['place-address'].textContent = address; infowindow.open(map, marker); } }
Java
UTF-8
1,753
2.4375
2
[]
no_license
package com.sunsoft_supplier.net.network; import android.os.CountDownTimer; import com.sunsoft_supplier.net.checknet.CheckNet; import com.sunsoft_supplier.utils.LogUtil; import com.sunsoft_supplier.utils.ToastUtil; import okhttp3.Call; /** * 监听网络请求时间 * Created by MJX on 2017/4/17. */ public class HttpCountDown { private static CountDownTimer countDownTimer; /** * 是否需要取消当前的request请求,false不取消当前的请求,true取消当前的请求 */ private static boolean cancelCurrentRequest; /** * 是否已经取消了当前的请求 */ public static boolean hasCanceledCurrentRequest = false; public static void startCountDownRequestHttp(final Call call, final HttpMethod.OnDataFinish onDataFinish) { cancelCurrentRequest = false; hasCanceledCurrentRequest = false; countDownTimer = new CountDownTimer(10000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { endCountDownTime(); if (call != null) { call.cancel(); hasCanceledCurrentRequest = true; onDataFinish.OnError("超时"); if (CheckNet.isHaveNetWork()) { ToastUtil.toastDes("网络连接失败"); LogUtil.logMsg("网络连接失败-----------定时器onFinish"); } } } }; countDownTimer.start(); } public static void endCountDownTime() { if (countDownTimer != null) { countDownTimer.cancel(); } } }
Markdown
UTF-8
1,139
2.9375
3
[]
no_license
# Worker-as-a-promise ## A WebWorker enhancer for communicate through a classical asynchronous promised base interface ### Example ```js import { decorateWorker } from 'worker-as-a-promise'; const myWorker = new Worker('My/worker/script.js'); const worker = decorateWorker(myWorker); // Comunicate using promise interface worker.sendMessage({message: `Hii!`}) .then(response => console.log('Message processed succesfully', response) .catch(responseError => console.error('Error processing message', responseError)); // Classical WebWorker interface still available worker.postMessage({message: 'Message with classical interface'}); worker.addMessageListener(({data}) => { console.log('Response with classical interface', data); }); ``` Utilities functions are provided by **Worker-as-a-promise** for manage messages in a worker-as-a-promise - - isMessageAsPromised - getMessage - createMessage - createResponse - createError For more informations about how Multithread-it should be used. Have a look to example: [Usage example](https://github.com/Proxy-wasted-time-counter/worker-as-a-promise/tree/master/examples)
Python
UTF-8
355
3.046875
3
[]
no_license
import serial # set ports and other constants for collecting data ARDUINO_COM_PORT = "/dev/ttyACM0" BAUD_RATE = 9600 SERIAL_PORT = serial.Serial(ARDUINO_COM_PORT, BAUD_RATE, timeout=1) speed = 1 while speed != 0: speed = int(input("Choose a speed from 1-32, or type '0' to stop.")) if 0 <= speed <= 32: SERIAL_PORT.write(bytes(str(speed), 'utf-8'))
Java
UTF-8
4,727
2.46875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2013 Sebastian Kaspari * * 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.androidzeitgeist.ani.discovery; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import org.junit.Assert; import org.junit.Test; /** * Unit tests for the {@link Discovery} class. */ public class DiscoveryTest { /** * Calling {@link Discovery#enable(DiscoveryListener)} is a shortcut for calling * {@link Discovery#setDisoveryListener(DiscoveryListener)} and * {@link Discovery#enable()}. */ @Test public void testEnableWithListenerIsShortcut() throws Exception { DiscoveryListener listener = mock(DiscoveryListener.class); Discovery discovery = spy(new Discovery()); doNothing().when(discovery).enable(); discovery.enable(listener); verify(discovery).setDisoveryListener(listener); verify(discovery).enable(); } /** * Calling {@link Discovery#enable()} without setting a listener will throw an * {@link IllegalStateException}. */ @Test(expected=IllegalStateException.class) public void testEnableThrowsExceptionIfNoListenerIsSet() throws Exception { Discovery discovery = new Discovery(); discovery.enable(); } /** * Calling {@link Discovery#disable()} without a matching call to * {@link Discovery#enable()} will throw an {@link IllegalAccessError}. */ @Test(expected=IllegalAccessError.class) public void testDisableWithoutEnablingWillThrowException() throws Exception { Discovery discovery = new Discovery(); discovery.disable(); } /** * Calling {@link Discovery#enable()} will create and start a {@link DiscoveryThread}. */ @Test public void testEnableWillCreateAndStartDiscoveryThread() throws Exception { DiscoveryThread thread = mock(DiscoveryThread.class); DiscoveryListener listener = mock(DiscoveryListener.class); Discovery discovery = spy(new Discovery()); discovery.setDisoveryListener(listener); doReturn(thread).when(discovery).createDiscoveryThread(); discovery.enable(); verify(discovery).createDiscoveryThread(); verify(thread).start(); } /** * Calling {@link Discovery#enable()} twice without calling {@link Discovery#disable()} * in between throws an {@link IllegalAccessError}. */ @Test(expected=IllegalAccessError.class) public void testEnablingDiscoveryTwiceThrowsException() throws Exception { DiscoveryThread thread = mock(DiscoveryThread.class); DiscoveryListener listener = mock(DiscoveryListener.class); Discovery discovery = spy(new Discovery()); discovery.setDisoveryListener(listener); doReturn(thread).when(discovery).createDiscoveryThread(); discovery.enable(); discovery.enable(); } /** * Calling {@link Discovery#disable()} will call {@link DiscoveryThread#stopDiscovery()} */ @Test public void testCallingDisableWillCallDisableDiscoveryOnThread() throws Exception { DiscoveryThread thread = mock(DiscoveryThread.class); DiscoveryListener listener = mock(DiscoveryListener.class); Discovery discovery = spy(new Discovery()); discovery.setDisoveryListener(listener); doReturn(thread).when(discovery).createDiscoveryThread(); discovery.enable(); discovery.disable(); verify(thread).start(); verify(thread).stopDiscovery(); } /** * Calling {@link Discovery#createDiscoveryThread()} returns new {@link DiscoveryThread} * instance. */ @Test public void testCreateDiscoveryThreadReturnsNewInstance() { Discovery discovery = new Discovery(); DiscoveryThread thread1 = discovery.createDiscoveryThread(); DiscoveryThread thread2 = discovery.createDiscoveryThread(); Assert.assertNotNull(thread1); Assert.assertNotNull(thread2); Assert.assertNotSame(thread1, thread2); } }
Java
UTF-8
556
1.6875
2
[]
no_license
package com.fontar.proyecto.presupuesto.excel.parser.labels; public class Labels { public static final DefaultLabels Default = DefaultLabels.instance; public static final ANRLabels ANR = ANRLabels.instance; public static final ARAILabels ARAI = ARAILabels.instance; public static final CFLabels CFGeneral = CFLabels.instance; public static final CFLabels CF = CFLabels.instance; public static final CFConsejeriasLabels CFConsejerias = CFConsejeriasLabels.instance; public static final ConsejeriasLabels Consejerias = ConsejeriasLabels.instance; }
Python
UTF-8
1,993
3.625
4
[]
no_license
class Node(object): """ docstring """ def __init__(self, elem=-1, left=None, right=None): """ docstring """ self.elem = elem self.left = left self.right = right class Tree(object): """ docstring """ def __init__(self): """ docstring """ self.root = Node() self.myQueue = [] def add(self, elem): """ docstring """ node = Node(elem) if self.root.elem == -1: self.root = node self.myQueue.append(self.root) else: treeNode = self.myQueue[0] if treeNode.left == None: treeNode.left = node self.myQueue.append(treeNode.left) else: treeNode.right = node self.myQueue.append(treeNode.right) self.myQueue.pop(0) def front_traverse(self, root): """ docstring """ if root == None: return print(root.elem) self.front_traverse(root.left) self.front_traverse(root.right) def middle_traverse(self, root): """ docstring """ if root == None: return self.front_traverse(root.left) print(root.elem) self.front_traverse(root.right) def later_traverse(self, root): """ docstring """ if root == None: return self.front_traverse(root.left) self.front_traverse(root.right) print(root.elem) def level_traverse(self, root): if root == None: return myQueue = [] node = root myQueue.append(node) while myQueue: node = myQueue.pop(0) print(node.elem) if node.left != None: myQueue.append(node.left) if node.right != None: myQueue.append(node.right)
Python
UTF-8
2,926
2.84375
3
[ "MIT" ]
permissive
import collections import os import sys # take a list of user ids and and clustering assignment # assign labels to each user # also need the user <--> activity mapping def get_labels_for_users(user_list_path, activity_list_path, clusters_file_paths, out_dir, addtl_act_ids_path=None): out_dir = out_dir.rstrip(os.sep) + os.sep # keep a count of the number of users that are given each cluster label cluster2user_count = collections.defaultdict(int) # load the user list users = [] with open(user_list_path) as user_file: users = [user.strip() for user in user_file.readlines()] # load the cluster assignment # build a dictionary {activity_id:cluster_id} aid2cluster = {} for clusters_file_path in clusters_file_paths: with open(clusters_file_path) as clusters_file: for line in clusters_file: aid,cluster = line.strip().split() aid2cluster[aid] = cluster # get all activities for each user in the list # for each activity, get the cluster_id that it is in # user2aids = collections.defaultdict(list) user2clusters = collections.defaultdict(list) with open(activity_list_path) as activity_list_file: header = activity_list_file.readline() for line in activity_list_file.readlines(): parts = line.split(',',3) userid = parts[1] aid = parts[0] # user2aids[userid].append(aid) cluster_id = aid2cluster.get(aid,None) # NOTE: there may be users who don't have any activities because the activities were filtered out # ("I thought" or wildcard match not in correct order). Don't create a file for these users. if cluster_id: user2clusters[userid].append(cluster_id) cluster2user_count[cluster_id] += 1 # in the output directory, save a file per user that contains the list of cluster_ids # the first cluster_id should be the one from the query. This will allow us to do multiple different # setups-- some where we train on all valid clusters and some where we only train on the query cluster. # at test time, we will only evaluate on the prediction of the query activity (which is not in the history) for user,clusters in user2clusters.items(): print user,' '.join(list(set(clusters))) # with open(out_dir + user,'w') as out_file: # out_file.write(' '.join(list(set(clusters)))) def usage(): print("usage: python " + os.path.basename(__file__) + " user_list_path activity_list_path cluster_file_path out_dir") if __name__ == "__main__": if len(sys.argv) < 5: usage() user_list_path = sys.argv[1] activity_list_path = sys.argv[2] cluster_file_path_1 = sys.argv[3] out_dir = sys.argv[4] get_labels_for_users(user_list_path, activity_list_path, [cluster_file_path_1], out_dir)
Python
UTF-8
515
3.890625
4
[]
no_license
import numpy as np arr = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]]) bool_arr = arr > 3 print("bool\n", bool_arr) print("true values\n", arr[bool_arr]) # or in sigle way print("true values\n", arr[arr>3]) arr1 = np.array([[1, 2, 3.23],[4, 5, 6],[7, 8, 9]], dtype=np.float64) print("arr1\n", arr1) # or np .add .subtract .multiply .divide .sqrt print("add\n", arr1+arr) print("sub\n", arr1-arr) print("div\n", arr1/arr) print("mul\n", arr1*arr) print("exp\n", arr**arr1) print("sqrt\n", np.sqrt(arr))
Python
UTF-8
9,708
2.703125
3
[]
no_license
""" test.py - functions to support tests """ import logging import numpy as NP from .. import (DigitalSignal, QuadratureHybrid, SignalGenerator, is_quadrature, rect_to_polar) logger = logging.getLogger(__name__) class SignalProber(object): """ tests various DigitalSignal objects created with SignalGenerator Attrs ===== logger: (logging.Logger) M: (int) signal size """ def __init__(self, M=256): """ Args ==== M: (int) signal size """ self.M = M self.logger = logging.getLogger(logger.name+".SignalProber") def check_signal_type(self, signal): """ returns ``True`` for ``dtype`` of ``float`` or ``complex``, or False otherwise """ if signal.dtype == float: return True elif signal.dtype == complex: return True else: logger.error("check_signal_type: %s type signal is not '%s'", (signal.dtyp, sigmode)) return False def empty_signal(self): """ test DigitalSignal for no data (empty signal) """ zeros = DigitalSignal(M=self.M) if zeros.any(): self.logger.debug("empty_signal: creating empty %s signal failed", zeros.dtype) return False else: self.logger.debug("empty_signal: created empty %s signal", zeros.dtype) return True def noisy_signal(self, rms=0.1): """ test DigitalSignal for noisy data """ noise = DigitalSignal(M=self.M, rms=rms) if noise.any(): std = noise.std() if abs(std - rms) < 1/self.M: self.logger.debug("noisy_signal: created noisy %s signal %s", noise.dtype, noise.std()) return True else: self.logger.error("noisy_signal: rms is %s; should be %s", std, rms) return False else: self.logger.error("noisy_signal: creating noisy %s signal failed" % noise.dtype) return False def peak_test(self, peak, ampS, phsS, ampC, phsC): """ tests that component peak amplitude is what is expected Args ==== peak: (int or float) frequency of the peak ampS: (float) amplitude of the peak in the signal phsS: (float) phase in cycles of the peak in the signal ampC: (float) amplitude of the injected component phsC: (float) phase in cycles of the injected component """ if abs(ampS-self.M*ampC/2) < 1e-6: return True else: self.logger.error("peak_test: %4d: expected amp %5.2f, phase %4.2f", peak, ampC, 360*phsC) self.logger.error("peak_test: %4d: got amp %5.2f, phase %4.2f", peak, ampS, 360*phsS) return False def check_signal_peaks(self, sigmode, spectrum, components): """ check each peak's parameters to match a component For each peak in the spectrum, checks that its properties match a component Args ==== sigmode: (int) signal mode ("real", "analytic", or "complex") spectrum: (ndarray) voltage spectrum of the signal components: (list of lists) component properties """ peaks, negpeaks, pospeaks, S2 = get_peaks(self.M, spectrum) passed = True for peak in peaks: # get spectral feature amplitude and phase ampS, phsS = rect_to_polar(spectrum[peak]) if sigmode == "real": # real modee test response = check_component(peak,components) if response: pass else: response = check_component(-peak,components) if response: # check that the feature amplitude and component amplitude agree ampC, phsC = response passed = passed and self.peak_test(peak, ampS, phsS, ampC, phsC) else: self.logger.error("check_signal_peaks: no response for peak %d", peak) freqs = [] for comp in components: freqs.append(comp[1]) self.logger.error("check_signal_peaks: frequencies are %s", freqs) passed = False elif sigmode == "analytic": if peak > self.M/2: response = check_component(peak-self.M,components) else: response = check_component(peak,components) if response: ampC, phsC = response passed = passed and self.peak_test(peak, ampS, phsS, ampC, phsC) elif sigmode == "complex": self.logger.debug("check_signal_peaks: checking %s", peak) if peak > self.M/2: response = check_component(peak-self.M, components, idx_pos=0) else: response = check_component(peak, components, idx_pos=0) if response: v = response[0]+1j*response[1] ampC, phsC = rect_to_polar(v) # the signal amplitude is twice the component amplitude because both # the sine term and the cosine term contribute to it passed = passed and self.peak_test(peak, ampS, phsS, 2*ampC, phsC) else: self.logger.error( "check_signal_peaks: no response from check_component") else: self.logger.error("check_signal_peaks: invalid signal mode: %s", sigmode) passed=False if not passed: self.logger.error("check_signal_peaks: %s mode test failed", sigmode) return passed def test_SG(self, sigmode): """ test SignalGenerator for signals """ components = signal_components(sigmode) signal = SignalGenerator(mode=sigmode, M=self.M, components=components).signal() self.check_signal_type(signal) spectrum = signal.spectrum() passed = self.check_signal_peaks(sigmode, spectrum, components) self.logger.info("test_SG: signal type %s passed = %s", sigmode, passed) return passed, signal, spectrum def test_QH(self): """ test QuadratureHybrid creates a real signal which is converted with a Quadrature Hybrid object into an analytic signal. It then uses DSP function is_quadrature() to test it. It also checks that the spectrum peaks of the analytic signal match what is expected. """ components = signal_components("real") signal = SignalGenerator(mode="real", M=self.M, components=components).signal() self.logger.debug("test_QH: signal in is %s", signal.dtype) qh = QuadratureHybrid() I,Q = qh.convert(signal) analsignal = I + 1j*Q self.logger.debug("test_QH: signal out is %s", analsignal.dtype) if is_quadrature(analsignal): pass else: self.logger.error("test_QH: signal is not quadrature") passed = False spectrum = signal.spectrum() passed = self.check_signal_peaks("real", spectrum, components) self.logger.info("test_QH: passed = %s", passed) return passed, signal, spectrum #################### functions useful for testing ############################## def signal_components(sigmode): """ provides three frequency components for a test signal The components can specify the components in exponential/trogonmetric form or complex number form. """ if sigmode == "real" or sigmode == "analytic": components=[[0.5, -60, 0.5], [1, 75, 0], [0.25, 90, 0.25]] elif sigmode == "complex": # should give same signal as analytic # frq I Q components=[[-60, -0.5, 0], [ 75, 1, 0], [ 90, 0, 0.25]] else: logger.error("signal_components: mode %s is invalid", sigmode) components = [] return components def extra_components(sigmode): """ provides two different frequency components for a test signal """ if sigmode == "real": components = [[1, 45, .25], [1, 85, .75]] else: raise ValueError("no extra components defined for sigmode %s", sigmode) return components def check_component(freq, components, idx_pos=1, sigmode=None): """ returns parameters for a component given the frequency Args ==== freq: (int) frequency of component to be checked components: (list of lists) idx_pos: (int) index of the frequency in the component list sigmode: (str) signal mode, which determines frequency position index Notes ===== For a component in complex form, it returns the cosine and sine coefficients. For exponential/trigometric form, it returns amplitude and phase. The sine and cosine components add in quadrature so a given frequency component has twice """ if sigmode == "real" or sigmode == "analytic": idx_pos=1 elif sigmode == "complex": idx_pos=0 for comp in components: if idx_pos: if freq == comp[1]: return comp[0], comp[2] else: continue elif idx_pos == 0: if freq == comp[0]: return comp[1], comp[2] else: continue else: raise ValueError("check_component: idx_pos=%d is invalid" % idx_pos) return None def get_peaks(M, spectrum): """ returns the peaks in the spectrum A peak is defined as having a power > 1. ``pospeaks`` are in the first Nyquist zone. ``negpeaks`` are in the second Nyquist zone, i.e. have negative frequencies. Args ==== M - (int) number of data samples spectrum - (ndarray) signal voltage spectrum """ S2 = spectrum*spectrum.conjugate() sorted_ids = S2.argsort()[::-1] pk_ids = NP.where(S2[sorted_ids] > 1) peaks = sorted_ids[pk_ids] negpeaks = peaks[NP.where(peaks >= M/2)] pospeaks = peaks[NP.where(peaks <= M/2)] return peaks, negpeaks, pospeaks, S2
Java
UTF-8
670
1.585938
2
[]
no_license
package com.hqyj.javaSpringBoot.modules.account.service; import com.github.pagehelper.PageInfo; import com.hqyj.javaSpringBoot.modules.account.pojo.Role; import com.hqyj.javaSpringBoot.modules.common.vo.Result; import com.hqyj.javaSpringBoot.modules.common.vo.SearchVo; import java.util.List; /** * @author qb * @version 1.0 * NO.1 * come on * @date 2020/8/22 17:11 */ public interface RoleService { List<Role> getRoles(); PageInfo<Role> getRolesBySearchVo(SearchVo searchVo); Result<Role> insertRole(Role role); Role getRolesByRoleId(int roleId); Result<Role> deleteRoleByRoleId(int roleId); Result<Role> updateRole(Role role); }
C++
UTF-8
828
2.6875
3
[ "MIT" ]
permissive
#include <iostream> #include <bits/stdc++.h> using namespace std; typedef long long number; number n, result, temp; vector<number> tree[500001]; bool used[500001] = { false }; void pairUp(number node, number prev) { for (auto next : tree[node]) { if (next == prev) continue; pairUp(next, node); } for (auto next : tree[node]) { if (next == prev) continue; if (used[next] == false) { used[node] = true; used[next] = true; result++; break; } } } int main() { cin.sync_with_stdio(0); cin.tie(0); cin >> n; if (n == 1) { cout << 1 << endl; return 0; } number a, b; for (number i = 1; i < n; i++) { cin >> a >> b; tree[a].push_back(b); tree[b].push_back(a); } pairUp(1, 0); cout << result << endl; return 0; }
Java
UTF-8
389
2.21875
2
[]
no_license
package PageClasses; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import Utility.Constants; public class ShippingPage { private static WebElement element = null; public static WebElement shippingOptionOne(WebDriver driver){ element = driver.findElement(By.xpath(Constants.SHIPPING_OPTION1)); return element; } }
JavaScript
UTF-8
792
2.671875
3
[]
no_license
const express = require('express'); const morgan = require('morgan'); const app = express(); // tell the express to use morgan app.use(morgan('tiny')) // app.use((req, res, next) => { // defining Middleware // console.log('First mIDDLEWARE'); // return next(); // callBack // }); app.use((req, res, next) => { req.requestTime = Date.now(); console.log(req.method, req.path); next() }) app.get('/', (req, res) => { res.send('Welcome To The Home Page') }); app.get('/cars', (req, res) => { console.log(`Request date: ${req.requestTime}`) res.send('Vroom Vroom Vroom') }); app.use((req, res) => { // Define error-handling res.status(404).send('Something broke!') }) app.listen(3000, () => { console.log('localhost:3000....................'); })
JavaScript
UTF-8
8,809
2.515625
3
[ "MIT", "Apache-2.0", "PHP-3.0" ]
permissive
$(function() { //模拟下拉框 $('.input_1').on('click', function () { if ($('.food1').is('.hide')) { $('.food1').removeClass('hide'); } else { $('.food1').addClass('hide'); } }) $('.input_2').on('click', function () { if ($('.food2').is('.hide')) { $('.food2').removeClass('hide'); } else { $('.food2').addClass('hide'); } }) $('.input_3').on('click', function () { if ($('.food3').is('.hide')) { $('.food3').removeClass('hide'); } else { $('.food3').addClass('hide'); } }) $('.input_4').on('click', function () { if ($('.food4').is('.hide')) { $('.food4').removeClass('hide'); } else { $('.food4').addClass('hide'); } }) $('.input_5').on('click', function () { if ($('.food5').is('.hide')) { $('.food5').removeClass('hide'); } else { $('.food5').addClass('hide'); } }) $('.input_6').on('click', function () { if ($('.food6').is('.hide')) { $('.food6').removeClass('hide'); } else { $('.food6').addClass('hide'); } }) $('.input_7').on('click', function () { if ($('.food7').is('.hide')) { $('.food7').removeClass('hide'); } else { $('.food7').addClass('hide'); } }) $('.input_8').on('click', function () { if ($('.food8').is('.hide')) { $('.food8').removeClass('hide'); } else { $('.food8').addClass('hide'); } }) $('.input_9').on('click', function () { if ($('.food9').is('.hide')) { $('.food9').removeClass('hide'); } else { $('.food9').addClass('hide'); } }) $('.input_10').on('click', function () { if ($('.food10').is('.hide')) { $('.food10').removeClass('hide'); } else { $('.food10').addClass('hide'); } }) $('.input_11').on('click', function () { if ($('.food11').is('.hide')) { $('.food11').removeClass('hide'); } else { $('.food11').addClass('hide'); } }) $('.input_12').on('click', function () { if ($('.food12').is('.hide')) { $('.food12').removeClass('hide'); } else { $('.food12').addClass('hide'); } }) $('.input_13').on('click', function () { if ($('.food13').is('.hide')) { $('.food13').removeClass('hide'); } else { $('.food13').addClass('hide'); } }) $('.input_14').on('click', function () { if ($('.food14').is('.hide')) { $('.food14').removeClass('hide'); } else { $('.food14').addClass('hide'); } }) $('.input_15').on('click', function () { if ($('.food15').is('.hide')) { $('.food15').removeClass('hide'); } else { $('.food15').addClass('hide'); } }) $('.input_16').on('click', function () { if ($('.food16').is('.hide')) { $('.food16').removeClass('hide'); } else { $('.food16').addClass('hide'); } }) $('.input_17').on('click', function () { if ($('.food17').is('.hide')) { $('.food17').removeClass('hide'); } else { $('.food17').addClass('hide'); } }) $('.input_18').on('click', function () { if ($('.food18').is('.hide')) { $('.food18').removeClass('hide'); } else { $('.food18').addClass('hide'); } }) $('.food1 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_1 input').val($(this).html()); $('.food').addClass('hide'); $('.input_1 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food2 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_2 input').val($(this).html()); $('.food').addClass('hide'); $('.input_2 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food3 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_3 input').val($(this).html()); $('.food').addClass('hide'); $('.input_3 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food4 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_4 input').val($(this).html()); $('.food').addClass('hide'); $('.input_4 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food5 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_5 input').val($(this).html()); $('.food').addClass('hide'); $('.input_5 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food6 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_6 input').val($(this).html()); $('.food').addClass('hide'); $('.input_6 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food7 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_7 input').val($(this).html()); $('.food').addClass('hide'); $('.input_7 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food8 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_8 input').val($(this).html()); $('.food').addClass('hide'); $('.input_8 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food9 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_9 input').val($(this).html()); $('.food').addClass('hide'); $('.input_9 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food10 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_10 input').val($(this).html()); $('.food').addClass('hide'); $('.input_10 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food11 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_11 input').val($(this).html()); $('.food').addClass('hide'); $('.input_11 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food12 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_12 input').val($(this).html()); $('.food').addClass('hide'); $('.input_12 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food13 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_13 input').val($(this).html()); $('.food').addClass('hide'); $('.input_13 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food14 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_14 input').val($(this).html()); $('.food').addClass('hide'); $('.input_14 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food15 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_15 input').val($(this).html()); $('.food').addClass('hide'); $('.input_15 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food16 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_16 input').val($(this).html()); $('.food').addClass('hide'); $('.input_16 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food17 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_17 input').val($(this).html()); $('.food').addClass('hide'); $('.input_17 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food18 ul li').on('click', function () { console.log($(this).html(), '$(this).html()'); $('.input_18 input').val($(this).html()); $('.food').addClass('hide'); $('.input_18 input').css('border-bottom', '1px solid $d6d6d6'); }) $('.food ul li').hover(function () { $(this).css({'backgroundColor': '#aaf556', 'font-size': '14px'}); }, function () { $(this).css({'backgroundColor': '#fff', 'font-size': '8px'}); }) })
Java
UTF-8
3,339
3.59375
4
[]
no_license
import java.util.ArrayList; public class Part1 { public static void main(String[] args) { // TODO Auto-generated method stub ComparableList c = new ComparableList(); String obj[] = { "345", "1", "2", "3" }; c.addFromArray(obj); A a1 = new A(6); A a2 = new A(7); B b1 = new B(2, 4); B b2 = new B(3, 5); System.out.println(a1.compareTo(b1)); // returns 0, since 6 = (2+4) System.out.println(a1.compareTo(b2)); // returns -1, since 6 < (3+5) System.out.println(b1.compareTo(a1)); // returns 0, since (2+4) = 6 System.out.println(b2.compareTo(a1)); // returns 1, since (3+5) > 6 System.out.println(b1.compareTo(b2)); // returns -1, since (2+4) < (3+5) // test(); } public static void addToCList(A z, ComparableList<?> a) { a.add(z); } public static void addToCList(B z, ComparableList<?> a) { a.add(z); } public static void test() { ComparableList<A> c1 = new ComparableList<A>(); ComparableList<A> c2 = new ComparableList<A>(); for (int i = 0; i < 10; i++) { addToCList(new A(i), c1); addToCList(new A(i), c2); } addToCList(new A(12), c1); addToCList(new B(6, 6), c2); addToCList(new B(7, 11), c1); addToCList(new A(13), c2); System.out.print("c1: "); System.out.println(c1); System.out.print("c2: "); System.out.println(c2); switch (c1.compareTo(c2)) { case -1: System.out.println("c1 < c2"); break; case 0: System.out.println("c1 = c2"); break; case 1: System.out.println("c1 > c2"); break; default: System.out.println("Uh Oh"); break; } } } @SuppressWarnings("rawtypes") class ComparableList<T extends ComparableList> extends ArrayList implements Comparable { @SuppressWarnings("unchecked") @Override public int compareTo(Object o) { int returnVal = 0; int firstSize = this.size(); int secondSize = ((T) o).size(); for (int i = 0; i < (firstSize < secondSize ? firstSize : secondSize); i++) { if (((T) (this.get(i))).compareTo(((T) o).get(i)) < 0) { returnVal = -1; break; } else if (((T) (this.get(i))).compareTo(((T) o).get(i)) > 0) { returnVal = 1; break; } } if (returnVal == 0 && firstSize < secondSize) return -1; else if (returnVal == 0 && firstSize > secondSize) return 1; return returnVal; } @SuppressWarnings("unchecked") public void addFromArray(Object[] O) { for (int i = 0; i < O.length; i++) { this.add(O[i]); } } } @SuppressWarnings("rawtypes") class A extends ComparableList { int x; A() { } A(int x) { this.x = x; } @Override public int compareTo(Object o) { if (o.getClass() == B.class) { return (new B(this.x, 0)).compareTo((B) o); } if (this.x < ((A) o).x) return -1; else if (this.x == ((A) o).x) return 0; return 1; } @Override public String toString() { return "A<" + this.x + ">"; } } @SuppressWarnings("rawtypes") class B extends A { int x; int y; B(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Object o) { if (o.getClass() == A.class) { return (new A(this.x + this.y)).compareTo((A) o); } if (this.x + this.y < ((B) o).x + ((B) o).y) return -1; else if (this.x + this.y == ((B) o).x + ((B) o).y) return 0; return 1; } @Override public String toString() { return "B<" + this.x + "," + this.y + ">"; } }
JavaScript
UTF-8
349
3.25
3
[]
no_license
let PorcDeEstudents = 33; let PorcDeMentors = 11; let total = PorcDeEstudents + PorcDeMentors; PorcDeEstudents = Math.round((100 * PorcDeEstudents) / total); PorcDeMentors = Math.round((100 * PorcDeMentors) / total); console.log("Percentaje of students: " + PorcDeEstudents + "%"); console.log("Percentaje of mentors: " + PorcDeMentors + "%");
Python
UTF-8
170
3.734375
4
[]
no_license
num1=1.5 num2=2.5 print(num1+num2) x=10 y=14 z=18 print("x+y+z",x+y+z) print(type(x)) print(type(y)) print(type(z)) print("x+y",x+y) print("x+y-z",x+y-z)
Python
UTF-8
12,021
2.53125
3
[ "BSD-3-Clause" ]
permissive
import pytest from pyecore.ecore import * from pyecore.commands import * from pyecore.resources import URI, ResourceSet from pyecore.utils import DynamicEPackage from pyecore.notification import EObserver, Kind from os import path class LastObserver(EObserver): def __init__(self, notifier=None): super().__init__(notifier=notifier) self.last = None def notifyChanged(self, notification): self.last = notification @pytest.fixture(scope='module') def mm(): Root = EClass('Root') A = EClass('A') B = EClass('B') Root.eStructuralFeatures.append(EReference('a_s', A, upper=-1, containment=True)) Root.eStructuralFeatures.append(EReference('bs', B, upper=-1, containment=True)) A.eStructuralFeatures.append(EAttribute('name', EString)) simple_tob = EReference('simple_tob', eType=B, containment=True) A.eStructuralFeatures.append(simple_tob) A.eStructuralFeatures.append(EReference('many_tob', eType=B, containment=True, upper=-1)) B.eStructuralFeatures.append(EReference('toa', A)) B.eStructuralFeatures.append(EReference('inverseA', A, eOpposite=simple_tob)) package = EPackage(name='package') package.eClassifiers.extend([Root, A, B]) return DynamicEPackage(package) def test_orderedset_insert(mm): a = mm.A() b = mm.B() a.many_tob.insert(0, b) assert b in a.many_tob assert a.many_tob.index(b) == 0 a.many_tob.insert(0, b) assert b in a.many_tob b2 = mm.B() a.many_tob.insert(0, b2) assert b2 in a.many_tob assert a.many_tob.index(b) == 1 assert a.many_tob.index(b2) == 0 def test_orderedset_pop(mm): a = mm.A() with pytest.raises(KeyError): a.many_tob.pop() with pytest.raises(KeyError): a.many_tob.pop(0) # add/remove one element b = mm.B() a.many_tob.append(b) assert b in a.many_tob a.many_tob.pop() assert len(a.many_tob) == 0 b2 = mm.B() a.many_tob.extend([b, b2]) assert b in a.many_tob and b2 in a.many_tob a.many_tob.pop() assert b in a.many_tob and b2 not in a.many_tob assert a.many_tob.index(b) == 0 a.many_tob.append(b2) a.many_tob.pop(0) assert b not in a.many_tob and b2 in a.many_tob assert a.many_tob.index(b2) == 0 a.many_tob.pop(-1) assert len(a.many_tob) == 0 def test_command_abs(): class A(Command): def can_execute(self): super().can_execute def can_undo(self): super().can_undo def execute(self): super().execute() def undo(self): super().undo() def redo(self): super().redo() a = A() a.can_execute() a.execute() a.can_undo() a.undo() a.redo() def test_command_set_name(mm): a = mm.A() with pytest.raises(BadValueError): Set(owner='R', feature='name', value='testValue') set = Set(owner=a, feature='name', value='testValue') assert set.__repr__() assert set.can_execute set.execute() assert a.name == 'testValue' assert set.can_undo set.undo() assert a.name is None set.redo() assert a.name == 'testValue' def test_command_set_b(mm): a = mm.A() b = mm.B() set = Set(owner=a, feature='simple_tob', value=b) assert set.can_execute set.execute() assert a.simple_tob is b assert b.inverseA is a assert set.can_undo set.undo() assert a.simple_tob is None assert b.inverseA is None set.redo() assert a.simple_tob is b assert b.inverseA is a def test_command_add_b(mm): a = mm.A() b = mm.B() add = Add(owner=a, feature='many_tob', value=b) assert add.can_execute add.execute() assert b in a.many_tob assert add.can_undo add.undo() assert b not in a.many_tob add.redo() assert b in a.many_tob def test_command_add_b_index(mm): a = mm.A() b = mm.B() a.many_tob.append(b) b2 = mm.B() add = Add(owner=a, feature='many_tob', index=0, value=b2) assert add.can_execute add.execute() assert b2 in a.many_tob and b in a.many_tob assert a.many_tob.index(b2) == 0 and a.many_tob.index(b) == 1 assert add.can_undo add.undo() assert b2 not in a.many_tob and b in a.many_tob assert a.many_tob.index(b) == 0 add.redo() assert b2 in a.many_tob assert a.many_tob.index(b2) == 0 and a.many_tob.index(b) == 1 def test_command_remove_b(mm): a = mm.A() b = mm.B() b2 = mm.B() a.many_tob.extend([b, b2]) remove = Remove(owner=a, feature='many_tob', value=b) assert remove.can_execute remove.execute() assert b2 in a.many_tob and b not in a.many_tob assert a.many_tob.index(b2) == 0 assert remove.can_undo remove.undo() assert b2 in a.many_tob and b in a.many_tob assert a.many_tob.index(b) == 0 and a.many_tob.index(b2) remove.redo() assert b2 in a.many_tob and b not in a.many_tob assert a.many_tob.index(b2) == 0 def test_command_remove_index(mm): a = mm.A() b = mm.B() b2 = mm.B() with pytest.raises(ValueError): Remove(owner=a, feature='many_tob', index=0, value=b) a.many_tob.extend([b, b2]) remove = Remove(owner=a, feature='many_tob', index=0) assert remove.can_execute remove.execute() assert b2 in a.many_tob and b not in a.many_tob assert a.many_tob.index(b2) == 0 assert remove.can_undo remove.undo() assert b2 in a.many_tob and b in a.many_tob assert a.many_tob.index(b) == 0 and a.many_tob.index(b2) remove.redo() assert b2 in a.many_tob and b not in a.many_tob assert a.many_tob.index(b2) == 0 def test_command_move_fromindex(mm): a = mm.A() b = mm.B() b2 = mm.B() a.many_tob.extend([b, b2]) with pytest.raises(ValueError): Move(owner=a, feature='many_tob', from_index=0, value=b) assert a.many_tob.index(b) == 0 and a.many_tob.index(b2) == 1 move = Move(owner=a, feature='many_tob', from_index=0, to_index=1) assert move.can_execute move.execute() assert a.many_tob.index(b) == 1 and a.many_tob.index(b2) == 0 assert move.can_undo move.undo() assert a.many_tob.index(b) == 0 and a.many_tob.index(b2) == 1 move.redo() assert a.many_tob.index(b) == 1 and a.many_tob.index(b2) == 0 def test_command_move_b(mm): a = mm.A() b = mm.B() b2 = mm.B() a.many_tob.extend([b, b2]) assert a.many_tob.index(b) == 0 and a.many_tob.index(b2) == 1 move = Move(owner=a, feature='many_tob', to_index=1, value=b) assert move.can_execute move.execute() assert a.many_tob.index(b) == 1 and a.many_tob.index(b2) == 0 assert move.can_undo move.undo() assert a.many_tob.index(b) == 0 and a.many_tob.index(b2) == 1 move.redo() assert a.many_tob.index(b) == 1 and a.many_tob.index(b2) == 0 def test_command_delete_b(mm): a = mm.A() b = mm.B() b2 = mm.B() a.many_tob.extend([b, b2]) b.toa = a delete = Delete(owner=b) assert delete.can_execute delete.execute() assert b not in a.many_tob assert b.toa is None assert delete.can_undo delete.undo() assert b in a.many_tob assert b.toa is a delete.redo() assert b not in a.many_tob assert b.toa is None def test_command_delete_graph(mm): root = mm.Root() a = mm.A() b = mm.B() b2 = mm.B() a.many_tob.extend([b, b2]) b.toa = a root.a_s.append(a) delete = Delete(owner=a) assert delete.can_execute delete.execute() assert a not in root.a_s assert b not in a.many_tob assert b2 not in a.many_tob assert b.toa is None assert delete.can_undo delete.undo() assert a in root.a_s assert b in a.many_tob assert b2 in a.many_tob assert b.toa is a delete.redo() assert a not in root.a_s assert b not in a.many_tob assert b2 not in a.many_tob assert b.toa is None def test_command_delete_inverse(mm): root = mm.Root() a = mm.A() b = mm.B() b.toa = a delete = Delete(owner=a) assert delete.can_execute delete.execute() assert b.toa is None assert delete.can_undo delete.undo() assert b.toa is a delete.redo() assert b.toa is None def test_command_compound_basics(mm): a = mm.A() b = mm.B() b.toa = a set = Set(owner=a, feature='name', value='testValue') delete = Delete(owner=a) compound = Compound(set, delete) assert len(compound) == 2 assert compound[0] is set assert compound[1] is delete assert compound.__repr__() del compound[0] assert len(compound) == 1 assert compound[0] is delete compound.insert(0, set) for i, c in enumerate(compound): if i == 0: assert isinstance(c, Set) else: assert isinstance(c, Delete) del compound[0] assert len(compound) == 1 compound[0:0] = [set] assert len(compound) == 2 assert compound[0] is set def test_command_compound_exec(mm): a = mm.A() set = Set(owner=a, feature='name', value='testValue') compound = Compound(set, Set(owner=a, feature='name', value='testValue2')) assert compound.can_execute compound.execute() assert a.name == 'testValue2' assert compound.can_undo compound.undo() assert a.name is None compound.redo() assert a.name == 'testValue2' assert compound is compound.unwrap() del compound[1] assert set is compound.unwrap() def test_command_set_name_stack(mm): root = mm.Root() a = mm.A() name_feature = mm.A.findEStructuralFeature('name') stack = CommandStack() set = Set(owner=a, feature=name_feature, value='testValue') assert set.__repr__() stack.execute(set) assert a.name == 'testValue' stack.undo() assert a.name is None stack.redo() assert a.name == 'testValue' assert set.__repr__() def test_stack_simple(mm): stack = CommandStack() with pytest.raises(IndexError): stack.undo() a = mm.A() with pytest.raises(ValueError): stack.execute(Set(a, 'names', 'test')) stack.execute(Set(a, 'name', 'testValue')) stack.execute(Set(a, 'name', 'testValue2')) assert a.name == 'testValue2' stack.undo() assert a.name == 'testValue' stack.undo() assert a.name is None def test_stack_complex(mm): stack = CommandStack() a = mm.A() b1 = mm.B() b2 = mm.B() stack.execute(Set(a, 'name', 'testValue')) stack.execute(Add(a, 'many_tob', b1)) stack.execute(Add(a, 'many_tob', b2)) stack.execute(Set(b1, 'toa', a)) stack.execute(Delete(b1)) stack.execute(Set(a, 'name', 'final')) assert a.name == 'final' assert b2 in a.many_tob and b1 not in a.many_tob stack.undo() assert a.name == 'testValue' stack.undo() assert b1 in a.many_tob assert b1.toa is a stack.undo() assert b1.toa is None stack.undo() stack.undo() assert len(a.many_tob) == 0 stack.undo() assert a.name is None with pytest.raises(IndexError): stack.undo() def test_stack_multiple_undo_redo(mm): stack = CommandStack() a = mm.A() b1 = mm.B() stack.execute(Set(a, 'name', 'testValue')) stack.execute(Add(a, 'many_tob', b1)) assert a.name == 'testValue' assert b1 in a.many_tob stack.undo() stack.undo() assert a.name is None assert b1 not in a.many_tob stack.redo() stack.redo() assert a.name == 'testValue' assert b1 in a.many_tob def test_command_resource(mm): rset = ResourceSet() resource = rset.create_resource(URI('http://logical')) a = mm.A() resource.append(a) cmd = Set(a, 'name', 'test_value') assert cmd.resource is resource
Java
UTF-8
3,020
2.5
2
[]
no_license
package controllers; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.User; /** * Servlet implementation class ImageServlet */ @WebServlet("/image") @MultipartConfig public class ImageServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ImageServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("in doPost of image servlet"); HashMap<Integer,User> users = (HashMap<Integer,User>)request.getServletContext().getAttribute("users"); User user = (User)request.getSession().getAttribute("user"); String filename = "" + user.getId() + ".png"; // need to fill imgPath with the path to the desired folder. //String imgPath = request.getServletContext().getRealPath("/") + "userPics\\" + filename; File base = new File(System.getProperty("catalina.home")); //File uploadDir = new File(base.getAbsolutePath() + File.separator + "userPics"); String imgPath = base.getAbsolutePath() + File.separator + "userPics" + File.separator + filename; System.out.println("Path: " + imgPath); InputStream fileContent = null; try(OutputStream out = new FileOutputStream(new File(imgPath))) { fileContent = request.getPart("image").getInputStream(); int read = 0; final byte[] bytes = new byte[1024]; while ((read = fileContent.read(bytes)) != -1) { out.write(bytes, 0, read); } request.setAttribute("profileMessage", "Your profile picture is uploaded"); // modify the user URL newURL = request.getServletContext().getResource("userPics" + File.separator + filename); String newPath = newURL.getPath().substring(1); user.setImagePath(newPath); users.put(user.getId(), user); request.getServletContext().setAttribute("users", users); } catch (FileNotFoundException e) { e.printStackTrace(); } request.getRequestDispatcher("/profile").forward(request, response); } }
JavaScript
UTF-8
728
2.796875
3
[]
no_license
import React from 'react'; class State extends React.Component{ constructor(props){ super(props); this.state = { name :' ', }; this.changeToHanh = this.changeToHanh.bind(this); } changeToHanh(){ if(this.state.name === 'THAI'){ this.setState({ name : 'HANH', }); }else{ this.setState({ name : 'THAI', }); } } render(){ return( <div> <h3>Username:{this.state.name}</h3> <button onClick={this.changeToHanh}>Click to change - HANH</button> </div> ); } } export default State;
Java
UTF-8
608
2.296875
2
[]
no_license
package com.dh.mediaplayer.bean; /** * Created by DH on 21/05/2015. */ public class PlaylistOff { private long id; private String namePlaylist; public PlaylistOff() { } public PlaylistOff(int id, String namePlaylist) { this.id = id; this.namePlaylist = namePlaylist; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNamePlaylist() { return namePlaylist; } public void setNamePlaylist(String namePlaylist) { this.namePlaylist = namePlaylist; } }