text
stringlengths
175
47.7k
meta
dict
Q: Difference between require and load wrt to "load" and "execute" Below are some snippets from the documentation for Kernel: Kernel#load Loads and executes the Ruby program in the file filename... Kernel#require Loads the given name... I know there are differences between require and load for example: require will tack on an rb extension while load will not require will store the ruby file path inside $LOADED_FEATURES aka $" while load will not require will search $LOADED_FEATURES before "loading" the file again while load will not I'm wondering about the distinction between the word "load" and the word "executes". The documentation makes it seem like they are two different things. To me, "load" would mean "Hey I know about this file now" while "execute" would mean "Hey I know about this file now and I'm going to run all the commands also" But I don't think that's right. For example, given the following structure: $ tree . ├── bar.rb ├── baz.rb └── foo.rb 0 directories, 3 files with foo.rb: $LOAD_PATH << __dir__ require 'bar' load 'baz.rb' bar.rb: puts "Inside of bar..." baz.rb: puts "Inside of baz..." When I run foo.rb I would expect "Inside of baz..." to print but not "Inside of bar..." because load "loads and executes" while require just "loads". But what actually happens is both seem to "execute": $ ruby foo.rb Inside of bar... Inside of baz... So is there a difference between "loading" and "executing" a ruby file? A: The file is always executed. In Ruby there is no such thing as loading a file without executing it. Everything is a statement in Ruby and has to be executed. Even class and def are just statements. To illustrate this here's a silly example class Mystery < [Array, Object, String, Fixnum].sample ... end This creates a class with a random superclass. Just to illustrate that Ruby has no declarations but executable statements only. So there is no such thing as not executing a Ruby file. The difference between load and require is as you described, the latter keeps track of all loaded files to avoid reloading them. PS, and another example ruby --dump insns -e 'def example; end' == disasm: <RubyVM::InstructionSequence:<main>@-e>====================== 0000 trace 1 ( 1) 0002 putspecialobject 1 0004 putspecialobject 2 0006 putobject :example 0008 putiseq example 0010 opt_send_without_block <callinfo!mid:core#define_method, argc:3, ARGS_SIMPLE> 0012 leave == disasm: <RubyVM::InstructionSequence:example@-e>===================== 0000 trace 8 ( 1) 0002 putnil 0003 trace 16 ( 1) 0005 leave As you can see def example; end is a statement and internally calls the define_method method. So def is just syntactic sugar for a method call.
{ "pile_set_name": "StackExchange" }
Q: Declaring a variable and setting its value from a SELECT query in Oracle In SQL Server we can use this: DECLARE @variable INT; SELECT @variable= mycolumn from myTable; How can I do the same in Oracle? I'm currently attempting the following: DECLARE COMPID VARCHAR2(20); SELECT companyid INTO COMPID from app where appid='90' and rownum=1; Why this is not working? A: SELECT INTO DECLARE the_variable NUMBER; BEGIN SELECT my_column INTO the_variable FROM my_table; END; Make sure that the query only returns a single row: By default, a SELECT INTO statement must return only one row. Otherwise, PL/SQL raises the predefined exception TOO_MANY_ROWS and the values of the variables in the INTO clause are undefined. Make sure your WHERE clause is specific enough to only match one row If no rows are returned, PL/SQL raises NO_DATA_FOUND. You can guard against this exception by selecting the result of an aggregate function, such as COUNT(*) or AVG(), where practical. These functions are guaranteed to return a single value, even if no rows match the condition. A SELECT ... BULK COLLECT INTO statement can return multiple rows. You must set up collection variables to hold the results. You can declare associative arrays or nested tables that grow as needed to hold the entire result set. The implicit cursor SQL and its attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN provide information about the execution of a SELECT INTO statement. A: Not entirely sure what you are after but in PL/SQL you would simply DECLARE v_variable INTEGER; BEGIN SELECT mycolumn INTO v_variable FROM myTable; END; Ollie.
{ "pile_set_name": "StackExchange" }
Q: Questions about calculating a transaction ID As I know, Transaction ID is calculated from H( H(tx_prefix) || H(tx_stuff) || H(Signatures) ) Where tx_prefix = {tx version || keyoffset || keyimage || one-time addresses || extra} tx_stuff = {signature type || tx fee || pseudo output commitments || ecdhInfo || output commitments} Signatures = {MLSAGs || range proofs} So I test a example tx: b43a7ac21e1b60ad748ec905d6e03cf3165e5d8c9e1c61c263d328118c42eaa6 with MiniNero but failed nevertheless. tx_version = "02" key_offset = "c8e230afe12f958d49809d0dfaaf33" key_image = "595a612d0df27181c46a8af70a9bd682f2a000124b873ba5d2b9f4b4e4efd672" signature_type = "01" ont_time_addr = "aa9595f55f2cfaed3bd2a67453bb064dc7fd454a09c2418d7338782790185fe30ccb48ed2ebbcaa8e8831111029f3300069cff0d1408acffbfc3810b362ea217" extra = "02210081464dc2f85d185e0f6be900e552aff37b3acc87ab6465c02abb9da8de62c06e0101b957162674517c5544242ce5eb2e9f8b72ead332291c5c1af9b8e4c5408b05" txnfee = "8088e2ed60" ecdhInfo = "68f508c5515694ce5a33b316b990e8b67a944725c93d806767e61b2e0b13d300fbc3e5bdb36fc58e5800ffc549ab7bd533fadb7e6b64898c82ea620d749fc80e913372a2424b22bd9712183f5a7c8027c8d9af89b52d1e7d06fd1f87a1e5d20db9335c3dc0afb774f812f9f58a412c849f3c828d873f1c16ab102963799d9809" output_commitment = "cf141f5dfe04df14afad6b451d600aa5826a9be44a76a1630850c1d5951d482ee10bb69b66af5dabec765c7f5f7528926088877fa36746833828a0575896ae57" MLSAG = ""a8120b96f5f2a...611e395a409"" range_proof = "b9b544a75ad5a4df48156aff...16119b7a023303a6752" L = MiniNero.cn_fast_hash(tx_version+key_offset+key_image+ont_time_addr+extra) M = MiniNero.cn_fast_hash(signature_type+txnfee+ecdhInfo+output_commitment) R = MiniNero.cn_fast_hash(MLSAG+range_proof) result = MiniNero.cn_fast_hash(L+M+R) What I get is 60f983800f9791b97368318d21924f8e7ec63012af70db4b45dc831528e28e20. Not the right transaction id. Is there any wrong with my thought? Many thanks! A: Where are you getting your information about the structure of a transaction? You forgot to include the hex 0001020005, which consists of the unlock time 00, the number of real inputs in the transaction 01, the input type of the first real input 02, the input amount 00 (0 to indicate it's an encrypted amount), and 05 indicating the number of key offsets that are listed. You also forgot the hex 020002 which is the number of outputs 02, the amount of the first output 00, the type of the first output 02. Then you're missing the hex 0002 prior to the second output public key, which again indicates the output amount and type. Then, you've not specified the size of the tx_extra field as 44. I'm sure there is much more. Please cross check your work with the C source code, then you'll have a definitive list of things you need to include. At the very least, you should know something is wrong if you're missing out things which you can obviously observe are part of the raw hex of the transaction. The JSON summary of a transaction is not the same as the raw bytes of the transaction, as it excludes things such as the hex of the field lengths and input counts etc. A: Also take tx b43a7ac21e1b60ad748ec905d6e03cf3165e5d8c9e1c61c263d328118c42eaa6 as an example. We calculate H( H(prefix) || H(base) || H(prunable) ) for TXID. Actually, we can divide the transaction into 3 parts perfectly without removing any bit. The first part prefix should be L = "020001020005c8e230afe12f958d49809d0dfaaf33595a612d0df27181c46a8af70a9bd682f2a000124b873ba5d2b9f4b4e4efd672020002aa9595f55f2cfaed3bd2a67453bb064dc7fd454a09c2418d7338782790185fe300020ccb48ed2ebbcaa8e8831111029f3300069cff0d1408acffbfc3810b362ea2174402210081464dc2f85d185e0f6be900e552aff37b3acc87ab6465c02abb9da8de62c06e0101b957162674517c5544242ce5eb2e9f8b72ead332291c5c1af9b8e4c5408b05" which includes components from version to extra. The second part base should be M = "018088e2ed6068f508c5515694ce5a33b316b990e8b67a944725c93d806767e61b2e0b13d300913372a2424b22bd9712183f5a7c8027c8d9af89b52d1e7d06fd1f87a1e5d20dfbc3e5bdb36fc58e5800ffc549ab7bd533fadb7e6b64898c82ea620d749fc80eb9335c3dc0afb774f812f9f58a412c849f3c828d873f1c16ab102963799d9809cf141f5dfe04df14afad6b451d600aa5826a9be44a76a1630850c1d5951d482ee10bb69b66af5dabec765c7f5f7528926088877fa36746833828a0575896ae57" which includes all components of rct_signatures, that is from type to outPK. The last part prunable is all the rest content. R = "b9b544a75ad5a4df48156aff37800994cb906cef835709b0d139eee1c85e39037f79e2434edb0038971775926ced8de2df00a0ba91eec023e2adb2bfc6aa9907178d6faffcf66cfe2acb5a9b2d24ed2336b4520a0250a6cf08f2817572d42a07b786ac61b76124d41048d59126f1df353d959692154fcef4d4bcf1874c70d9074c8415afe5a4a251199dbb9c66fdaa27b052b94daddaec96d14d3b6166004600759f38fda5a18bd49d196a442a56e17709b0f86f4b87a95cefa26d0ccde7c3042f4599f6bc41e5c8c1c19ec63dfdc660870339c67c1bdc2e1828023d36d76e0d578c13bf4119e6b336e48030419f78488f08981a9f078b808030951317eb18052b94fa43bc9618efd0d1f3917f935f49a292d61f109ee166fdbe0b2f9541ce058569df9d95a99eb320a43c3a5a73b2a0e7d04c48de5092dc102339e9f635150db7546f948d586645b32575735131b9bbaa7882810bb6a3c5c9089a4f84f6a90e26cd5be07a1e86cbbed36e855f4027b4f492c9c646967e4f77c58e877f094606254f655312ff61b206d4091e93eb2a7ee781a7d1d2f0f00fe17b7e284b1f4609e9d80c4905415867ecdd5917c5b2b4329e194dd81d593d318f5f55d126f959036c93dd1f0525729056c3ed594cd9f85d282844ef213b196ba3b18bbe28166a02c25d5b58d1af1ddde3605b641a491165fd5895b8e58ab26ba54f13c68765ab00da449fed7f9499f963b72fdcdfcc61e80186510a457b5a15647fd39d4e8e060e7dca3f84ced64fd1d6c7d6892991b63bd84b53713b642551f2cc1a67a4b4ca06fa74e4d75cb4af8c4ceb9c06b9047a177db103600a55ec0740afc8e5e1f9710e3467d35b2e2c19eb9fe8a96ff8a12670b89d4cb5432aa035f4b0d4cb0497720760dc701f225f06b1731e12cf9e8e6e58653e037db0ccd628065f3caff715d00637054d156f1bf76e7538ab5c11ecd18059093e3abd377b42b6f6470e817fa30b201ff5ac0a9e79e4cfcf3e4fb5a3e5db8f8e39ebd837124545b252b28f8fdf03ffe44f4357b907c95b6386161a612a7658d685be7415a79348370a8dd7421c0bd5718484434c11d1095daa16581181d4eec075dce940d30873e596957b90160114c841108e32e4a50be7a69ea297d05af86be46ebe0e5e0777945380cf903a06bda79071fb1ac71991786fe64438bc3ecb7cf9edf273653158db5e5a82fd0e03da379c768c036c4de2b44feb13fbf7caa7bb24e1471e2c71fdaa6caa0179fa0b878e3b16e58fd012167f6735952cc6546b0cd92028aecbd036e15e4f0aac9903fd6d1cef10a6359c1af7e7e486b9ba2825bd78586cd4736a90b705ca724a98045cd53d8facfa077c33c689b51ea40468721660e63fc3950f3abf524a7017420f0939e0d6c66bbdb1663ddc1344ee8360bf18918ad24fc6212bfd7d3b7691a302be42b78b2f9f1d7059b1c8a0de00ef4e4d5638828d6904cfe2417099d4e1d204b0b094b00e02aad6c0463e3b1729ab5fea7b274d301254d609379cfc575de30c0d9b2926a06b7500c34c189d6275e8f0e6f12dacf97cc6f6c99f8d4f981917016847bd2288347cd398bd29b26875e1447ff606e3827c450a73cac8dc0a63ac0daac031698dce131aad69ca9da8fb2f2c2d3d17dec7169bfc96f15851e257cf0fa894c5406d0bac021890f1bb1da3e577be0ad4598836b8c27938c6a6acaf46049322c38075d773d83af782ad6e13597ca84221d04f1a428a5b1651e97fdf680ef36ee19580700d6574b2b8894c32ac3840a3f3a3a675cdec32caef0b1923660f6706028988cdb7d7fed7de65380db888a597d45d9c55b9ab54ec5ec411c50301b2e6f580109c4a4085e1e96995f171f58211d3ed1c4ab4ded6d811fe7524ae0b14bc7e2583b1f5b05fbfd0c1e2be67c089bc4502074165be32c97fe944fbf909dd59a1a45c338f94cffb4959587d18e6047b18eeac71cca77205742310bb2e009488d439d37c63d9a1e6b33b8f525c77049412208f86e4adc640e4f340668f0d27a5fa83d84feeff791f3bd96f88f1476bd490c175fc6e055e4992ebb0845e0c5f84219b03d618ee62d5c41b71cb9eef13a625381ce750116711f220e4461b021323f986e18d05080696bcf81440512255b1daee5eb449267736a35f757a71015ceaae0cde58d4deea0c8c1f6d60d3b9f0bb54e5351b36e5c69f7115c14c750cd8ad7ac3dfe49ab74c5952a06ccd94ab5d6a16cba583509bc1aed108d8eaf10e31be0a5e537ca6227030cf1f36e22226863ed8c396e9f6eed26447a5c1e5f108162a2d9b88c7efaa297f92d9cde1e3be521b6cf270d285f11976d82c8387cb0e5c81468fc8f89e207d7ace46f9f5e2a3cd84119e0ab6c99757f1182abe5c3c0bd6461930c3061105c0e64db80efb9120c3e991cc08ac0904fd4235d07e67a50967ec8d97c476392975e5f6d7b62b44abe7ae27795a025b2262dbb0c42cd3790ab204e08f91508dab69ae9cb2b273f0d286153537d8af06a7f17443667c830c0293bea634ff203f3feada7c8792d5a5547e51d25be453b2f19b18c348cb6fff0352f2fb6d6b65ffa528df82d0beba7f5b824f5ca44befe7b5b773ed0fa2df090c9798cc81e4c5fe8c32aa9b3d231046232566af93e142c9931df040c2bacfab0db340f9bdf8747d37fe21cfd16891b2aa01db915371a1a68afa395d09019896037b1f50dc40fde64538462aacf26f8e4007eae0897c18389b77a7c036c18cf90f71c966569970bb842151a9346017390e0cf24d39d3e2a94f84d80c035719540df8e1c6465c2260cc8dc965efa9efc84f5bb7e4e3c186d6a8346d8687f0eeab0fed4b9baf3287c0ef58f82d83c5811cb231efa93b9ed90d894661a8951489c50c0f567c73ab8a3b7c052fa24f5c70fe265718bd10acebe1323bc507a5b94bbb01d1bd15dd880bb37a79f4ead21cc3a7074264ce4afd24f946a83dc1cea53c71024a81583ae0a8d03daee6980190cb2e74ae69e0c1161f9583d24de34803626303b548fd8e8e5c18dfed0e3a413037bf73481d69715dfdccb978ecac108c18fe005dff08ddc912fb33aec32cf829b69d7db49e90ebede4491fefdb9cf2eddfdf020fd1b878c4d4799c07bbb2b770f5d88617a6685b218a8257bb92ac2173331c0929c630beddaca6916d7e1d24ef5b77d80c322cb56ba2d586dfae9d414667240b94e1d8cd984eca91d4486ea2a41c3ea48fb8ef5a5180c2b4361ed9ba63d078080955a46d68a0d0c1b6b744d5844c3f3136f98c611b50e8840a396c688499e70336f72284464be3abe75728d90e4bf625bffc5a1baf3fcf7844d45a872f627a0ae98e5487097369551fd27527fe36f643625571c0765d700ddeb3c99d8e4fbb0967f2de04de741b44ea52b463fa9aeaf9b6cfa42575b27f3bc5b946670c5fe103e273cc1490ee97b6e166d3b970f8e1ae3627f877dd0a4ebddb776097fae9f30f58745e588c5fd0dbd71fdf775f98c991c9381c568ba6d94d75e93ffed3de6f08aa7e1203e02f87daae4aa657059ad04b038523e9fda514c0b3c63f2970d4a00981c8047c2852b000f505e8c5a211a8d1755539d529ba36dbb699e1a6e380bf03e999d2247573e424276f485b17b20f39dab133c07b83fa40d47bab2e7424b30df768a7c5c9fd12546c95592103cc33c0ce743da65faeec410434ec3c379bb00cebc8a21967b05cc65886efe944a7b487a0fa9c133d85763f3423e30fec75a20c7468d43f7e292c5b2e6fbfbbf7514ca6fc9fd567e9e2d764da6946919482d90c23e5d3403d19ff42b26620144a58c9f7528c975553256c92232bbbac2dbc170c7722209157c82078b855d439b6fa81d2d090e55903b1e9111624c7ee32347c04f4ae622af2ec4781d71d9f201a197bdb05c73f05f2ec33b25498a665e4b7a408d3e6ec1aaedaf79cfee296f8251451e0d616b5ebc5383ec61a05d7eb3ed09d0bb85d8b361a16d94b6c24437a73b8f9effe05da721a3fb576409d20d250105a0d47e90c5538580dab2546944aecbbfb9f86a07e0b6617f72b0d7e6f33e5d9790609b81aa9808f51e675d1ee2ee9f29552b07470c6f8a2d49c0c545da259dd550be8835585ab93a9c381eed54f08ef36192198f76611fafe6744a18e6674338b0319935792e2f0893d743b6435a099ef70374dc1c6800aa67472e7ad16bdef880209a66f3062a9bf89e53f3106c72fc10857f3e7be924f4589a10f47745832f306e8584a6e66975d5ba3a526cabe7d24dbd75c5031045fe1bc4ff77e94d102d20eeb0a62f43bc3788bc22002f69ca56758a5952f3352db399c370e5ad89085130927bb7c640f316fa7bed901c3bf9a0a630936c625234278694056bda9a9b876058135500d62f19256ea06a948df06b7e559f425f61767e8c6cf4e04ae49324c057de8b5ad070930bcb8c0850b7cf510b56f832dad2220769570a29489ee4d5c054f77113f1fe96a4dd2a8e65c553e8d2c06686a3aaa9362636a7118473fb3510d7c6ed1e296f0cae069853407ee0435d674b011f9e50fdf6e56180546b5f2f40701cfd424df1504e695c1c62e7ccd447087242fe9bb5e4afea5f665cf2c6e63018b51b441984dcb5d03316ac0aa7d08054c2836f61b1fba50ade6401c5c222601c830a10844b17248dfa99c96e2a90968d37b34738db7137f37d144f1fd92fc0c84c219de0366728a4caea612d786ff2d7031deea627153699442e48dbe6358012ba373eed74ffb992f5e5732faa8b26ac4b402db5a2aca25ea626b040434be0fa01de4134dbed0fb99735c439058fd88278bbb4cd7c21237620840d71271bd0b30f33f612edbcdab36e64dd6cc50ee0b9494e2344bc41669dab5d6e1b01fbc0ab973d1edaf017dbbede2f1efb064f44d8709e936b10674f0254f600b822a3809684f1c856325f77217ebe97774dfd710478a50c6005641629b7a57c1145ce40e69e192b0fc155601669ce9af0511789ba5a18345ffe0de0b5eb7fb09c50eb90c1ef575e2c29b7acbbeee84f962c65a14c28461e8169fa8e6f0d3886ff9e96209c10cae6f4a5e34b20589df86cfd55fd48ac2aec18f42a12fc68e6598d63c3309c0bdb65b9eb9649e281d7974f7a7a8f4d9d939af486790e727c7afefa0922101927afda118c80abb1fab7952481e2fb7b3c5ece0bc7cb147bbfddb8bd4438d017856c235fdf7be47d86d704d0357e8e013ceacbd3e1ed77d209c9b0467a3e40dea113e03c68a8cebedce66c9b55f03a4a87d891ca29d972253e4f35190f6a101168a092bd04765870929f594c2c32081a010da282aa87f60b8b5b97c95ee950461706b0336e5546f0b8bd6104363a4b18d73be08e2fb4a077eca3517af52920be8265ef2320ff112fc1a35ff4623918f60b764d1dfba38e2d3954b692c0d790124c9659c1b0d2f5a396015aa2f9c9ecd798170abef0d4827ff6f2ca63fa3830b205f48e2e29662f8b8f226153ab4ee2e87ac901ab53da7035a67af9f77e11c0aa6946d116eef66980338ed755ea60671b96a258e7b682a2b66da8cd17582ba0a56d09bc74961d24fe63d1d077b977a8b273c9592b8f4ab44bad8b4365f35cc0f7fc2a37cdff5b8a8322fd1d358cbcfaef36465a4150b19ad0804613c76292200804367e16fe88b4b407c1459ccaff2cfa87e0acfb5780f17373cc3352041f50219db8bf88e9a70b25504f12cc0a1d088466b99e15710ea711a983f69576a6c0cdba2e78ee911db97c306bffb1220fe9574a6b75a64e9676066218dfd0accb908f053a9122876fae57498147740331e64c73bd4c5726e81c4c4b6205dacc05208bc7ae45729f2084c01b10a766c7c397cc1039798d86cbfe9789cd196a60f32cf2f9a3c9d9854b355978830e39350fe6ef04b71c33b72d9fdb72a34cbc90a370dc99ca464e53b4110018a50f32e8521afe1bb69e8a08f15a8229b4c925db0baabb76d47e110d644ccb0c68c2039584caa0712045076aaecfbdc26d248fa31d8696178fcec6cba1fd54356300538653317fa990b3ddf7e9bf0eeabbf7df4d3a9383561b9fbbbd0457026dd6b1b171731f418aaf08b72d6fac50bd5485b10994b8b09419ade40de119ecad69eb6fa116f4a3256c70e179aed4370dfa20bec1eb9b97a0f5f6fdb7bae2f4051100fad7070e6d065845290675baa98851dcd8677b5b964df38b0a8945d8b1a27f7c49e947ca801cb3abaa24b2bac58fd1edbd69736722f522b4719970e1255e8b344d3e309eadda2f9fccd423604cab35b89227f90b28febefe091c738a9dd1804e610fbe17ba1578c83616d73df305a12a2cdc5c087336af4646e32ec09460c3e8d0a14686808e3290c9e341404d937ee520ab2844c5bc85735faa42388dc2c1b4844cb2abb4dafe5e6047a676beee9f7aecb782bfad8f106fd87b62a47e4cd9f040819b24e51ad4dec266548eef2e3306d235a5da0d558535a010b8dfe196b7a9e624e1bc5bd5a37142a327b84e92e0d4bc86b280c7074b799ca34eeb76bbf316700d275a6c0e96de73642f8f3aaedbdc1795f803be947a47fd67773053373e4013f8fa20419166a0b81ca93a64427c8e2f5b529d28dd776e455b89d4061ab97f53efdab8698b37a0bd9cc1b34a656a848ef6e8f22c778ca59e806480d2b64f0cb522d2dc5c330c3db93a25e96d18b77d0c24fbc3a636375af4fd726b96834ef6e0495eb7c8ddc57504e162ad42c1dc2513b8e0502de93f9992e41121779abbfde8fb5f8ce11866d037c77bf03c3323985e979376133a57be3f1bdca2d4983cc2abd0ac9a0189f0e5ce8687c25f50707f1c07d35783da76f4a30b736f3a050f22dd902027eb4b2fc2f38b98dc8d24512330c9a6e270197693fd266f45d9c5f53da116865f20969ee0528837bcf7ca190446ffb64842f154637f32c59874c7f3596ead221836fa4e562bbfef3a47ee4accad55c85ad3ff2336672b66a6ec897287da6d991872debf9ae2d740a0be79f9d4871b8a89558427c677dfc5f61d612ac889918c61410d8908e0844e79318c6e93d491ce0764eabca769b96ccbcce8f670805f05bd5e8ef183956265a9abdc20376af2615c032c21da6bbbd0affb571695968f26d08d14140dc7bd3fb7fb91f32e35d4ee8c08439f3055eaebb395888c5744122a6f4064d587262b6cb31c3ac1275a0c11a4cce9b5aa64a2f2d5cc930035834f009f5c8987b1f354e527e82093967f022bdc4bd818f9557ec18164653d3e3ca8be896fe94a844a4c0541f111165ff9c23d39ddade586a884fe2a962c1499d03077bd0d9d1354a05bcdbb97c03bc66de933ee433c2e7e085688032c4cd5e4e963887927a6339dd5926108e661edb07a6c7e8830ddb320f25aab848cba850235ff18b2c2dc0fa3ca8d63b01da36fb93906899fd83f4bc86b02a768a5d321ad7acf9877e82e4ce4a20f49a8d0938f5a44f84a3720c20c70e56ff70bda03d3d7cdf7d29fe91aaaf3e7dc80ed8d2729a2e5a6301f54132a57759fc438ad7fa207d329955442f11d4247ec6c83aadb9b20cc54f09d1d53952aa3444942f3512365d001fc08794b4258a7812a05d0afc19fe656be7da8236b3676e8178ea5735dd30bd4a710ada19c6a7909c07be8aeb2a5a563709a9b4f1838440ba2212959abedd2978f390106a0c87b54afbf6f587366c5535119767517ab9e8e9b8d4848b6e772df73aa637ab0e02610fe910d22ccea347c35d3451f5e44ca052604678f327b6bdc47fe100312fbf1b27da2f79b35e64c16d8e482f6b7118efd22e335df149c822ea172d632327fabc4697bcea7b64e1d8f67da7fd939d026c121e664b1c4ad376daf614f09981afe72f1256ee0d4d0f41d5b5035f0264bb60a37c6e520e959673499f28ce17bf30596c898115a59aad5d7711f73b18b4c3f0015b39ee3a88e054ed43797aaefffb154ac1f730be3275fbb6b0c2f67cd060f2b92dc24e1727a15be1a23bdd4e2068272c384a95467feb069d1516d3e87678b0ec6701a28f6b2a36c7a0bdb67cb886949a1ac828e0448dab09bf916fabb1d883ee176669b9370311ec7edefe264c13f08f66ceae4e0fc46d9cb634f190be84eb0d908505950c2326948adb55944a065e879dd3f75302c008609011c331881c6a9f61efe5b9c5e17fe73f5b91b554cc0e3e2a7398b97c389d6f9cf98fd603c028712d8ff01d823b2733cb592cca1004913864c825c86a5adedc97273fdb2059d485dee00b67110f2ddc3c67df3a4538ffe41c0aeb0c1cedade043eba962a81b4bbf619b783a184865c8d0dc51ee48b71b4012e742be7cd585c915f5ceb4acf9b783ba903dc1c29100dcc429b1c0e7134ce9620a31e2413057c337463b802eefe4d49796315d90502a0527859375ef8ca024a4ad624b239248ee41bb0d34ffd1772c23264d43b6f59750a9626e7f36c36b996a5e5305fc1e09c371937ab63135c6549b4bcac37a9f4d11750eaabc459bf2b1b385f4cbc1d544db17b1c139beba46bbec36e48414d9fef616a1a6ba9f0ac30c9f605d735dba79ecd1e26f5dac664b332620d67a003838aa1eca9f28120a463fbd2c673a6617bbeea0cf269749d7d0773b717c1838660e71d2d7a69b7516972288aa37ca4f1618a4d2fedbc11285743f6e3b5324a804efad66ff8d56580e4ab28de551435c9f149658f9eb0df04567532381f428eb6e7647937f4ddd8b879b7cc5756bb8743dfe4904589c457b41c6a1d707927c1100cddfe78614db787a90910560737b9f4139459904e26b1389647992e2fea7b4752922dc4dff1eb72db9e47852d425345cb625b503f152c7e4fe0e57a3c49209c1007acedc5f8d235c3397e63ea619239c44a5710f01f7581c9e51dcafa9de25f0d2c8c68c56ea156001ae8eb621ac39daef6906075bc8a3390976987b3b190b697f99fcfb01fd8213acc8d9862e88acf75db0b402f5035d7c4e1bb28958d4bafc0ab4ad254558a3d2246d3e863393d68d054d86058f2b826c5a6e6399360a5fa017b774a564788f3232a2a784692fc8dbdbf2a80ccde4c338b6966f0bbb8479378b7ad3957eeced127be03fc074849417830a990098ffe9886d7c96b3d759f06a0d5e935b32eb11acc5d0fec4e073b11433ddb7068ddafe4d5dd3436c9bbbb75f8583d888f331e6c36978327019d2af92c2fa290d3a7c0580daf16f050911b1fa10cd82ebc5ce9f1db1961a40a2acc58e7880040959ffb8eeecc356619669a6f3753856639f21f5b2fcce1d1460833bb1c3adc506afc599da2915ea35eb962d8d03bd05cb3893ba52edddc14e2364a723001a110c5abc4733703a50d9a4bf9a8d97754cd691185575cb59d168f8d02d93db6f1e031782fe8a9c6a77e686646295d50a952cc7fc11f9c93c2382d54fe6eaa69c1b02c58a67a1b12151645fa89ec89ff91d0c069d3949c403e265732c1445641a520fc15bb242f4547c0192a754d99babf922b5d8a82839e1fc8e5b7916be3172c90b23f6ca52a97f2bb59534b66ade5416b64ad34823de16884f4e79100a592ab90ad499ee51fbbd24319b836857e8f2ceca82cc87140fc16d0485a92d4279cdea005f6ebceb788544dd85bdef5c2c958e25994917f371ac1e83e910bdeab86a1b0e90060c6547dace6aa366ff8d17eb821e7b054ac04438718e468be5935730550cc835940e70f201d8b24a88653152bcf5fbcb32705d0e6549b818521ed07d4b020014832548538e7f2711030218b7222c223acb75b79e363d068094ef6649de00ccca86fc0c5eba687a50479d7561fd1f302e3710823341117f08682ed832ba04fc737d02593d12925979cde82ca4ee9c83e3909ad08488adaf30465ba878d005bddfa62c350a8e113437275b29afeeb6a12e7fe9d15a77fccd3b9ea943ecdb0c303e111cae708d64da96a2101f9b30142805d3618a2ac365579254b310d9b705824cc4815dcfbc5eb521d5f4bd53b179f006ba0ac42af5efdab9e79771851a0982692fa51f9f6f9680f5798332c10975adf806970d53d6b03d8c97131a6e54093e7a22626ae1f34b257c4d2856c1e34679ef6a6633e38b5461568f5ccf43e30ef34ae6849c01d60846c577d350ec60bdc0a725e96229cd5ffa73cdd30242f2031280e05bee09aeb0577b3a5cf440aff5ebea52a45eb070ce4e7d1b8f5f229f0eb4f3363dc070a2a6fe7e943c68f8898920e1e66aaf07f00f2cfa0979faeea20c7f3e08a5f3ae59c8e83a2d6a1e8f20e12b21d1f581efc933a12741f2326c5f0fe109ff44c08cf054c1e9109beb7602853925696d8010ffdd2bd0edb46dbbe80a2564b8e46c0621fecc482adf12e304a851744e8bff4e992e9b2e425163016a06edf4af5be36b2d06b2fded36d7aba838e8483f4608b8ec85aff29c464c7567054d66d5c48e151ac7617ffd5a521143fdb3c50e5cba7b894ca44840e601737c04084d566f70299cca8d19cfc1f7c80c93b6fd4ba9621b3009993a27ad5713880c5108995c9e16032bdb17d98072d6e9d65a2141a5d7b38c3637868ed07a712407705e2f6e341e7d9a4089cd580d1f015fff0bd274fa13e9124cabf3d0d5ade20eabd9394903d96665f31cb19034ef5a43dc6334eb6e582093439f07bf6c915f052e2419068081cda7d9df91bf81560fbf4ece15281872c82a83ef2878794af70ed78ab91baa65f2d8019bc190fcf0be67347fc0de5122882cb2adad5eed0da80666cb4e78a3de2a9b58da3dcf74d250d06793269be80b2321a5f003721b501b086ef7127d82a6ec20cad15a64b1b4735a4b02ddba821738b8f56214977e81710121703f8cede950103745dd65feb9c8e5ed4ba3d4b0f0320d840ac7d986df540d60f8d4c463fb629a3fd22c818d1010d48c839ba51a47845f7cf8bfd7dec5e203030b301be1dfe78e63f79427f7590db8b4ef9e9cb1b1e0eb67f76aa40d57a20a0763940c78c989bb96a07e6decf9fd44b374854e19867e414c9bd92c0997f309180081889e3a344d634c5431cd39ced4c6d391d20fb788f2025af58e093d730b834f55f7054611be0052ab23bf6b1d2a26dafc24ab8315cd1c23c25d92fd58013342ddec6208a908e1c30957680b4d2cfce4efd30372a5d046ecc0f7f6af840d8853f6afa8f505e1c8ebab215d1cac88f965dfe9ad470d326e8bfc6df6c25e0234d468be1b6aff31cf039cf0449905addb7c1703d31f13ec767bb52b9c6b3908d8e6abdad80c399d2e11803fda8e2612546a526b9198632575c8d20df159020f8da6cd3f62663a2c80e143dbab9b3d4c3d76d92ed89ef00c18588a50393b93067dd7dce2162c53503c9e1e0429f0aa6ed9748dd0a78152f17b1dd9c77dd91c09ab493cbf705e3713e15fe66ef70fecd0541ea7dbd714c545ca6f53a4936f44034cd24a272bd96eb3fda5eef11713dda72edd90c38400d12993073c66f2ae500f059d37276090ee82eda3464a70d736c80c5908d1f6d0a8bdc357782b7e0704093835b8c0c177efa0ed5306940dae54a6a219b027f92412875e9a923e30c34c007abfbbfe86bc8f63e91432c257a209fdac1113e818250e06642062c851cbaf0de593fd896c50b79dc41d1f000ff91953d2b873b7b914dac3417cb96dadbe5301e9ca564f0725d1f615314edba8defe6258c9b06b956fa3aa801cb7bc4aa0420e9905c97da1a9bc23e6a734f119ab6b9df325b5117cdb269ac41a0a0421ed440abc7c49a1cf2a9c4e4273e126ae007cf9105c5ed173cbfe1d9149f97e5944ff03e8896aa936a8a3004c4b50d8a7c61629a426f6c0e884731f9b5195085ed28e017c8b725d90c378987a2061a31309f8939f2896514a73260200eb4cb270e0e70608310723f2695d1cc0fa57ca6a138738dd91d457f1b0f1997a59765edbfb3308a404a338c84e0b45bb8612bf338dbc75c55c4ffee07fce100221b848b1b6530f95024d84991f25c6faa28356a3310afaffeddc1b5353040ec3ca02ed19ce5106c13862b9a7766beff32fec523e7df45bd0b53b35233f09bcc3783b7c76c2dc0ad96ec0340142b39e48e3bd5bda2d131c4ec4578d9bf18ed558e1027f2192cb0e0cc91480a3d46e06063c2361e79c9bee1b00ca4ad316c959713f4e9d9780fe07db5f9b5e6cb4d42eb08579b1034fc56049ec167053d808724e5eb2e77445890fc2c9a76ccb8e909de5398938dd7c05771a1398863b97603568fa5e3813f6fb08fc8ecddcf7a93b0b3f6b9322e49d0c953e146fab601082be1669fa0607efd40eb7ce0f14563fbbf4024332ac3f18fd3fb214742c3096b443708f7183b13fd40c1afed3aa0920ded62d548537f6331068b276d1d7654915bd60f9941df5f5bb02c54580a5aa93b97c313e0ff666c8afb7cbf908bcf910de426d7a9b6925966600995d9b366be7117ada0b9382001d1d01161e84a64e687a379c807d7f333b9d0cfb299503633f34dddff2d6a45c452cbb9242cf0e025b3150a155747af1f4d50374d7005291f4aee6da5bdef01c5190f3edaef57eb650a500c6c9a362490db90b5895387b6a033e3e6a1c8920f19c33fc3695ad45691ae7f281bb2bbadb655407cf55137956898b9c34c7dd376615ab59b0964a7060eeafbcd239ed9d052dde0dc406b6e75ef9127c915681c21e01a77b8f465ee86d8799b1e49879bbacb22a0335ee2d638293933bec08e578542d414cb212e8d36247e1c029a9ebf41eb2c3015e015cb15da1cd43ffc77499597d3ed9cd41f961675911d5b0062c54b037d7072d08b4006986d134da8ae46b9336eb82f8fc4bf2d17a15274ffedf8a8c7457014840eb5f9cef06bbc2d7b30055e4e9443e6975fc49998dd9dc14012ccd9b740c5dbe585679da613bc26d4f5428a522f049c93adc2ad63030ef94cae2cfc2900d1f31fde0103a9a2f26b093030a202b8221d5191c2a5443756c57a4a94e9a96067364ba04194d6d91ea306ef1d85d9d17d4a83429ab2d3ac6588518526505310a48d661f15675da76fd6d68b7eb629051f397a37938f585fd49c865d3c3d0810b0f232d738e89ce41d5bc267ef33d2857a464c15960a4b9fcfcf13d399be94a056258ceb9573fc3f542afe6c6b4c201f6d57ae82f5448626f60603f66f9b91e066f60fb6f19c95b297114f8f70ecb0dcfbffa12ff30e2353d5aeee0bf5ec161025a331757596166745263bc41cf7f8eb5abe2ee8c4f39a85b180644c5a9a22b0daf2168e6daf31648ab66ef91a5278b2cdf52634551eccff8a30c658df523ed0fed5617c86c86a54d09d40e816a5ff8d8a807c659b1157f8cdecea87cb330920e15b637dd3f2ea0f7f23f6bd33a3fc6eade81996556166b13f50c736a2ce3c4026921c3bd1aa389a4120cbb3c19a1c31925949a0338139127c7bc54d4a88e0c00a1bc7c9e34f5ca33ef4230b8edb8170bc4dcd15ed50ca572fb74d9dd4d6e0a0f44aca3fa73545015787d863e09357dbdaf40eea3718874b7ef4f36198ec2da0f6a6893f8c0acb9b5493b971c41acd84c0e615301a553e1808844ee5704cdd2092be870fe2bba328710158aee9db8bb36c8ca97702cf8e341854b631b43f4d40a062907a24c75033bc35139a39941f2e8155fdd3c48eea383f23320d978c9d80ff210f00a238934f2333cfdf3ac96efef4893b9d867c4c63b6d16f57b869b4107c8213624aec445eda3203a8cb2703bd81fdc7f51447b39d1941d4baca54faa00bff17b060790b3e8c3ae205dec7f219464eae97fa42d5aa9149be82aa8438e06c648638e71d96a4a851e7e7ce7d076c3613e8bfab2997be48b1cdda8d1244c02aff3a9c626bf7f69b5ce24d69fe42881d7ca2a00f1fecbf3a15c21437d99e500baf164c04866d4d87d6e9106df2ec4319afa0fe9d9113acdf0b16c0f24bc910754bec182fa30834a7a770552d281122d6071bb3fe18b1bb52fff909a7c20310c773db70173495068d6be8cb854f3a0d54ac1950caea9127881debb02c712ac059ad333a502945c4b3b86ffbcba095daed54803d9212dae24c9113ddcf52d070f6ef7402e80ffedfb6b86735f57f8e9e92edbcffa5b1beb71e52757f3c0cf5105ab9bce4baaa97fbd49833a9616849a39a11c651e1ad29d8351b18c6aa2cfeb07673976c52d8ac842d15e7291e0c51b17133aef0581c9e877f096f103ccd3cf068ea205cd2739d696cc8221d7dee0155d85914d8035630facc31a9df91b255f0117bac7f463096ff75c659789797e9049c90f86086202ee7fc3461e65de47010424284674d8b55e5b1efdbccc01d0f3cda1b9e32724730e863c995b486d5fd803b8041e2602e6d3417b9ec4750a26722c2d637908fecf87aadd9f350ab42f410460641fa6c13cc522f4cf8216dbae6c7e1faf7fc4ec2b62ed7044309fb6f7d30853bbfd66e74025e3b9f8f7c620308352041536f7909ba25a28ac7a3c7a65a406d32f6a062c5fa12d3baaf6d3d3b4fbb50516ac71807cc957c536de77c3bffa09699d4acf6397b524dec855e28b4deec81e10475aae4d866575405f642e9bb70a334591f85d2c857a3666958e9b7fcda278360f757743f14ed6d715ac9545b60cce9b4d8e8d47438f9c68c10c9f6723afe1bd934de98c65e49cfdda190f48b30f64316c6a4c30cbc655d1e9fe8e03f59e6a681f57fccce3ff379d73ee569f59248c85ec86e1c62d56f06d6fd01a04f2835d1642f984a9223f08c63985d9e88995a0d127229a56cd984e16d15a9c3a4be49fe7d62f8c92e541d99815f46a5fb2224f7b062830d2b23d9721cae65991255e37413b2de2a18844ec33c9f03f4da8a56115e5c04ecb90bb38a7e298a736316f282af5b97f336e209168d4611c1cf393b8c497b260b0f78ec078d6a75249c0db3a477eb50d8b6203af1bd9948e030011097f5a0df86cccc36ef276f77d245a3715932f3dbbcf85c86a64a153e18754443391ba3a435fb321409ce0e7fb59f5338851c9de1d848fbf2b82d0b662dca9165c2ad84b6e8fed9fd77cdc85ba93ec5a6dbdd346c1c967a62469cece6b1630e9cb1eaedb1ad2b8db823cb777d4b11e66fabf3ce45d5027a4653ea13c01b21e97255f329314fd0eb7142c209a1afc50ba53474fe13a4c180f1b5aa9e362803ebd783175efb84e1d277c4cc9d72f36c1416cb5d6f7a497013c3a1a2f4ac3f032fcb21884725ec368486a864f72d3369791c61759da5696d8130428d79220558bbff572aed0fe4ec56ec7749e54c8fb74daef5ce9a593e84244e167cd1c8e901cae04bedc416b434d6cb680620f6e2beb388b7afaa78a6504f6bef96be108e989019082812bf28e97c1f75e587a84a805702de5322cb14b20662614fe90fec010b5a2d3a5407c3d5756c8e3ed6e670a036114589e15499544bd60e517d6f99acf44fa106c05ec7ca78b8a5914f912cdcc3629f1a08dd3987c4e38bad85557d81f2b48e11d6935c5ac57aff5390a73d348e50fa8f4be41fdcf329d781730b6fe1da73d157c25c568e194bbe7a4871b9e4e7d2b48609eb5771990a8f3bf58fe30bccfa94ed3128fe2ccc3b46d954de3d98a9f341c7253ece281eccd425740ad0d3ca6a2c8b706a384233385ff076d9338702b507b18e20c7509fdf622cf27dd49374fb092432fc6466ec51a35bf39571d48cb8672a76a9d87f7cad8baaa1a1b30e261057960b5d4a8a1080f19c960a2e78917ce1b5dd4e198ec98739361dc45c963e7ed3ac4cc38d828c97fe760df726bd81fc767084babd313421c6eb26d0cb7924ee8e11a573e332f03aa83d96b4c27b770b13558745df6ef92a981f177720dbd46269f51a7f23c70817b9c9f9c2916cf4895038ec5b0357e5f847df1ceaa038d078783cf7d3c8ee8fe686f0597340ed9fca3b0e61c0c69830437ec2660befa6cdba55af99b82427b395bec0c406b16553deac18e9314551d3bbe3ec87ad91adef9c4f9c38ef3f6082ac4571aa29b5016dc34de4865b02291b866c7ecf61b138f2da19d7e855dfeab0eee712ea875954c9811c9309c186a55e71786de2f4ff1c5979a6730183d391d386619b539cf2f364c83876ffcfee73eb367dc3a8c373650718df4efaf0e8e3265d56f0831d19fb08b98b67e33bfc262389c9bab0b3f898995d8bd03416bb02add44825c9afda58503780672e8103490922e73a957841ad7a2ae9d5669e2939bc6df9ee10d634fef50bf2151284be28440ca65697631b7ebb637068053eb834356b52e44e74964dc5f430b8b02c58632b9a3f632b3635f0987fe251eca196a3ea7a3ddeccc1c902f266ee8145c582d35050cbef4142f0ad507d6dafdc8e44adedff4f9cab3146e3baa2a755aff2919483341e4f718c0bb14b6439c18c9cd41d82cef22e9f20ba71fe8a942da03b21a67dc9a306dfa92c449716fc6731a8161faede3d77edab637e4aa1ba4b2285dde10d665f77e491cfdfcbe01f821095952dfe843de2b477cfda6e9eff69f71e98d12902dd3eda64d24cfe63e02bc9faee523d4d0427c19f8f8b27251a9a52024006f6e17bd5d5fe8727a458d2d0f891fa97acc06127b6f3a5d34e1f2be868c37e82e1439b6f98caf3b706eb24a82dd34eaf508e4a5acf789c166a8c5389439d08f4ebcb2918334918ed39ef397ac3e8d36e4a2a2c1913ac9b621681d5b190b73dda5d44991062a3638b0ba3fedc1055d551509b5dcfe92d0a18175b424a215b7cabac6e0495dc818abe4c28e1d5dbfd8d5c4c04f75d426a7da4f2922344b77edb3a69b64356789436fc718def84bb93877d9d0efbbe9351e2ab2949ce6883e9c648e22f38e94a9ae861c37b2c0d6ec1f5048fee351e2955576b3c80e0195e5d607c940047a63a58e06c56d1db5df03eef9ca00fc0cb7c8d362d83037eda9e7e8a02798ec5294243dddaa60c3e29f03d9aa48d5b5f14df3971e7c4ec8807c7fcc637699e27d3435ee0ad4b71ee8047be2ae1ae4b972041ece4efa82ade156c9b136626873a1dd8be66a172478c882e28d030392e0fedf04a5a681575c0cfc1bfbf67bb978e86c7f4521255d260b8615f2792d5c01e1a8e9234809d69255cb8c587a5a092885125103ea3f6bee9aae7c8a72b474d8c91362d80191712404dd816de7ee03166bf200c4d53823e32f15523a9095fd61ff540fa21cdc71b7daeca8b34c271ae69b233896e566ec4490e7a31ec19cd09af191ba1f718cb2fd1db65786bd2b19a04434c5c34136e84d2b1571582a9d396ab3ff389e93a51b86026d1bd87187e57a11eacf3e1421c534930af853c9e894cf4a07237382eee450c4335d5c9221e86d6b9c8892996140b65fd7e3f8637ba203a4415be2c653d6120c05fade3227cd1d4cabd3bd22b16f1199344d9297749f87a1958cf79ff550d1c5978db49f6d4eef732a62991a82e77450611cb13951a624652405201955345b9e9cd1eae27ca256513b24491b460b3d776ce8bfa7b118cd16e2926c0f80aeba8d6753bebf716119b7a023303a6752a8120b96f5f2ac5bceab37f7d6bf8d86554d87c4af3441007cad92f54a24d9082e6bc016297a5d398936c9f45e7a80215138f69e55179b337922e2d51c1a9f001e1052a68c38bb88b6e8f257d999c13f1d5f4fa219cc23479ccbfa6b14b5960ae914d35eed0d27344fbc3a89b91bd445d433b561efc844c9f466a61ebb5f6d09e04d011f515461fdbd8d13536c23143dc365d87dd323defb1af834e540a8fc0ef9b41a117a1415fec54f1cc16aeef859b2cab1494b9e26a95fc9eaf4f571fa00de7a7b30795cab310b632f708c6c2546847a5cbcc27ff48e75c1556c3f6f180c6218695558359d115e308b008d9aa368c38672732d2fc21c6317ad7d15918c050ca70bbdea0e391b1e24e2540f33b48dd9dc554c61ebf23bb3691aab5094e40fdafecd436b2448504c0a3a1997b356c141f1d4b5977cc66e5f55592f137315015059757cf06216215955aaa108e8dd40be157856749a9d883bcac611e395a409" Hash them respectively. L1 = MiniNero.cn_fast_hash(L) M1 = MiniNero.cn_fast_hash(M) R1 = MiniNero.cn_fast_hash(R) The last step is to concatenate each result and hash again. result = MiniNero.cn_fast_hash(L1+M1+R1) The result is the same with TXID b43a7ac21e1b60ad748ec905d6e03cf3165e5d8c9e1c61c263d328118c42eaa6
{ "pile_set_name": "StackExchange" }
Q: How to make flashlight Blink in android In my code after exiting from thread the flash light is still on. I can't understand the logical error. How can I turn the flash light off at the end of the thread? Thread thread = new Thread((new Runnable() { @Override public void run() { SystemClock.sleep(200); int led = 1; while (blink_enabler) { if (led == 1) { params = cam.getParameters(); params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); cam.setParameters(params); cam.startPreview(); led = 0; } else { params = cam.getParameters(); params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); cam.setParameters(params); cam.stopPreview(); led = 1; } SystemClock.sleep(1000); } params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); cam.stopPreview(); } })); A: After the while loop, set the parameters for the camera before stopPreview(): params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); cam.setParameters(params); cam.stopPreview();
{ "pile_set_name": "StackExchange" }
Q: Suppose $p$ is a polynomial with real coefficients. Then which of the following statements are necessarily true? Suppose $p$ is a polynomial with real coefficients. Then which of the following statements are necessarily true? There is no root of the derivative $p$' between two real roots of the polynomial $p$. There is exactly one root of the derivative $p$' between any two real roots of the polynomial $p$. There is exactly one root of the derivative $p$' between any two consecutive real roots of the polynomial $p$. There is at least one root of the derivative $p$' between any two consecutive roots of $p$ I have taken $p(x)=x^2-1$ then $p'(x)=2x$, here 0 is the root of $p'$ that is lying between the roots of $p$ that is -1 and 1. Hence option 1 is wrong. For option 2, i have chosen $p(x)=x$. I guess that option 3 is true but i am not able to prove. Also i am not able to give example for option 4. Please help me! A: Hint: Rolle's theortem If a real-valued function $f$ is continuous on a proper closed interval $[a, b]$, differentiable on the open interval (a, b), and $f(a) = f(b)(=0)$, then there exists at least one c in the open interval $(a, b)$ such that $f'(c) = 0$. Now, what about a polynomial and two consequtive roots of it? (The first three statements can be falsified by simple examples.)
{ "pile_set_name": "StackExchange" }
Q: Backlight adjustment not working in Lenovo IdeaPad Y580 I installed Ubuntu 13.04 on my Y580, and I added the acpi_backlight=vendor option to the bootloader. The OS boots without the black screen now, but I can't adjust the brightness with Fn+Up/Down keys. Is there any solution for this? A: Alright solved this on my own. Open file /etc/default/grub. Find a line GRUB_CMDLINE_LINUX="" (there might be something between the quotes). Add acpi_osi=Linux between the quotes, so the result might be something like GRUB_CMDLINE_LINUX="acpi_osi=Linux" Run sudo update-grub
{ "pile_set_name": "StackExchange" }
Q: Parsing an enum with the Flags attrubute not giving expected value My enum: [Flags] public enum EqualityOperator { Equal, NotEqual, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual, Like, NotLike, In, NotIn } My code for parsing it: var operatorVal = (EqualityOperator)Enum.Parse(typeof (EqualityOperator), filterInfo[3]); When I debug, I can see that filterInfo[3] is "Like" However, operatorVal comes out as "LessThan | GreaterThan" What am I missing? Can you not parse enums with the Flags attribute? A: You need to also specify the values: [Flags] public enum EqualityOperator { Equal = 0, NotEqual = 1, LessThan = 2, LessThanOrEqual = 4, GreaterThan = 8, GreaterThanOrEqual = 16, Like = 32, NotLike = 64, In = 128, NotIn = 256 } The reason that Like is parsing as LessThan | GreaterThan is because as you've defined it, LessThan has value 2 and GreaterThan has value 4. If you take the bitwise-or of these, you end up with LessThan | GreaterThan = 6. But look, Like has the value 6 as you've defined your enum! So, it did parse "correctly". I'll be frank with you though, I don't see the point of marking this enum with Flags though. The point of Flags is so that you can do bitwise operations on the enum values. Why do you think you need to do bitwise operations on the values of this enum?
{ "pile_set_name": "StackExchange" }
Q: Did Salman the Persian meet Isa AS? ‘Asim b. ‘Umar b. Qatada on the authority of a trustworthy informant from ‘Umar b. ‘Abdu’l-‘Aziz b. Marwan said that he was told that Salman the Persian told the apostle that his master in ‘Ammuriya told him to go to a certain place in Syria where there was a man who lived between two thickets. Every year as he used to go from one to the other, the sick used to stand in his way and everyone he prayed for was healed. He said, ‘Ask him about this religion which you seek, for he can tell you of it.’ So I went on until I came to the place I had been told of, and I found that people had gathered there with their sick until he came out to them that night passing from one thicket to the other. The people came to him with their sick and everyone he prayed for was healed. They prevented me from getting to him so that I could not approach him until he entered the thicket he was making for, but I took hold of his shoulder. He asked me who I was as he turned to me and I said, ‘God have mercy on you, tell me about the Hanifiya, the religion of Abraham.’ He replied, ‘You are asking about something men do not inquire of today; the time has come near when a prophet will be sent with this religion from the people of the haram. Go to him, for he will bring you to it.’ Then he went into the thicket. The apostle said to Salman, ‘If you have told me the truth, YOU MET JESUS THE SON OF MARY.’ (Guillaume, The Life of Muhammad, p. 98) What is the authenticity of this report? Did Salman the Persian really meet Prophet Isa AS? A: There is an unknown (potentially weak) narrator between Asim and Umar and a break in the chain between Umar and Salman so its authenticity is questionable. Ibn Kathir in البداية والنهاية comments on this tradition as follows: هكذا وقع في هذه الرواية. وفيها رجل مبهم وهو شيخ عاصم بن عمر بن قتادة. وقد قيل إنه الحسن ابن عمارة ثم هو منقطع بل معضل بين عمر بن عبد العزيز وسلمان رضي الله عنه. قوله لئن كنت صدقتني يا سلمان لقد لقيت عيسى بن مريم غريب جدا بل منكر. فإن الفترة أقل ما قيل فيها أنها أربعمائة سنة، وقيل ستمائة سنة بالشمسية، وسلمان أكثر ما قيل أنه عاش ثلاثمائة سنة وخمسين سنة. وحكى العباس ابن يزيد البحراني إجماع مشايخه على أنه عاش مائتين وخمسين سنة. واختلفوا فيما زاد إلى ثلاثمائة وخمسين سنة والله أعلم. والظاهر أنه قال لقد لقيت وصى عيسى بن مريم فهذا ممكن بالصواب. وقال السهيلي: الرجل المبهم هو الحسن بن عمارة وهو ضعيف وإن صح لم يكن فيه نكارة. لأن ابن جرير ذكر أن المسيح نزل من السماء بعد ما رفع فوجد أمه وامرأة أخرى يبكيان عند جذع المصلوب فأخبرهما أنه لم يقتل وبعث الحواريين بعد ذلك. قال وإذا جاز نزوله مرة جاز نزوله مرارا ثم يكون نزوله الظاهر حين يكسر الصليب ويقتل الخنزير ويتزوج حينئذ امرأة من بني جذام وإذا مات دفن في حجرة روضة رسول الله صلى الله عليه وسلم. English translation by Trevor LeGassick That, then, is how this anecdote is worded. There is (in its chain of authorities) one man of questionable reliability {unknown}, he being Sheikh { teacher of; from whom narrates} 'Asim b. Umar b. Qatada. That link is also said to have been al-Hasan b. Umara. The tradition is also missing a link, indeed untraceable, between Umar b. 'Abd al-'Aziz and Salman, may God be pleased with him. As for his words, "If you have told me the truth, O Salman, you have met Jesus son of Mary," these are very strange, if not unacceptable. For the period involved must, by all accounts, be one of 400 years, perhaps even 600 years by the solar calendar. The longest anyone suggests that Salman lived is some 350 years. Al-Abbas b. Yazid al-Bahrani related that the consensus of his elders was that he lived for 250 years; they differed as to whether it could have been as much as 350 years. But God knows best. And it seems that he was saying, "You met a (good) follower of Jesus, son of Mary." And that could well be true. Al-Suhayli stated, "The man of questionable reliability (in the above chain of authorities) is al-Hasan b. Umara, a weak authority. But if he was correct, then there is nothing unacceptable about it. Because Ibn Jarir related that Jesus came down again to earth after he had been resurrected { raised up } and that he found his mother and another woman weeping at the cross of the crucified man. Jesus told them that he had not been killed, and after that he sent his disciples." He went on: "And if it is possible that he came down once, then it is possible he did so many times. Moreover there is his evident return when he broke {will break} the cross and killed {will kill} the pig and thereafter married {marry} a woman of Banu Jidham and finally was {be} buried in a chamber of the grave (usually referred to as the garden) of the Messenger of God (SAAS)." Note that this translation contains several errors I've added some corrections in {}.
{ "pile_set_name": "StackExchange" }
Q: turbolinks / redirects after a delete Having a delete response handled via js, I'm reloading the curent page via turbolinks. In other words : // onclick setup encapsulates the following axios({ method: "delete", url: e.target.getAttribute("href"), headers: Csrf() // passes the csrf token to keep things 'rails' }).then(() => { Turbolinks.visit(locationWithoutHash, { action: "replace" }); }); Our signout link is handled like so. Signing out then redirects to the root_url. The problem is, Turbolinks.visit seems to preserve the initial method : Started DELETE "/auth/sign_out" for 127.0.0.1 at 2018-04-22 11:21:12 +0200 Processing by Devise::SessionsController#destroy as HTML ...stuff Redirected to http://demodemo.lvh.me:3000/ Completed 302 Found in 11ms (ActiveRecord: 1.9ms) Started DELETE "/" for 127.0.0.1 at 2018-04-22 11:21:12 +0200 ActionController::RoutingError (No route matches [DELETE] "/"): etc... It might just be a matter of syntax/grammar which I could not spot within the source code Without discussing the fact that such behaviour makes sense or not, is it possible to specify a method to Turbolinks.visit in order to make sure it effectively passes a GET ? (as I'm just using it to reload the current page no matter what happens, it will always be a GET) A: It's happening when the destroy method is like this after delete redirect_to request.referer or any URL something like this if you has like this then change to like this def destroy @obj = Model.find(params[:id]) respond_to do |format| if @obj.destroy flash[:error] = 'Deleted' format.html { redirect_to request.referer, status: 303 } format.js { redirect_to request.referer, status: 303 } end end end I think it will help
{ "pile_set_name": "StackExchange" }
Q: Как поснимать checkbox Имеется Чек Бокс вот такого вида, как на него нажать, при помощи, Python + Selenium? <input data-v-3719c1ac="" type="checkbox" testid="ns-chbox"> A: Альтернативный, более лаконичный, и, кстати, быстрый способ нахождения этого элемента - это "by css selector": checkbox = browser.find_by_css_selector("input[testid=ns-chbox]") checkbox.click()
{ "pile_set_name": "StackExchange" }
Q: принадлежность переменной к списку в Python есть функция: def checkSomething(var,varList): if var in varList: doSomeStuff() else: print("error") передаваемые значения таковы, что ветка else не должна выполняться(например, var=354, varList=[123,321,354]). Вывод переданных значений перед проверкой условия это подтверждает, однако каким-то непостижимым образом выполняется ветка else. при этом если попробовать то же самое запустить в командной строке(без всяких фреймворков и библиотек) то все работает как надо(т.е. else не выполняется) вопрос в том, как такое вообще возможно и как этого избежать? A: в общем я сам дурак, проблема была в том, что var на самом деле был не int (как я считал), а unicode
{ "pile_set_name": "StackExchange" }
Q: Extrema of Real-Valued Functions Let $ f(x,y) = 1 + xy + x - 2y $ and let $ D $ be the trangular region in $ \Bbb R^2 $ with vertices $ (1, -2) $ , $ (5, -2), $ and $ (2, 1) $. Find the absolute maximum and minimum values of $ f $ on $ D $. Give all the points where these extreme values occur. A: Welcome to the site. Normally you should include your own thoughts on the problem, and tell us where you are stuck. I will give you some general pointers for your problem. We have $f_x(x,y) = y+1$ and $f_y(x,y) = x-2$. These two derivatives are simultaneously $0$ at $(x,y) = (2,-1)$. Check if this point is inside of your triangle. You also need to check the values of your function on the boundary of the triangle. For instance, the edge connecting $(1,-2)$ to $(5,-2)$ is part of the line $y=-2$ in the $(x,y)$-plane. Plug this into your function and see what it looks like: $f(x,-2) = 1-2x+x+4 = 5-x$. Then check where this function has its maximum on this particular side of the triangle. Do this for all three sides.
{ "pile_set_name": "StackExchange" }
Q: Remove/Hide Text at Footer of Contact Form I'm using Wordpress and FormGet. When I paste the HTML code of the contact from of FormGet into a page on my site (http://jrbweddings.com/contact/) it adds a "Report Abuse' text at the bottom of the form. Is there a way to remove this or make the text white? It has an 'a' tag and if I try to use css code it changes the whole site. Here is the code for the form: <iframe style="width: 100%; border: none;" src="//www.formget.com/app/forms/view/FELr-104915/i?w=328" width="300" height="1257" frameborder="0" scrolling="no">Your Contact </iframe> A: I'm assuming the HTML and CSS for the page inside the <iframe> are out of your control. If so (and alternative inline contact plugins are out of the question), I can only suggest you use the <iframe> parameters to "cut off" the lower part of the frame's content with a smaller height: <iframe style="width: 100%; border: none;" src="//www.formget.com/app/forms/view/FELr-104915/i?w=328" width="300" height="990" frameborder="0" scrolling="no">Your Contact </iframe>
{ "pile_set_name": "StackExchange" }
Q: obtener JSON creado por API con JQUERY Estoy tratandod e consumir un API a traves de Jquery, al momento he logrado conectarme sin problema e incluso obtengo la respuesta del API el cual tiene el siguiente formato: { "status": "OK", "status_codes": [ 200 ], "status_messages": [ { "request": "Request processed." } ], "data": { "package": { "contentValue": 120.01, "weight": 1.01, "length": 30.01, "height": 15.01 }, "insurance": { "contentValue": 120.01, "amountInsurance": 2.09 }, "originZipCode": "44100", "destinationZipCode": "44510", "rates": [ { "idRates": 999999, "idProduct": 11, "product": "Dos días", "vehicle": "bike", "idCarrier": 6, "carrier": "ESTAFETA", "total": 203.15, "deliveryType": "Ocurre", "deliveryDays": 1 } ], "idCarriersNoWsResult": "44510" } } Esta información la puedo ver en la consola mediante console.log, pero no he podido plasmarla en un div, el código que uso es: $.ajax({ headers: {'Authorization':'Mi Clave de Usuario o API KEY', 'Content-Type':'application/json'}, url: 'https://api.envioclickpro.com/api/v1/quotation', type: 'POST', dataType: 'json', data: packInfo, success: function(respuesta){ console.log(respuesta); } }) Como puedo almacenar ese JSON en un array ya sea de php o JS para poder acceder a su información? A: Nat, parece que debes aprender como imprimir cosas en el dom y mas allá de ello empezar a trabajar con tecnología y APIs mas modernas, aunque en teoría está bien, en la practica es mejor actualizarse, por eso te dejo fetch que es mas moderno y es estandar para manejar peticiones, puede que hasta mas intuitivo, por otro lado estaría bien que trabajaras con JS Vanilla aunque en principio aún ne he visto donde has utilizado Jquey. A continuación te dejo un ejemplo de como imprimir Json en el dom: var preformato = document.querySelector("#main"); fetch("https://api.myjson.com/bins/hinqa") .then(res => res.json()) .then(res => main.innerHTML = JSON.stringify(res,null,2)) <pre id="main"></pre> Como ves obteniendo un Json de cualquier fuente podemos imprimirlo en nuestro documento dentro de una etiqueta pre y formateandolo con JSON.stringify(json,null,2) el dos del tercer parámetro indica la cantidad del tabulado. Si quieres hacerlo con Jquery seria tan sencillo como: $("#main").html(JSON.stringify(res,null,2)) Espero que te sea de ayuda, un saludo.
{ "pile_set_name": "StackExchange" }
Q: Best practice for recursive class Problem: I want to build a class for a custom dice. But it should also provide the following: Every side can contain an other dice The number of sides should be dynamically expandable, but must at least contain one Logically the dice need to have a currentSide Every side has a property, which provides the content of this side (on a D6, it would be "4") So far so good, I went and made two classes dice and side and gave them the properties I think they needed. public class Side { //public bool HasDice { get { return Dice != null; } } - Removed not needed public Dice Dice { get; set; } public string Value { get; set; } } public class Dice { public ObservableCollection<Side> Sides { get; set; } public string Name { get; set; } public Side CurrentSide { get; set; } } Is this right, I never made any recursive classes so I'm not sure ? Also how am I able to detect if the same dice and side are "endlessly" referring to them self. Like: D1.CurrentSide = Side1; Side1.Dice = D1; Should I check this when building objects ? Edit: If D1 rolls S2 then D2 shouldn't be rolled. Also D2.Dice = Null. If D1 rolls S1 then D2 should be rolled. If D2 rolls S1 then D3 should be rolled. If D2 rolls S2 then D4 should be rolled. D3 and D4 shouldn't trigger any roll. A: What you are making is called a state machine. Your program (the "machine") is always in some state, but can change the state as a consequence of performing some action. Depending on the logic it can be quite acceptable that the machine can be in the same state more than once. So, I wouldn't bother too much about loops in the machine's logic. If a user wants the loop then let him have it, as long as the machine can reach some final state and program reaches the end of execution.
{ "pile_set_name": "StackExchange" }
Q: Where does the "arguments" variable come from in "this.callParent(arguments)"? While learning ExtJS 4, I found out that while defining a new class, in the initComponent method the constructor of the parent class can be called using this.callParent(arguments). I would like to know where this arguments variable (I know it can be args or a or arg too) is defined, and where its value is assigned. For example, if I define my class as follows: Ext.define('shekhar.MyWindow', { extend : 'Ext.Window', title : 'This is title', initComponent : function() { this.items = [ // whatever controls to be displayed in window ]; // I have not defined argument variable anywhere // but still ExtJS will render this window properly without any error this.callParent(arguments); } }); Does anyone know where this arguments variable is defined, and how values are assigned to it? A: The arguments variable is a special variable in Javascript, available within any function. It's not a true array, but it contains the argument values passed to the function which can be accessed like array elements (so, arguments[0] is the first argument, arguments[1] is the second, and so on). Check out this page on the Mozilla Developer Network for more information and examples.
{ "pile_set_name": "StackExchange" }
Q: MySQL: Which join is better between left outer join and inner join Which join is better peforming if all of them provides the same result? For example, I have a two tables employees(emp_id,name, address, designation, age, sex) and work_log(emp_id,date,hours_wored). To get some specific results both inner join and left join gives the same result. But, I have still some doubts which is not limited to this question only. which join is more efficient which should prefer in case of same result values ? What are other factors which must be considered at the time of applying join? Is there any relationship between inner join and cross join? A: There is not a "better" or a "worse" join type. They have different meaning and they must be used depending on it. In your case, you probably do not have employees with no work_log (no rows in that table), so LEFT JOIN and JOIN will be equivalent in results. However, if you had such a thing (a new employee with no registered work_log), a JOIN wold omit that employee, while a left join (whose first table is employees) would show all of them, and nulls on the fields from work_log if there are not matches. Again, performance is a secondary thing to query correctness. Some people say that you shouldn't use LEFT JOINs. It is true that a LEFT JOIN forces the optimizer to execute the query in one particular order, preventing some optimizations (table reordering) in some cases. Here is one example. But you should not choose one over the other if correctness/meaning is sacrified, as an INNER JOIN is not inherently worse. The rest of the usual optimizations apply as usual. In summary, do not use LEFT JOIN if you really mean INNER JOIN. In MySQL CROSS JOIN, INNER JOIN and JOIN are the same. In the standard, and semantically, a CROSS JOIN is an INNER JOIN without an ON clause, so you get every combination of rows between tables. You have examples of all semantic types of join on Wikipedia. In practice, in MySQL, we tend to only write JOIN and LEFT JOIN.
{ "pile_set_name": "StackExchange" }
Q: How do I call a method inside ApplicationHelper from my Model? # application_helper.rb def do_some_stuff ... end # my_model.rb def my_model_method # I want to call the method "do_some_stuff" here, how exactly? end Obviously, I can't just call do_some_stuff, since it would tell me that the model does not have this method. A: You can accomplish this by adding the following line to your model file: include ActionView::Helpers Now, you may want to reconsider placing your helper method somewhere else (e.g. the model, or a mixin module), but use the above line to do what you've asked for.
{ "pile_set_name": "StackExchange" }
Q: How to Map Database Lookup Tables Automatically on Insert (Oracle) I have existing tables that are pretty much denormalized. There are no lookup tables for things list status, type, country, etc... This original design was done just to simplify the application's access to the database, so there was no performance reason for this denormalization. This has resulted in tables with tons of duplicate data, and I would like to normalize properly by introducing lookup tables for various status/type/country columns. Is there some was I can do this in the database (oracle) that would remain transparent to clients? Applications would continue to do inserts but the database would map things to the proper lookup tables behind the scenes. I've been experimenting with a combination of views and triggers that will do the mapping, but it feels like there should be a more automatic way of doing this. A: In the general case, you can make your changes transparent to the users if you can create updatable views. Normalize a base table to 3NF, BCNF, or 5NF. Rename the original base table. Build an updatable view that has the same name, columns, and rows as the original, denormalized base table. Make sure the permissions on the new view correlate with the permissions on the original base table. Test. Repeat until done. Any client software that tries to SELECT, INSERT, UPDATE, or DELETE the original base table will hit the updatable view instead. (That's because tables and views share a namespace, and that's not an accident.) The dbms and your supporting code will make sure the Right Thing happens. Depending on your platform and decomposition, building an updatable view might be easy, and it might be impossible. On Oracle, I think the worst case is that you'd have to write INSTEAD OF triggers to support all the query operations. That's not too bad. But based on a few months knocking around on SO, I have to say I'm not 100% confident you really need to do this, or that you really want to do this. Post your tables' DDL and representative sample data as SQL INSERT statements, and we can offer better, more concrete suggestions.
{ "pile_set_name": "StackExchange" }
Q: java.lang.NullPointerException in jsp Hi all I am a fresher in java and jsp and honestly I dont have knowledge of json. but I have some requirement that I have to pull the data from database and display on jsp page. but the criteria is that I have to use Bootstrap Data Table why I am using this because it provide lot of flexibility like Pagination Filtering Sorting Multi-column sorting Individual column filter. I am getting a java.lang.NullPointerException in my jsp can any body tell me why am I getting this error. This is my jsp page dataTable.jsp <%@page import="org.codehaus.jettison.json.JSONObject"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import ="java.util.*" %> <%-- <%@ page import="com.varun.DataBase"%> --%> <%@ page import="java.sql.*" %> <%-- <%@ page import="org.json.*"%> --%> <%@ page import ="net.sf.json.JSONArray" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>DataTable</title> </head> <body> <h1>Lets display the data from database using dataTabel</h1> <% String[] cols = { "id","engine", "browser", "platform", "version", "grade" }; String table = "ajax"; JSONObject result = new JSONObject(); JSONArray arr = new JSONArray(); int amount = 10; int start = 0; int echo = 0; int col = 0; int id=0; String engine = ""; String browser = ""; String platform = ""; String version = ""; String grade = ""; String dir = "asc"; String sStart = request.getParameter("iDisplayStart"); String sAmount = request.getParameter("iDisplayLength"); String sEcho = request.getParameter("sEcho"); String sCol = request.getParameter("iSortCol_0"); String sdir = request.getParameter("sSortDir_0"); engine = request.getParameter("sSearch_0"); browser = request.getParameter("sSearch_1"); platform = request.getParameter("sSearch_2"); version = request.getParameter("sSearch_3"); grade = request.getParameter("sSearch_4"); List<String> sArray = new ArrayList<String>(); if (!engine.equals("")) { String sEngine = " engine like '%" + engine + "%'"; sArray.add(sEngine); //or combine the above two steps as: //sArray.add(" engine like '%" + engine + "%'"); //the same as followings } if (!browser.equals("")) { String sBrowser = " browser like '%" + browser + "%'"; sArray.add(sBrowser); } if (!platform.equals("")) { String sPlatform = " platform like '%" + platform + "%'"; sArray.add(sPlatform); } if (!version.equals("")) { String sVersion = " version like '%" + version + "%'"; sArray.add(sVersion); } if (!grade.equals("")) { String sGrade = " grade like '%" + grade + "%'"; sArray.add(sGrade); } String individualSearch = ""; if(sArray.size()==1){ individualSearch = sArray.get(0); }else if(sArray.size()>1){ for(int i=0;i<sArray.size()-1;i++){ individualSearch += sArray.get(i)+ " and "; } individualSearch += sArray.get(sArray.size()-1); } if (sStart != null) { start = Integer.parseInt(sStart); if (start < 0) start = 0; } if (sAmount != null) { amount = Integer.parseInt(sAmount); if (amount < 10 || amount > 100) amount = 10; } if (sEcho != null) { echo = Integer.parseInt(sEcho); } if (sCol != null) { col = Integer.parseInt(sCol); if (col < 0 || col > 5) col = 0; } if (sdir != null) { if (!sdir.equals("asc")) dir = "desc"; } String colName = cols[col]; int total = 0; Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","system","admin"); try { String sql = "SELECT count(*) FROM "+table; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if(rs.next()){ total = rs.getInt("count(*)"); } }catch(Exception e){ } int totalAfterFilter = total; //result.put("sEcho",echo); try { String searchSQL = ""; String sql = "SELECT * FROM "+table; String searchTerm = request.getParameter("sSearch"); String globeSearch = " where (engine like '%"+searchTerm+"%'" + " or browser like '%"+searchTerm+"%'" + " or platform like '%"+searchTerm+"%'" + " or version like '%"+searchTerm+"%'" + " or grade like '%"+searchTerm+"%')"; if(searchTerm!=""&&individualSearch!=""){ searchSQL = globeSearch + " and " + individualSearch; } else if(individualSearch!=""){ searchSQL = " where " + individualSearch; }else if(searchTerm!=""){ searchSQL=globeSearch; } sql += searchSQL; sql += " order by " + colName + " " + dir; sql += " limit " + start + ", " + amount; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { // JSONArray ja = new JSONArray(); net.sf.json.JSONArray ja = new net.sf.json.JSONArray(); ja.add(rs.getInt("id")); ja.add(rs.getString("engine")); ja.add(rs.getString("browser")); ja.add(rs.getString("platform")); ja.add(rs.getString("version")); ja.add(rs.getString("grade")); arr.add(ja); } String sql2 = "SELECT count(*) FROM "+table; if (searchTerm != "") { sql2 += searchSQL; PreparedStatement ps2 = conn.prepareStatement(sql2); ResultSet rs2 = ps2.executeQuery(); if (rs2.next()) { totalAfterFilter = rs2.getInt("count(*)"); } } result.put("iTotalRecords", total); result.put("iTotalDisplayRecords", totalAfterFilter); result.put("aaData", arr); response.setContentType("application/json"); response.setHeader("Cache-Control", "no-store"); out.print(result); conn.close(); } catch (Exception e) { } %> </body> </html> Stack Trace 11:26:50,224 ERROR [[jsp]] Servlet.service() for servlet jsp threw exception java.lang.NullPointerException at org.apache.jsp.dataTable_jsp._jspService(dataTable_jsp.java:114) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:322) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:249) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) A: If the answer of Ajil Mohan prevent the error to appear, it means that you have no value in your ParametersMap. engine = request.getParameter("sSearch_0"); browser = request.getParameter("sSearch_1"); platform = request.getParameter("sSearch_2"); version = request.getParameter("sSearch_3"); grade = request.getParameter("sSearch_4"); These lines just get the data in the Parameter map of your request. If the given is not in the map it returns null (https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29). This map is created when you send the POST request on the previous page with the data contained in your form. Your input field has to be set with the name you give to the getParameter method. If you don't have previous page with a form then you may want to send data from server to JSP. If you use Servlet then you should use the request AttributeMap. public class BasicTotoServlet extends HttpServlet { /** * Manage GET HTTP Request */ protected void doGet(HttpServletRequest request, HttpServletResponse response) { String data = getData(); request.setAttibute("sSearch_0", data) } } Then in your JSP : engine = request.getAttribute("sSearch_0"); I hope I was clear enough. Ask for precision if needed EDIT : Here is what I understand. You arrive on your JSP and you get several Parameter from the previous page's form. This form may not give to you all the information, that is why you get a NPE on this engine = request.getParameter("sSearch_0"); engine.equals("") To solve this as told you Ajil Mohan, just turn the equals the other way round, so that if engine is NULL you have no problem "".equals(engine); As "" is never null you'll never get NPE. Now you don't have any data in you table. Why? If I'm correct you create a SQL Query by concatenating several data. searchSQL = globeSearch + " and " + individualSearch; individualSearch is the result of concatenating your Parameters but what if they're null? if (!"".equals(browser)) { String sBrowser = " browser like '%" + browser + "%'"; sArray.add(sBrowser); } In this code, if browser is null (as we saw earlier it can be), you will add the String " browser like '%null%'" to you query with the and key word. I'm not sure there will be any browser with "null" in its name. You better put this test : if (!"".equals(browser) && browser != null) { String sBrowser = " browser like '%" + browser + "%'"; sArray.add(sBrowser); }
{ "pile_set_name": "StackExchange" }
Q: How to output variables such as the current page's entry_id in the script tag One one of our sites, we have ChannelFiles add-on installed and in the control panel (when editing an entry) it outputs a useful set of variables (see attached). But this is only part of add-on and if it's not installed, those variables aren't outputted. Is there anyway I can output these variables without ChannelFiles? Background: There are certain fields that I only want to ever appear when editing a specific entry so I include a bit of jquery in the field instruction to hide/show field by checking against the variables outputted by ChannelFiles add-on in the script tag. http://imagebin.org/258416 Thanks UPDATE (to clarify): I need this when editing the entry in the control panel of EE (see Background section on why) and not in the front end. As far as I know, I don't have access to the templates for the control panel (or do I?). A: You can output entry ids from within the channel:entries tag pair like this: {exp:channel:entries channel="my_channel"} entry_id: {entry_id}<br> {/exp:channel:entries The Channel Entries documenation at EllisLab provide all the variable options available to you. Update You can add this script to any of the field's Field Instructions section. <script> $(document).ready(function() { entryId = (document.URL).split('entry_id=')[1].replace(/\D/g,''); $('.heading h2').append(' #' + entryId); // adds to heading at top of form alert("entry id = " + entryId); }); </script> Second Update The previous script wasn't removing numerical characters from the url that occurred after the entry_id. The problem is that EE encodes the & as &amp;. So here's this: <script> $(document).ready(function() { firstPart = (document.URL).split('entry_id=')[0]; entryId = (document.URL).split('entry_id=')[1].split(firstPart[firstPart.length -1])[0]; $('.heading h2').append(' #' + entryId); }); </script>
{ "pile_set_name": "StackExchange" }
Q: Double Summation $\sum_{i=1}^{n+1}\sum_{j=0}^{n-1}(i+j)=(2n+1)\sum_{r=1}^n r=3\sum_{r=1}^n r^2$ It can be easily shown by step-by-step and rather messy summation over $j$ and then over $i$ that $$\sum_{i=1}^{n+1}\sum_{j=0}^{n-1}(i+j)=\tfrac12 (2n+1)n(n+1)$$ Note that RHS is equivalent to $$\displaystyle (2n+1)\sum_{r=1}^n r$$ (1) Is there a clever transform that will simplify the original summation into the summation above without first working out the closed form? It is interesting to note that RHS is also equivalent to $$3\sum_{r=1}^n r^2$$ (2) Is there also another clever transform to convert the original summation into this summation without first working out the closed form? A: (1) $$\sum_{i=1}^{n+1}\sum_{j=0}^{n-1}(i+j)=\sum_{j=0}^{n-1}\sum_{i=1}^{n+1}i + \sum_{i=1}^{n+1}\sum_{j=0}^{n-1}j=n\left((n+1)+\sum_{i=1}^n i\right)+(n+1)\left(-n+\sum_{j=1}^n j\right) \\ =(n+(n+1))\sum_{r=1}^n r=(2n+1)\sum_{r=1}^n r$$ (2) $$\sum_{i=1}^{n+1}\sum_{j=0}^{n-1}(i+j)= \sum_{\begin{array} c 1 \le i \le n+1,\\ 0 \le j \le n-1, \\ 1 \le i+j \le n \end{array}} \!(i+j) + \!\!\sum_{\begin{array} c 1 \le i \le n+1,\\ 0 \le j \le n-1, \\ n+1 \le i+j \le 2n \end{array}} \!((i-1)+(j+1)) \\ =\sum_{k=1}^n\sum_{\begin{array} c 1 \le i \le n+1,\\ 0 \le j \le n-1, \\ i+j=k \end{array}} \!k + \!\sum_{\begin{array} c k=0 \\ (i-1=k) \end{array}}^n\!\!\sum_{\begin{array} c 0 \le j \le n-1, \\ n-k \le j \le 2n-1-k \end{array}} \!\!\!\!k + \!\sum_{\begin{array} c k=1 \\ (j+1=k) \end{array}}^n\!\sum_{\begin{array} c 1 \le i \le n+1, \\ n+2-k \le i \le 2n+1-k \end{array}} \!\!\!\!\!k \\ =\sum_{k=1}^n \,k \!\sum_{\begin{array} c 1 \le i \le k \\ (j=k-i) \end{array}} \!\!1 + \!\sum_{k=1}^n \,k \sum_{j=n-k}^{n-1} \!1 + \!\sum_{k=1}^n \,k\sum_{i=n+2-k}^{n+1} \!1 \\ = \sum_{k=1}^n k \cdot k + \sum_{k=1}^n k \cdot k + \sum_{k=1}^n k \cdot k = 3 \sum_{r=1}^n r^2$$
{ "pile_set_name": "StackExchange" }
Q: Comparator - overloading the operator < I am trying to use the std::set to contain a struct of three member variables. struct blah{ int a,b,c; bool operator < ( const blah& blo ) const{ return ( a < blo.a || (a == blo.a && (b != blo.b || c != blo.c ) ) ); } }; But I keep getting an error that my operator < is invalid. What is wrong with my approach? struct blah { int a,b,c; blah(int aa,int bb,int cc){ a=aa; b=bb; c=cc; } bool operator < ( const blah& blo ) const{ return ( a < blo.a || (a == blo.a && b < blo.b ) || (a == blo.a && b == blo.b && c < blo.c ) ); } }; int main() { std::set<blah> st; st.insert(blah(1,2,3)); st.insert(blah(1,1,1)); st.insert(blah(1,3,2)); return 0; } After altering the code following @paxdiablo code, this worked well. Thanks y'all! A: That code compiles fine for me in the following complete program: #include <iostream> struct blah { int a,b,c; bool operator < ( const blah& blo ) const{ return ( a < blo.a || (a == blo.a && (b != blo.b || c != blo.c ) ) ); } }; int main (void) { blah x, y; x.a=2; x.b=2; x.c=2; y.a=2; y.b=2; y.c=2; if (x < y) std::cout << "x<y\n"; if (y < x) std::cout << "x>y\n"; if (!(y < x) && !(x < y)) std::cout << "x=y\n"; return 0; } Changing the fields of x and y outputs different messages. But I see one major problem with the function. It can tell you that both x < y and y < x, in the situation where the two a fields are identical but the b fields differ between the two. If you set both a fields to 1 and set the b fields to 2 and 1, you see: x<y y<x That's not going to end well :-) The fact that what you're getting is a debug assertion (something specifically built to catch runtime errors in mostly debug code) leads me to believe that the runtime libraries may explicitly be checking for incorrect operator< overloads by detecting that latter case (ie, both x < y and y < x are true). You should really fix that because it will cause all sorts of problems with collections where (for example) you need to keep things sorted. By way of example, let's say you wanted to use a, b and c as keys in that priority. A function to do that would contain something like: // Check primary key. if (a < blo.a) return true; if (a > blo.a) return false; // Primary key equal here, use secondary key. if (b < blo.b) return true; if (b > blo.b) return false; // Primary and secondary keys equal here, use tertiary key. return (c < blo.c);
{ "pile_set_name": "StackExchange" }
Q: Haskell - Maybe arithmetic I have been asked to implement a function which uses the following profile: maybe_divide :: Maybe Integer -> Maybe Integer -> Maybe Integer and responds in the following manner: > maybe_divide (Just 5) (Just 2) Just 2 > maybe_divide (Just (-5)) (Just 2) Just (-3) > maybe_divide (Just (-5)) (Just 0) Nothing > maybe_divide Nothing (Just 1) Nothing > maybe_divide (Just 1) Nothing Nothing I have written the following but it will not compile. Do you guys have any suggestions? maybe_divide :: Maybe Integer -> Maybe Integer -> Maybe Integer maybe_divide x y = case x of Just x' -> case y of Just y' | y' == 0 -> Nothing | otherwise -> x' `div` y' Nothing -> Nothing A: Separate from the output type, I'd like to point out a few alternative styles you may prefer for writing this sort of code: First, you can case on multiple expressions by putting them in a tuple: case (x,y) of (_ , Just 0) -> Nothing (Just x', Just y') -> Just (x' `div` y') _ -> Nothing there are a couple different ways to write this using guards, or even the function Control.Monad.guard. case (x,y) of (Just x', Just y') -> (x' `div` y') <$ guard (y' /= 0) _ -> Nothing The second approach would start with a function: safeDiv :: Integer -> Integer -> Maybe Integer safeDiv x 0 = Nothing safeDiv x y = Just (x `div` y) Now that you have safeDiv, you can lift it into Maybe-wrapped arguments. It's pretty close to Applicative style code, except for an extra layer of Maybe in the output. Fortunately nested monads (e.g. Maybe (Maybe t)) are trivial to collapse: maybe_divide x y = join $ safeDiv <$> x <*> y or even maybe_divide = (join .) . liftM2 safeDiv if you're fluent in point-free. Personally, I would use one of the two tuple-case variants. But it's fairly common to already have a function like safeDiv, in which case the second form can be useful. A: You should post the error you are getting, but x' `div` y' has type Integer and not Maybe Integer. Perhaps you need to wrap this in a Just. A: You need to wrap the successful result in Just here: ... | otherwise -> Just (x' `div` y')
{ "pile_set_name": "StackExchange" }
Q: `@Transactional` not working for Spring 2 controller I have an old controller within my app that is defined as a spring bean in xml and makes use of Spring's SimpleFormController. I've tried to make the processes within the onSubmit method of the controller transactional by adding the @Transactional annotation but it doesn't work. According to this guide the invocation of the annotation must happen "outside of the bean", does this mean that the annotation cannot be used in old Spring controllers like mine? Are there any alternatives or workarounds? The reason I know it's not working is because 1) changes to the db are not rolled back on error (this is despite the fact that I have defined rollbackFor = Exception.class, and even in some instances used TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();, in this instances where it tries to use the latter it throws an error stating there is no transaction present. 2) I've added breakpoints to where @Transactional is instantiated within Spring and none of them get hit. EDIT: So people are asking for reproducible examples of code. The problem doesn't lie within the business logic code, I'm looking for clarity on the usage of the annotation within a Spring 2 controller. So what I have for example is this: public class ImportController extends SimpleFormController { @Override @Transactional(rollbackFor = Exception.class) public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { ... } } A: You are right. @Transactional will not work here because onSubmit is invoked by the same bean. And in this case the call is done directly and the default spring transaction handling does not work. See answers in this question for a detailed explanation of the options you have
{ "pile_set_name": "StackExchange" }
Q: How to inner join two select queries on same table I am stuck... A 'data' table with columns 'value' and 'datatype' is populated with engine load and vehicle speed and each record is stamped with date, time, lat, long. I want to query for engine load over 10% while the vehicle is moving (e.g. speed > 0). I can create a query to select the engine load and I can create a query to select the vehicle speed but how do I create a query to select engine load when > 10% AND the Vehicle is moving where their date, time lat, and long are equal? This Query does not work, but it provides a jist of what I am trying to do. Can anyone help me create a query? tables TName: data PK datakey value fk1 dataeventkey fk2 datatypenamekey TName: datatypename PK datatypenamekey datatypename TName: dataevent PK dataeventkey datetime lat long SELECT d1.datetime FROM (data INNER JOIN datatypename ON data.datatypenamekey = datatypename.datatypenamekey INNER JOIN dataevent ON dataevent.dataeventkey = data.dataeventkey) d1 WHERE ( d1.datatypename = "Engine Load [%]" AND d1.value > 10 ) INNER JOIN SELECT d2.datetime FROM (data INNER JOIN datatypename ON data.datatypenamekey = datatypename.datatypenamekey INNER JOIN dataevent ON dataevent.dataeventkey = data.dataeventkey) d2 WHERE ( d2.datatypename = "Vehicle Speed [mph]" AND d2.value > 0 ) ON d1.datetime = d2.datetime A: I'm not 100% sure I understand, but I think you just need to reference two instances of the same table. Kind of making some assumptions based on your SQL, but giving it a shot here: SELECT engineLoad.dateTime FROM ( SELECT d.datakey, de.datetime FROM data d INNER JOIN datatypename dt ON data.datatypenamekey = dt.datatypenamekey INNER JOIN dataevent de ON de.dataeventkey = d.dataeventkey WHERE d.value > 10 AND dt.datatypename = "Engine Load [%]" ) engineLoad INNER JOIN ( SELECT d.datakey, de.datetime FROM data d INNER JOIN datatypename dt ON data.datatypenamekey = dt.datatypenamekey INNER JOIN dataevent de ON de.dataeventkey = d.dataeventkey WHERE d.value > 0 AND dt.datatypename = "Vehicle Speed [mph]" ) vehicleSpeed ON engineLoad.dataKey = vehicleSpeed.dataKey <==might need to remove this line AND engineLoad.datetime = vehicleSpeed.datetime Edit Looks like you need to reference datatypename twice as well? Edited the above, so try again.
{ "pile_set_name": "StackExchange" }
Q: form submission not working? I had this simple form.. where I was taking an input from user like the following <form action="/data" autocomplete="on" method="POST"> <input id="search" name="search" type="text" placeholder="Search for song or artists.."> <input id="search_submit" value="Submit" type="submit"> </form> And everything was working fine.. Now.. I wanted to add slider to it and send the slider value to python. How do i do this? I modified the form to this: <form action="/data" autocomplete="on" method="POST"> <input id="search" name="search" type="text" placeholder="Search for song or artists.."> <input type="range" min="-1" max="1" value="0" step="0.05" onchange="showValue(this.value)" /><input id="search_submit" value="Submit" type="submit"> <span id="range" style="color:#BDBDBD">0</span> </form> But it is not working I get Bad Request The browser (or proxy) sent a request that this server could not understand. EDIT @app.route("/data", methods=['POST']) def entry_post(): query = request.form["search"] print request.form["range"] # I just added this line in the code A: You are missing the "name" attribute on the range input field.
{ "pile_set_name": "StackExchange" }
Q: Command Query Separation violation What do you think about if(!DoSomething()) return; In Clean Code this is viewed as violation of Command Query Separation. But how can we understand if something in command DoSomething() went wrong? What about sql command (ex: void Delete(Table))? How can we know if that table existed? Thanks. A: I agree with the comments from rObiwahn that you should check CanDoSomething before issuing a command of DoSomething. In a pure CQRS environment, DoSomething would not return anything and if anything prevented Something from happening (not due to an exception, but a race condition or something else changing between CanDoSomething and DoSomething), your domain would issue a DoSomethingWasInvalid event (or something like that) which would allow your application to eventually become consistent. It may sound complex, but it really becomes pretty simple once you start breaking down the logic into small chunks and allow your application to embrace eventual consistency. There are a lot of good resources on the DDD/CQRS group in google groups. A question like 'How do you tell the sender that a command failed?' is similar to your question a bit. People like Udi Dahan, Greg Young, Rinat Abdullin and others monitor that group and provide some really great answers. I'd recommend checking that out every now and then, too. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Not allowing user exit the app using Home Button In my app i do not want the user be able to exit my app on pressing the Home press key. There's a specific reason for not allowing the user to do this. Can anyone suggest what can be the correct way to achieve this? At present what i am doing is Overriding the onKeyDown()-Method. The Code for it is as follows: @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) { Intent intent = new Intent(this, LockScreen.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } return true; } In the Manifest file i am making changes as below: <activity android:name=".LockScreen" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> <intent-filter> <category android:name="android.intent.category.HOME"/> </intent-filter> </activity> A: I agree with inazaruk but if you still want to do that then you need to override: @Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); } A: Android doesn't support this scenario for simple apps, so you can't do this. Read this article by CommonsWare: Please ignore the Home Button. It will explain why handling Home button the way you want is not really a good idea.
{ "pile_set_name": "StackExchange" }
Q: Merge or Combine Two Array Into Single Array I have a case to create or merge two arrray into single array. First array like this : Array // First Array ( [0] => Array ( [hotel] => cempaka [vendor] => mas ) [1] => Array ( [hotel] => permata [vendor] => sip ) ) Second array : Array ( [0] => Array ( [order_type] => 1 [currency] => 26 [net] => 26000 [rate] => 26000 [amount] => 26000 [bank_surcharge] => 26000 [ticket] => 26000 [profit] => 26000 [selling_price] => 26000 [description] => a ) [1] => Array ( [order_type] => 2 [currency] => 27 [net] => 27000 [rate] => 27000 [amount] => 27000 [bank_surcharge] => 27000 [ticket] => 27000 [profit] => 27000 [selling_price] => 27000 [description] => b ) [2] => Array ( [order_type] => 5 [currency] => 28 [net] => 28000 [rate] => 28000 [amount] => 28000 [bank_surcharge] => 28000 [ticket] => 28000 [profit] => 28000 [selling_price] => 28000 [description] => c ) [3] => Array ( [order_type] => 3 [currency] => 29 [net] => 29000 [rate] => 29000 [amount] => 29000 [bank_surcharge] => 29000 [ticket] => 29000 [profit] => 29000 [selling_price] => 29000 [description] => d ) [4] => Array ( [order_type] => 4 [currency] => 30 [net] => 30000 [rate] => 30000 [amount] => 30000 [bank_surcharge] => 30000 [ticket] => 30000 [profit] => 30000 [selling_price] => 30000 [description] => e ) [5] => Array ( [order_type] => 6 [currency] => 31 [net] => 31000 [rate] => 31000 [amount] => 31000 [bank_surcharge] => 31000 [ticket] => 31000 [profit] => 31000 [selling_price] => 31000 [description] => f ) [6] => Array ( [order_type] => 1 [currency] => 32 [net] => 32000 [rate] => 32000 [amount] => 32000 [bank_surcharge] => 32000 [ticket] => 32000 [profit] => 32000 [selling_price] => 32000 [description] => g ) [7] => Array ( [order_type] => 2 [currency] => 33 [net] => 33000 [rate] => 33000 [amount] => 33000 [bank_surcharge] => 33000 [ticket] => 33000 [profit] => 33000 [selling_price] => 33000 [description] => h ) [8] => Array ( [order_type] => 5 [currency] => 34 [net] => 34000 [rate] => 34000 [amount] => 34000 [bank_surcharge] => 34000 [ticket] => 34000 [profit] => 34000 [selling_price] => 34000 [description] => i ) [9] => Array ( [order_type] => 3 [currency] => 35 [net] => 35000 [rate] => 35000 [amount] => 35000 [bank_surcharge] => 35000 [ticket] => 35000 [profit] => 35000 [selling_price] => 35000 [description] => j ) [10] => Array ( [order_type] => 4 [currency] => 36 [net] => 36000 [rate] => 36000 [amount] => 36000 [bank_surcharge] => 36000 [ticket] => 36000 [profit] => 36000 [selling_price] => 36000 [description] => k ) [11] => Array ( [order_type] => 6 [currency] => 37 [net] => 37000 [rate] => 37000 [amount] => 37000 [bank_surcharge] => 37000 [ticket] => 37000 [profit] => 37000 [selling_price] => 37000 [description] => l ) ) and then this the output that i want to get: Array ( [0] => Array ( [hotel] => cempaka [vendor] => mas [order_type] => 1 [currency] => 26 [net] => 26000 [rate] => 26000 [amount] => 26000 [bank_surcharge] => 26000 [ticket] => 26000 [profit] => 26000 [selling_price] => 26000 [description] => a ) [1] => Array ( [hotel] => cempaka [vendor] => mas [order_type] => 2 [currency] => 27 [net] => 27000 [rate] => 27000 [amount] => 27000 [bank_surcharge] => 27000 [ticket] => 27000 [profit] => 27000 [selling_price] => 27000 [description] => b ) [2] => Array ( [hotel] => cempaka [vendor] => mas [order_type] => 5 [currency] => 28 [net] => 28000 [rate] => 28000 [amount] => 28000 [bank_surcharge] => 28000 [ticket] => 28000 [profit] => 28000 [selling_price] => 28000 [description] => c ) [3] => Array ( [hotel] => cempaka [vendor] => mas [order_type] => 3 [currency] => 29 [net] => 29000 [rate] => 29000 [amount] => 29000 [bank_surcharge] => 29000 [ticket] => 29000 [profit] => 29000 [selling_price] => 29000 [description] => d ) [4] => Array ( [hotel] => cempaka [vendor] => mas [order_type] => 4 [currency] => 30 [net] => 30000 [rate] => 30000 [amount] => 30000 [bank_surcharge] => 30000 [ticket] => 30000 [profit] => 30000 [selling_price] => 30000 [description] => e ) [5] => Array ( [hotel] => cempaka [vendor] => mas [order_type] => 6 [currency] => 31 [net] => 31000 [rate] => 31000 [amount] => 31000 [bank_surcharge] => 31000 [ticket] => 31000 [profit] => 31000 [selling_price] => 31000 [description] => f ) [6] => Array ( [hotel] => permata [vendor] => sip [order_type] => 1 [currency] => 32 [net] => 32000 [rate] => 32000 [amount] => 32000 [bank_surcharge] => 32000 [ticket] => 32000 [profit] => 32000 [selling_price] => 32000 [description] => g ) [7] => Array ( [hotel] => permata [vendor] => sip [order_type] => 2 [currency] => 33 [net] => 33000 [rate] => 33000 [amount] => 33000 [bank_surcharge] => 33000 [ticket] => 33000 [profit] => 33000 [selling_price] => 33000 [description] => h ) [8] => Array ( [hotel] => permata [vendor] => sip [order_type] => 5 [currency] => 34 [net] => 34000 [rate] => 34000 [amount] => 34000 [bank_surcharge] => 34000 [ticket] => 34000 [profit] => 34000 [selling_price] => 34000 [description] => i ) [9] => Array ( [hotel] => permata [vendor] => sip [order_type] => 3 [currency] => 35 [net] => 35000 [rate] => 35000 [amount] => 35000 [bank_surcharge] => 35000 [ticket] => 35000 [profit] => 35000 [selling_price] => 35000 [description] => j ) [10] => Array ( [hotel] => permata [vendor] => sip [order_type] => 4 [currency] => 36 [net] => 36000 [rate] => 36000 [amount] => 36000 [bank_surcharge] => 36000 [ticket] => 36000 [profit] => 36000 [selling_price] => 36000 [description] => k ) [11] => Array ( [hotel] => permata [vendor] => sip [order_type] => 6 [currency] => 37 [net] => 37000 [rate] => 37000 [amount] => 37000 [bank_surcharge] => 37000 [ticket] => 37000 [profit] => 37000 [selling_price] => 37000 [description] => l ) ) (This two array i get from dynamic field generated via javascript) Any solution will be appreciated a lot.. Thanks A: Use the following since you are trying to merge arrays based on the key number of the second array: foreach($second_array as $key => $value){ if($key >= 0 && $key <= 5){ $new_array[$key] = array_merge($second_array[$key], $first_array[0]); } if($key >= 6 && $key <= 11){ $new_array[$key] = array_merge($second_array[$key], $first_array[1]); } //etc....... }
{ "pile_set_name": "StackExchange" }
Q: Checking visibility of layer in KineticJS I am trying to figure out how to check whether or not a layer in KineticJS is visible. I need this in order to appropriately toggle the visibility of any given layer when the user clicks a button. If it's visible, I want to hide it when they click the button. If it isn't visible, then I want to show it. Thoughts? I saw that there is a isVisible function, but nothing at all happens when I try to use it on a layer. The below code doesn't error, but it isn't doing anything. This is written in KineticJS on Angular. In my tests, I found that this event is appropriately getting triggered, so it's not that. I also found that the draw function is appropriately firing. scope.$on('layertoggle', function(event){ var layerShapes = scope.kineticStageObj.get('#layer1'); if(!layerShapes.isVisible()){ layerShapes.hide(); } else{ layerShapes.show(); } scope.kineticStageObj.draw(); }); A: Try this: var layerShapes = scope.kineticStageObj.get('#layer1')[0]; get returns a collection of shapes that match that criteria. Despite id being unique, you still have to access the first position of the array to access the desired shape.
{ "pile_set_name": "StackExchange" }
Q: Remove all just before closing I would like to remove any <br> tag which comes up just before a closing </p> tag. For example this is ok : <p>Bla bla bla <br> bla bla </p> But this is NOT ok : <p>Bla bla bla <br> </p> In other words, every time I have : <br> + white space or tab or new line or whatever providing no content + </p> Then, I want to remove that <br>. How would this be achieved with javascript Regex ? (or any other javascript way) A: Try this one: Iterate through each p, get its html (not text, in order to get the <br> element), replace the <br> with empty string using regex (one that matches <br> just before the </p>), replace the original with the updated html. $('p').each(function(){ var p = $(this); p.html(p.html().replace(/(<br)\s?\/?>\s?$/g,'')); }); REGEX: /(<br)\s?\/?>\s?$/g matches: <br>, <br/>, <br />, <br >
{ "pile_set_name": "StackExchange" }
Q: Obscure error on Symfony on form->handleRequest() and validation I have a Symfony 2.8.9 application where a single form cause a big obscure error on the line $form->handleRequest($request); My form is very simple : just an id and a commentaire field. It seems the error occurs during validation tasks (the full trace below). [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}class', attribute 'name': 'Symfony\Component\Form\Form' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 7, column 0) [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}constraint', attribute 'name': 'Symfony\Component\Form\Extension\Validator\Constraints\Form' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 8, column 0) [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}property', attribute 'name': 'children' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 9, column 0) [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}constraint', attribute 'name': 'Valid' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 10, column 0) 500 Internal Server Error - MappingException 1 linked Exception: InvalidArgumentException » [2/2] MappingException: [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}class', attribute 'name': 'Symfony\Component\Form\Form' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 7, column 0) [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}constraint', attribute 'name': 'Symfony\Component\Form\Extension\Validator\Constraints\Form' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 8, column 0) [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}property', attribute 'name': 'children' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 9, column 0) [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}constraint', attribute 'name': 'Valid' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 10, column 0) - in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Loader\XmlFileLoader.php at line 179 + at XmlFileLoader ->parseFile ('D:\Documents\workspace\MyProject\vendor\symfony\symfony\src\Symfony\Component\Form/Resources/config/validation.xml') in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Loader\XmlFileLoader.php at line 40 + at XmlFileLoader ->loadClassMetadata (object(ClassMetadata)) in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Loader\LoaderChain.php at line 57 + at LoaderChain ->loadClassMetadata (object(ClassMetadata)) in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Loader\LoaderChain.php at line 57 + at LoaderChain ->loadClassMetadata (object(ClassMetadata)) in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory.php at line 128 + at LazyLoadingMetadataFactory ->getMetadataFor ('Traversable') in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory.php at line 124 + at LazyLoadingMetadataFactory ->getMetadataFor ('IteratorAggregate') in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory.php at line 124 + at LazyLoadingMetadataFactory ->getMetadataFor (object(Form)) in vendor\symfony\symfony\src\Symfony\Component\Validator\Validator\RecursiveContextualValidator.php at line 343 + at RecursiveContextualValidator ->validateObject (object(Form), '', array('Default'), '1', object(ExecutionContext)) in vendor\symfony\symfony\src\Symfony\Component\Validator\Validator\RecursiveContextualValidator.php at line 153 + at RecursiveContextualValidator ->validate (object(Form), null, false) in vendor\symfony\symfony\src\Symfony\Component\Validator\Validator\RecursiveValidator.php at line 132 + at RecursiveValidator ->validate (object(Form)) in vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Validator\EventListener\ValidationListener.php at line 68 + at ValidationListener ->validateForm (object(FormEvent), 'form.post_bind', object(EventDispatcher)) at call_user_func (array(object(ValidationListener), 'validateForm'), object(FormEvent), 'form.post_bind', object(EventDispatcher)) in app\cache\dev\classes.php at line 1858 + at EventDispatcher ->doDispatch (array(array(object(ValidationListener), 'validateForm'), array(object(DataCollectorListener), 'postSubmit')), 'form.post_bind', object(FormEvent)) in app\cache\dev\classes.php at line 1773 + at EventDispatcher ->dispatch ('form.post_bind', object(FormEvent)) in vendor\symfony\symfony\src\Symfony\Component\EventDispatcher\ImmutableEventDispatcher.php at line 43 + at ImmutableEventDispatcher ->dispatch ('form.post_bind', object(FormEvent)) in vendor\symfony\symfony\src\Symfony\Component\Form\Form.php at line 660 + at Form ->submit (array('commentaire' => 'dqsdqs', 'save' => '', '_token' => 'FogMqUyv366NxySj8w1t4PLEI03pIc_V3eoiQ0tHesA'), true) in vendor\symfony\symfony\src\Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler.php at line 116 + at HttpFoundationRequestHandler ->handleRequest (object(Form), object(Request)) in vendor\symfony\symfony\src\Symfony\Component\Form\Form.php at line 489 + at Form ->handleRequest (object(Request)) in src\MyBundle\Controller\CalendrierController.php at line 34 + at CalendrierController ->addAction (object(Request)) at call_user_func_array (array(object(CalendrierController), 'addAction'), array(object(Request))) in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php at line 144 + at HttpKernel ->handleRaw (object(Request), '1') in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php at line 64 + at HttpKernel ->handle (object(Request), '1', true) in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel.php at line 69 + at ContainerAwareHttpKernel ->handle (object(Request), '1', true) in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php at line 185 + at Kernel ->handle (object(Request)) in web\app_dev.php at line 30 + [1/2] InvalidArgumentException: [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}class', attribute 'name': 'Symfony\Component\Form\Form' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 7, column 0) [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}constraint', attribute 'name': 'Symfony\Component\Form\Extension\Validator\Constraints\Form' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 8, column 0) [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}property', attribute 'name': 'children' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 9, column 0) [ERROR 1824] Element '{http://symfony.com/schema/dic/constraint-mapping}constraint', attribute 'name': 'Valid' is not a valid value of the atomic type 'xs:time'. (in file:/D:/Documents/workspace/MyProject/web/ - line 10, column 0) - in vendor\symfony\symfony\src\Symfony\Component\Config\Util\XmlUtils.php at line 96 + at XmlUtils ::loadFile ('D:\Documents\workspace\MyProject\vendor\symfony\symfony\src\Symfony\Component\Form/Resources/config/validation.xml', 'D:\Documents\workspace\MyProject\vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Loader/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd') in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Loader\XmlFileLoader.php at line 177 + at XmlFileLoader ->parseFile ('D:\Documents\workspace\MyProject\vendor\symfony\symfony\src\Symfony\Component\Form/Resources/config/validation.xml') in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Loader\XmlFileLoader.php at line 40 + at XmlFileLoader ->loadClassMetadata (object(ClassMetadata)) in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Loader\LoaderChain.php at line 57 + at LoaderChain ->loadClassMetadata (object(ClassMetadata)) in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Loader\LoaderChain.php at line 57 + at LoaderChain ->loadClassMetadata (object(ClassMetadata)) in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory.php at line 128 + at LazyLoadingMetadataFactory ->getMetadataFor ('Traversable') in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory.php at line 124 + at LazyLoadingMetadataFactory ->getMetadataFor ('IteratorAggregate') in vendor\symfony\symfony\src\Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory.php at line 124 + at LazyLoadingMetadataFactory ->getMetadataFor (object(Form)) in vendor\symfony\symfony\src\Symfony\Component\Validator\Validator\RecursiveContextualValidator.php at line 343 + at RecursiveContextualValidator ->validateObject (object(Form), '', array('Default'), '1', object(ExecutionContext)) in vendor\symfony\symfony\src\Symfony\Component\Validator\Validator\RecursiveContextualValidator.php at line 153 + at RecursiveContextualValidator ->validate (object(Form), null, false) in vendor\symfony\symfony\src\Symfony\Component\Validator\Validator\RecursiveValidator.php at line 132 + at RecursiveValidator ->validate (object(Form)) in vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Validator\EventListener\ValidationListener.php at line 68 + at ValidationListener ->validateForm (object(FormEvent), 'form.post_bind', object(EventDispatcher)) at call_user_func (array(object(ValidationListener), 'validateForm'), object(FormEvent), 'form.post_bind', object(EventDispatcher)) in app\cache\dev\classes.php at line 1858 + at EventDispatcher ->doDispatch (array(array(object(ValidationListener), 'validateForm'), array(object(DataCollectorListener), 'postSubmit')), 'form.post_bind', object(FormEvent)) in app\cache\dev\classes.php at line 1773 + at EventDispatcher ->dispatch ('form.post_bind', object(FormEvent)) in vendor\symfony\symfony\src\Symfony\Component\EventDispatcher\ImmutableEventDispatcher.php at line 43 + at ImmutableEventDispatcher ->dispatch ('form.post_bind', object(FormEvent)) in vendor\symfony\symfony\src\Symfony\Component\Form\Form.php at line 660 + at Form ->submit (array('commentaire' => 'dqsdqs', 'save' => '', '_token' => 'FogMqUyv366NxySj8w1t4PLEI03pIc_V3eoiQ0tHesA'), true) in vendor\symfony\symfony\src\Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler.php at line 116 + at HttpFoundationRequestHandler ->handleRequest (object(Form), object(Request)) in vendor\symfony\symfony\src\Symfony\Component\Form\Form.php at line 489 + at Form ->handleRequest (object(Request)) in src\MyBundle\Controller\CalendrierController.php at line 34 + at CalendrierController ->addAction (object(Request)) at call_user_func_array (array(object(CalendrierController), 'addAction'), array(object(Request))) in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php at line 144 + at HttpKernel ->handleRaw (object(Request), '1') in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php at line 64 + at HttpKernel ->handle (object(Request), '1', true) in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel.php at line 69 + at ContainerAwareHttpKernel ->handle (object(Request), '1', true) in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php at line 185 + at Kernel ->handle (object(Request)) in web\app_dev.php at line 30 The controller (only the addAction method): public function addAction(Request $request) { $calendrier = new Calendrier(); $form = $this->createForm(CalendrierType::class, $calendrier); $hasError = false ; if ($request->isMethod('POST')) { // Here the error occurs $form->handleRequest($request); } return $this->render('MyBundle:Calendrier:add.html.twig', array( 'form' => $form->createView() )); } The form (CalendrierType.php) namespace MyBundle\Form ; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class CalendrierType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('commentaire', TextareaType::class, array('required' => false)) ->add('save', SubmitType::class); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'MyBundle\Entity\Calendrier' )); } public function getBlockPrefix() { return 'mybundle_calendrier' ; } } And my Calendrier entity (Calendrier.php) : <?php namespace MyBundle\Entity; use Doctrine\ORM\Mapping as ORM; use MyBundle\Entity\AbstractEntity ; use Symfony\Component\Validator\Constraints as Assert; /** * Calendrier * * @ORM\Table(name="calendrier") * @ORM\Entity(repositoryClass="MyBundle\Repository\CalendrierRepository") */ class Calendrier extends AbstractEntity { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="commentaire", type="string", nullable=true) */ private $commentaire; /************ Getters and setters ******/ /** * Get id * * @return integer */ public function getId() { return $this->id; } public function getCommentaire() { return $this->commentaire; } public function setCommentaire($commentaire) { $this->commentaire = $commentaire; return $this; } } All of this is very simple. I have another bigger entity/Form/Controller with the same error, but two days ago, it was working fine, and I didn't changed anything in this other form nor in the config files... The stack trace and Symfony error message are too strange for me, anyone can help me please ? A: I just restart the Apache server, then the error has gone, without changing a single space in the code.
{ "pile_set_name": "StackExchange" }
Q: Laravel adding middleware inside a controller function as the title says I want to use a middleware inside a controller function. I have resource controllers, which their functions inside will have different access rights so I can't use a middleware in the web.php file, I have to use or apply it separately in each function to limit access, my googling hasn't been successful in getting a solution to that so far. Any help please and thanks in advance. P.S. I believe no code is necessary here. A: Middleware could also be applied to just one function, just add the method name in your controller constructor public function __construct() { // Middleware only applied to these methods $this->middleware('loggedIn', [ 'only' => [ 'update' // Could add bunch of more methods too ] ]); } OR public function __construct() { // Middleware only applied to these methods $this->middleware('loggedIn')->only([ 'update' // Could add bunch of more methods too ]); } Here's the documentation A: There are 3 ways to use a middleware inside a controller: 1) Protect all functions: public function __construct() { $this->middleware('auth'); } 2) Protect only some functions: public function __construct() { $this->middleware('auth')->only(['functionName1', 'functionName2']); } 3) Protect all functions except some: public function __construct() { $this->middleware('auth')->except(['functionName1', 'functionName2']); } Here you can find all the documentation about this topic: Controllers I hope this can be helpful, regards!
{ "pile_set_name": "StackExchange" }
Q: Python for loop ignoring if statement For some reason python is ignoring my if statement, even if the str(search) is in my list lista it still prints the elif statement regardless. Am I doing something wrong? search = input("what would you like to search for?:") for n in range(len(lista)): if str(search) in lista[n]: print(lista[n]) elif str(search) not in lista[n]: print("search not found in list") break A: Your elif will end the loop (because of the break) if the search wasn't found at the first position (because the if and elif are executed for each item in your list). In your case you could simply use a "trigger" to indicate at least one finding and do the if after the loop: found = False for n in range(len(lista)): if str(search) in lista[n]: print(lista[n]) found = True if not found: print("search not found in list") However better would be to iterate over the list directly instead of a range of the length: found = False for item in lista: if str(search) in item: print(item) found = True if not found: print("search not found in list") If you don't like the trigger you can also use a conditional comprehension to get all the matches and use the number of matches as indirect trigger: findings = [item for item in lista if str(search) in item] if findings: # you got matches: for match in findings: print(match) else: # no matches print("search not found in list")
{ "pile_set_name": "StackExchange" }
Q: Angular Code Coverage wrong output My stack is: Angular.js, Karma, Karma-coverage (Istanbul) and Jasmine. I have been running Code Coverage analysis over my app, the problem, and thus the question, is that I get Service A marked as covered by tests (in green) when it actually does not have any tests associated. I suspect that the following scenario is to blame: I know that Service A is used by Controller B. Controller B is covered by tests, and the Code Coverage results mark it correctly as covered by tests. Service A is not being mocked when testing Controller B. I think that since service A is indirectly called by Controller B's tests, I get the wrong result. Any ideas? Am I suspecting the right thing? Is there any ways around it so I can get an accurate test coverage result in this aspect? Thanks in advance! A: Unfortunately, this is how code coverage is evaluated. If the code is executed, it is considered to be "covered". Luckily, there is something you can do to reduce some of the false positives. You can mock out your dependencies! The following example will execute a jasmine spy instead of the actual service: describe('Controller Tests', function() { var $scope, mockServiceA; beforeEach(module('app', function($provide) { mockServiceA = jasmine.createSpyObj('mockServiceA', ['foo']); $provide.value('ServiceA', mockServiceA); })); beforeEach(inject(function($rootScope, $controller) { $scope = $rootScope.$new(); $controller('ControllerB', { $scope: $scope }); })); describe('ControllerB', function() { it('should call mock service', function() { expect(mockServiceA.foo).not.toHaveBeenCalled(); $scope.useServiceA(); expect(mockServiceA.foo).toHaveBeenCalled(); }); }); }); Here is a working Plunker: http://plnkr.co/edit/x8gQQNsHT0R5n5iJSxKw?p=info
{ "pile_set_name": "StackExchange" }
Q: Why does limit not exist? I don't understand how the limit does not exist for the composite function. The limit as x approaches -2 for g(x) is zero. So, the last step is to evaluate h(0), which is -1. Yes, there is a hole at x=0 but that doesn't mean you can't evaluate h(0). A: It's true that $\lim_{x\to-2}g(x)=0$, but as $g(x)$ goes to $0$, it gets there from two directions. Namely, from above and from below. It goes through values like $-0.1$, $-0.001$, $-0.0001$, etc. from below and through values like $0.1$, $0.001$, $0.0001$, etc. from above. That's equivalent to evaluating $\lim_{x\to 0}h(x)$ which, according to the theory of limits, is really two one-sided limits under the hood. And what does the function $h(x)$ approach as you go to $0$ from the right and from the left? $$\lim_{x\to 0^-}h(x)=1$$ and $$\lim_{x\to 0^+}h(x)=-1.$$ Those two limits don't agree and thus the limit itself does not exist. A: For the limit to exist the following must hold: $$\lim_{x\uparrow-2}h(g(x))=\lim_{x\downarrow-2}h(g(x))=h(g(0)),$$ Looking at the picture we can see that the left limit $$\lim_{x\uparrow-2}h(g(x))=\lim_{x\uparrow0}h(x)=1$$ the right limit $$\lim_{x\downarrow-2}h(g(x))=\lim_{x\downarrow0}h(x)=-1$$ and $h(g(-2))=h(3)=1$.
{ "pile_set_name": "StackExchange" }
Q: Input 0 of layer conv1d_1 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 200] I'm working on application that should predict interesting moments in 10 sec audio files. I divided audio on 50ms chunks and extracted notes, so I have 200 notes for each example. When I add convolutional layer it returns an error: ValueError: Input 0 of layer conv1d_1 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 200] Here is my code: def get_dataset(file_path): dataset = tf.data.experimental.make_csv_dataset( file_path, batch_size=12, label_name='label', na_value='?', num_epochs=1, ignore_errors=False) return dataset train = get_dataset('/content/gdrive/My Drive/MyProject/train.csv') test = get_dataset('/content/gdrive/My Drive/MyProject/TestData/manual.csv') feature_columns = [] for number in range(200): feature_columns.append(tf.feature_column.numeric_column('note' + str(number + 1) )) preprocessing_layer = tf.keras.layers.DenseFeatures(feature_columns) model = tf.keras.Sequential([ preprocessing_layer, tf.keras.layers.Conv1D(32, 3, padding='same', activation=tf.nn.relu, input_shape=[None, 200]), tf.keras.layers.Flatten(), tf.keras.layers.Dense(50, activation=tf.nn.relu), tf.keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) model.compile( loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(train, epochs=20) What causes this problem and how can it be fixed? A: The 1D convolution over sequences expects a 3D input. In other words, for each element in the batch, for each time step, a single vector. Consider the following: X = tf.random.normal([10, 200]) convolved = tf.keras.layers.Conv1D(32, 3, padding='same', activation=tf.nn.relu, input_shape=[None, 200]) print(convolved(X)) This throws an error: ValueError: Input 0 of layer conv1d_3 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [10, 200] However, If we provide for each of the 10 batch samples, for each of the 5 time steps, a 200 dimensional vector: X = tf.random.normal([10, 5, 200]) convolved = tf.keras.layers.Conv1D(32, 3, padding='same', activation=tf.nn.relu, input_shape=[None, 200]) print(convolved(X) This works as it should. Therefore, in your case, for each audio file, for each second (depends on how you sample the data), you will have a single vector.
{ "pile_set_name": "StackExchange" }
Q: Python print hyperlinked text to Spyder Console I'm using the WinPython distribution on Windows 7, which comes with the Spyder IDE (and I hope this will work the same on Anaconda). I would like to know how to print hyperlinked text to the console output. I assume it's possible, because when I get an error in my code, I get the traceback that shows me where it crashed, and those links are clickable, and will then open the line of the function where it raised the error. See below: (I can't post the image without 10 rep, that's lame, I'm new to the site) See here: http://i.stack.imgur.com/oJ3Aw.png However, I don't want to just open a file within the IDE, what I want to do is have a link to the folder location where my code just saved some plot images to disk, and when I click on the link, have it open the folder within windows explorer. Bonus points if there is a platform independent way of doing this, but a windows only solution would be sufficient for me. I have some previously existing Matlab code that would do this for me, but I can't determine if there is a Python equivalent: save_path = pwd; fprintf('Plots saved to: <a href="matlab: web(''%s'',''-browser'');">%s</a>\n',save_path,save_path); A: It has been deprecated. I find a reference here: https://github.com/pydata/pandas/pull/7499#issue-36016539
{ "pile_set_name": "StackExchange" }
Q: How do I organize strings into a table in visual c#? I was trying to sort up strings into grids in Visual c#, but couldn't do it. What code do I need to do so? I've already tried going to many websites and writing the code specified, but it did not work. I was expecting at least something, but all I got was a blank table when I copied code from a website. private void Form1_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'vendorDataSet.Vendor' table. // You can move, or remove it, as needed. this.vendorTableAdapter.Fill(this.vendorDataSet.Vendor); } A: If I understood what you want: You have some strings (ie in an array) and you want to insert them into a DataTable. DataTable dt = new DataTable(); dt.Columns.Add("Column1",typeof(string)); foreach(string str in yourStringArray){ DataRow dr = dt.NewRow(); dr["Column1"]= str; dt.Rows.Add(dr); }
{ "pile_set_name": "StackExchange" }
Q: Can Akka Actors replace Service layer? This is more of a design and best practices question. I am converting an app to use Actors and Futures. Currently these are the layers (before Akka is in the mix) . Play Controller -> Service layer -> (Slick) DAOs Now want to have something like Play Controller -> Actors ->Services (Now they'll return Futures) ->DAO In doing so I am finding that since original Service layer had all the methods with required business logic, Actors layer is looking just like a mediator. Wondering if it's okay (from design point of view) to get rid of Service layer now that everything is going to be through Actors? Play controller->Actors (with business methods) -> business methods calling into DAO (which Service methods were doing before) Or continue with existing Service layer and use those methods from Akka Actors only? Risk with keeping Service layer as it is, is all Service methods will remain public and free to be called from anywhere else (breaking the pattern ~ if somebody called Service method directly in controller (by passing Actors) or something). A: There are 2 approaches to actor-based system design: Actors are just a multithreading abstraction, e.g. TaskExecutors Actors are a foundation for business modelling, e.g. GhostActor in a Pac-Man game. You need to ask yourself which one do you want to follow with your refactoring. And why. The first option you mentioned (Actors talk to Services via Futures) is a multithreading abstraction. You want to do that when you have just hit a major performance bottleneck. Possibly actors can help, but there are many other tools that can do that. The second option you mentioned (Actors replace Services) uses actors for business domain modelling. And it's very powerful. You put your logic in actors, which consist of smaller actors, which consist of smaller actors and so on. Each of them represent a tiny bit of your business domain. The smaller the actor the better. There are many advantages of using this approach: Each of those actors can use internally a different strategy for obtaining and storing information. Some of them may use an HTTP service via Futures, some of them may use actor communication, some of them may be event-sourced. You have a declarative and human-understandable abstraction you can use in your entire system: the Actor. You just need to switch your brain from thinking about technical obstacles to thinking about business obstacles. When you follow some simple technical rules, you have scalability built into your system without thinking about it too much. Those rules become a second nature after some time. Of course, there are also some cons: There are business domains that cannot be easily modelled with actors. You are making your system totally dependent on one toolkit. I hope this can help you somehow. If you want to follow-up on something, just shout it out. Thanks!
{ "pile_set_name": "StackExchange" }
Q: Is it possible to generate .docx files without having MS Word installed? I want to use "OLE automation" (or whatever it's called now) to generate a Word document. I assume that it's possible to perform the following programmatically: Set page size (height, width, margin vals) Set font type/name, style, and size Add page numbering Add pages Insert page breaks What I'm not sure of is if I need to have MS Word on my system to do this (to have the necessary DLLs, perhaps)? I use Open Office (I like it, and it's free), but I reckon controlling the creation of docs programmatically is probably easier/better documented for MS Word than it is for Open Office and/or Libre Office - that's why I'm strongly considering making this "rendezvous with Redmond." This question is tangentially related to this one If Google Docs is a possibility here, I'd be willing to have a "meeting with Mountain View" but I know nothing about that file format or whether it can be "automated" etc. I need to end up with something that I can either convert to a PDF file or a DOCX file. Open Office can open DOCX and convert files to PDF, but I don't know about Google Docs. A: I've found https://docx.codeplex.com/ to be very useful in dynamically building docx documents.
{ "pile_set_name": "StackExchange" }
Q: Modify a string in a .properties file with batch I am trying to modify a certain property in my csm.properties by executing a script. I looked up a lot and in the end, came to this code. set "search=CLASSPATH" set "insert=CLASSPATH^=plugins^/Numbering.jar^\^:" set "textFile="%workingPlace%bin\csm.properties"" FOR /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do ( FOR /f "tokens=1*delims==" %%g IN ("%%i") DO ( IF /i "%%g" == %search% ( set "line=%%i" setlocal enabledelayedexpansion >>"%textFile%" echo(!line:%search%=%insert%! endlocal )ELSE ( %%i ) ) ) This code should read every line in my file and use = as a delimiter. If the code gets "CLASSPATH" as property, that line should get modified. But it seems like CLASSPATH isn't found. This is how csm.properties looks like: #Tue Jul 10 08:50:23 CEST 2018 JAVA_ARGS=-Xmx20000M -DLOCALCONFIG\=true -splash\:data/splash.png -Dmd.class.path\=$java.class.path -Dcom.nomagic.osgi.config.dir\=configuration -Desi.system.config\=data/application.conf -Dlogback.configurationFile\=data/logback.xml -Dsun.locale.formatasdefault\=true -Dinitial.user.language\=de JAVA_HOME=jre1.8.0_152 BOOT_CLASSPATH=lib/xalan.jar MAIN_CLASS=com.nomagic.osgi.launcher.ProductionFrameworkLauncher MAC_JAVA_ARGS="-Xdock\:name\=Cameo Systems Modeler" -Xdock\:icon\=bin/md.icns -Dapple.laf.useScreenMenuBar\=true APP_ARGS= DEFAULT_MEMORY_SETTINGS_64=-Xmx[30%,1200,4000]M DEFAULT_MEMORY_SETTINGS_32=-Xmx800M CLASSPATH=lib/patch.jar\:lib/brand_api.jar CONSOLE=false After modifications, CLASSPATHshould look like this: CLASSPATH=plugins/Numbering.jar\:lib/patch.jar\:lib/brand_api.jar A: Simpler... @echo OFF setlocal set "search=CLASSPATH" set "insert=plugins/Numbering.jar\:" set "textFile=%workingPlace%bin\csm.properties" (FOR /f "usebackq tokens=1* delims==" %%i in ("%textFile%") do ( if "%%i" equ "%search%" ( echo %search%=%insert%%%j ) else if "%%j" neq "" ( echo %%i=%%j ) else ( echo %%i ) )) > temp.tmp move /Y temp.tmp "%textFile%"
{ "pile_set_name": "StackExchange" }
Q: Java bytecode asm - How can I create a clone of a class with only the class name changed? Java asm - How can I create a clone of a class with only the class name changed ? I know that there's a simple way to modify the class name using asm SimpleRemapper, but I just want the outer class name changed without modifying the class names used in the methods. (please see below example) Basically if I have a target class public class Target { public Target clone(...) ... public int compare(another: Target) ... } I just wanted to create a clone that looks as: public class ClonedTarget { public Target clone(...) ... public int compare(another: Target) ... } (Note that the return type of clone and arg type of compare hasn't changed. This is intentional for my use case). A: Cloning a class and changing the name and only the name, i.e. leave every other class reference as-is, is actually very easy with the ASM API. ClassReader cr = new ClassReader(Target.class.getResourceAsStream("Target.class")); ClassWriter cw = new ClassWriter(cr, 0); cr.accept(new ClassVisitor(Opcodes.ASM5, cw) { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, "ClonedTarget", signature, superName, interfaces); } }, 0); byte[] code = cw.toByteArray(); When chaining a ClassReader with a ClassWriter, the ClassVisitor in the middle only needs to overwrite those methods corresponding to an artifact it wants to change. So, to change the name and nothing else, we only need to override the visit method for the class’ declaration and pass a different name to the super method. By passing the class reader to the class writer’s constructor, we’re even denoting that only little changes will be made, enabling subsequent optimizations of the transform process, i.e. most of the constant pool, as well as the code of the methods, will just get copied here. It’s worth considering the implications. On the bytecode level, constructors have the special name <init>, so they keep being constructors in the resulting class, regardless of its name. Trivial constructors calling a superclass constructor may continue to work in the resulting class. When invoking instance methods on ClonedTarget objects, the this reference has the type ClonedTarget. This fundamental property does not need to be declared and thus, there is no declaration that needs adaptation in this regard. Herein lies the problem. The original code assumes that this is of type Target and since nothing has been adapted, the copied code still wrongly assumes that this is of type Target, which can break in various ways. Consider: public class Target { public Target clone() { return new Target(); } public int compare(Target t) { return 0;} } This looks like not being affected by the issue. The generated default constructor just calls super() and will continue to work. The compare method has an unused parameter type left as-is. And the clone() method instantiates Target (unchanged) and returns it, matching the return type Target (unchanged). Seems fine. But what’s not visible here, the clone method overrides the method Object clone() inherited from java.lang.Object and therefore, a bridge method will be generated. This bridge method will have the declaration Object clone() and just delegate to the Target clone() method. The problem is that this delegation is an invocation on this and the assumed type of the invocation target is encoded within the invocation instruction. This will cause a VerifierError. Generally, we can not simply tell apart which invocations are applied on this and which on an unchanged reference, like a parameter or field. It does not even need to have a definite answer. Consider: public void method(Target t, boolean b) { (b? this: t).otherMethod(); } Implicitly assuming that this has type Target, it can use this and a Target instance from another source interchangeably. We can not change the this type and keep the parameter type without rewriting the code. Other issues arise with visibility. For the renamed class, the verifier will reject unchanged accesses to private members of the original class. Besides failing with a VerifyError, problematic code may slip through and cause problems at a later time. Consider: public class Target implements Cloneable { public Target duplicate() { try { return (Target)super.clone(); } catch(CloneNotSupportedException ex) { throw new AssertionError(); } } } Since this duplicate() does not override a superclass method, there won’t be a bridge method and all unchanged uses of Target are correct from the verifier’s perspective. But the clone() method of Object does not return an instance of Target but of the this’ class, ClonedTarget in the renamed clone. So this will fail with a ClassCastException, only when being executed. This doesn’t preclude working use cases for a class with known content. But generally, it’s very fragile.
{ "pile_set_name": "StackExchange" }
Q: How to update package? when I use `<< PhysicalConstants`` I get the message like :General::obspkg: PhysicalConstants is outdated... see the Compatibility Guide for more infomation... The question is how to update it? My version is MA9.0. A: It can't be updated. The Physical Constants package is obsolete as of 9.0 and is no longer updated. You can ignore that warning message and still use it if you want, but mostly the same functionality is now provided by the Units framework (new in 9.0). In addition to the warning message you saw, there's a note at the top of the Physical Constants package guide page to this effect. That note is suffixed with an unfortunately barely visible link to the Units framework guide page.
{ "pile_set_name": "StackExchange" }
Q: Twitter Trending List Printing First Character Instead of First Entry I'm having an issue where I can get the Twitter API to provide me with the top 10 list of trending topics in a given area, but I can only get the entirety to print, or the first character to print, but not the first entry in the list. The following code is what I tried to just print the first entry in the list (entry 0) but I get the first character for each list entry instead (character 0). from twitter import * access_token = "myaccesstoken" access_token_secret = "myaccesstokensecret" consumer_key = "consumerkey" consumer_secret = "consumersecret" t = Twitter(auth=OAuth(access_token, access_token_secret, consumer_key, consumer_secret)) results = t.trends.place(_id = 2442047) #I used the Los Angeles WOEID for location in results: for trend in location["trends"]: trendlist = trend["name"] print trendlist[0] If I just use a simple list like this, I can get Python to just print the first entry: trendlist = ['one', 'two', 'three'] print trendlist[0] Can anyone provide a pointer on why this behavior is different and how to just get one entry to print from the Trending list? Thank you! A: The trends api returns something like this: "trends": [ { "events": null, "name": "#GanaPuntosSi", "promoted_content": null, "query": "%23GanaPuntosSi", "url": "http://twitter.com/search/?q=%23GanaPuntosSi" }...] With your second for loop you iterate through each of the above trend "objects". trendlist = trend["name"] doesn't get you a list, but the trend name. print trendlist[0] prints out the first letter of the name. Just print trend["name"] and you are done. Here's a little repl.it for you https://repl.it/BLww/1. You are printing all 10 because you are looping through them all. If you want to print just the first one, you can do this: for location in results: print location["trends"][0]['name']
{ "pile_set_name": "StackExchange" }
Q: How does trading work? During the last event (The one that spawned a ton of Ralts with increased shiny chance) I got multiple shiny Ralts. My friend didn't get any so I wanted to trade him one of mine. But when I tried it said that I didn't have enough stardust. It doesn't say how much more I need it just says I can't trade. How much stardust do I need to trade? Then later I traded with another friend and we tried to trade again but it said I can only do one special trade per day. Is there another way to trade pokemon so we can do it multiple times in one day? A: Special trades are unregistered, shiny or Legendary Pokemon. The amount of stardust depends on your friendship level and what you are trading it can be between 100- 1,000,000 stardust. You can find the exact value of the trade you want to do with a quick search. For shiny Pokemon that is new: Good - 1,000,00 Great - 800,000 Ultra - 80,000 Best - 40,000 The only time they have allowed multiply special trade in one day is if you are at a go fest.
{ "pile_set_name": "StackExchange" }
Q: Random graph with $p \ll n^{-1+\epsilon}$ a.a.s has no subgraph with $k$ vertices with at least $k+1$ edges Let $G=(n,p)$ with $p \ll n^{-1+\epsilon}$ for all $\epsilon >0$. Then for each $k\in \mathbb{N}$ there are a.a.s no $k$ vertices with at least $k+1$ edges. Proof: We want to show $$\Pr(\exists S\subseteq V: |S|=k, |E_S|\geq k+1) \to 0\quad (n\to \infty).$$ Let $S\subseteq V$ with $|S|=k$. Then there are ${k}\choose{2}$$=\frac{k(k-1)}{2}$ possible subsets with 2 elements. Lets call them $A_i$, Define the random varibles $1_{A_i}$ such that $$1_{A_i}=1 \text{ when } A_i \subset{E_S},\quad 0 \text{ else}$$ We have $$\Pr(|S|=k, |E_S|\geq k+1)=\Pr(\sum_i 1_{A_i} \geq k+1)\leq \frac{E\sum_i 1_{A_i}}{k+1}$$ Then $E\sum_i 1_{A_i}=\frac{k(k-1)}{2}\Pr(1_{A_i}=1)=\frac{k(k-1)}{2}p$ since the probability of the edges is independent. Now we have $$\Pr(|S|=k, |E_S|\geq k+1)=\Pr(\sum_i 1_{A_i} \geq k+1)\leq \frac{E\sum_i 1_{A_i}}{k-1}<\frac{k}{2}p \ll \frac{k}{2} \frac{1}{nn^{-\epsilon}}$$ Now pick: $n^{\epsilon}=k$. is this correct? does the result follow? A: The approach you have taken is not strong enough to get the desired conclusion. The use of $1_{A_i}$ is a bit strange, but everything you've done can be phrased in terms of the random variable $|E_S|$ (for a fixed $S$). You are applying Markov's inequality to $|E_S|$, saying that $$ \Pr[|E_S| \ge k+1] \le \frac{\mathbb E[|E_S|]}{k+1}. $$ By linearity of expectation, $\mathbb E[|E_S|] = \binom k2 p$. It is not quite correct that $\binom k2 = \frac{k(k+1)}{2}$; rather, $\binom k2 = \frac{k(k-1)}{2}$. But this is not important, since we still have $\frac{\binom k2 p}{k+1} < \frac {kp}{2} \ll \frac{k}{n^{1-\epsilon}}$. Here, $k = |S| \le n$, and this inequality is potentially strong enough to prove that for any given $S$, we have $|E_S| \le |S|$ with high probability. But that's not what we want: we want a result that holds for all $S$. Consider $k=4$, for example: then there are $\binom n4$ sets $S$ we could consider, and if the probability is $\ll \frac{4}{n^{1-\epsilon}}$ for each one, that only tells us that the expected number of sets $S$ with $5$ edges is $\ll \binom n4 \frac{4}{n^{1-\epsilon}}$ or in other words it is $\ll n^{3+\epsilon}$, which still could be very large. We can improve on Markov's inequality for bounding the probability that a set $S$ induces a subgraph we don't like. First of all: for any $k$, there is only a constant number of $k$-vertex graphs with $k+1$ edges. So if we show that for a fixed graph $H$ (on $k$ vertices and with $k+1$ edges) the random graph doesn't have an $H$-subgraph a.a.s., then we immediately conclude that the random graph doesn't have any such subgraphs with $k$ vertices and $k+1$ edges a.a.s. (Since the subgraphs are not necessarily induced, this also rules out subgraphs with $k$ vertices and more than $k+1$ edges.) As an upper bound, the expected number of labeled $H$-subgraphs in $\mathcal G_{n,p}$ is less than $n^{|V(H)|}p^{|E(H)|}$. (The power of $n$ is actually at most $n(n-1)(n-2)\dotsb$ with $|V(H)|$ factors.) If $H$ has $k$ vertices and $k+1$ edges, this is $n^k p^{k+1}$. We have $p \ll n^{-1+\epsilon}$ for all $\epsilon>0$, so in particular, $p \ll n^{-1 + \frac{1}{k+1}}$. Therefore $p^{k+1} \ll n^{-k}$, and $n^k p^{k+1} \to 0$ as $n \to \infty$. Therefore $\mathcal G_{n,p}$ has no copies of $H$ a.a.s., and by doing this for every $k$-vertex graph with $k+1$ edges we get the statement you want. A subtle point here is that we are proving the statement "for each $k$, a.a.s., $\mathcal G_{n,p}$ contains no $k$-vertex subgraph with at least $k+1$ edges" not "a.a.s., $\mathcal G_{n,p}$ contains no $k$-vertex subgraph with at least $k+1$ edges for each $k$". That is, $k$ is a constant fixed outside the limit as $n \to \infty$. If we didn't do this, then the statement would not be true, because $\mathcal G_{n,p}$ for $p \gg \frac1n$ does contain large subgraphs with more edges than vertices (in particular, the whole graph is such a subgraph).
{ "pile_set_name": "StackExchange" }
Q: vectorizing a script with cellfun I'm aiming to import data from various folder and text files into matlab. clear all main_folder = 'E:\data'; %Directory of data TopFolder = dir(main_folder); %exclude the first two cells as they are just pointers. TopFolder = TopFolder(3:end); TopFolder = struct2cell(TopFolder); Name1 = TopFolder(1,:); %obtain the name of each folder dirListing = cellfun(@(x)dir(fullfile(main_folder,x,'*.txt')),Name1,'un',0); Variables = cellfun(@(x)struct2cell(x),dirListing,'un',0); FilesToRead = cellfun(@(x)x(1,:),Variables,'un',0); %obtain the name of each text file in each folder This provides the name for each text file in each folder within 'main_folder'. I am now trying to load the data without using a for loop (I realise that for loops are sometimes faster in doing this but I'm aiming for a compact script). The method I would use with a for loop would be: for k = 1:length(FilesToRead); filename{k} = cellfun(@(x)fullfile(main_folder,Name{k},x),FilesToRead{k},'un',0); fid{k} = cellfun(@(x)fopen(x),filename{k},'un',0); C{k} = cellfun(@(x)textscan(x,'%f'),fid{k},'un',0); end Is there a method which would involve not using loops at all? something like cellfun within cellfun maybe? A: folder = 'E:\data'; files = dir(fullfile(folder, '*.txt')); full_names = strcat(folder, filesep, {files.name}); fids = cellfun(@(x) fopen(x, 'r'), full_names); c = arrayfun(@(x) textscan(x, '%f'), fids); % load data here res = arrayfun(@(x) fclose(x), fids); assert(all(res == 0), 'error in closing files'); but if the data is in csv format it can be even easier: folder = 'E:\data'; files = dir(fullfile(folder, '*.txt')); full_names = strcat(folder, filesep, {files.name}); c = cellfun(@(x) csvread(x), full_names, 'UniformOutput', false); now all the data is stored in c
{ "pile_set_name": "StackExchange" }
Q: How to stop R from creating empty Rplots.pdf file when using ggsave and Rscript I have an R script that saves some plots using ggsave. When I run the script from the command line, it not only saves my plots but also an empty Rplots.pdf file. How can I prevent R from creating this unnecessary file? Here is an example script that reproduces the error: #!/usr/bin/env Rscript # Code that creates unnecessary Rplots.pdf file library(ggplot2) my.data <- data.frame(x = 1:10, y = 1:10) my.plot <- qplot(x, y, data = my.data) ggsave('example.png', my.plot) All the following ways of running the script create the unnecessary file: Rscript script.R Rscript --vanilla script.R chmod a+x script.R ./script.R Also, when I source the code from within an interactive session, an unnecessary blank R Graphics Device window opens. Furthermore, I do not have these problems if I use the the following more verbose code in place of ggsave: #!/usr/bin/env Rscript # Code that does NOT create unnecessary Rplots.pdf file library(ggplot2) my.data <- data.frame(x = 1:10, y = 1:10) my.plot <- qplot(x, y, data = my.data) png(file = 'example.png') print(my.plot) dev.off() Here is my session info (which is the same whether running Rscript or interactively): R version 3.0.1 (2013-05-16) Platform: x86_64-pc-linux-gnu (64-bit) locale: [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 [7] LC_PAPER=C LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C attached base packages: [1] methods stats graphics grDevices utils datasets base other attached packages: [1] ggplot2_0.9.3.1 loaded via a namespace (and not attached): [1] colorspace_1.2-2 dichromat_2.0-0 digest_0.6.3 grid_3.0.1 [5] gtable_0.1.2 labeling_0.1 MASS_7.3-26 munsell_0.4 [9] plyr_1.8 proto_0.3-10 RColorBrewer_1.0-5 reshape2_1.2.2 [13] scales_0.2.3 stringr_0.6.2 Update 5 years later (2018-08-02): This problem comes and goes. ggplot2 2.2.1 does not produce the empty file, ggplot2 3.0.0 does, and the ggplot2 team is currently working to fix this. For development history, see ggplot2 Issues #1326, #2363, #2758, and #2787. A: If you look at the defaults for the width and height arguments in ggsave, you'll see that they are par("din")[1] and par("din")[2]. If you run this in the console, you'll see that it opens a graphics window, if one isn't already open. This sort of makes sense, since in order to get the device width/height in inches, you need an actual device. I suppose one could argue that par("din") should return an error if no device is open, in which case Hadley surely would have written ggsave differently. Indeed, from ?par: If the current device is the null device, par will open a new device before querying/setting parameters. Hence, specifying a width/height will prevent the spurious device from opening.
{ "pile_set_name": "StackExchange" }
Q: Looping through a range using a msgbox I have hit a bit of a wall when looping through a range. What I have done is created a table which when a qty is selected in the table a range from that table is transported to another array on the next blank line. What I would like to do to speed up the process is if I would like to add the same information a second time to the next line down a msgbox asking yes or no, and then to loop through. Below is my code and I have tried a couple variations of this without success Sub Add() Dim foundCell As Range Dim mysearch As Integer Dim iRow As Long, Last As Long Dim ws1 As Worksheet, ws2 As Worksheet Set ws2 = Worksheets("Output") iRow = ws2.Cells(ws2.Rows.Count, "V").End(xlUp).Row + 1 Last = ws2.Cells(ws2.Rows.Count, "N").End(xlUp).Row mysearch = ws2.Range("N10").Value If ws2.Range("N10").Value = 0 Then MsgBox "No Product Selected" Exit Sub Else Do Set foundCell = ws2.Range("N12:N" & Last).Find(What:=mysearch, Lookat:=xlWhole) If Not foundCell Is Nothing Then ws2.Cells(iRow, 22).Value = foundCell.Offset(0, -3).Value ws2.Cells(iRow, 23).Value = foundCell.Offset(0, -4).Value ws2.Cells(iRow, 24).Value = foundCell.Offset(0, -2).Value ws2.Cells(iRow, 25).Value = foundCell.Offset(0, -1).Value ws2.Cells(iRow, 26).Value = foundCell.Offset(0, 1).Value ws2.Cells(iRow, 27).Value = foundCell.Value ws2.Cells(iRow, 28).Value = foundCell.Offset(0, 2).Value answer = MsgBox("Would you like to add this product to the next line?", vbYesNo + vbQuestion, "MORE PRODUCTS?") If answer = vbYes Then Loop Else 'Exit Sub End If End If End If Sheets("Output").Range("N12:N35").ClearContents End Sub A: I'm not sure if i get you right but this is what i understood Option Explicit Sub Add() Dim foundCell As Range Dim mysearch As Integer Dim iRow As Long, Last As Long Dim ws1 As Worksheet, ws2 As Worksheet Dim answer As Boolean Set ws2 = Worksheets("Output") iRow = ws2.Cells(ws2.Rows.Count, "V").End(xlUp).Row + 1 Last = ws2.Cells(ws2.Rows.Count, "N").End(xlUp).Row mysearch = ws2.Range("N10").Value If ws2.Range("N10").Value = 0 Then MsgBox "No Product Selected" Exit Sub Else Set foundCell = ws2.Range("N12:N" & Last).Find(What:=mysearch, Lookat:=xlWhole) If Not foundCell Is Nothing Then Do 'this way it'll copy at least once answer = CopyCells(foundCell, ws2, iRow) Loop While answer 'copy till user choose NO End If End If Sheets("Output").Range("N12:N35").ClearContents End Sub Function CopyCells(SrcRange As Range, DestWs As Worksheet, iRow As Long) As Boolean Dim UserChoice As Long DestWs.Cells(iRow, 22).Value = SrcRange.Offset(0, -3).Value DestWs.Cells(iRow, 23).Value = SrcRange.Offset(0, -4).Value DestWs.Cells(iRow, 24).Value = SrcRange.Offset(0, -2).Value DestWs.Cells(iRow, 25).Value = SrcRange.Offset(0, -1).Value DestWs.Cells(iRow, 26).Value = SrcRange.Offset(0, 1).Value DestWs.Cells(iRow, 27).Value = SrcRange.Value DestWs.Cells(iRow, 28).Value = SrcRange.Offset(0, 2).Value UserChoice = MsgBox("Would you like to add this product to the next line?", vbYesNo + vbQuestion, "MORE PRODUCTS?") If UserChoice = 6 Then CopyCells = True iRow = iRow + 1 Else CopyCells = False End If End Function Might need some adjustments. Maybe you could post your input and desired output?
{ "pile_set_name": "StackExchange" }
Q: Bad lighting using Phong Method I'm trying to make a cube, which is irregularly triangulated, but virtually coplanar, shade correctly. Here is the current result I have: With wireframe: Normals calculated in my program: Normals calculated by meshlabjs.net: The lighting works properly when using regular size triangles for the cube. As you can see, I'm duplicating vertices and using angle weighting. lighting.frag vec4 scene_ambient = vec4(1, 1, 1, 1.0); struct material { vec4 ambient; vec4 diffuse; vec4 specular; float shininess; }; material frontMaterial = material( vec4(0.25, 0.25, 0.25, 1.0), vec4(0.4, 0.4, 0.4, 1.0), vec4(0.774597, 0.774597, 0.774597, 1.0), 76 ); struct lightSource { vec4 position; vec4 diffuse; vec4 specular; float constantAttenuation, linearAttenuation, quadraticAttenuation; float spotCutoff, spotExponent; vec3 spotDirection; }; lightSource light0 = lightSource( vec4(0.0, 0.0, 0.0, 1.0), vec4(100.0, 100.0, 100.0, 100.0), vec4(100.0, 100.0, 100.0, 100.0), 0.1, 1, 0.01, 180.0, 0.0, vec3(0.0, 0.0, 0.0) ); vec4 light(lightSource ls, vec3 norm, vec3 deviation, vec3 position) { vec3 viewDirection = normalize(vec3(1.0 * vec4(0, 0, 0, 1.0) - vec4(position, 1))); vec3 lightDirection; float attenuation; //ls.position.xyz = cameraPos; ls.position.z += 50; if (0.0 == ls.position.w) // directional light? { attenuation = 1.0; // no attenuation lightDirection = normalize(vec3(ls.position)); } else // point light or spotlight (or other kind of light) { vec3 positionToLightSource = vec3(ls.position - vec4(position, 1.0)); float distance = length(positionToLightSource); lightDirection = normalize(positionToLightSource); attenuation = 1.0 / (ls.constantAttenuation + ls.linearAttenuation * distance + ls.quadraticAttenuation * distance * distance); if (ls.spotCutoff <= 90.0) // spotlight? { float clampedCosine = max(0.0, dot(-lightDirection, ls.spotDirection)); if (clampedCosine < cos(radians(ls.spotCutoff))) // outside of spotlight cone? { attenuation = 0.0; } else { attenuation = attenuation * pow(clampedCosine, ls.spotExponent); } } } vec3 ambientLighting = vec3(scene_ambient) * vec3(frontMaterial.ambient); vec3 diffuseReflection = attenuation * vec3(ls.diffuse) * vec3(frontMaterial.diffuse) * max(0.0, dot(norm, lightDirection)); vec3 specularReflection; if (dot(norm, lightDirection) < 0.0) // light source on the wrong side? { specularReflection = vec3(0.0, 0.0, 0.0); // no specular reflection } else // light source on the right side { specularReflection = attenuation * vec3(ls.specular) * vec3(frontMaterial.specular) * pow(max(0.0, dot(reflect(lightDirection, norm), viewDirection)), frontMaterial.shininess); } return vec4(ambientLighting + diffuseReflection + specularReflection, 1.0); } vec4 generateGlobalLighting(vec3 norm, vec3 position) { return light(light0, norm, vec3(2,0,0), position); } mainmesh.frag #version 430 in vec3 f_color; in vec3 f_normal; in vec3 f_position; in float f_opacity; out vec4 fragColor; vec4 generateGlobalLighting(vec3 norm, vec3 position); void main() { vec3 norm = normalize(f_normal); vec4 l0 = generateGlobalLighting(norm, f_position); fragColor = vec4(f_color, f_opacity) * l0; } Follows the code to generate the verts, normals and faces for the painter. m_vertices_buf.resize(m_mesh.num_faces() * 3, 3); m_normals_buf.resize(m_mesh.num_faces() * 3, 3); m_faces_buf.resize(m_mesh.num_faces(), 3); std::map<vertex_descriptor, std::list<Vector3d>> map; GLDebugging* deb = GLDebugging::getInstance(); auto getAngle = [](Vector3d a, Vector3d b) { double angle = 0.0; angle = std::atan2(a.cross(b).norm(), a.dot(b)); return angle; }; for (const auto& f : m_mesh.faces()) { auto f_hh = m_mesh.halfedge(f); //auto n = PMP::compute_face_normal(f, m_mesh); vertex_descriptor vs[3]; Vector3d ps[3]; int i = 0; for (const auto& v : m_mesh.vertices_around_face(f_hh)) { auto p = m_mesh.point(v); ps[i] = Vector3d(p.x(), p.y(), p.z()); vs[i++] = v; } auto n = (ps[1] - ps[0]).cross(ps[2] - ps[0]).normalized(); auto a1 = getAngle((ps[1] - ps[0]).normalized(), (ps[2] - ps[0]).normalized()); auto a2 = getAngle((ps[2] - ps[1]).normalized(), (ps[0] - ps[1]).normalized()); auto a3 = getAngle((ps[0] - ps[2]).normalized(), (ps[1] - ps[2]).normalized()); auto area = PMP::face_area(f, m_mesh); map[vs[0]].push_back(n * a1); map[vs[1]].push_back(n * a2); map[vs[2]].push_back(n * a3); auto p = m_mesh.point(vs[0]); deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(n.x(), n.y(), n.z()) * 4); p = m_mesh.point(vs[1]); deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(n.x(), n.y(), n.z()) * 4); p = m_mesh.point(vs[2]); deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(n.x(), n.y(), n.z()) * 4); } int j = 0; int i = 0; for (const auto& f : m_mesh.faces()) { auto f_hh = m_mesh.halfedge(f); for (const auto& v : m_mesh.vertices_around_face(f_hh)) { const auto& p = m_mesh.point(v); m_vertices_buf.row(i) = RowVector3d(p.x(), p.y(), p.z()); Vector3d n(0, 0, 0); //auto n = PMP::compute_face_normal(f, m_mesh); Vector3d norm = Vector3d(n.x(), n.y(), n.z()); for (auto val : map[v]) { norm += val; } norm.normalize(); deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(norm.x(), norm.y(), norm.z()) * 3, Vector3d(1.0, 0, 0)); m_normals_buf.row(i++) = RowVector3d(norm.x(), norm.y(), norm.z()); } m_faces_buf.row(j++) = RowVector3i(i - 3, i - 2, i - 1); } Follows the painter code: m_vertexAttrLoc = program.attributeLocation("v_vertex"); m_colorAttrLoc = program.attributeLocation("v_color"); m_normalAttrLoc = program.attributeLocation("v_normal"); m_mvMatrixLoc = program.uniformLocation("v_modelViewMatrix"); m_projMatrixLoc = program.uniformLocation("v_projectionMatrix"); m_normalMatrixLoc = program.uniformLocation("v_normalMatrix"); //m_relativePosLoc = program.uniformLocation("v_relativePos"); m_opacityLoc = program.uniformLocation("v_opacity"); m_colorMaskLoc = program.uniformLocation("v_colorMask"); //bool for unmapping depth color m_useDepthMap = program.uniformLocation("v_useDepthMap"); program.setUniformValue(m_mvMatrixLoc, modelView); //uniform used for Color map to regular model switch program.setUniformValue(m_useDepthMap, (m_showColorMap && (m_showProblemAreas || m_showPrepMap || m_showDepthMap || m_showMockupMap))); QMatrix3x3 normalMatrix = modelView.normalMatrix(); program.setUniformValue(m_normalMatrixLoc, normalMatrix); program.setUniformValue(m_projMatrixLoc, projection); //program.setUniformValue(m_relativePosLoc, m_relativePos); program.setUniformValue(m_opacityLoc, m_opacity); program.setUniformValue(m_colorMaskLoc, m_colorMask); glEnableVertexAttribArray(m_vertexAttrLoc); m_vertices.bind(); glVertexAttribPointer(m_vertexAttrLoc, 3, GL_DOUBLE, false, 3 * sizeof(GLdouble), NULL); m_vertices.release(); glEnableVertexAttribArray(m_normalAttrLoc); m_normals.bind(); glVertexAttribPointer(m_normalAttrLoc, 3, GL_DOUBLE, false, 0, NULL); m_normals.release(); glEnableVertexAttribArray(m_colorAttrLoc); if (m_showProblemAreas) { m_problemColorMap.bind(); glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL); m_problemColorMap.release(); } else if (m_showPrepMap) { m_prepColorMap.bind(); glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL); m_prepColorMap.release(); } else if (m_showMockupMap) { m_mokupColorMap.bind(); glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL); m_mokupColorMap.release(); } else { //m_colors.bind(); //glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL); //m_colors.release(); } m_indices.bind(); glDrawElements(GL_TRIANGLES, m_indices.size() / sizeof(int), GL_UNSIGNED_INT, NULL); m_indices.release(); glDisableVertexAttribArray(m_vertexAttrLoc); glDisableVertexAttribArray(m_normalAttrLoc); glDisableVertexAttribArray(m_colorAttrLoc); EDIT: Sorry for not being clear enough. The cube is merely an example. My requirements are that the shading works for any kind of mesh. Those with very sharp edges, and those that are very organic (like humans or animals). A: The issue is clearly explained by the image "Normals calculated in my program" from your question. The normal vectors at the corners and edges of the cube are not normal perpendicular to the faces: For a proper specular reflection on plane faces, the normal vectors have to be perpendicular to the sides of the cube. The vertex coordinate and its normal vector from a tuple with 6 components (x, y, z, nx, ny, nz). A vertex coordinate on an edge of the cube is adjacent to 2 sides of the cube and 2 (face) normal vectors. The 8 vertex coordinates on the 8 corners of the cube are adjacent to 3 sides (3 normal vectors) each. To define the vertex attributes with face normal vectors (perpendicular to a side) you have to define multiple tuples with the same vertex coordinate but different normal vectors. You have to use the different attribute tuples to form the triangle primitives on the different sides of the cube. e.g. If you have defined a cube with the left, front, bottom coordinate of (-1, -1, -1) and the right, back, top coordinate of (1, 1, 1), then the vertex coordinate (-1, -1, -1) is adjacent to the left, front and bottom side of the cube: x y z nx ny nz left: -1 -1 -1 -1 0 0 front: -1 -1 -1 0 -1 0 bottom: -1 -1 -1 0 0 -1 Use the left attribute tuple to form the triangle primitives on the left side, the front to form the front and bottom for the triangles on the bottom. In general you have to decide what you want. There is no general approach for all meshes. Either you have a fine granulated mesh and you want a smooth appearance (e.g a sphere). In that case your approach is fine, it will generate a smooth light transition on the edges between the primitives. Or you have a mesh with hard edges like a cube. In that case you have to "duplicate" vertices. If 2 (or even more) triangles share a vertex coordinate, but the face normal vectors are different, then you have to create a separate tuple, for all the combinations of the vertex coordinate and the face normal vector. For a general "smooth" solution you would have to interpolate the normal vectors of the vertex coordinates which are in the middle of plane surfaces, according to the surrounding geometry. That means if a bunch of triangle primitives form a plane, then all the normal vectors of the vertices have to be computed dependent on there position on the plane. At the centroid the normal vector is equal to the face normal vector. For all other points the normal vector has to be interpolated with the normal vectors of the surrounding faces. Anyway that seems to be an XY problem. Why is there a "vertex" somewhere in the middle of a plane? Probably the plane is tessellated. But if the plan is tessellated, why are the normal vectors not interpolated too, during the tessellation process? A: In your image, we can see that the inner triangle (the one that doesn't have point on cube edges, in top left quarter) has an homogeneous color. My interpretation is that triangles that have points on the edge/corner of the cube share the same vertex and then share the same normal and some how the normal are averaged. So it's not perpendicular to the faces. To debug this, you should create a simple geometry of a cube with 6 faces and 2 triangles per face. Hence it's make 12 triangles. Two options: If you have 8 vertex in the geometry, the corner are shared between triangles of different face and the issue came from the geometry generator. If you have 6×4=24 vertex in the geometry the truth lies elsewhere. A: As mentioned in the other answers the problem is your mesh normals. Computing an average normal, like you are doing currently, is what you would want to do for a smooth object like a sphere. cgal has a function for that CGAL::Polygon_mesh_processing::compute_vertex_normal For a cube what you want is normals perpendicular to the faces cgal has a functoin for that too CGAL::Polygon_mesh_processing::compute_face_normal To debug the normals you can just set fragColor = vec4(norm,1); in mainmesh.frag. Here the cubes on the left have averaged (smooth) normals and on the right have face (flat) normals:And shaded they look like this: shading has to work for any kind of mesh (a cube or any organic mesh) For that you can use something like per_corner_normals whitch: Implements a simple scheme which computes corner normals as averages of normals of faces incident on the corresponding vertex which do not deviate by more than a specified dihedral angle (e.g. 20°) And this is what it looks like with a angle of 1°, 20°, 100°:
{ "pile_set_name": "StackExchange" }
Q: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead I am trying to import data from a json file and render a list of images. But I get an error saying: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead. This is the file which seems to generate the error: import React from 'react'; import Product from "./Product/index"; const ProductList = () => { const renderedList = import("../../../data/data.json").then(json => json.goods.map(image => { return <div><Product images={image.pictures} /></div> } )); return <div>{renderedList}</div> } export default ProductList; This is my data.json file: { "goods": [ { "id": "1", "name": "Cat Tee Black T-Shirt", "prices": "$ 10.90", "pictures": "120642730401995392_1.jpg", "size": "", "quantity": "" }, { "id": "2", "name": "Dark Thug Blue-Navy T-Shirt", "prices": "$ 29.45", "pictures": "51498472915966370_1.jpg", "size": "", "quantity": "" }] } This is my Product component: import React, { Component } from "react"; import Thumb from "../../../Thumb/index"; const Product = props => { return ( <div className="shelf-item"> <div className="shelf-stopper">Free shipping</div> <Thumb classes="shelf-item__thumb" src={props.images} /> <p className="shelf-item__title">product</p> <div className="shelf-item__price"> productInstallment </div> <div className="shelf-item__buy-btn">Add to cart</div> </div> ); } export default Product; Could someone help me figure it out? Thanks a lot! A: In your productList component you are using a promise instead of rendering child, to overcome this you can make it a stateful component fix this like: import React, { Component } from 'react'; import Product from "./Product/index"; class ProductList extends Component { constructor(props) { super(props) this.state = { goods: [] } } componentDidMount = () => { import("../../../data/data.json") .then(json => this.state({ goods: json.goods })) } render() { const { goods } = this.state return ( <div> {goods.map(image => <div><Product images={image.pictures} /></div>)} </div> ) } } export default ProductList; or alternatively you can import it in beginning like: import React from 'react'; import Product from "./Product/index"; import goods from "../../../data/data.json" const ProductList = () => { const renderedGoods = goods.map(image => { return <div><Product images={image.pictures} /></div> }) return <div>{renderedGoods}</div> } export default ProductList; Not an issue, yes you resolved the promise correct, but as even when you type in console what you are actually returning is a promise and .then or .catch are callbacks called when its either resolved or rejected so you see react wants is something to render and you cannot render a promise
{ "pile_set_name": "StackExchange" }
Q: Algorithm for N-way merge A 2-way merge is widely studied as a part of Mergesort algorithm. But I am interested to find out the best way one can perform an N-way merge? Lets say, I have N files which have sorted 1 million integers each. I have to merge them into 1 single file which will have those 100 million sorted integers. Please keep in mind that use case for this problem is actually external sorting which is disk based. Therefore, in real scenarios there would be memory limitation as well. So a naive approach of merging 2 files at a time (99 times) won't work. Lets say we have only a small sliding window of memory available for each array. I am not sure if there is already a standardized solution to this N-way merge. (Googling didn't tell me much). But if you know if a good n-way merge algorithm, please post algo/link. Time complexity: If we greatly increase the number of files (N) to be merged, how would that affect the time complexity of your algorithm? Thanks for your answers. I haven't been asked this anywhere, but I felt this could be an interesting interview question. Therefore tagged. A: How about the following idea: Create a priority queue Iterate through each file f enqueue the pair (nextNumberIn(f), f) using the first value as priority key While queue not empty dequeue head (m, f) of queue output m if f not depleted enqueue (nextNumberIn(f), f) Since adding elements to a priority queue can be done in logarithmic time, item 2 is O(N × log N). Since (almost all) iterations of the while loop adds an element, the whole while-loop is O(M × log N) where M is the total number of numbers to sort. Assuming all files have a non-empty sequence of numbers, we have M > N and thus the whole algorithm should be O(M × log N). A: Search for "Polyphase merge", check out classics - Donald Knuth & E.H.Friend. Also, you may want to take a look at the proposed Smart Block Merging by Seyedafsari & Hasanzadeh, that, similarly to earlier suggestions, uses priority queues. Another interesting reasonsing is In Place Merging Algorithm by Kim & Kutzner. I also recommend this paper by Vitter: External memory algorithms and data structures: dealing with massive data. A: One simple idea is to keep a priority queue of the ranges to merge, stored in such a way that the range with the smallest first element is removed first from the queue. You can then do an N-way merge as follows: Insert all of the ranges into the priority queue, excluding empty ranges. While the priority queue is not empty: Dequeue the smallest element from the queue. Append the first element of this range to the output sequence. If it's nonempty, insert the rest of the sequence back into the priority queue. The correctness of this algorithm is essentially a generalization of the proof that a 2-way merge works correctly - if you always add the smallest element from any range, and all the ranges are sorted, you end up with the sequence as a whole sorted. The runtime complexity of this algorithm can be found as follows. Let M be the total number of elements in all the sequences. If we use a binary heap, then we do at most O(M) insertions and O(M) deletions from the priority queue, since for each element written to the output sequence there's a dequeue to pull out the smallest sequence, followed by an enqueue to put the rest of the sequence back into the queue. Each of these steps takes O(lg N) operations, because insertion or deletion from a binary heap with N elements in it takes O(lg N) time. This gives a net runtime of O(M lg N), which grows less than linearly with the number of input sequences. There may be a way to get this even faster, but this seems like a pretty good solution. The memory usage is O(N) because we need O(N) overhead for the binary heap. If we implement the binary heap by storing pointers to the sequences rather than the sequences themselves, this shouldn't be too much of a problem unless you have a truly ridiculous number of sequences to merge. In that case, just merge them in groups that do fit into memory, then merge all the results. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Finding new memory address? C++ (I tested the address because I was getting errors and I found out the address changed before it was deleted, by the time the delete is called the titlePTR has already changed its address and it is giving me an error saying "BLOCK TYPE IS VALID" I heard this is when you try to delete a pointer that wasn't made by new (So that made me think about the address) Btw I know I don't have to make a dynamic array but I am reading a book and it is saying to practice saving memory for times where your program doesn't need to run the code. I posted on a few other places and people always nag about "Don't use new blah blah blah" Here is what is says when it trys to delete titlePTR or bodyPTR: http://postimg.org/image/gt0f8kufn/ if (test == "MapleStory") { wchar_t *titlePTR = new wchar_t[30]; <-- Example Address: 051 cout << titlePTR; wchar_t *bodyPTR = new wchar_t[20]; titlePTR = L"MapleStory"; bodyPTR = L"Launching MapleStory..."; MessageBox(NULL, bodyPTR, titlePTR, MB_OK | MB_ICONINFORMATION); ShellExecute(NULL, L"open", L"GameLauncher.exe", NULL, L"C:\\Nexon\\MapleStory", 1); cout << endl << titlePTR; <-- Example Address: 0601 delete[] titlePTR; delete[] bodyPTR; } A: wchar_t *titlePTR = new wchar_t[30]; // (1) titlePTR = L"MapleStory"; // (2) delete[] titlePTR; // (3) This allocates memory and stores the address of the memory in the variable (1). Then you overwrite it with a new address (2). And then you delete the new address (3), instead of the allocated memory. So your problem is that the assignment in step (2) doesn't use the buffer you prepared but creates a new buffer. To fix, just do: const wchar_t *titlePTR = L"MapleStory"; And don't delete of course, since you didn't allocate any memory using new.
{ "pile_set_name": "StackExchange" }
Q: Finding an item's index in an array I was writing a function that takes two arguments, an array and a number, and returns the index of the number if it's present in the array. The issue I encounter is the fact that my code returns properly without the "else" part, however, when I add the code about returning "-1" it doesn't work properly and it seems as if the compiler only takes "return -1" into account, no matter what arguments I use. Could anyone help me solve this issue? function search(arr, item) { for(let i=0; i<arr.length; i++){ if(item===arr[i]){ return i; }else if(item!==arr[i]){ return -1; } } } It's always giving me an output of "-1", when it's supposed to give the index of the "item" argument if it's presents in the first array argument. A: You need return -1 outside the loop so it only returns -1 if it makes it all the way through the loop without finding something. If it finds something before that, it will return the index: function search(arr, item) { for(let i=0; i<arr.length; i++){ if(item===arr[i]){ return i; } } return -1; } console.log(search([1, 2, 3], 5)) console.log(search([1, 2, 3], 2))
{ "pile_set_name": "StackExchange" }
Q: How to extrapolate variables to make them become globals? Let's say I have to find out the window width, the code will be: $(window).width(); and if I want it to become a global variable i just have to declare its name: var windowWidth = $(window).width(); The result will be the window's width. But I need that variable to change when things happens, for example when I resize the window: $(window).resize(function(){ var windowWidth = $(window).width(); }); How can I extrapolate this variable in order to override the one before? I can override the variable before putting the function i need in the .resize(function(); but in this way my code confusionary and I need just a variable to use it in other functions outside the resize function, for example a .click(function) $(document).ready(function(){ var w = $(window).width(); $(window).resize(function(){ var w = $(window).width(); //click function goes here. }); }); how if I want that the function above will become a whole new variable? without putting a new function in it? A: the problem with your code is that you have var twice. every time you use var you create a new variable. so just leave out the second one like this: $(document).ready(function(){ var w = $(window).width(); $(window).resize(function(){ w = $(window).width(); //click function goes here. }); });
{ "pile_set_name": "StackExchange" }
Q: Frameless window with controls in electron (Windows) I want my app to have no title bar but still be closeable, draggable, minimizable, maximizable and resizable like a regular window. I can do this in OS X since there is a titleBarStyle option called hidden-inset that I can use but unfortunately it's not available for Windows, which is the platform that I'm developing for. How would I go about doing something like this in Windows? Here's an example of what I'm talking about. A: Assuming you don't want window chrome, you can accomplish this by removing the frame around Electron and filling the rest in with html/css/js. I wrote an article that achieves what you are looking for on my blog here: http://mylifeforthecode.github.io/making-the-electron-shell-as-pretty-as-the-visual-studio-shell/. Code to get you started is also hosted here: https://github.com/srakowski/ElectronLikeVS To summarize, you need to pass frame: false when you create the BrowserWindow: mainWindow = new BrowserWindow({width: 800, height: 600, frame: false}); Then create and add control buttons for your title bar: <div id="title-bar"> <div id="title">My Life For The Code</div> <div id="title-bar-btns"> <button id="min-btn">-</button> <button id="max-btn">+</button> <button id="close-btn">x</button> </div> </div> Bind in the max/min/close functions in js: (function () { var remote = require('remote'); var BrowserWindow = remote.require('browser-window'); function init() { document.getElementById("min-btn").addEventListener("click", function (e) { var window = BrowserWindow.getFocusedWindow(); window.minimize(); }); document.getElementById("max-btn").addEventListener("click", function (e) { var window = BrowserWindow.getFocusedWindow(); window.maximize(); }); document.getElementById("close-btn").addEventListener("click", function (e) { var window = BrowserWindow.getFocusedWindow(); window.close(); }); }; document.onreadystatechange = function () { if (document.readyState == "complete") { init(); } }; })(); Styling the window can be tricky, but the key use to use special properties from webkit. Here is some minimal CSS: body { padding: 0px; margin: 0px; } #title-bar { -webkit-app-region: drag; height: 24px; background-color: darkviolet; padding: none; margin: 0px; } #title { position: fixed; top: 0px; left: 6px; } #title-bar-btns { -webkit-app-region: no-drag; position: fixed; top: 0px; right: 6px; } Note that these are important: -webkit-app-region: drag; -webkit-app-region: no-drag; -webkit-app-region: drag on your 'title bar' region will make it so that you can drag it around as is common with windows. The no-drag is applied to the buttons so that they do not cause dragging. A: I was inspired by Shawn's article and apps like Hyper Terminal to figure out how to exactly replicate the Windows 10 style look as a seamless title bar, and wrote this tutorial. It includes a fix for the resizing issue Shawn mentioned, and also switches between the maximise and restore buttons, even when e.g. the window is maximised by dragging the it to the top of the screen. Quick reference Title bar height: 32px Title bar title font-size: 12px Window control buttons: 46px wide, 32px high Window control button assets from font Segoe MDL2 Assets (docs here), size: 10px Minimise: &#xE921; Maximise: &#xE922; Restore: &#xE923; Close: &#xE8BB; Window control button colours: varies between UWP apps, but seems to be Dark mode apps (white window controls): #FFF Light mode apps (black window controls): #171717 Close button colours Hover (:hover): background #E81123, colour #FFF Pressed (:active): background #F1707A, colour #000 or #171717 Note: in the tutorial I have switched to PNG icons with different sizes for pixel-perfect scaling, but I leave the Segoe MDL2 Assets font characters above as an alternative
{ "pile_set_name": "StackExchange" }
Q: Problema Funcion SQL Error: not allowed to return a result set from a function no veo para nada el problema de esta función, intento validar el pin de un usuario, pero me sale este error, he estado mirando en otras preguntas pero no veo el problema. Les dejo el código aquí abajo: CREATE DEFINER=`root`@`localhost` FUNCTION `validar_pin`(id_usuario int, pin int) RETURNS BOOLEAN BEGIN DECLARE pin_user int; DECLARE fecha DATE; select desbloqueo into fecha from Usuario where id = id_usuario; if fecha = null then SELECT pin into pin_user FROM Usuario where id_usuario = id; if (pin = pin_user) THEN UPDATE Usuario SET num_intentos = 0 WHERE id = id_usuario; UPDATE Usuario SET desbloqueo = NULL WHERE id = id_usuario; RETURN TRUE; else UPDATE Usuario SET num_intentos = (num_intentos + 1) WHERE id = id_usuario; end if; end if; if (select num_intentos from Usuario where id = id_usuario) = 3 then UPDATE Usuario SET desbloqueo = DATE_ADD(NOW(), INTERVAL 1 DAY) WHERE id = id_usuario; select "Has agotado todas las oportunidades, intentalo en 24h"; end if; RETURN FALSE; END Alguna sugerencia?? Gracias A: El problema es que dentro de las funciones no puedes hacer un select sin decir en donde quieres guardar los datos por así decirlo. O sea ésto estaría mal dentro de una función: select nombre from usuario; En tu función tienes varias partes en que haces un select y no insertas el valor, por ejemplo acá: if (select num_intentos from Usuario where id = id_usuario) = 3 then Deberías primero obtener ese numero y guardarlo en una variable y luego es que preguntas por esa variable: select num_intentos into _num_intentos from Usuario where id = id_usuario if(_num_intentos = 3) then .... En la documentación lo indican (si es que usas mysql, asumo eso): procedimientos y funciones Statements that return a result set can be used within a stored procedure but not within a stored function. This prohibition includes SELECT statements that do not have an INTO var_list clause and other statements Dice las declaraciones que retornan un listado de resultados pueden ser usadas dentro de procedimientos almacenados pero no dentro de funciones almacenadas, esta prohibición incluye los SELECTS que no tengan una claúsula INTO a una variable y otras declaraciones.
{ "pile_set_name": "StackExchange" }
Q: What does "All examples have been tested directly from the text, which is in machine-readable form" mean? I am reading the classic book on C - The C Programming Language Book by Brian Kernighan and Dennis Ritchie. The preface of the book says All examples have been tested directly from the text, which is in machine-readable form. What does this mean? A: (just a guess) Probably that every code example has been indeed tested on a system with a C compiler, and pretty-printed in the book (perhaps using troff or whatever document formatter was used by K&R) by some automatic tool (I don't know what tool was used by K&R. Today, you'll use e.g. vgrind or pygments or LaTeX's listings package, or some other pretty-printer). So there cannot be typos while converting C code to paper (e.g. as if the C code has been manually copied and typeset)
{ "pile_set_name": "StackExchange" }
Q: How can I chain cases in Bash 3.2, which doesn't have `;&`? I have a bash script that resumes aborted execution with a case statement. It works great with Bash 4 under CentOS 6 but does not work with CentOS 5 because of Bash 3.2. Is there any programming logic I can use to replace the following with something more "portable"? last-action=$(cat /tmp/last-action) case last-action in) beginning) function1 ;& middle) function2 ;& end) function3 ;& esac The thing is, wherever task execution stopped it must resume there and execute everything that comes after. For example, if last-action=middle it would execute function2 and then function3. That's where the operator ;& came in handy. Any clues to do this without a lot of if statements? A: I understand that fallthrough is very convenient, but given your example snippet I don't see how case "${last_action}" in beginning) function1 function2 function3 ;; middle) function2 function3 ;; end) function3 ;; esac would add much overhead to your code. It's still prettier than lots of ifs. However, if your switch is more complex and you want this to be more dynamic, you can do something along the lines of: #!/bin/bash function1() { echo 1; } function2() { echo 2; } function3() { echo 3; } last_action=$1 actions_beginning="function1 function2 function3" actions_middle="function2 function3" actions_end="function3" _actions="actions_${last_action}" for action in ${!_actions}; do "${action}" done   $ ./test.sh beginning 1 2 3 $ ./test.sh middle 2 3 $ ./test.sh end 3 EDIT: Just looked at your code on github and I myself would definitely go this route.
{ "pile_set_name": "StackExchange" }
Q: Django Rest Framework, display data from a table referenced with a foreign key I got stuck a bit with a small problem when doing my school project, the problem is that I have an api with DRF and wanting to show my patient data "main table" shows them without problems but when I want to show other patient data in a different table (this table is this reference with a foreign key to Patient) I have not managed to obtain the patient data from this other table. I can not make my api send me the other patient data from the foreign key referenced to the patient, could you help me? models.py class Paciente(TimeStampedModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) udi = models.UUIDField(default=uuid.uuid4, editable=False) first_name = models.CharField('Nombre(s)', max_length=100) last_name = models.CharField('Apellidos', max_length=100) gender = models.CharField('Sexo', max_length=20, choices=GENDER_CHOICES) birth_day = models.DateField('Fecha de nacimiento', blank=True, null=True) phone_number = models.CharField('Número de telefono', max_length=13) civil_status = models.CharField('Estado civil', max_length=20, choices=CIVIL_STATUS_CHOICES) etc..... class Antecedentes(TimeStampedModel): """ Modelo de motivo y antecedentes de la enfermedad presentada en el momento de la consulta """ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE, null=True) motivo = models.TextField('Motivo de la consulta') antecedentes = models.TextField('Antecedentes de la enfermedad actual', blank=True, null=True) serializers.py class antecedenteSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source="user.username") class Meta: model = Antecedentes fields = ('paciente' ,'motivo', 'antecedentes', ) views.py I was trying this but I'm not if this is correct or not from historiaClinica import models as modelsHC class antecedenteList(APIView): """ Lista todos los antecedentes o crea uno nuevo """ def get_object(self, pk): try: paciente = get_object_or_404(pk=pk) return modelsHC.Antecedentes.objects.get(paciente=paciente) except modelsHC.Antecedentes.DoesNotExist: raise Http404 def get(self, request, pk, format=None): antecedente = self.get_object(pk) serializer = antecedenteSerializer(antecedente) return Response(serializer.data) A: If you need to show all Antecedentes related to the specific Paciente you can use reverse lookup paciente.antecedentes_set.all() so in view you can do this: class antecedenteList(APIView): """ Lista todos los antecedentes o crea uno nuevo """ def get_object(self, pk): try: paciente = get_object_or_404(pk=pk) return paciente except modelsHC.Antecedentes.DoesNotExist: raise Http404 def get(self, request, pk, format=None): paciente = self.get_object(pk) antecedentes = paciente.antecedentes_set.all() serializer = antecedenteSerializer(antecedentes, many=True) return Response(serializer.data) Note I am using serializer's many=True argument to serialize multipe objects at the same time. Also you may need in the future nested serialization to show all antecedentes in the paciente data. Details of nested serialization you can find here.
{ "pile_set_name": "StackExchange" }
Q: Send data from Telerik Grid to new tab/page on button click I have a Telerik Grid as below ( I'm relatively new to MVC and brand new to Telerik controls). The grid is a partial view that gets updated from a list of search criteria. @(Html.Kendo().Grid((IEnumerable<MyModel>)Model.MyModel) .Name("grid") .DataSource(ds => ds.Ajax() .Model(mod => { mod.Id(m => m.Id); mod.Field(p => p.Name).Editable(false); })) .Columns(columns => { columns.Template(@<text></text>).ClientTemplate("<input type='checkbox' #= IsSelected ? checked='checked':'' # class='chkbx' value='#= Id#' name='SelectedArea' />") .HeaderTemplate("<input type='checkbox' id='masterCheckBox' onclick='checkAll(this)'/>").Width(20); columns.Bound(p => p.Name).Filterable(false).Width(100); }) .Editable(ed => ed.Mode(GridEditMode.InCell)) .Pageable() .Sortable() .Scrollable() .Filterable() ) The users need to be able to select from the grid with the check boxes, then click a button which should pop-up (new window/new tab) with a report generated from the selected items in the grid, leaving the original page alone. If I submit the page, it sends the selected list back but loses the partial page of the Grid (and all the selected items. If I just create a link and open a new page it doesn't post any of the data so I don't know which ones were selected. here are some of the attempts I made for buttons/actions. I suspect this is much simpler than I am finding it to be, but I can't see the forest through the trees... <input type="submit" name="Command" value="Print Call List" formtarget="_blank" /> <input type="submit" name="Command" value="Print Call List" onclick="location.href='@Url.Action("CallList", "Reports", new { target="_blank" })'" /> @Html.ActionLink("Print Call List", "CallList", "Reports", null, new { target = "_blank" }) A: Finally figured it out myself. I am still submitting the form just like clicking on the search button. Using a different button I validate what is asked for, (search vs. print list), if it is searching, continue to do what it was before. If a report is requested,then I added a flag to the view object called ShowCallList if (Request.IsAjaxRequest()) { if ("Print Call List" == command) { TempData.Add("SelectedArea", searchModel.SelectedArea); searchModel.ShowCallList = true; } searchModel.SearchResults = ExecuteSearch(searchModel); return PartialView("_SearchResults", searchModel); } then added the following code to the view. @if (Model.ShowCallList) { @Html.Raw("window.open('") @Url.Action("CallList", "Reports", new { target="_blank" }) @Html.Raw("')"); } It will print out an open window command and the url has a target of blank to open in a new window. I put the needed list of id's into the TempData to pass it to the report page. So the report gets the needed parameters from the TempData when it is called when the search page reloads. I also had to make a small modification to the search method to recheck the check boxes in the search results grid so it appears to the end user that only the new page was opened with the requested report. IsSelected = searchModel.SelectedArea.Contains(item.ID),
{ "pile_set_name": "StackExchange" }
Q: Read from Kafka and write to hdfs in parquet I am new to the BigData eco system and kind of getting started. I have read several articles about reading a kafka topic using spark streaming but would like to know if it is possible to read from kafka using a spark job instead of streaming ? If yes, could you guys help me in pointing out to some articles or code snippets that can get me started. My second part of the question is writing to hdfs in parquet format. Once i read from Kafka , i assume i will have an rdd. Convert this rdd into a dataframe and then write the dataframe as a parquet file. Is this the right approach. Any help appreciated. Thanks A: You already have a couple of good answers on the topic. Just wanted to stress out - be careful to stream directly into a parquet table. Parquet's performance shines when parquet row group sizes are large enough (for simplicity, you can say file size should be in order of 64-256Mb for example), to take advantage of dictionary compression, bloom filters etc. (one parquet file can have multiple row chunks in it, and normally does have multiple row chunks in each file; although row chunks can't span multiple parquet files) If you're streaming directly to a parquet table, then you'll end up very likely with a bunch of tiny parquet files (depending on mini-batch size of Spark Streaming, and volume of data). Querying such files can be very slow. Parquet may require reading all files' headers to reconcile schema for example and it's a big overhead. If this is the case, you will need to have a separate process that will, for example, as a workaround, read older files, and writes them "merged" (this wouldn't be a simple file-level merge, a process would actually need to read in all parquet data and spill out larger parquet files). This workaround may kill the original purpose of data "streaming". You could look at other technologies here too - like Apache Kudu, Apache Kafka, Apache Druid, Kinesis etc that can work here better. Update: since I posted this answer, there is now a new strong player here - Delta Lake. https://delta.io/ If you're used to parquet, you'll find Delta very attractive (actually, Delta is built on top of parquet layer + metadata). Delta Lake offers: ACID transactions on Spark: Serializable isolation levels ensure that readers never see inconsistent data. Scalable metadata handling: Leverages Spark’s distributed processing power to handle all the metadata for petabyte-scale tables with billions of files at ease. Streaming and batch unification: A table in Delta Lake is a batch table as well as a streaming source and sink. Streaming data ingest, batch historic backfill, interactive queries all just work out of the box. Schema enforcement: Automatically handles schema variations to prevent insertion of bad records during ingestion. Time travel: Data versioning enables rollbacks, full historical audit trails, and reproducible machine learning experiments. Upserts and deletes: Supports merge, update and delete operations to enable complex usecases like change-data-capture, slowly-changing-dimension (SCD) operations, streaming upserts, and so on. A: For reading data from Kafka and writing it to HDFS, in Parquet format, using Spark Batch job instead of streaming, you can use Spark Structured Streaming. Structured Streaming is a scalable and fault-tolerant stream processing engine built on the Spark SQL engine. You can express your streaming computation the same way you would express a batch computation on static data. The Spark SQL engine will take care of running it incrementally and continuously and updating the final result as streaming data continues to arrive. You can use the Dataset/DataFrame API in Scala, Java, Python or R to express streaming aggregations, event-time windows, stream-to-batch joins, etc. The computation is executed on the same optimized Spark SQL engine. Finally, the system ensures end-to-end exactly-once fault-tolerance guarantees through checkpointing and Write Ahead Logs. In short, Structured Streaming provides fast, scalable, fault-tolerant, end-to-end exactly-once stream processing without the user having to reason about streaming. It comes with Kafka as a built in Source, i.e., we can poll data from Kafka. It’s compatible with Kafka broker versions 0.10.0 or higher. For pulling the data from Kafka in batch mode, you can create a Dataset/DataFrame for a defined range of offsets. // Subscribe to 1 topic defaults to the earliest and latest offsets val df = spark .read .format("kafka") .option("kafka.bootstrap.servers", "host1:port1,host2:port2") .option("subscribe", "topic1") .load() df.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)") .as[(String, String)] // Subscribe to multiple topics, specifying explicit Kafka offsets val df = spark .read .format("kafka") .option("kafka.bootstrap.servers", "host1:port1,host2:port2") .option("subscribe", "topic1,topic2") .option("startingOffsets", """{"topic1":{"0":23,"1":-2},"topic2":{"0":-2}}""") .option("endingOffsets", """{"topic1":{"0":50,"1":-1},"topic2":{"0":-1}}""") .load() df.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)") .as[(String, String)] // Subscribe to a pattern, at the earliest and latest offsets val df = spark .read .format("kafka") .option("kafka.bootstrap.servers", "host1:port1,host2:port2") .option("subscribePattern", "topic.*") .option("startingOffsets", "earliest") .option("endingOffsets", "latest") .load() df.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)") .as[(String, String)] Each row in the source has the following schema: | Column | Type | |:-----------------|--------------:| | key | binary | | value | binary | | topic | string | | partition | int | | offset | long | | timestamp | long | | timestampType | int | Now, to write Data to HDFS in parquet format, following code can be written: df.write.parquet("hdfs://data.parquet") For more information on Spark Structured Streaming + Kafka, please refer to following guide - Kafka Integration Guide I hope it helps! A: Use Kafka Streams. SparkStreaming is an misnomer (it's mini-batch under the hood, at least up to 2.2). https://eng.verizondigitalmedia.com/2017/04/28/Kafka-to-Hdfs-ParquetSerializer/
{ "pile_set_name": "StackExchange" }
Q: How to start osgi console (Equinox) I'm trying to start an OSGi console in Windows 7. I used this statement on a terminal window: java -jar org.eclipse.osgi.jar -console But it doesn't work that is nothing does happen nor doesn't appear prompt osgi>. And typing on keyboard is ineffective except for ^C that makes to reappear usual terminal prompt. Anyone has any suggestion? A: Starting from Equinox 3.8.0.M4, it has a new console. So you need also these four bundles for it to run properly. org.eclipse.equinox.console.jar org.apache.felix.gogo.shell.jar org.apache.felix.gogo.command.jar org.apache.felix.gogo.runtime.jar These jar files can be found in your Eclipse installation folder under 'plugins' folder. Copy these jars and put them in the same folder with your org.eclipse.osgi.jar and it would look like: somedir/ configuration/ config.ini org.eclipse.osgi.jar org.eclipse.equinox.console.jar org.apache.felix.gogo.shell.jar org.apache.felix.gogo.command.jar org.apache.felix.gogo.runtime.jar Then edit config.ini as: osgi.bundles=org.apache.felix.gogo.runtime@start, org.apache.felix.gogo.command@start, org.apache.felix.gogo.shell@start, org.eclipse.equinox.console@start After doing this, run java -jar org.eclipse.osgi.jar -console in your command line and the OSGi console will start. Reference Bug 371101 A: The equinox built-in console is deprecated and disabled since version 3.8. If you use a newer version, you should use the osgi.console.enable.builtin=true property. See http://hwellmann.blogspot.hu/2012/08/new-osgi-console-in-equinox-380.html. You can set these properties as system properties. Your command will be: java -Dosgi.noshutdown=true -Dosgi.console.enable.builtin=true -jar org.eclipse.osgi.jar -console This worked for me with 3.8. I have just tried it with 3.10 but it does not work. I guess the builtin console is removed completely. You should use the gogo console that has become a de-facto standard. You can find information about it at the link above.
{ "pile_set_name": "StackExchange" }
Q: Using PyQt5, How do I make a QComboBox searchable? I am using PyQt5 to make a GUI. On it, I have a QComboBox that has a dropdown list that has over 400 items. I was wondering if there is any way in which I can type into the QComboBox to search for a matching case? A: You could use a QCompleter for this. For an editable QComboBox a QCompleter is created automatically. This completer performs case insensitive inline completion but you can adjust that if needed, for example from PyQt5 import QtWidgets from itertools import product app = QtWidgets.QApplication([]) # wordlist for testing wordlist = [''.join(combo) for combo in product('abc', repeat = 4)] combo = QtWidgets.QComboBox() combo.addItems(wordlist) # completers only work for editable combo boxes. QComboBox.NoInsert prevents insertion of the search text combo.setEditable(True) combo.setInsertPolicy(QtWidgets.QComboBox.NoInsert) # change completion mode of the default completer from InlineCompletion to PopupCompletion combo.completer().setCompletionMode(QtWidgets.QCompleter.PopupCompletion) combo.show() app.exec()
{ "pile_set_name": "StackExchange" }
Q: passing data parameters to updata SQL table A user enters in his information via 8 JTextFields. This information is passed via parameters into the updateUser method and the method updates the SQL table with this information. This is what I am currently trying to do although when User presses update button, no changes are made to the database table retrieve user data, create UserOperation and call updateUser method String userName = textFieldUserName.getText(); String userPassword = textField_1.getText(); String securityQuestion = textFieldSecQuestion.getText(); String securityAnswer = textFieldAnswer.getText(); String email = textFieldEmail.getText(); String fName = textFieldName.getText(); String phoneNumber = textFieldPhone.getText(); String department = textFieldDepartment.getText(); UserOperations userOperations = new UserOperations(); userOperations.updateUser(userName, userPassword, securityQuestion, securityAnswer, email, fName, phoneNumber, department); the updateUser method public void updateUser (String userName, String userPassword, String securityQuestion, String securityAnswer, String email, String fName, String phoneNumber, String department) { try { String sql = "UPDATE systeuser SET username = ?,userpassword = ?,securityquestion = ?,securityanswer = ?,email = ?,fname = ?,phonenumber = ?,department = ? WHERE username = ?"; stmt = conn.prepareStatement(sql); stmt.setString (1, userName); stmt.setString (2, userPassword); stmt.setString (3, securityQuestion); stmt.setString (4, securityAnswer); stmt.setString (5, email); stmt.setString (6, fName); stmt.setString (7, phoneNumber); stmt.setString (8, department); stmt.setString (9, userName); stmt.executeUpdate( ); } catch (Exception e) { e.printStackTrace ( ); } } A: Its because of the single quotes placed around the ?. You need not give those single quotes, since you're doing this:- stmt.setString(1, userName); // setString says that this parameter is a String Thus, the single quote generally used to enclose String in a query is not needed in your case.
{ "pile_set_name": "StackExchange" }
Q: Text Scrolling in java Pleae help to solve this problem... I has a page designed in JFrames Now i need to make a text scrolling at the top of the page.... Please provide me the code... A: Check this out, is is commented and will most likely help you. http://www.abbeyworkshop.com/howto/java/ta_scroll/index.html
{ "pile_set_name": "StackExchange" }
Q: Issue of convertHtml data missing Have you guys faced the data loss after converted HTML to pdf? Here is my problem. $scope.current.clause_note = '<ul><li>This is for testing <strong>TINTERIOR WORKS</strong></li></ul><p><br></p>' $scope.current.clause_note = self.convertHtml($scope.current.clause_note); The result remained the TINTERIOR WORKS strong parts and other tags were missing. How to ensure all the contents convert to pdf without data loss? A: Use $sce as shown below. var app = angular.module('myApp', []); app.controller('MyController', function MyController($scope, $sce) { $scope.current = '<ul><li>This is for testing <strong>TINTERIOR WORKS</strong></li></ul><p><br></p>' $scope.current = $sce.trustAsHtml($scope.current); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <div ng-controller='MyController' ng-app="myApp"> <div ng-bind-html="current"></div> </div>
{ "pile_set_name": "StackExchange" }
Q: Android Bulk insert Or Update rather then insertOrReplace My Problem: I m working on an Android application (using SQLite) where I have to fetch a lot of data from a server and store it to DB. Currently, I m getting a list from the server, Loop over it and inserting it into DB one by one. But before every record insertion, I m checking if it already exists in DB. If does then I update that record. This is happing across the application ( My app have over 50 tables ). Now a week ago I noticed this process taking extra time. I mean we got a list from the server, we loop through it and run two queries for each record ( One to check whether it already exist or not and one is for insert or update). Now I need to optimise it. I know about batch insertion and I'm thinking about inserting all records at once. But there's a problem in it. I need to check if the record already exists in DB or not. If yes then update else insert. I know about insetOrReplace but it does not serve my purpose. I need to update some specific records rather than replacing everything (in the case of data already in DB and filled by the user from the app locally). So what would be the solution of it? Do I have to check which records already exists in DB by one query then run one query to update the records and one to insert remaining? But it still three queries? Can it be solved by one query only? Or any other solution? A: After two days of work. I finally found a solution. Which increase process speed more than 35%. Also, this technique helps my case (insert If not exist else update). SQLite has method insertOrIgnore. As name refer, it inserts the record or ignores it (on primary Key). So for the first part. insert or ignore into contact ( _id , cntct_id ) ) values ( COALESCE ( ( Select _id from contact where _id = '10' or cntct_id = '46' ) ,null ), '46') ; Now, this insert check, if primary key _id already exists it will ignore the insertion. Here is the other part. Which will update the record? Update contact set cntct_id = '46' ,_id='10' , where _id = 10 or cntct_id = '46'; So I generate 30 queries like these (create a single String which holds all of these) and run it using SQL Batch insertion. Like this SQLiteStatement statementAdd = database.compileStatement(addQuery); statementAdd.execute(); One thing to consider here while doing this. Once a record is inserted it will update ( with same values ) as well ( A little overhead but in the case of ignore it works perfectly. Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: Understanding undefined behavior for a binary stream using fseek(file, 0, SEEK_END) with a file The C spec has an interesting footnote (#268 C11dr §7.21.3 9) "Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state." Does this ever apply to binary streams reading a file? (as from a physical device) IMO, a binary file on a disk is just a sea of bytes. It seems to me that a binary file could not have state-dependent encoding as it is a binary file. I'm fuzzy on the concept of "binary wide-oriented streams" and if that even could apply to disk I/O. I see that calling fseek(file, 0, SEEK_END) on a serial stream like a com port or maybe stdin may not get to the true end as the end is yet to be determined. Thus the narrowing of the question to physical files. [edit] Answer: A concern with older (maybe up to late 1980s). Presently in 2014, Windows, POSIT-specific and non-exotic others: not a problem. @Shafik Yaghmour provides a good reference in Using fseek and ftell to determine the size of a file has a vulnerability?. There @Jerry Coffin discusses CP/M as binary files not always having a precise length. (128-byte records per wiki). Thanks to @Keith Thompson answer for the meat of the answer. Together this explains the specs's "(because of possible trailing null characters)" comment. A: Binary files are going to be sequences of 8-bit bytes, with an exact specified size, on any system you're likely to use. But not all systems store files that way, and the C standard is carefully designed to allow portability to systems with unusual characteristics. For example, a conforming C implementation might run on an operating system that stores files as sequences of 512-byte blocks, with no indication of how many bytes of the final block are significant. On such a system, when a binary file is created, the OS might pad the remainder of the final block with zero bytes. When you read from such a file, the padding bytes might either appear in the input (even though they were never explicitly written to the file), or they might be ignored (even though the program that created the file might have written them explicitly). If you're reading from a non-seekable stream (for example keyboard input), then fseek(file, 0, SEEK_END) won't just give you a bad result, it will indicate failure by returning a non-zero result. (On POSIX-compliant systems, it returns -1 and sets errno; ISO C doesn't require that.) On most systems, fseek(file, 0, SEEK_END) on a binary file will either seek to the actual end of the file (a position determined by exactly how many bytes were written to the file), or return a clear failure indication. If you're using POSIX-specific features anyway, you can safely assume this behavior; you can probably make the same assumption for Windows and a number of other systems. If you want your code to be 100% portable to exotic systems, you shouldn't assume that binary files won't be padded with extra zero bytes.
{ "pile_set_name": "StackExchange" }
Q: How to power a device using a USB port instead of AA batteries? I have a device that uses 3 AA batteries and I would like to power it from a USB port instead. As I understand I will have to use resistors but I have no idea on which ones. I have found the following calculator: Voltage Divider Calculator While it does its work, the wiring shown in diagram is quite confusing: I guess this is some logical schema rather than real wiring schema. Question: What resistor values do I need to get ~3.6V from a 5V USB port, and how should I wire them ? Is there a better way than using resistors to get 3.6V from 5V? A: Resistors will not be the best option, you need to know the source current of the device and there will be large voltage swings if the device changes it's current. Resistors may also not be possible if the device draws large amounts of current. Three alkaline batteries is lower than 4.5V (could be as low as 3.6V when their dead). Since the device running from 3 alkaline batteries should be able to accept 4.5V, a voltage regulator like the might be a good way to ensure that the device is getting the appropriate voltage, however you might need to select one with a lower dropout than 0.5V which might be hard if your device needs more than 100mA. Another option would be to find out if the device already has a linear regulator or switching regulator on the input. If it does, then you might be able to run 5V straight into the device.
{ "pile_set_name": "StackExchange" }
Q: How to auto resize contents in CollectionViewCell after the cell's size changed? In Xcode, I created a UICollectionView and dragged some labels to the UICollectionViewCell. The issue was that when changing devices, the cell won't adjust its size to the screen size. So I implemented the following code: func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) return CGSize(width: self.collectionView.frame.width * 0.9, height:self.collectionView.frame.height *0.8) } After this, I noticed that the cell's size did change. However, the width and height of the labels inside the cell remained the same. I'm not sure how to resolve this problem. Thank you in advance for your help!! A: set Constraint of your labels, like, for Constraint pic. your label pic. or you can also use UI property autoresizingMask like, yourLbl.autoresizingMask = [.flexibleWidth, .flexibleHeight]
{ "pile_set_name": "StackExchange" }
Q: Applying Button+Macro across all worksheets Forgive my ignorance (newby and little knowledge of VBA)... I have developed some macros that are attached to buttons, and working in one worksheet in a workbook. The macros perform various jobs on a calendar. There is one calendar for each of 10 bedrooms in the wing of a hospital. I now want to make identical worksheets with the same buttons and macros for each bedroom i.e. 10 worksheets. But try as I might I cant get the macros to work in the other worksheets. The macros are in the VBA code editor for the first worksheet (Bed1). I have copied the code into the "This Workbook" page within the VBA editor - but that had no effect, other than to stop them working at all. This is a typical macro: '============================================ Private Sub Prevw1_Click() '============================================ ' DAILY PATIENT TIMETABLE ' PRINT PREVIEW '============================================ ActiveSheet.Select ActiveSheet.AutoFilterMode = False Range("_Daily").Select ActiveSheet.PageSetup.PrintArea = "_Daily" ' Call page_SetUp ' ' Variations for page setup With ActiveSheet.PageSetup .LeftMargin = Application.InchesToPoints(1.5) .RightMargin = Application.InchesToPoints(0.9) .Zoom = 75 End With ActiveSheet.PrintPreview ActiveSheet.PageSetup.PrintArea = "" Range("H126, H126").Select End Sub Q. What have I done wrong that makes this only work in the Bed1 worksheet where it was developed first? Kind regards Russ A: Take the code out of the ThisWorkbook module and put it in a normal code module. In Design Mode, in the Excel window (not VBE), right-click the button and do Assign Macro, then choose the macro "Prevw1_Click". That should work. You'll have to assign the macro to each button, or you could simply copy/paste the button to the other sheets. If your button is an ActiveX Control, then I think you may need to have the subroutine for each button in the worksheet where the button resides. So, each worksheet may have an activeX command button called "CommandButton1", then each Worksheet code module should have a subroutine like: Sub CommandButton1_Click() Call ClickTheButton End Sub You will basically put all of this same code in each of the 10 worksheet code modules. Then, rename your routine in the ordinary code module, like: Private Sub ClickTheButton() '============================================ ' DAILY PATIENT TIMETABLE ' PRINT PREVIEW '============================================ ActiveSheet.Select ActiveSheet.AutoFilterMode = False Range("_Daily").Select ActiveSheet.PageSetup.PrintArea = "_Daily" ' Call page_SetUp ' ' Variations for page setup With ActiveSheet.PageSetup .LeftMargin = Application.InchesToPoints(1.5) .RightMargin = Application.InchesToPoints(0.9) .Zoom = 75 End With ActiveSheet.PrintPreview ActiveSheet.PageSetup.PrintArea = "" Range("H126, H126").Select End Sub The reason I would do this, instead of copying the existing macro to each of 10 worksheets is simple: If you ever need to modify your subroutine, you only need to modify it in one place. Likewise, if you add a new worksheet(s) you need only copy 3 lines of code instead of 20. It's just easier to maintain this way, since each sheet's button is calling the same code, each sheet's button should just have a simple sub that calls the "main" procedure.
{ "pile_set_name": "StackExchange" }
Q: Multiple ColladaLoader loads fail. Is it thread safe? I am trying to load multiple pieces simultaneously. Either only one piece shows up, correctly, or both pieces show up, with one correct and one incorrect. Here's my code: var loader = THREE.ColladaLoader(); loader.load('model.dae', function colladaReady(result) { var piece = result.scene.children[0]; piece.position.set(-100, 0, 0); scene.add(piece); renderer.render(scene, camera); }); loader.load('model2.dae', function colladaReady2(result2) { var piece2 = result2.scene.children[0]; piece2.position.set(100, 0, 0); scene.add(piece2); renderer.render(scene, camera); }); A: The reason is because ColladaLoader is not thread-safe, so multiple load() calls cannot be made on the same object. Simply create a new instance of ColladaLoader like so and all should work var loader = THREE.ColladaLoader(); loader.load('model.dae', function colladaReady(result) { var piece = result.scene.children[0]; piece.position.set(-100, 0, 0); scene.add(piece); renderer.render(scene, camera); }); /*** Line added here! ***/ var loader2 = THREE.ColladaLoader(); loader.load('model2.dae', function colladaReady2(result2) { var piece2 = result2.scene.children[0]; piece2.position.set(100, 0, 0); scene.add(piece2); renderer.render(scene, camera); });
{ "pile_set_name": "StackExchange" }
Q: Chrome extension : jQuery.js conflicts in background file conflics with plugins in websites I am including jQuery in background_page like this, <script type="text/javascript" src="libs/jquery.js"></script> Here's the problem: In websites, where jQuery plugins are used (with jQuery.extend method), they do not work when my extension is installed. I guess this is because I had my jQuery.js over 'their' jQuery.js' file and all .extend do not work. So, I thought of adding jQuery.js only when its not avaialable. So, I tried adding jQuery like this, <script type="text/javascript"> if (typeof jQuery == 'undefined') { var script = document.createElement('script'); script.type = "text/javascript"; script.src = "libs/jquery.js"; document.getElementsByTagName('head')[0].appendChild(script); } </script> But no luck. Can someone suggest me a good way to add jQuery.js file in background page. A: Found an answer later, Doing jQuery.nocConflict jQ = jQuery.noConflict and replacing $ with jQ everywhere, solved the problem. Conclusion: content_scripts can also interfere with webpage javascripts.
{ "pile_set_name": "StackExchange" }
Q: In The Dark Knight, what happened to all the bank robbers? The opening scene of The Dark Knight shows a bank robbery being perpetrated by a gang hired by the Joker. It transpires that they are all supposed to kill each other, with presumably each of them thinking he will be the only one left to split the takings with the Joker, but as they are all wearing clown masks you only find out towards the end of the scene that one of them is The Joker himself. The scene starts with five robbers; two on the roof, and three in the van. One is killed by another after he bypasses the emergency phone call. One is killed after he opens the safe. One is shot by the bank manager after being tricked into believing the manager has run out of ammo in his shotgun, but is shown alive after that as he says to the other "Who taught you how to count?" One (this same one) is killed by the bus when it hits him, and the Joker then kills the bus driver. We don't see what happened to the other one. Are there any deleted scenes or transcripts that tell us what happened to him? A: For the record, the official screenplay identifies the two men on the roof as Dopey and Happy, the three men in the car as Grumpy, Chuckles and Bozo. You've confused Chuckles (whose gunshot was fatal) with Grumpy (whose gunshot was 'superficial') GRUMPY: He’s got three left? [Bozo raises two fingers. Grumpy squeezes off a shot. The Bank Manager fires. Fires again. Grumpy looks at Bozo, who nods. Grumpy jumps up. The Bank Manager fires. Grumpy grunts as buckshot clips his shoulder. Falls. The Bank Manager moves in for the kill, fumbling for new shells. Bozo stands – shoots him.] [Bozo picks up the shotgun. Grumpy checks his wound – it’s superficial. He struggles to his feet.] GRUMPY: Where’d you learn to count?! He was killed by the bus coming in through the front of the bank GRUMPY: Bus driver? What bus – [Bozo steps backwards. Smash. Hostages scream as the tail end of a yellow school bus rockets through the front of the bank, slamming Grumpy into the teller’s window.] For the avoidance of doubt. Happy shoots Dopey on the roof Grumpy shoots Happy in the vault Chuckles is killed by the Bank Manager Grumpy is killed by the bus Bozo presumably kills the unnamed bus driver Bozo survives
{ "pile_set_name": "StackExchange" }
Q: Facebook: How to get fanpage by domain search? I would love to get the Facebook fanpage for a domain with the Facebook Graph search. I tried the following, but only got a random id but not the pages id? https://graph.facebook.com/?domain=stackoverflow.com Question: How to get the Facebook Pages Name or ID when i only have the url to query for? Does the id from the above graph search help? A: You can do it with this the Graph API search: https://graph.facebook.com/search?type=page&q=stackoverflow.com
{ "pile_set_name": "StackExchange" }
Q: Disable super + s in ubuntu 13.04 I tried this thread but it didn't work. How can I disable super + s which previews workspaces A: You can use CompizConfig to do this. (sudo apt-get install compizconfig-settings-manager in a terminal to install if it isn't on your computer already) To open, type "CompizConfig" into your Dash, or ccsm in the terminal. Once it's open, scroll to the "Expo" option, which can be found in the Desktop section (I assume this is in the default plugins but cannot remember for certain) Click on Expo, and then on the Bindings tab, look at the top option (Expo key). Click on the right, where it says "<Super>s". Then either uncheck the "Enabled" box to disable it entirely, or click "Grab key combination" and enter a different combo to change it to something else. Click OK to accept your settings and you should be good to go. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Audio file does not persist in Cordova with LocalFileSystem.PERSISTENT I have been trying to store Audio file in persistent storage for two days without success. So far I am able to create an audio file which records audio from Microphone (The app has the permission) using the code attached below. The audio file is getting generated & stored successfully, I can play it. But the real problem is when I close the app and come back and try to play the file it shows error. "{"message": "Cannot use audio file from resource '/myrecording.wav'", "code":1}" The file is not persistent across app sessions even though I used LocalFileSystem.PERSISTENT. I am not sure whether the problem is with my Media/Audio code or File storage code. Please find the code attached below: Below function records the audio from the microphone. function _recordAudio() { var deferred = $q.defer(); var src = "myrecording.wav"; alert("SRC:" + src); window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { fileSystem.root.getFile(src, { create: true, exclusive: false }, function (fileEntry) { alert("File " + src + " created at " + fileEntry.fullPath); var mediaRec = new Media(fileEntry.fullPath, function () { alert("Success"); }, function (error) { alert("error:" + JSON.stringify(error)); }); // Record audio mediaRec.startRecord(); // Stop recording after 10 sec var recTime = 0; var recInterval = setInterval(function () { recTime = recTime + 1; if (recTime >= 5) { clearInterval(recInterval); mediaRec.stopRecord(); deferred.resolve(fileEntry.fullPath); } }, 1000); }, function (error) { alert("getFile error:" + JSON.stringify(error)); deferred.reject(); }); //of getFile }, function (error) { alert("requestFileSystem error:" + JSON.stringify(error)); deferred.reject(); }); //of requestFileSystem return deferred.promise; } Below function plays the audio. function _play2() { var src = "myrecording.wav"; window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { fileSystem.root.getFile(src, null, function (fileEntry) { alert("File " + src + " created at " + fileEntry.fullPath); var mediaRec = new Media(fileEntry.fullPath, function () { alert("Success play2"); }, function (error) { //Getting error after closing and opening the app //Error message = {"message": "Cannot use audio file from resource '/myrecording.wav'","code":1} alert("error play2:" + JSON.stringify(error)); }); mediaRec.play(); }); }); } A: I solved this problem by passing cdvfile: path to the Media plugin in PlayAudio function code and copying the file from Temp storage to persistent storage. I had to use localURL of the file. This part solved my problem: fileEntry.file(function (file) { _playNow(file.localURL); } For full functions refer code snippets below: recordAudio: function (projectNo, ItemNo) { try { var deferred = $q.defer(); var recordingTime = 0; _audioLoader = $("#audioLoader"); _audioLoader.show(); UtilityService.showPopup('audio'); _isRecording = true; _recordFileName = "Audio_" + projectNo + "_" + ItemNo + ".wav"; _mediaRecord = new Media(_recordFileName); //Record audio _mediaRecord.startRecord(); var recordingInterval = setInterval(function () { recordingTime = recordingTime + 1; $('#audioPosition').text(_secondsToHms(recordingTime)); if (!_isRecording) { clearInterval(recordingInterval); _mediaRecord.stopRecord(); _mediaRecord.release(); deferred.resolve(); } }, 1000); //document.getElementById('audioPosition').innerHTML = '0 sec'; $('#audioPosition').text('0 sec'); return deferred.promise; } catch (ex) { alert('WMMCPA|recordAudio:- ' + ex.message); } }, Get file path from the persistent storage and send it to the play method. //To play recorded audio for specific project item playAudio: function (projectNo, ItemNo) { try { _recordFileName = "Audio_" + projectNo + "_" + ItemNo + ".wav"; var newFileUri = cordova.file.dataDirectory + _recordFileName; window.resolveLocalFileSystemURL(newFileUri, function (fileEntry) { fileEntry.file(function (file) { _playNow(file.localURL); }, function (error) { alert("WMMCPA|playAudio.file:-" + JSON.stringify(error)); }); }, function (error) { alert("WMMCPA|playAudio.resolveLocalFileSystemURL:-" + JSON.stringify(error)); }); } catch (ex) { alert("WMMCPA|playAudio:-" + ex.message); } } function _playNow(src) { try { var mediaTimer = null; _audioLoader = $("#audioLoader"); _audioLoader.show(); UtilityService.showPopup('audio'); //Create Media object from src _mediaRecord = new Media(src); //Play audio _mediaRecord.play(); } catch (ex) { alert('WMMCPA|_playNow.mediaTimer:- ' + ex.message); } }, 1000); } catch (ex) { alert('WMMCPA|_playNow:- ' + ex.message);
{ "pile_set_name": "StackExchange" }
Q: Need a bootable OS X installer iso I removed the OS X partition off my HDD and installed Ubuntu. Now I want OS X back but I can't install it considering I have no access to Mac OS X. I need either an OS X Snow Leopard or OS X Lion .iso so I can put it on an installer USB. A: Since OS X Lion was around $30 USD on release you definitely, definitely wouldn't want to torrent the .iso. I would image you could find the torrent fairly easily if you were to look. But you wouldn't do that, would you, because that would be immoral and possibly illegal in your area.
{ "pile_set_name": "StackExchange" }
Q: Code is HttpClient or servlet API to parse Cookie header Is there any existing code in Apache HttpClient or in the servlet API to parse Cookie header and obtain from a string that contains "name1=value1; name2=value2; ..." a list of Cookie? Writing code to parse this doesn't seem too hard, but if there is already some existing code, I'd like to use it. A: If you call getCookies() on the HttpServletRequest object, it will return an array of Cookie objects. If you need to frequently look up cookies by name, then it may be easier to put them in to a Map so it's easy to look them up (rather than iterate over the Array each time). Something like this: public static Map<String,Cookie> getCookieMap(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); HashMap<String,Cookie> cookieMap = new HashMap<String,Cookie>(); if (cookies != null) { for (Cookie cookie : cookies) { cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } If you're using HttpClient and not servlets, you can get the Cookie array using: client.getState().getCookies() where client is your HttpClient object.
{ "pile_set_name": "StackExchange" }
Q: Problem with vertical alignment in tabular environment I'm having a few issues with vertically aligning table elements. There seems to be too much space either above or below the text or image. Is this to do with the fbox environment? I want both the image and text to be centered vertically in each table cell. \documentclass[a4paper,11pt]{article} \usepackage[english]{babel} \usepackage{graphicx} \usepackage[top=1in,bottom=1in,left=1in,right=1in]{geometry} \usepackage{array} \newcommand{\mybox}[1]{ \begin{center} \fbox{ \parbox{0.8\linewidth}{ \begin{center} \begin{tabular}{ c m{4.5in} } \includegraphics[height=0.3in]{./myfig} & {#1} \end{tabular} \end{center} } } \end{center} } \begin{document} \mybox{hello} \mybox{hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello} \end{document} Edit: Following Gonzalo Medina's suggestion, I get: and there is no difference between center and centering. A: You can use a m{length} column type for the first column: \documentclass[a4paper,11pt]{article} \usepackage[english]{babel} \usepackage{graphicx} \usepackage[top=1in,bottom=1in,left=1in,right=1in]{geometry} \usepackage{array} \newcommand{\mybox}[1]{ \begin{center} \fbox{% \parbox{0.8\linewidth}{% \begin{center} \begin{tabular}{m{0.3in}m{4.5in} } \includegraphics[height=0.3in]{example-image-a} & #1 \end{tabular} \end{center} } } \end{center}% } \begin{document} \mybox{hello} \mybox{hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello} \end{document} I wasn't sure if some of the blank spaces at end of lines were intentional or not; I commented them out. Also take into account that center adds some vertical spacing so perhaps you could consider using \centering instead. As an alternative, I'd like to propose the tcolorbox package to easily produce your box; you can even customize it even further: \documentclass[a4paper,11pt]{article} \usepackage[english]{babel} \usepackage{graphicx} \usepackage[top=1in,bottom=1in,left=1in,right=1in]{geometry} \usepackage[many]{tcolorbox} \newcommand\mybox[1]{% \begin{tcolorbox}[ sidebyside, lefthand width=.3in, colback=white, outer arc=0pt, arc=0pt. colframe=black, boxrule=0.4pt, segmentation engine=empty ] \includegraphics[width=.3in]{example-image-a} \tcblower #1 \end{tcolorbox}% } \begin{document} \mybox{hello} \mybox{hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello} \end{document} A: You can use valign macro from the adjustbox package in \includegraphics[valign=c,height=0.3in]{example-image-a} Code: \documentclass[a4paper,11pt]{article} \usepackage[english]{babel} \usepackage[export]{adjustbox} %% export is needed \usepackage[top=1in,bottom=1in,left=1in,right=1in]{geometry} \usepackage{array} \newcommand{\mybox}[1]{% \begin{center} \fbox{% \parbox{0.8\linewidth}{% \begin{center} \begin{tabular}{ c m{0.75\linewidth} } \includegraphics[valign=c,height=0.3in]{example-image-a} & #1 \end{tabular} \end{center} }% }% \end{center} } \begin{document} \mybox{hello} \mybox{hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Android get all assets folder images How to retrive all images from folder named 'imagesf' in assets folder and using it as int[] instead of int[] mImages = new int[]{ R.drawable.pic1 ,R.drawable.pic2 ,R.drawable.pic3 ,R.drawable.pic4 }; To use it in a viewpager A: Use below code to get all image name from 'imagesf' in assets folder private List<String> getImage(Context context) throws IOException { AssetManager assetManager = context.getAssets(); String[] files = assetManager.list("imagesf"); List<String> it = Arrays.asList(files); return it; } and get one by one image as Bitmap by using below code iterating in loop: private Bitmap getBitmapFromAsset(String strName) { AssetManager assetManager = getAssets(); InputStream istr = null; try { istr = assetManager.open(strName); } catch (IOException e) { e.printStackTrace(); } Bitmap bitmap = BitmapFactory.decodeStream(istr); return bitmap; }
{ "pile_set_name": "StackExchange" }
Q: Scroll for checkboxlist doesn't work I have this CheckBoxList : <asp:CheckBoxList class="checkBoxList" ID="CheckBoxList1" runat="server" TextAlign="Right" float="right" > and this css: .checkBoxList { direction:rtl; float:right; text-align:right; width:100%; height:200px%; overflow-y:scroll } But my CheckBoxList doesn't have scroll, why? A: alternate method of this is wrap your checkboxlist in to div and make div scrollable here is the code <div class="checkBoxList"> <asp:CheckBoxList runat="surver" ID="CheckBoxList1"> // Your Code </asp:CheckBoxList> </div> and css is .checkBoxList { direction:rtl; float:right; text-align:right; width:100%; height:200px; overflow-y:scroll }
{ "pile_set_name": "StackExchange" }
Q: Combining Nodejs Net socket and Socket IO I have a windows application (Built on C# as windows service) that sends data to NodeJs Net Socket, So since Socket.IO helps making a Web Application a live one , without the need of reload. How can i allow Socket.IO stream the received data from NodeJs Net Socket to the Web Application , in the exact moment the Net Socket receives data from C#? So in the code that receives the socket data from C#: var net = require('net'); net.createServer(function (socket) { socket.on('data', function (data) { broadcast(socket.name + "> \n" + data + " \n", socket); socket.end("<EOF>"); //send data to web interface , does it work that way? //SomeFooToSendDataToWebApp(Data) }); }); Further more for the Socket.IO i have those lines , which i cant really figure out how to deal with them: //Should it listen to net socket or web socket? server.listen(8080); // Loading socket.io var io = require('socket.io').listen(server); // It works but only for one request io.sockets.on('connection', function (socket2) { socket2.emit('message' , 'Message Text'); }); P.S: I am new to nodejs & socket.io , so if its possible as well to explain their behavior. Edit 1 : My Front End Javascript to check it if it has any problems: //for now it listens to http port , which Socket.IO listens to var socket = io.connect('http://localhost:8080'); var myElement = document.getElementById("news"); socket.on('message', function(message) { document.getElementById("news").innerHTML = message; }) Edit 2 : Did follow jfriend00's answer as it seems my previous code tries were trying to send messages to an unknown socket, i only added this since i needed it to be sent to all the connected clients , so only one line fixed it ! socket.on('data', function (data) { broadcast(socket.name + "> \n" + data + " \n", socket); socket.end("<EOF>"); //send data to web interface , does it work that way? //The Added code here: io.emit('message',data + " more string"); }); A: It's a bit hard to tell exactly what you're asking. If you have some data you want to send to all connected socket.io clients (no matter where the data came from), then you can do that with: io.emit("someMessage", dataToSend); If you want to send to only one specific connected client, then you have to somehow get the socket object for that specific client and then do: socket.emit("someMessage", dataToSend); How you get the specific socket object for the desired connected client depends entirely upon how your app works and how you know which client it is. Every socket connection on the server has a socket.id associated with it. In some cases, server code uses that id to keep track of a given client (such as putting the id in the session or saving it in some other server-side data). If you have the id for a socket, you can get to the socket with the .to() method such as: io.to(someId).emit("someMessage", dataToSend); Your question asked about how you send data received from some C# service over a normal TCP socket. As far as sending it to a socket client, it does not matter at all where the data came from or how you received it. Once you have the data in some Javascript variable, it's all the same from there whether it came from a file, from an http request, from an incoming TCP connection in your C# service, etc... It's just data you want to send.
{ "pile_set_name": "StackExchange" }
Q: Testing GestureDetector on Image widget I have made a simple test case app where you click a widget using GestureDetector which triggers an update using setState to the tapCount variable. The app is working in the emulator with the text updating correctly as shown above, but as soon as I try a Flutter widget test, the widget test fails as the text does not update correctly in the test environment. Reproducible example: import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { MyApp(); @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { int tapCount = 0; Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child: Column( children: <Widget>[ MyImage( onTap: () { setState(() { tapCount += 1; }); }, imagePath: 'assets/my-image.jpg', ), Text(tapCount.toString()) ], ), ), ), ); } } class MyImage extends StatelessWidget { final Function() onTap; final String imagePath; const MyImage({ Key key, @required this.onTap, @required this.imagePath, }) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: () { this.onTap(); }, child: Image.asset( imagePath, height: 100.0, ), ); } } In the pubspec, I downloaded a random image and verified the image successfully displays in the emulator. assets: - assets/my-image.jpg My test is the same as the sample with the addition of await tester.pumpAndSettle(); and tapping the image: void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); await tester.pumpAndSettle(); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the image and trigger a frame. await tester.tap(find.byType(MyImage)); await tester.pump(); await tester.pumpAndSettle(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); // this test fails expect(find.text('1'), findsOneWidget); // this test fails }); } When I run the test I get this error ══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════ The following TestFailure object was thrown running a test: Expected: no matching nodes in the widget tree Actual: ?:<exactly one widget with text "0" (ignoring offstage widgets): Text("0")> Which: means one was found but none were expected When the exception was thrown, this was the stack: #4 main.<anonymous closure> (file:///Projects/untitled/test/widget_test.dart:27:5) <asynchronous suspension> #5 testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:82:23) #6 TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:566:19) <asynchronous suspension> #9 TestWidgetsFlutterBinding._runTest (package:flutter_test/src/binding.dart:550:14) #10 AutomatedTestWidgetsFlutterBinding.runTest.<anonymous closure> (package:flutter_test/src/binding.dart:893:24) #16 AutomatedTestWidgetsFlutterBinding.runTest (package:flutter_test/src/binding.dart:890:15) #17 testWidgets.<anonymous closure> (package:flutter_test/src/widget_tester.dart:81:22) #18 Declarer.test.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:168:27) <asynchronous suspension> #19 Invoker.waitForOutstandingCallbacks.<anonymous closure> (package:test_api/src/backend/invoker.dart:249:15) <asynchronous suspension> #24 Invoker.waitForOutstandingCallbacks (package:test_api/src/backend/invoker.dart:246:5) #25 Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:166:33) #30 Declarer.test.<anonymous closure> (package:test_api/src/backend/declarer.dart:165:13) <asynchronous suspension> #31 Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:399:25) <asynchronous suspension> #45 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19) #46 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5) #47 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12) (elided 28 frames from class _FakeAsync, package dart:async, and package stack_trace) This was caught by the test expectation on the following line: file:///Projects/untitled/test/widget_test.dart line 27 The test description was: Counter increments smoke test ════════════════════════════════════════════════════════════════════════════════════════════════════ Test failed. See exception logs above. The test description was: Counter increments smoke test If I try the same test, but with the Image inside MyImage replaced with another widget (e.g. another Text widget) inside main.dart, the test passes: class MyImage extends StatelessWidget { final Function() onTap; final String imagePath; const MyImage({ Key key, @required this.onTap, @required this.imagePath, }) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: () { this.onTap(); }, child: Text( // replaced Image with Text and test passes! imagePath, ), ); } } This makes me think the issue is due to using the Image, but I can't figure out why. Code is also uploaded on GitHub if you want to try the test. A: Here is my take on why it's not working with an image. The flutter tests run in a FakeAsync zone and when you need to run real async code like loading an asset through an assetBundle the asset is not getting loaded and the image widget's size stays as zero and because of this the hit testing fails. If you set height and width of the image before hand the test passes.
{ "pile_set_name": "StackExchange" }
Q: Split a dataset into a list of dataframes with equal number of columns I have a data set with 36 columns and single observation. I want to split it into a list with each dataframe having 3 columns and then rbind them into a single data frame. I have been using the following code: m=12 nc<-ncol(df) df1<-lapply(split(as.list(df), cut(1:nc, m, labels = FALSE)), as.data.frame) df1<-do.call("rbind",df1) This code is working. But the problem comes when I try to run this code in shiny app. Can someone suggest a replacement for above code A: We can split the one row dataframe by generating a specific sequence do.call("rbind", split(c(t(df)), rep(seq(1, ncol(df)/3), each = 3))) where rep(seq(1, ncol(df)/3), each = 3) would generate [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 10 10 10 11 11 11 12 12 12
{ "pile_set_name": "StackExchange" }
Q: php / mysql / javascript mindate and maxdate In .net, there are the static properties DateTime.MinDate, and DateTime.MaxDate that conveniently return the minimum and maximum valid dates for a DateTime object. I'm dabbling in web programming right now, using php + mysql + javascript. There doesn't seem to be the same convenient min/max date values in that programming environment? For example, the max value of a date object in mysql is 9999-12-31, but the php function strtotime() doesn't like that value. I would like a cross-language minimum date (to be used to mean 'not set yet' for example), and a cross-language maximum date (to be used to mean 'good forever'). That means there could be those min dates and max dates stored in a database, which php would retrieve (and it would have to differentiate between 'normal' dates and min/max date), and eventually they would trickle down to some javascript (which, again would have to differentiate between 'normal' dates and min/max date). So, which date value do you use for min/max dates when working in php + mysql + javascript? And how do you store these constants -- it'd be nice to define them only in one place and have them be available in each of php + mysql + javascript... Thanks A: For the JavaScript side, the range is a lot bigger: The date is measured in milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. The Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC. So you could do this in your JavaScript: var min_date = new Date(-100000000*86400000); var max_date = new Date( 100000000*86400000); A: I'll just answer the PHP portion of the question. According to the PHP date() documentation: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer) PHP uses 32 bit integer values to represent date/time — that means you can use the PHP_INT_MAX constant to derive the integer values associated with the min/max dates: echo date('m/d/Y G:i:s', PHP_INT_MAX + 1); // minimum valid date echo date('m/d/Y G:i:s', PHP_INT_MAX); // maximum valid date OUTPUT: 12/13/1901 15:45:52 01/18/2038 22:14:07 Not sure why that's off by 2 seconds on the min date they quoted, but you get the general idea.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to go up a certain number of directories depending on the current location? I'm trying to implement Jekyll to my site and I'm having a hard time setting paths for my images since I don't know how to allot for the different paths since the permalink to each post is one folder deeper than the homepage. How can I make it so that my images both show in the homepage and in their individual pages? A: Use absolute paths for your images: <img src="/image_folder/image.jpg" /> This way it doesn't matter where in the hierarchy the HTML file is as the image always is permanent in relation to the root folder.
{ "pile_set_name": "StackExchange" }
Q: How can I get any expression in C# as string? In many cases one needs the name of an expression, parameter, statement, etc. For example: public abstract void Log(string methodName, string parameterName, string message); public void FooMethod(string value) { if (value == null) { this.Log("FooMethod", "value", "The value must be whatever..."); throw new ArgumentNullException("value"); } if (value.Length < 5) { this.Log("FooMethod", "value.Length", "The value length must be whatever..."); throw new ArgumentException("value"); } } Is there any way of getting these string literals automatically like for example with a keyword that can be used like typeof(string)? Or is there a simple and performant approach based on reflection? I'm not looking for a way to check and log this parameter (which is actually only an example). I'm looking for a method to get part of the code as string. The following would be more accurate, could be checked by the compiler and would also be considered when refactoring the code: public void FooMethod(string value) { if (value == null) { this.Log(literal(this.FooMethod), literal(value), "The parameter '" + literal(value) + "' must be whatever..."); throw new ArgumentNullException(literal(value)); } if (value.Length < 5) { this.Log(literal(this.FooMethod), literal(value.Length), "The value length must be whatever..."); throw new ArgumentException(literal(value)); } } A: You can create static methods like this for all possible types. Below is for method name. public static string GetString(Action obj) { return obj.Method.Name; } public static string GetString(Delegate obj ) { return obj.Method.Name; }
{ "pile_set_name": "StackExchange" }
Q: N1ql -> IN operator does not work with other conditions The following query works just fine when only IN operator is used SELECT META().id FROM bucket_name WHERE description IN ['Item1','Item2'] But when I fire this query it gives me a blank result SELECT META().id FROM bucket_name WHERE id = 123 AND description IN ['Item1','Item2'] Am I doing something wrong or somebody else has faced the same problem? A: I think you have to take your "IN" condition into parenthesis to make it work: SELECT META().id FROM bucket_name WHERE id = 123 AND (description IN ['Item1','Item2']) It has to do with the precedence level of the operators evaluation by N1QL processor If you run it with EXPLAIN keyword it will show how it links conditions against each other. e.g. explain SELECT META().id FROM bucket_name WHERE id = 123 AND (description IN ['Item1','Item2']) vs explain SELECT META().id FROM bucket_name WHERE id = 123 AND description IN ['Item1','Item2'] A: With the latest N1QL developer preview (http://docs.couchbase.com/developer/n1ql-dp3/n1ql-intro.html) the IN clause does not need to be parenthesized, so this should work: SELECT META(b).id FROM bucket_name b WHERE id = 123 AND description IN ['Item1','Item2'] You need to pass the bucket name (or alias) to META() I think because N1QL now supports queries on multiple buckets.
{ "pile_set_name": "StackExchange" }
Q: If Wolverine broke a bone which protruded his skin, what would happen if he started to heal before it was set and splinted? In X-Men Origins: Wolverine we see that Wolverine’s bones can be broken in the fight between him and Sabretooth. So if he was to suffer an injury (let's say a very high fall) and broke his leg and the bone snapped and came through the skin (an open break), what would be the effect of his healing powers if the bone wasn't reset and splinted? A: Wolverine can regenerate fully. That means while he has even a single cell alive, he can regenerate from it. This already happened once. A single cell will re-create his skeleton, muscles, and skin. That means a single cell knows how Wolverine is, and every cell retains his "blueprint" so to speak. In your case, I'm guessing that would also mean his body would pull itself together. The bone would adjust to the right place, and the muscle and skin heal shut. But this raise worm-split-in-half questions. I'm discussing Wolverine at the peak of his mutant powers. It's usual for his powers to vary greatly from author to author. Hulk split Wolverine in half once, and threw his legs hundreds of miles away. In that universe, Wolverine had to crawl over to them to fuse and heal his lower body.
{ "pile_set_name": "StackExchange" }
Q: Does a "body-only" DSLR need a lens added before use? What does it mean for a DSLR camera to be described as "body-only"? I found one advertised for sale that was described as such, and I don't know if I'll need to add a lens. I assume that it means either that the camera is used without attaching an external lens, or that the camera is sold without a lens but and will need to have one added. If it needs no additional lens, like a regular digital camera, what is its focal length likely to be? A: You need a lens. It's probably possible to persuade the camera to expose the sensor without a lens on it, but nothing would be in any sort of focus whatsoever. As an aside, if you're asking this kind of basic question about cameras, I'd question whether a full-frame SLR like the D750 is the right choice. You'll end up spending a lot more on your equipment (potentially 3x as much) for a relatively small change in the abilities of the system. A: Yes, it's possible to capture some kind of images without a lens, but it's not useful. It's like a bike without tires. It's possible to use it to transport yourself some distance, but it's not anything that you would call riding a bike. A: Yes, you do need a lens. But for starting out, a simple, cheap one will do - and there is a healthy market for used lenses. The best choices would be either a 50mm f/1.8 prime lens, often called "nifty fifty" because for technical reasons it is a very simple lens design that can be made very cheaply while still providing great quality. As a prime lens it has no zoom, but makes up for it with its large aperture that shines in low light conditions. It can be found used for under $100. an 18-55mm kit lens - "kit lens" means it's one that is usually sold with a body, which means it's produced in very high numbers and gives good value for its (low) price. Unfortunately, full frame cameras like the D570 need FX lenses, and there aren't any really cheap FX kit lenses.
{ "pile_set_name": "StackExchange" }
Q: Angular4 Exclude Property from dirty check I've implemented a custom form control via template driven forms which wraps an input in html and adds a label, etc. It talks to the form just fine with the 2way data binding on the ngModel. The problem is, the form is automatically marked as dirty when it is initialized. Is there a way to prevent this from happening so I can use those properties on the form and they will be accurate? Custom selector (This works fine other than automatically being marked dirty): <form class="custom-wrapper" #searchForm="ngForm"> {{searchForm.dirty}} {{test}} <custom-input name="testing" id="test" label="Hello" [(ngModel)]="test"></custom-input> <pre>{{ searchForm.value | json }}</pre> </form> Custom input template: <div class="custom-wrapper col-xs-12"> <div class="row input-row"> <div class="col-xs-3 col-md-4 no-padding" *ngIf="!NoLabel"> <label [innerText]="label" class="inputLabel"></label> </div> <div class="col-xs-9 col-md-8 no-padding"> <input pInput name="cust-input" [(ngModel)]="value" /> </div> </div> </div> Custom Input Component: import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms"; import { Component, Input, forwardRef } from "@angular/core"; @Component({ selector: "custom-input", template: require("./custom-input.component.html"), providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => QdxInputComponent), multi: true } ] }) export class CustomInputComponent implements ControlValueAccessor { @Input("value") _value = ""; get value() { return this._value; } set value(val: string) { this._value = val; this.propagateChange(val); } @Input() noLabel: boolean = false; @Input() label: string = "Label required"; propagateChange = (_: any) => {}; writeValue(value) { if (value !== undefined) { this.value = value; } } registerOnChange(fn) { this.propagateChange = fn; } registerOnTouched(fn) {} } A: I solved that just with an attribute directive: import { Directive } from '@angular/core'; import { NgControl } from '@angular/forms'; @Directive({ selector: '[ignoreDirty]' }) export class IgnoreDirtyDirective { constructor(private control: NgControl) { this.control.valueChanges.subscribe(v => { if (this.control.dirty) { this.control.control.markAsPristine(); } }); } } And you can use it in your code in a way like this: <input ignoreDirty type="text" name="my-name" [(ngModel)]="myData"> A: You propagate your change that is why it is marked dirty. Just adapt your writeValue function to not propagate the change because logically it should not create a change: export class CustomInputComponent implements ControlValueAccessor { @Input("value") _value = ""; get value() { return this._value; } set value(val: string) { this._value = val; this.propagateChange(val); } @Input() noLabel: boolean = false; @Input() label: string = "Label required"; propagateChange = (_: any) => {}; writeValue(value) { if (value !== undefined) { this._value = value; } } registerOnChange(fn) { this.propagateChange = fn; } registerOnTouched(fn) {} } Shortly: use this._value instead of this.value in your writeValue
{ "pile_set_name": "StackExchange" }
Q: How do I convince my colleagues not to implement IDisposable on everything? I work on a project where there is a huge number of objects being instanced by a few classes that stay in memory for the lifetime of the application. There are a lot of memory leaks being caused with OutOfMemoryExceptions being thrown every now and again. It seems like after the instantiated objects ago out of scope, they are not being garbage collected. I have isolated the problem to being mostly about the event handlers that are attached to the long-living object that are never detached, thus causing the long-living object to still have a reference to the out of scope objects, which then will never be garbage collected. The solution that has been proposed by my colleagues is as follows: Implement IDisposable on all classes, across the board and in the Dispose method, null all the references in your objects and detach from all event that you attached to. I believe this is a really really bad idea. Firstly because it's 'overkill' since the problem can be mostly solved by fixing a few problem areas and secondly because the purpose of IDisposable is to release any unmanaged resources your objects control, not because you don't trust the garbage collector. So far my arguments have fallen on deaf ears. How can I convince them that this is futile? A: By coincidence I just posted this comment elsewhere: An reference to an object being incorrectly retained is still a resource leak. This is why GC programs can still have leaks, usually due to the Observer pattern - the observer is on a list instead the observable and never gets taken off it. Ultimately, a remove is needed for every add, just as a delete is needed for every new. Exactly the same programming error, causing exactly the same problem. A "resource" is a really just a pair of functions that have to be called an equal number of times with corresponding arguments, and a "resource leak" is what happens when you fail to do that. And you say: the purpose of IDisposable is to release any Unmanaged resources your objects controls Now, the += and -= operators on an event are effectively a pair of functions that you have to call an equal number of times with corresponding arguments (the event/handler pair being the corresponding arguments). Therefore they constitute a resource. And as they are not dealt with (or "managed") by the GC for you, it can be helpful to think of them as just another kind of unmanaged resource. As Jon Skeet points out in the comments, unmanaged usually has a specific meaning, but in the context of IDisposable I think it's helpful to broaden it to include anything resource-like that has to be "torn down" after it has been "built up". So event detaching is a very good candidate for handling with IDisposable. Of course, you need to call Dispose somewhere, and you don't need to implement it on every single object (just those with event relationships that need management). Also, bear in mind that if a pair of objects are connected by an event, and you "cast them adrift", by losing all references to them in all other objects, they don't keep each other alive. GC doesn't use reference counting. Once an object (or island of objects) is unreachable, it is up for being collected. You only have to worry about objects enlisted as event handlers with events on objects that live a long time. e.g. a static event such as AppDomain.UnhandledException, or events on your application's main window. A: Point them at Joe Duffy's post about IDisposable/finalizers - combined wisdom of many smart people. I'm currently finding it hard to see a statement there saying "don't implement it when you don't need it" - but aside from anything else, showing them the complexity involved in implementing it properly may well help to dissuade them from it... Unfortunately, if people won't listen, they won't listen. Try to get them to explain why they think they need IDisposable. Do they think the garbage collector doesn't work? Show them that it works. If you can convince them that it's doing no good (for most types) then surely they'll stop adding work for themselves... As Brian says, implementing IDisposable isn't going to help with the event problem on its own - it needs to actually be called by something. Finalizers aren't going to help you in this case either. They really need to explicitly do something to remove the event handlers. A: Just implementing Dispose() across all types is not going to solve your problem. Remember that Dispose() is not automatically called and it has nothing to do with reclaiming managed memory. In order to have any effect of your Dispose() methods, you need to call it in all relevant place - either explicitly or via using. In other words just implementing IDisposable all around will not magically solve your problems cause the Dispose() methods will not be called unless you also change the usage of every type in your code. However, I would not recommend implementing IDisposable on all your types, simply because it makes no sense. The interface is used to indicate that the type in question uses some resource, which isn't handled by the garbage collector. Event references are handled by the garbage collector. You just need to unsubscribe if your publisher lives significantly longer than your subscribers. Once the publisher dies the subscribers will die as well.
{ "pile_set_name": "StackExchange" }
Q: NSTextCheckingResult for phone numbers Can someone tell me why this evaluates every time to true?! The input is: jkhkjhkj. It doesn't matter what I type into the phone field. It's every time true... NSRange range = NSMakeRange (0, [phone length]); NSTextCheckingResult *match = [NSTextCheckingResult phoneNumberCheckingResultWithRange:range phoneNumber:phone]; if ([match resultType] == NSTextCheckingTypePhoneNumber) { return YES; } else { return NO; } Here is the value of match: (NSTextCheckingResult *) $4 = 0x0ab3ba30 <NSPhoneNumberCheckingResult: 0xab3ba30>{0, 8}{jkhkjhkj} I was using RegEx and NSPredicate but I've read that since iOS4 it's recommended to use NSTextCheckingResult but I can't find any good tutorials or examples on this. Thanks in advance! A: You are using the class incorrectly. NSTextCheckingResult is the result of a text checking that is done by NSDataDetector or NSRegularExpression. Use NSDataDetector instead: NSError *error = NULL; NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error]; NSRange inputRange = NSMakeRange(0, [phone length]); NSArray *matches = [detector matchesInString:phone options:0 range:inputRange]; // no match at all if ([matches count] == 0) { return NO; } // found match but we need to check if it matched the whole string NSTextCheckingResult *result = (NSTextCheckingResult *)[matches objectAtIndex:0]; if ([result resultType] == NSTextCheckingTypePhoneNumber && result.range.location == inputRange.location && result.range.length == inputRange.length) { // it matched the whole string return YES; } else { // it only matched partial string return NO; }
{ "pile_set_name": "StackExchange" }
Q: Active Directory not replicating I have a windows server 2003 as a PDC ("server 1"). I am attempting to take it offline once I get several issues cleared up. I have two other windows server 2008 servers that have been promoted as DC's ("server 2" and "server 3"). When I run dcdiag on any of the servers I get failed connectivity to "server 2" and "server 3" the host guid._msdcs.domain could not be resolved to an ip address...although the guid dns name couldnt be resolved, the server name resolved to the ip address. Check that the ip address is registered correctly with the dns server. "server 2" failed test connectivity. While there could be several issues preventing replication, I noticed one thing on the pdc ("server 1"). In DNS under the msdcs folder there is an "" folder (along with "dc", "domains", "gc" and "pdc". The "_" folder references "server 2" with the guid thats referenced in the dcdiag connectivity failure. What does the "_" folder represent? Is that where my problems begin? The pdc has the wrong guid for "Server 2". I need to be able to replicate to "server 2" and "server 3" A: Answers to your questions re: the DNS records are certainly something you should know about (and I'd encourage you to look at something like this article from Microsoft for some background on what they do), but I think you're probably interested in a more practical answer here. What are the "server 2" and "server 3" computers using for DNS servers? I'm guessing that your "server 1" computer is a DNS server (since it's your existing Domain Controller), but it's unclear if you've configured "server 2" and "server 3" to be DNS servers. I'd configure both "server 2" and "server 3" to be DNS servers, with "server 1" specified as their sole DNS server initially. Once Active Directory replication is working as-expected I'd reconfigure "server 2" to use "server 3" as its primary DNS server and itself as its secondary, and the converse on "server 3". Then you can go about transferring the Floating/Flexible Single-Master Operations (FSMO) roles from the "server 1" computer to either of these new machines, and demote "server 1" to a member server for removal from the network.
{ "pile_set_name": "StackExchange" }
Q: How to strip column values in Active record through loop before saving in rails framework? I have to remove spaces for every record before saving into the database. I can do that by specifying it for each column, but when there 100 columns in each record, it is a pain and no of lines of code increases enormously. Need help in changing the code into a loop, but being an amateur in rails I am not able to complete it. class hello < ActiveRecord::Base before_validation :remove_spaces def remove_spaces self.login = self.login.strip if self.login.present? self.email = self.email.strip if self.email.present? . so on ....... end end A: I would is attributes.each to iterate over all attribute names and the values of the current instance (while ignoring the attribute names). For each value I would call try(:strip!) to strip whitespace from the value. Please note that try only calls strip! on values that actually respond_to strip (that means basically just strings), therefore it would ignore nil values or values of unsupported types - like timestamps or booleans. before_validation :sanitize_strings private def sanitize_strings attributes.each { |_, value| value.try(:strip!) } end Or when you only want to sanitize specific attributes then you can just iterate over their names: ATTRIBUTES_TO_SANITIZE = %i[name title description] def sanitize_strings ATTRIBUTES_TO_SANITIZE.each { |attr| send(attr).try(:strip!) } end
{ "pile_set_name": "StackExchange" }
Q: Why is the Django decimal max_digits validation failing with strange behaviour? I have a model field full_time_equivalent: full_time_equivalent = models.DecimalField( max_digits=5, decimal_places=2, default=100, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100)) ] ) To ensure that the validators fire I have override save with: def save(self, *args, **kwargs): # Run validations self.full_clean() return super().save(*args, **kwargs) With the following test: project2_membership = ProjectMembership( user=self.new_user, project=project2, is_project_manager=False, full_time_equivalent=10.01 ) When I step into the validation the following value is shown and respective error: Decimal('10.0099999999999997868371792719699442386627197265625') django.core.exceptions.ValidationError: {'full_time_equivalent': ['Ensure that there are no more than 5 digits in total.'] What am I doing wrong? A: The decimal value 10.01 can't be expressed exactly as a float. When the value is converted to a decimal, you end up with Decimal('10.0099999999999997868371792719699442386627197265625'), which is very nearly equal to Decimal('10.01'), but fails your max_digits validation. You can prevent the error by using the string '10.01' or the decimal Decimal('10.01') in your test. from decimal import Decimal project2_membership = ProjectMembership( user=self.new_user, project=project2, is_project_manager=False, full_time_equivalent=Decimal('10.01') )
{ "pile_set_name": "StackExchange" }