text
stringlengths
64
89.7k
meta
dict
Q: How to read a text file using vhdl I am working with altera QuartusII version 13.I want to write a program that reads data from a text file and outputs this data serially at every positive clk edge. I have tried writing a code,but it did not work.The simulation result shows a value '1' for y(data read from) all the time even when reset is set '1' initially .Could someone help me in resolving this problem. --code LIBRARY ieee; USE ieee.std_logic_1164.ALL; use STD.textio.all; ENTITY readfile IS port(rst,clk:in std_logic; EOR:out std_logic; y:out std_logic ); END readfile; ARCHITECTURE behav OF readfile IS BEGIN process (rst,clk) file file_pointer : text; variable line_content : character; variable line_num : line; variable j : integer := 0; variable char : character:='0'; variable cnt:integer range 0 to 80:=0; begin if rst='1'then EOR<='0'; file_open(file_pointer,"C:\input.txt",READ_MODE); elsif rising_edge(clk) then if cnt<80 then readline (file_pointer,line_num); READ (line_num,line_content); EOR<='1'; char := line_content; if(char = '0') then y <= '0'; else y <= '1'; end if; cnt:=cnt+1; end if; end if; file_close(file_pointer); end process; end behav; --text file(input.txt) 1 1 0 0 1 1 1 1 0 0 1 1 1 1 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 1 0 0 1 1 0 1 0 0 0 1 0 0 0 1 0 1 0 1 0 1 0 1 1 0 0 1 1 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 0 0 A: Not surprisingly, readline reads one line of text and stores it into the variable you confusingly named line_num. Your input file seem to have only one line of text, which starts with 1. read is called with a line_content output argument which is a single character, so it reads the first character of the line and outputs it in line_content. That's why you only see a single 1 in the output. You have to split your input file into multiple lines (each containing a single character). Alternatively, you can make a single call to readline and then iterate through your line_num variable by calling read on it multiple times. In any case, rename line_num to line_buf or something similar. It looks confusing, especially side by side with line_content, which doesn't hold the line contents as its name advertises. A: You're trying to readline from a file you've closed. I wrote a little testbench: library ieee; use ieee.std_logic_1164.all; entity readfile_tb is end entity; architecture foo of readfile_tb is signal rst: std_logic := '1'; signal clk: std_logic := '0'; signal eor: std_logic; signal y: std_logic; begin DUT: entity work.readfile port map ( rst => rst, clk => clk, eor => eor, y => y ); CLOCK: process begin wait for 5 ns; clk <= not clk; if now > 830 ns then wait; end if; end process; STIMULUS: process begin wait for 10 ns; rst <= '0'; wait; end process; end architecture; I created input.txt from the 1 and 0 values in your question, one per line. The first thing my simulator told me was there was a null access (pointer), which would have been the line (line_num). It occurred on the rising edge clock edge after rst is released in the READLINE procedure call. On closer look, at the end of process you're obliviously doing a FILE_CLOSE, and the next READLINE will fail. The solution to that is to perform a FILE_OPEN and FILE_CLOSE only once. This also raises the point that we're hanging our hat on rst to hold off readlines, and we could add an enable as an embellishment. So, modifying the process: process (rst, clk) file file_pointer: text; variable line_content: character; variable line_num: line; -- variable j: integer := 0; variable char: character := '0'; variable cnt: integer range 0 to 80 := 0; -- defaults to 0 begin if rst = '1' then eor <= '0'; -- file_open (file_pointer, "c:\input.txt", read_mode); elsif rising_edge(clk) then if cnt < 80 then if cnt = 0 then -- open file once file_open (file_pointer, "input.txt", READ_MODE); eor <= '1'; end if; readline (file_pointer, line_num); read (line_num, line_content); -- eor <= '1'; char := line_content; if char = '0' then y <= '0'; else y <= '1'; end if; cnt := cnt + 1; end if; if cnt = 80 then -- variable updated immediately file_close (file_pointer); -- close only once eor <= '0'; -- signal end of input end if; end if; end process; We get only one file_open and one file_close. I modified eor to show when y is valid from the file. That can easily be changed. And this gives us: I made a change to the path to input.txt for my environment. I can imagine adding an enable to the elsif rising_edge(clk) portion of the if statement so you don't have to hold readfile in reset. Another useful modification might be to enclose the readline and read in an if statement with a condition test using function ENDFILE for the case of a short file being read.
{ "pile_set_name": "StackExchange" }
Q: Hibernate link between 2 persistence units? my question is a bit tricky so I will try to make it as simple as possible: I have two maven projects: ProjetA and ProjectB. ProjectA has the following persistence.xml file: <persistence-unit name="ProjectAUnit" transaction-type="RESOURCE_LOCAL"> <class>com.projectA.Client</class> <class>com.projectA.InterventionA</class> </persistence-unit> InterventionA has a OneToOne relationship with the Client entity. ProjectB has the following persistence.xml file: <persistence-unit name="projectBUnit" transaction-type="RESOURCE_LOCAL"> <class>com.projectB.InterventionB</class> <class>com.projectB.InterventionOrder</class> </persistence-unit> InterventionB extends the InterventionA class (contained in a .jar dependency): All 3 classes InterventionA, InterventionB and Client are defined in the same MySQL schema (schema1). BUT InterventionB also has a @OneToOne relationship with the InterventionOrder entity defined in another MySQL schema (schema2). private InterventionOrder interventionOrder; I am getting the following exception: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.projectA.InterventionA.client references an unknown entity: com.projectA.Client So here is my question: Is why I am trying to achieve even possible with Hibernate/Spring? if yes how? :-) thanks in advance for your help. A: InterventionB has inherited the one-to-one relationship between itself and Client (from InterventionA). To be able to define a relationship the target entity must be mapped, in Project B Client is not mapped, hence the error. As Project B depends on Project A you can simply add the target entity to Project B's persistence.xml: <persistence-unit name="projectBUnit" transaction-type="RESOURCE_LOCAL"> <class>com.projectB.InterventionB</class> <class>com.projectB.InterventionOrder</class> <class>com.projectA.Client</class> </persistence-unit>
{ "pile_set_name": "StackExchange" }
Q: Can I repair this crack in my sprinkler backflow preventer? I have a crack in one part of my sprinkler backflow preventer/vacuum breaker. It looks a lot like this: Can I re-seal this crack? Or do I have to buy a whole new assembly? A: It's a fairly standard quarter turn ball valve, for permanent repair, take the union loose, remove the valve and replace with like. No patch you can apply will properly seal against expansion propagating through the patch material or breaking the patch material off eventually. Any moisture underneath the patch allowed to freeze will spall it off of the casting. Water pressure under the material tends to work it off akin to how the pressure in a blister separates the skin layers. About the only thing I would recommend for patching is MarineTex which is a super duty industrial Marine Epoxy made for use on water containing castings in damp environments. You will have to sand the area to remove casting skin, extending the area beside and well beyond the crack, clean the surface thoroughly with MEK or Acetone and then mix up and apply the MarineTex per directions.
{ "pile_set_name": "StackExchange" }
Q: Server Side / Cloud Coding for the app? I am am making an app for iOS & Android whose frontend UI is ready. Now I wanted to learn some server side coding to connect my backend with Amazon services. MY app will feature 1.image upload & download 2. storing of data and meta data 3. user registration and stuff I have no clear idea about server side and cloud coding ? so want you guys push me a bit from where should I begin and how should I begin to make the above features for my app working ? A: It sounds like you are looking to do mobile app development that works with cloud datastores. Here are a few blogs that you can take a look at get started with: http://mobile.awsblog.com/post/TxERCU1UMRFNPB/DynamoDB-on-Mobile-Part-5-Fine-Grained-Access-Control The above blog post talks about using AWS Mobile SDKs with DynamoDB. In general, mobile.awsblog.com has more resources for developing with other datastores and might be a good resource. For DynamoDB's support for enabling mobile developers to build serverless architectures, please take a look: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/FGAC_DDB.html Hope this helps. Swami
{ "pile_set_name": "StackExchange" }
Q: php combine keys with values in associative multidimensional array I'm trying to manipulate an associative multidimensional array. I've extracted the keys from an array that I want to apply to another's values . . . These are the keys that I've extracted in another function $keys = array ( "id" => "id", "addr_street_num" => "addr_street_num", "addr_street" => "addr_street", "price" => "price", "days" =>"days", "state" => Array ( "id" => "id", "name" => "name" ), "city" => Array ( "id" => "id", "web_id" => "web_id", "name" => "name" ) ); This array has the values I'd like to combine together $vals = array ( "0" => "830680", "1" => "20", "2" => "Sullivan Avenue", "3" => "333000", "4" => "12", "5" => Array ( "0" => "4", "1" => "Maryland", ), "6" => Array ( "0" => "782", "1" => "baltimore", "2" => "Baltimore", ) ); When I try to do array_combine($keys, $val); I get 2 Notices about Array to string conversion I guess array_combine only works on one dimensional arrays, any ideas on how to approach this? If $keys was modified could it be combined with the values - problem is the shape of $keys is what I want to end up with? A: It can be done recursively. function combine_recursive($keys, $values) { $result = array(); $key = reset($keys); $value = reset($values); do { if (is_array($value)) { $result[key($keys)] = combine_recursive($key, $value); } else { $result[key($keys)] = $value; } $value = next($values); } while ($key = next($keys)); return $result; } This works for me with your example arrays. I'm sure this will give you all kinds of weird results/errors if the array structures are different from each other at all.
{ "pile_set_name": "StackExchange" }
Q: Function auto-assigns values in my matrix I am trying to make a game like 2048 but I've encountered a problem. #include <iostream> #include <conio.h> #include <windows.h> #include <time.h> using namespace std; void random(); void randomCoord(); int gt[3][3]; int r,coordi,coordj; void initiate() { for(int i=0;i<=3;i++) for(int j=0;j<=3;j++) gt[i][j]=0; random(); // randomCoord(); // gt[coordi][coordj]=r; // randomN(); // randomCoord(); // gt[coordi][coordj]=r; for(int i=0;i<=3;i++) { cout<<endl; for(int j=0;j<=3;j++) cout<<gt[i][j]<<" "; } } void random() { srand (time(NULL)); do { r = rand() % 4 + 2; if(r==2 || r==4) break; } while(1); } void randomCoord() { srand (time(NULL)); coordi = rand() % 4; coordj = rand() % 4; } int main() { initiate(); return 0; } I am expecting that when I print the matrix on the screen to get a matrix full of zero...but for some reason the values gt[2][3] and gt[3][0] get the value of r. I don't understand the reason why. Thanks for help! A: If you want to write in gt[2][3] and gt[3][0], your gt must be int gt[4][4]; If your gt is gt[3][3], when you access in position 3 (for first or second index) you are (as far I know) in Undefined Behavior.
{ "pile_set_name": "StackExchange" }
Q: python selenium clearing cache and cookies I'm trying to clear the cache and cookies in my firefox browser but I can't get it to work. I have searched it up and i'm only getting solutions for java and C#. How do I clear the cache and cookies in Python? selenium version: 3.6.0 platform: python python version: 2.7.8 webdriver: geckodriver browser platform: Firefox A: for cookies use 'delete_all_cookies()' function driver.delete_all_cookies() for cache create profile profile = webdriver.FirefoxProfile() profile.set_preference("browser.cache.disk.enable", False) profile.set_preference("browser.cache.memory.enable", False) profile.set_preference("browser.cache.offline.enable", False) profile.set_preference("network.http.use-cache", False) driver =webdriver.Firefox(profile)
{ "pile_set_name": "StackExchange" }
Q: Very generic argmax function in C++ wanted I'm a spoiled Python programmer who is used to calculating the argmax of a collection with respect to some function with max(collection, key=function) For example: l = [1,43,10,17] a = max(l, key=lambda x: -1 * abs(42 - x)) a then contains 43, the number closest to 42. Is it possible to write a C++ function which takes any "iterable" and any function and returns the argmax like above? I guess this would involve template parameters, the auto keyword, and range-based iteration, but I was not able to piece it together. A: This is a two-step process. Define a function key which should get mapped to the elements, i.e. which is applied before the operation which finds the maximum. Wrap things together in a lambda expression defining the comparison for finding the maximum. auto key = [](int x){ return -abs(42 - x); }; std::max_element(l.begin(), l.end(), [key](int a, int b){ return key(a) < key(b); }); Here, we have to capture key which was defined outside the second lambda function. (We could also have defined it inside). You can also put this in one single lambda function. When the 42 should be parameterized from outside the lambda, capture this as a variable: int x = 42; std::max_element(l.begin(), l.end(), [x](int a, int b){ return -abs(x - a) < -abs(x - b); }); Note that std::max_element returns an iterator. To access the value / a reference to it, prepend it with *: int x = 42; auto nearest = std::min_element(l.begin(), l.end(), [x](int a, int b){ return abs(x - a) < abs(x - b); }); std::cout << "Nearest to " << x << ": " << *nearest << std::endl; You can nicely wrap this in a generic find_nearest function: template<typename Iter> Iter find_nearest(Iter begin, Iter end, const typename std::iterator_traits<Iter>::value_type & value) { typedef typename std::iterator_traits<Iter>::value_type T; return std::min_element(begin, end, [&value](const T& a, const T& b){ return abs(value - a) < abs(value - b); }); } auto a = find_nearest(l.begin(), l.end(), 42); std::cout << *a << std::endl; Live demo find_nearest: http://ideone.com/g7dMYI A higher-order function similar to the argmax function in your question might look like this: template<typename Iter, typename Function> Iter argmax(Iter begin, Iter end, Function f) { typedef typename std::iterator_traits<Iter>::value_type T; return std::min_element(begin, end, [&f](const T& a, const T& b){ return f(a) < f(b); }); } You can invoke this with the following code, having exactly the lambda function from your question: auto a = argmax(l.begin(), l.end(), [](int x) { return -1 * abs(42 - x); }); std::cout << *a << std::endl; Live demo argmax: http://ideone.com/HxLMap The only remaining difference now is that this argmax function uses an iterator-based interface, which corresponds to the design of the C++ standard algorithms (<algorithm>). It's always a good idea to adapt your own coding style to the tools you're using. If you want a container-based interface which returns the value directly, Nawaz provided a nice solution which requires the decltype-feature to correctly specify the return type. I decided to keep my version this way, so people can see the both alternative interface designs. A: Since @leemes solutions are too many. All are correct, except that none attempts to imitate the Python version in your example, Here is my attempt to imitate that: Convenient generic argmax-function just like Python version: template<typename Container, typename Fn> auto max(Container const & c, Fn && key) -> decltype(*std::begin(c)) { if ( std::begin(c) == std::end(c) ) throw std::invalid_argument("empty container is not allowed."); typedef decltype(*std::begin(c)) V; auto cmp = [&](V a, V b){ return key(a) < key(b); }; return *std::max_element(std::begin(c), std::end(c), cmp); } And use it as: std::vector<int> l = {1,43,10,17}; auto a = max(l, [](int x) { return -1 * std::abs(42-x); }; int l[] = {1,43,10,17}; //works with array also! auto a = max(l, [](int x) { return -1 * std::abs(42-x); }; Note: Unlike the other solution, this max() returns the element itself, not the iterator to the element! Also note this solution would work for user-defined container also: namespace test { template<size_t N> struct intcollection { int _data[N]; int const * begin() const { return _data; } int const * end() const { return _data + N; } }; } test::intcollection<4> c{{1,43,10,17}}; auto r = max(c, [](int x) { return -1 * std::abs(42-x); }); See the live demo.
{ "pile_set_name": "StackExchange" }
Q: cakephp 2 name variable in model and controller Is it necessary to declare the name variable in models and controllers? Or just good practice? For example: class User extends AppModel { public $name = 'User'; } class UsersController extends AppController { public $name = 'Users'; } A: Cake does that internally when you don't specify it based on the class name. However, this leads into a nice trap: When extending a model or controller the name is not constructed again. So you'll have to specify the name to make it work right. This is important because other things like view file folder, modelClass and in models alias depend on the name being correct. So no it is not required until you extend a class. In models pay attention when dealing with data: Models use Model::$alias not $name for that. The reason for that are associations. If Code hasMany Programmer but Programmer is your User model the alias is used and the alias is Programmer, not User. So use the alias in models when you do something like $this->data[$this->alias]['field'].
{ "pile_set_name": "StackExchange" }
Q: How to create a Second database connection with Symfony2? I'm trying to connect a second database to my project in Symfony2. First, I added into parameters.yml some parameters to create the connection. Then, I edited my config.yml, and now looks like: doctrine: dbal: default_connection: default connections: default: driver: pdo_mysql host: "%database_host%" port: "%database_port%" dbname: "%database_name%" user: "%database_user%" password: "%database_password%" charset: UTF8 circutor3: driver: pdo_sqlsrv host: "%database_host_circutor3%" port: "%database_port_circutor%" dbname: "%database_name_circutor%" user: "%database_user_circutor3%" password: "%database_password_circutor3%" charset: UTF8 orm: auto_generate_proxy_classes: "%kernel.debug%" naming_strategy: doctrine.orm.naming_strategy.underscore auto_mapping: true Finally, I tried to get connected, using the following code in my controller: $em = $this->getDoctrine()->getManager('circutor3'); And, the error returned by Symfony2: Doctrine ORM Manager named "circutor3" does not exist. The circutor3 makes connection to a database, external to my system, so I don't need to create entities or objects. I only need to execute some SELECT to get information and store it using an array. Is creating a typical mysqli connection the best way to solve my problem? I don't know how to solve this with Symfony. Thank you in advance. A: you could access to the database connection in the controller as follow: $connection = $this->getDoctrine()->getConnection('circutor3'); then use the connection as: $stmt = $connection->prepare($sql); $stmt->execute(); return $stmt->fetchAll(); Some help here and here Hope this help
{ "pile_set_name": "StackExchange" }
Q: Algorithm to find the "percolation" threshold in a weighed network I have some states that are linked by transition probabilities (embedded within a transition matrix as in a Markov chain). I want to summarise this transition matrix by considering only probabilities sufficiently high that they allow to go from one state (~node) to another (first and last in my transition matrix). A threshold so that if I consider only higher probabilities my transition matrix never allow to move from the first to the last states (or nodes). Two questions: Are there some well known libraries (preferentially python language) that implement such method? My naive/empiric/prototypic approach would be one loop that decreases value of the threshold then check if I can flow through the transition matrix from the first state to the last (kind of best path algorithm in a distance matrix?). But this may need very high computation time? Example 1: DistMatrix = [[ 'a', 'b', 'c', 'd'], ['a', 0, 0.3, 0.4, 0.1], ['b', 0.3, 0, 0.9, 0.2], ['c', 0.4, 0.9, 0, 0.7], ['d', 0.1, 0.2, 0.7, 0]] states are a,b,c,d. I want to find the value (threshold) that allow to go from a to d (no matter if other states are walked) Naive approach: - first loop: threshold 0.9, I get rid of lesser probabilities: I can only connect c and b - second loop: threshold 0.7, I get rid of lesser probabilities: I can only connect c, b, d - third loop: threshold 0.4, I get rid of lesser probabilities: I can connect a,c, b, d: here is my threshold: 0.4 --> should be incredibly complicated as soon as my transition matrix have many thousands states? --> Algorithm to propose? Example 2: DistMatrix = [ 'a', 'b', 'c', 'd'], ['a', 0, 0.3, 0.4, 0.7], ['b', 0.3, 0, 0.9, 0.2], ['c', 0.4, 0.9, 0, 0.1], ['d', 0.7, 0.2, 0.1, 0] ] states are a,b,c,d. I want to find the value (threshold) that allow to go from a to d (no matter if other states are walked) Naive approach: -first loop: threshold 0.9, I get rid of all others: I can only connect c and b -second loop: threshold 0.7, I get rid of lesser connexion: I connect b and c, and a and d but because a and d are connected, I have my threshold! A: To expand on what Mr E suggested, here are two versions of an algorithm that works decently on graphs with a few thousand nodes. Both versions use Numpy and the second one also uses NetworkX. You need to get rid of the 'a', 'b', 'c' and 'd' identifiers in order to be able to use Numpy arrays. This is easily done by translating your node names to integers between 0 and len(nodes). Your arrays should look as follow DistMatrix1 = np.array([[0, 0.3, 0.4, 0.1], [0.3, 0, 0.9, 0.2], [0.4, 0.9, 0, 0.7], [0.1, 0.2, 0.7, 0]]) DistMatrix2 = np.array([[0, 0.3, 0.4, 0.7], [0.3, 0, 0.9, 0.2], [0.4, 0.9, 0, 0.1], [0.7, 0.2, 0.1, 0]]) Use numpy.unique to get a sorted array of all probabilities in the distance matrix. Then, perform a standard binary search, as suggested by Mr E. At each step in the binary search, replace the entries in the matrix by 0 if they are below the current probability. Run a breadth first search on the graph, starting a the first node, and see if you reach the last node. If you do, the threshold is higher, otherwise, the threshold is lower. The bfs code is actually adapted from the NetworkX version. import numpy as np def find_threshold_bfs(array): first_node = 0 last_node = len(array) - 1 probabilities = np.unique(array.ravel()) low = 0 high = len(probabilities) while high - low > 1: i = (high + low) // 2 prob = probabilities[i] copied_array = np.array(array) copied_array[copied_array < prob] = 0.0 if bfs(copied_array, first_node, last_node): low = i else: high = i return probabilities[low] def bfs(graph, source, dest): """Perform breadth-first search starting at source. If dest is reached, return True, otherwise, return False.""" # Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py # by D. Eppstein, July 2004. visited = set([source]) nodes = np.arange(0, len(graph)) stack = [(source, nodes[graph[source] > 0])] while stack: parent, children = stack[0] for child in children: if child == dest: return True if child not in visited: visited.add(child) stack.append((child, nodes[graph[child] > 0])) stack.pop(0) return False A slower, but shorter version uses NetworkX. In the binary search, instead of running bfs, convert the matrix to a NetworkX graph and check whether there is a path from the first to the last node. If there is a path, the threshold is higher, if there is none, the threshold is lower. This is slow because of all the graph data structure in NetworkX is much less efficient than Numpy arrays. However, it has the advantage of giving access to a bunch of other useful algorithms. import networkx as nx import numpy as np def find_threshold_nx(array): """Return the threshold value for adjacency matrix in array.""" first_node = 0 last_node = len(array) - 1 probabilities = np.unique(array.ravel()) low = 0 high = len(probabilities) while high - low > 1: i = (high + low) // 2 prob = probabilities[i] copied_array = np.array(array) copied_array[copied_array < prob] = 0.0 graph = nx.from_numpy_matrix(copied_array) if nx.has_path(graph, first_node, last_node): low = i else: high = i return probabilities[low] The NetworkX version crashes on graphs with more than one thousand nodes or so (on my laptop). The bfs version easily find the threshold for graphs of several thousand nodes. A sample run of the code is as follows. In [5]: from percolation import * In [6]: print('Threshold is {}'.format(find_threshold_bfs(DistMatrix1))) Threshold is 0.4 In [7]: print('Threshold is {}'.format(find_threshold_bfs(DistMatrix2))) Threshold is 0.7 In [10]: big = np.random.random((6000, 6000)) In [11]: print('Threshold is {}'.format(find_threshold_bfs(big))) Threshold is 0.999766933071 For timings, I get (on a semi-recent Macbook Pro): In [5]: smaller = np.random.random((100, 100)) In [6]: larger = np.random.random((800, 800)) In [7]: %timeit find_threshold_bfs(smaller) 100 loops, best of 3: 11.3 ms per loop In [8]: %timeit find_threshold_nx(smaller) 10 loops, best of 3: 94.9 ms per loop In [9]: %timeit find_threshold_bfs(larger) 1 loops, best of 3: 207 ms per loop In [10]: %timeit find_threshold_nx(larger) 1 loops, best of 3: 6 s per loop Hope this helps. Update I modified the bfs code so that it stops whenever the destination node is reached. The code and timings above have been updated.
{ "pile_set_name": "StackExchange" }
Q: Convert a JSON to TW Object of type ANY Using IBM BPM 8.6 I have a JSON as follows: tw.local.person = "{\"firstName\":\"Ahmed\",\"job\":\"Doctor\"}"; I am using the BPM helper toolkit to convert the json to TW Object tw.local.outputObject = BPMJSON.convertJSONToTw(tw.local.person); RESULTS: If the outputObject is of type Person (with the attributes firstName and job), it works and the object is created. If the outputObject is of type any, it doesn't work How can I get the output in an any object? Any workaround or a a tweak in the BPM-JSON-Utils.js or json2.js files? A: The first thing I would note that in my 8.6 install, calling JSON.parse() just works, so you don't need the community toolkit. That being noted, that approach seems to encounter what is likely the same bug as you are seeing when you try to do it using ANY or Record. Based on the error it seems that the underlying TWObject won't let you reference member fields that are not explicitly declared. In my tests, using the JSON String - var json='{ "name" : "Andrew", "value" : "42"}'; I tried - tw.local.myNvp = JSON.parse(json); tw.local.myAny = JSON.parse(json); The first one which was parsing into a variable of type "NameValuePair" from the system data toolkit worked. The 2nd which was trying to parse into an "ANY" failed. I also tried with Record to see if we could get there, but that failed as well. My suggestion would be to return the raw JSON to the caller and have them invoke the parse line above. I'm assuming the caller is expecting a specific type back, which means the variable isn't an Abstract type, so the parse call should work. -Andrew Paier
{ "pile_set_name": "StackExchange" }
Q: Unable to view files copied using Ubuntu to a drive on Windows I am using a dual boot Laptop (Ubuntu 18.04 + Windows 10). I have the following partitions (please view the attached picture). The files that I copy from Ubuntu to my "General" and "Software" drives are not visible on Windows. These files are not hidden and have 777 permissions but I cannot find them anywhere on Windows. Is there any way I can access those files in both Ubuntu and Windows? Thanks! My partitions: A: You may be experiencing the hibernation issue with Windows 10. If I remember correctly, Windows 10 by default uses a setting called "fast start" which puts the system into a special hibernation state instead of a full shut down to improve boot times (more info here). When restarting from this state, the OS does a kind of check/repair on the filesystem I believe. This could be what is deleting your files. You can disable "fast start" in the system power options: If turning off "fast start" doesn't fix your problem, then after you copy the files in Ubuntu, unmount the NTFS partitions: $ sudo umount /mnt/General # or wherever "General" partition is mounted Then remount them to see if the files are still there. If they are, reboot into Windows. If you can now access the files from Windows, there could be an issue with files being cached for write to the filesystem but never actually get written. I'm not sure how that would be fixed, but usually (as I understand it) if files are cached, they will be written when the filesystem is unmounted. That could mean that the partitions are not being unmounted properly when the system is shut down. If all else fails, there are some tools for Windows that can give you access to the ext2/3/4 partitions: ext2fsd Ext2read (not sure if ext4 is supported) Linux Reader You should be able to use one of those to copy files from the Ext4 partition the NTFS ones in Windows.
{ "pile_set_name": "StackExchange" }
Q: Table of Values How can something like this be done in MacTex: A: One possibility using an array; numbering for the first column is done automatically: \documentclass{article} \usepackage{array} \newcounter{myrow} \begin{document} \[ \begin{array}{>{\stepcounter{myrow}\themyrow}c|*{5}{c}} \multicolumn{1}{c|}{} & 1 & 2 & 3 & 4 & 5 \\ \hline & 0 & 1 & 0 & 1 & 0 \\ & 1 & 1 & 0 & 1 & 0 \\ & 0 & 1 & 1 & 1 & 0 \\ & 1 & 0 & 0 & 1 & 0 \\ & 0 & 1 & 1 & 1 & 0 \\ \end{array} \] \end{document} Or: \documentclass{article} \usepackage{array} \newcounter{myrow} \begin{document} \[ \begin{array}{c|*{5}{c}} \multicolumn{1}{c|}{} & 1 & 2 & 3 & \cdots & n \\ \hline 1 & 0 & 1 & 0 & \cdots & \\ 2 & 1 & 1 & 0 & \cdots & \\ 3 & 0 & 1 & 1 & \cdots & \\ \vdots & \vdots & \vdots & \vdots & \ddots & \\ n & & & & & \\ \end{array} \] \end{document}
{ "pile_set_name": "StackExchange" }
Q: Elicit slot in dialogflow for actions on google (just like ElicitSlot Directive in alexa) I want to give the user a prompt and collect a value in particular slot. Then using this slot value for this particular slot, I want to frame a next response according to this value and ask for next slot's value in line. Now, this I can achieve in alexa quite easily with elicitSlot directive. But for action on google, I am not sure how to achieve this with dialogflow. A: You can use Dialogflow's required parameters and dates. Make each parameter you need required and move them so the order is consistent with the order in which you want Dialogflow to ask questions for you. Then click "Define Prompt" next to the parameter you wish to create a custom response for. In the prompt you can use any of the parameter values Dialogflow has already collected. For instance in the sample below we are collecting the date and time parameter. We collect the date first so that when we prompt fo the time we can use $date in the prompt and Dialogflow will fill in that value when asking the user for the time parameter. Here is what the Dialogflow console configuration looks like:
{ "pile_set_name": "StackExchange" }
Q: Doesn't update selectedItem in custom dropdown Suppose to have this dropdown: <p-dropdown [options]="list" [(ngModel)]="code"> <ng-template let-item pTemplate="selectedItem"> {{ item.value }} - {{ item.label }} </ng-template> <ng-template let-item pTemplate="item"> {{ item.value }} - {{ item.label }} </ng-template> </p-dropdown> and in my ts I have: //loadValue in an object that I have just loaded with this attribute({label, value]} //list is a list with current dropdown list and it is in this way ({label,vale}] let index= this.list.findIndex(x => x['value'] === this.loadValue['value']); this.code= this.list[index]; The problem is that list,loadValue and index are correct calculate, but the selectedItem value is not update because it show me the first value of the list but it is not correct result. A: You are assigning the item to your ngModel instead of the value. You need to pass the value. This is obviously a problem however if you think it is not getting updated after your assignment you need to debug what's the actual behavior. this.code= this.list[index].value;
{ "pile_set_name": "StackExchange" }
Q: How Will Register Transfer work in a Quantum computer ? If i am not wrong a qbit can have any value from 0 to 1 at any given time , But if you are moving some data from a register to another in a quantum computer how will we know what state will be transferred , to the register ? A: The no-cloning theorem says it's not possible to copy quantum states (pure or mixed). If you want a copy, you have to measure the qubits, collapsing them to classical information, and then copying that - but you loose almost all the information encoded in the system and you're left with normal 0's and 1's. However, it is possible to transfer a state using quantum teleportation - it destroys the original quantum state and re-creates it in another qubit using a classical information channel and a shared Bell state. But it is not exactly clear how this can be useful in a single processor as you could just use register renaming to the same effect (with a classical computer controlling the quantum processor, you can just tell it to start calling a certain physical qubit by some other name and achieve the same result).
{ "pile_set_name": "StackExchange" }
Q: Could not load file or assembly after deploy I am developing app, which uses PDFLibNet.dll, everythings works fine on my pc, but when I deploy application and try to use it in another pc, creating PDFWrapper class (from PFDLibNet.dll) throw me an exception: Could not load file or assembly "PDFLibNet.dll" or one of its dependencies.The specified module could not be found. The same scenario on Win7 and XP PDFLibNet.dll is stored in the same directory as binary .exe file of my app. Any suggestion how to fix it? I am using .Net4.0, Win7 Thanks! A: It can be 2 possible reasons: 1. Check if dll was build for x86 or x64 or AnyCPU if you target machine x64 build your dll x64 2. It can be because of MS C++ redistrubute updates! uninstall them and try to start app again. Or you can either install the redistributable on the target machine.
{ "pile_set_name": "StackExchange" }
Q: How to use JSON data returned from a local PHP file in Google Maps API instead of an online hosted JSON file? While combining data on a map using Google Maps API, I use a local PHP file which returns the same JSON result which I store online via hosting using a site like myjson. However I cannot use the local PHP file as I want (which would mean it returns a dynamic JSON file if I update database) and get an error. There's a similar example at this page which too uses a hosted static JSON file but not a JSON file returned using PHP queries using a PHP file as I want it to be Further this (https://developers.google.com/maps/documentation/javascript/reference/data#Data.getFeatureById ) does not help either as the feature does exist in the collection function showStation(crimeType) { var map; map = new google.maps.Map(document.getElementById('map'),{ zoom:9, center: {lat: 32.815939, lng: 73.305297} }); map.data.loadGeoJson('stations.js', { idPropertyName: 'name' }); var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.myjson.com/bins/1e0rkl', true); //works //xhr.open('GET', './data/stationdata.php', true); //does not work xhr.onload = function() { var crimeData = JSON.parse(xhr.responseText); crimeData.forEach(function(row){ //line 170 var crimeVariable = row[crimeType]; console.log(crimeVariable); var stationName = row.stationName; console.log(stationName); console.log(map.data.getFeatureById(stationName)); //error1 map.data.getFeatureById(stationName). //Line 180 setProperty(crimeType, crimeVariable); //error2 }); } xhr.send(); map.data.setStyle(styleFeature); } I get errors: undefined for //error1 and for //error2 I get: Uncaught TypeError: Cannot read property 'setProperty' of undefined at functions2.js:180 at Array.forEach (<anonymous>) at XMLHttpRequest.xhr.onload (functions2.js:170) This is the response from stationdata.php: [{"stationName":"PS Chotala","murder":"0.5238"},{"stationName":"PS City","murder":"0.6984"},{"stationName":"PS Civil Lines","murder":"0.5238"},{"stationName":"PS Dina","murder":"0.6984"},{"stationName":"PS Domeli","murder":"1.2222"},{"stationName":"PS Jalalpur Sharif","murder":"0.8730"},{"stationName":"PS Lilla","murder":"0.7857"},{"stationName":"PS Mangla Cantt","murder":"1.1349"},{"stationName":"PS Pind Dadan Khan","murder":"0.6984"},{"stationName":"PS Saddar","murder":"0.6984"},{"stationName":"PS Sohawa","murder":"3.1429"}] A: It seems that your row variable is empty or is missing required attributes/array keys. You did not share your PHP portion of the application nor a folder/file structure so its pretty hard to pinpoint the error per se. Are you sure your getting a good response code from './data/stationdata.php'? You can check your browsers networking tab to see if that XHR requests returns a error codes like 400, 500, 401. If on the other hand you are getting a good response code, your JSON encoding might be faulty or you are missing a JSON header within your PHP file. You can find a example with a JSON header here: Returning JSON from a PHP Script EDIT: As I mentioned in the comments section this could also be a timing issue. It is possible to attach a callback function to the gmaps script tag that will access your custom javascript once it is fully loaded. https://developers.google.com/maps/documentation/javascript/tutorial#Loading_the_Maps_API
{ "pile_set_name": "StackExchange" }
Q: windows mobile 6.5 - Motorola MC55 - strange directory names in device explorer view On Windows XP in device explorer view while I explore the content of my connected via Active Sync Motorola MC55 device I can see strange content. Look at the attached file. What may be wrong? Regards A: That looks a whole lot like the FAT is corrupted on the file store. A bad flash driver can cause this as well, but that would typically show up immediately and on every device. If it's a single device, or happened after time then it's likely a flash sector corruption. Reformatting the flash will likely correct it (though how you do that on your harward I don't know).
{ "pile_set_name": "StackExchange" }
Q: Products, Naturality and Functors i have the following problem: i want to show the following: Let $\bf{D}$ be a category with binary products, then $\bf{D}^{\bf{C}}$ also has binary products. Remark: $\bf{D}^{\bf{C}}$ is the category with objects functors from $\bf{C}$ to $\bf{D}$ and arrows natural transformations. My problem is not to define the natural transformations $\pi_1$ and $\pi_2$ from $F\times G$ to $F$ and $G$ resp. (since we have the projections in $\bf{D}$. But now let $h:D\rightarrow F$ and $k:D\rightarrow G$ be two arrows in $\bf{D}^{\bf{C}}$. My question is how to define the unique arrow $u:D\rightarrow F\times G$. Can someone help me? I am happy about hints, solutions, etc. Thanks. A: I'm assuming that you have understood that (up to natural isomorphism) the functor $F \times G \colon \mathbf C \to \mathbf D$ is just the functor sending every $c \in \mathbf C$ in $F(c) \times G(c)$ and every morphism $f \in \mathbf C(c,c')$ in $F(f)\times G(f)$, that is the unique morphism making the following diagram commute $$\require{AMScd}\begin{CD} F(c)@<<\pi_{F(c)}< F(c) \times G(c) @>\pi_{G(c)}>>G(c)\\ @VF(f)VV @VF(f)\times G(f)VV @VVG(f)V \\ F(c') @<<\pi_{F(c')}< F(c') \times G(c') @>>\pi_{G(c')}> G(c') \end{CD}$$ If $D \colon \mathbf C \to \mathbf D$ was another functor with natural transformations $h \colon D \to F$ and $k \colon D \to G$ then such natural transformations have components $h_c \colon D(c) \to F(c)$ and $k_c \colon D(c) \to G(c)$ for every $c \in \mathbf C$. By universal property of the product then there's a unique morphism $(h,k)_c \colon D(c) \to F(c) \times G(c)$ such that $\pi_{F(c)} \circ (h,k)_c=h_c$ and $\pi_{G(c)} \circ (h,k)_c=k_c$. It's now a diagram chase to prove that the morphisms $(h,k)_c$ are natural and give the only natural transformation from $D$ to $F \times G$ such that $\pi_F \circ (h,k) = h$ and $\pi_G \circ (h,k)=k$: where by $\pi_F$ and $\pi_G$ I denote the projections of the functor-product.
{ "pile_set_name": "StackExchange" }
Q: Untyped channel in golang I'm writing some package, where channel is only used to interrupt some process, so it is never read any value, just detects that it need to stop, like this: func myfunc(stop_chan chan /*bool*/) { for { //do something time consuming // .... // check on channel select{ case <-stop_chan: //cleanup return default: } // continue working } } later I wish this function to accept any type of channel. Is that possible? A: I wish this function to accept any type of channel. Is that possible? No, this is not possible. There are no untyped channels in Go. You could accept a channel of any type, using interface{}, then using reflection to interact with that channel. But this is cumbersome and slow, so not recommended. A better approach, probably, is to settle on a single type of channel (chan struct{} is the natural choice for your use-case), or use a context variable instead, which can handle cancellation in a standardized way.
{ "pile_set_name": "StackExchange" }
Q: How to replicate Jinja2 macros with JS/React? I'm trying to use React on an existing project and I tackled everything except for one thing; I can't use Jinja2 macros. I use them to create a dynamic list with multiple items. Set arguments: {% set botnewsArgs = [ ("channel", "Sets the channel to send bot news to"), ("toggle", "Toggles posting bot news") ] -%} Create entries from them: {% macro arg(arg_name, arg_description) -%} <hr> <p>{{ arg_name }}</p> <small>{{ arg_description }}</small> {%- endmacro %} Use them with the parent entry: {% macro main_expand(name, description, cmdargs) -%} <li class="list-group-item border"> <button>{{ name }}</button> <small>{{ description }}</small> <div class="args"> {% for arg_name, arg_description in cmdargs %} {{ arg(arg_name, arg_description) }} {% endfor %} </div> </li> {%- endmacro %} I set all this in a command_args.html file to import and use in commands.html. You can see the site live at gw2bot.info/commands I tried creating functions in JS such as: const arg = (argName, argDescription) => { <React.Fragment> <hr /> <p>{argName}</p> <small>{argDescription}</small> </React.Fragment> } and: const mainExpand = (name, description) => { <React.Fragment> <li class="list-group-item border"> <button>{{ name }}</button> <small>{{ description }}</small> <div class="args"> {arg()} {} </div> </li> </React.Fragment> } but I am at a loss when it comes to putting them together and get the same functionality from Jinja2 macros. Is it possible to replicate this with JS/React or is there a better approach to tackle this problem? A: Can't you do something like this? import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; const Arg = ({ argName, argDescription }) => <React.Fragment> <hr /> <p>{argName}</p> <small>{argDescription}</small> </React.Fragment>; const MainExpand = ({ name, description }) => <React.Fragment> <li class="list-group-item border"> <button>{ name }</button> <small>{ description }</small> <div class="args"> <Arg name={name} description={description} /> </div> </li> </React.Fragment>; function App() { return ( <div className="App"> <MainExpand argName="John Snow" argDescription="I know nothing!" /> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); Have two components Arg and MainExpand and render Arg in MainExpand.
{ "pile_set_name": "StackExchange" }
Q: How can I "filter" JSON for unique key name/value pairs? I've got some JSON data that is giving me a list of languages with info like lat/lng, etc. It also contains a group value that I'm using for icons--and I want to build a legend with it. The JSON looks something like this: {"markers":[ {"language":"Hungarian","group":"a", "value":"yes"}, {"language":"English", "group":"a", "value":"yes"}, {"language":"Ewe", "group":"b", "value":"no"}, {"language":"French", "group":"c", "value":"NA"} ]} And I want to "filter" it to end up like this: {"markers":[ {"group":"a", "value":"yes"}, {"group":"b", "value":"no"}, {"group":"c", "value":"NA"} ]} Right now I've got this, using jQuery to create my legend..but of course it's pulling in all values: $.getJSON("http://127.0.0.1:8000/dbMap/map.json", function(json){ $.each(json.markers, function(i, language){ $('<p>').html('<img src="http://mysite/group' + language.group + '.png\" />' + language.value).appendTo('#legend-contents'); }); }); How can I only grab the unique name/value pairs in the entire JSON object, for a given pair? A: I'd transform the array of markers to a key value pair and then loop that objects properties. var markers = [{"language":"Hungarian","group":"a", "value":"yes"}, {"language":"English", "group":"a", "value":"yes"}, {"language":"Ewe", "group":"b", "value":"no"}, {"language":"French", "group":"c", "value":"NA"}]; var uniqueGroups = {}; $.each(markers, function() { uniqueGroups[this.group] = this.value; }); then $.each(uniqueGroups, function(g) { $('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + this).appendTo('#legend-contents'); }); or for(var g in uniqueGroups) { $('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + uniqueGroups[g]).appendTo('#legend-contents'); } This code sample overwrites the unique value with the last value in the loop. If you want to use the first value instead you will have to perform some conditional check to see if the key exists.
{ "pile_set_name": "StackExchange" }
Q: UICollectionView: Waterfall layout with Drag & Drop I am using CHTCollectionViewWaterfallLayout as the layout for my collectionView, since my cells do all have different sizes. But I would also like to implement drag & drop in my collectionView. The libraries I have found would not allow me to implement both at the same time. Is there any way to do this? Thanks A: I found a way to do it, I used one of the existing Drag 'n Drop libraries and made sure it inherited from the CHTCollectionView instead of the UICollectionViewFlowLayout, this worked pretty good! Still some errors to work out, but the beginning is there
{ "pile_set_name": "StackExchange" }
Q: corosync/pacemaker/fencing - passive/active cluster with 2 nodes I'm configuring a cluster 2 nodes with pacemaker/corosync, and I have some question about it (and maybe best practice : i'm far to be specialist) **OS:** redhat 7.6 I configurated the cluster with those properties - **stonith-enabled:** true - **symmetric-cluster:** true (even if is default value i think) and added in corosync.conf - **wait_for_all:** 0 (i want a Node be able to start/work even if his twin is KO) - **two_nodes:** 1 Considering the fencing: - Using ILO of blade HP (ILO1 for Node1, ILO2 for Node2) I read that it was sometimes a good practice to prevent a node suicide, so added constraints - ILO1-fence can't locate in node1 - ILO2-fence can't locate on node2 The problems I have is the following, happening at starting Node2 when Node1 is shutdown : pacemaker/corosync can't start ILO2-fence on Node1 (of course cause Node 1 is down), and so don't start the other resources, and so my cluster is all not working >:[ I am wondering if I miss something in my configuration, or if I don't understand well how such a cluster should work. Because I'd expect Node2 to start, cluster sees Node1 is KO and just start the resources to make Node2 works on its own. But is true, since ILO2-fence can only be located on Node1 (because of constraint to avoid suicide), then this resource will always fails ... (when trying without those "anti-suicide" constraints, if Node2 has some services failure, then it shutdowns directly after start, which i don't want) I would apreciate some returns and enlightments :) Thank you :) A: You have, let's say, 4 votes in your cluster - 2 nodes and 2 ILO-fence. Cluster can run, if >2 (3) are accesible. ILO2 is configured with only node1, so if node1 is down - the qourum is lost. Using ILO-fencing is not recommended: "A common mistake people make when choosing a STONITH device is to use a remote power switch (such as many on-board IPMI controllers) that shares power with the node it controls. If the power fails in such a case, the cluster cannot be sure whether the node is really offline, or active and suffering from a network fault, so the cluster will stop all resources to avoid a possible split-brain situation." link You have 2 options for 2 node cluster: 1) Use one external fencing device (witness node, voting VSA or SMB2/3 file share). 2) Use solution developed for 2-node clusters (like Hyper-V/VMware + Datacore or StarWind).
{ "pile_set_name": "StackExchange" }
Q: array find method error element implicitly has an 'any' type I'm facing a problem with Typescript linting. The scenario is that data is coming from the API which contains an array of objects. [ { "id": 3, "name": "politics", "slug": "politics", }, { "id": 2, "name": "sport", "slug": "sport", }, { "id": 1, "name": "weather", "slug": "weather", } ] What I want is when there any new object is created and tries to post on the server before that we have to make sure slug is unique or not. So I created a utility function named uniqueStr that will check that slug is exist or not. ICategory.ts: export interface Category { id: number; name: string; slug: string; parent: number; } utility.ts import {Category} from './ICategory'; export const uniqueStr = (property: string, compareValue: string, data: Category[]): string => { if (Array.isArray(data) && data.length > 0) { const objectFind = data.find((element) => { return element[property] === compareValue; }); // If not undefined if (objectFind) { const message = `${property} value should be unique.`; alert(message); throw new Error(message); } else { // Return value return compareValue; } } return compareValue; }; At the following line return element[property] === compareValue Typescript linter is giving an error. TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Category'. No index signature with a parameter of type 'string' was found on type 'Category'. A: You can use indexable-types to specify that properties an instance of the Category interface can be accessed via string index. Example: interface Category { id: number; name: string; slug: string; parent: number; [key: string]: number | string; };
{ "pile_set_name": "StackExchange" }
Q: composer autoload + facebook sdk i'm confused about composer. I read in other post "Every package should be responsible for autoloading itself" but i can't resolve the problem. i have this composer.json file in root project folder: { "require": { "facebook/php-sdk-v4": "4.0.*" } } I run composer install and it creates this structure: vendor/ |-- autoload.php |-- composer | |-- autoload_classmap.php | |-- autoload_namespaces.php | |-- autoload_real.php | |-- ClassLoader.php | `-- installed.json `-- facebook `-- php-sdk-v4 |-- autoload.php |-- composer.json |-- CONTRIBUTING.md |-- LICENSE |-- phpunit.xml.dist |-- README.md |-- src | `-- Facebook | |-- Entities | | |-- AccessToken.php | | `-- SignedRequest.php | |-- FacebookAuthorizationException.php | |-- FacebookCanvasLoginHelper.php | |-- FacebookClientException.php | |-- FacebookJavaScriptLoginHelper.php | |-- FacebookOtherException.php | |-- FacebookPageTabHelper.php | |-- FacebookPermissionException.php | |-- FacebookRedirectLoginHelper.php | |-- FacebookRequestException.php | |-- FacebookRequest.php | |-- FacebookResponse.php | |-- FacebookSDKException.php | |-- FacebookServerException.php | |-- FacebookSession.php | |-- FacebookSignedRequestFromInputHelper.php | |-- FacebookThrottleException.php [...] vendor/facebook/php-sdk-v4/composer.json file shows: "autoload": { "psr-4": { "Facebook\\": "src/Facebook/" } } and autoload_classmap.php and autoload_namespaces.php return empty arrays. When run index.php throws this error: PHP Fatal error: Class 'Facebook\FacebookSession' not found on line 33 require 'vendor/autoload.php'; use Facebook\FacebookSession; use Facebook\FacebookRequest; use Facebook\GraphUser; use Facebook\FacebookRequestException; FacebookSession::setDefaultApplication('x','y'); I don't know if i have to put in this files (in this arrays that are returned) or composer must include them automatically. Can Composer autoload classes declared in file vendor/facebook/php-sdk-v4/composer.json? Thank you in advance, i really appreciate help A: Solved, i have updated composer and deps and works. Thank you!
{ "pile_set_name": "StackExchange" }
Q: Can you integrate an electromagnetic coil (torque rod) to a PCB design in EAGLE? I am new in using EAGLE and I am currently trying to design a magnetorquer board. I would like to ask if it is possible to somehow create a solid-core electromagnetic coil (torque rod) that has known electrical and physical values: core (material, size-diameter and length-)and wire characteristics (number of windings, size, max current carrying capabilities, etc) in such a way to integrate it into my PCB design. Moreover, i would like to create an air coil electromagnetic core in a rounded square for the back side of the same PCB. For better undestanding, I will link the ISIS Magnetorquer board with images of its top and bottom views. Therefore, succinctly,my question is I can somehow integrate the electromagnetic coils to the PCB design or in the worse case scenario if there exists a library that include any customizable electromagnetic coils or any pre-made ones. If not, is there any other program that can do this and that can be accessible to a newbie? (I'm running very low on time so I would take just about anything now) EDIT:As the question is a little bit abstract(i am truly sorry for that), I will try to make it more specific with the help of your feedback. EDIT4: In the links above, the electromagnetic coils (torque rods) are mounted on the PCB by using a plastic (or another material) support as seen in the links above, so they are separate components. The question above should have been how do I take these coils into consideration when designing the PCB in EAGLE. I believed that there is an electromagnetic coils library or that I can design it myself as a part somehow and this is the reasoning for the weirdly phrased question. EDIT2: A: You can integrate coils into the PCB, yes. Is it efficient? No. Q-factor of PCB inductors is generally lowered then Q-factor of the inductors having a coil of wire and less than that of the cylindrical microstrip coils. The self-capacitance of the printed inductors depends on the width of the spiral turns, the gap between them and the PCB material and can reach 3 to 5 pF, which is pretty high at such frequencies Source: https://coil32.net/pcb-coil.html The magnetic moment is a factor of the number of turns, the current and the area. So many torquer coils are simply rectangles built into one or more layers of the PCB. m = nAI More turns are easier to create with wire, which has a much higher packing factor for current carrying wires than a PCB (or flat flex), because enamel is much smaller than layers of a PCB or flat flex. It really depends on the magnetic moment needed, if you need a high magnetic moment, then you might have to resort to wire outside of the PCB, because most PCB's are fabricated with 4 layers (you can do more, but it comes with a cost). If you do wish to create a magnetorquer on a PCB, eagle (or any PCB software), just draw the pattern out by hand in the software. In the design I used for a magnetorquer (which flew) I personally wound a rectangular delrin frame with about 400 turns, which was then fastened to 4 posts on the PCB. The wire was soldered into vias. I remember that the other 2 torquer coils were built into the solar panel arrays. Here is a paper describing a satellite with coils built in to the PCB with copper traces forming the coil: Source: Innovative power management ADCS
{ "pile_set_name": "StackExchange" }
Q: Importing Wordpress Posts - Getting Load Error I was trying to import wordpress posts to my new jekyll site using these instructions: import.jekyllrb.com/docs/wordpress But when I follow those instructions including sucessfully installing "gem install unidecode sequel mysql2 htmlentities" into /Library/Ruby/Gems/2.0.0/gems/mysql2-0.4.5 like this: ruby -rubygems -e 'require "jekyll-import"; > JekyllImport::Importers::WordPress.run({ > "dbname" => "database_name", > "user" => "user_name", > "password" => "mypassword", > "host" => "localhost", > "socket" => "", > "table_prefix" => "wp_", > "site_prefix" => “utf8”, > "clean_entities" => true, > "comments" => false, > "categories" => true, > "tags" => true, > "more_excerpt" => true, > "more_anchor" => true, > "extension" => "html", > "status" => ["publish"] > })' I get this Load Error: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- jekyll-import (LoadError) from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require' from -e:1:in `<main>' Is this because my gems are in the wrong place or I installed something incorrectly? My locations: gem: /usr/bin/gem ruby: /usr/bin/ruby jekyll: /usr/local/bin/jekyll RubyGems Environment: - RUBYGEMS VERSION: 2.0.14.1 - RUBY VERSION: 2.0.0 (2015-12-16 patchlevel 648) [universal.x86_64-darwin16] - INSTALLATION DIRECTORY: /Library/Ruby/Gems/2.0.0 - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby - EXECUTABLE DIRECTORY: /usr/local/bin - RUBYGEMS PLATFORMS: - ruby - universal-darwin-16 - GEM PATHS: - /Library/Ruby/Gems/2.0.0 - /Users/mfrost/.gem/ruby/2.0.0 - /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/gems/2.0.0 - GEM CONFIGURATION: - :update_sources => true - :verbose => true - :backtrace => false - :bulk_threshold => 1000 - REMOTE SOURCES: - https://rubygems.org/ A: It looks like your script can't load the jekyll-import gem. Be sure it's installed following the instructions here: http://import.jekyllrb.com/docs/installation/ If you hit additional errors look at the stack trace for required dependencies during the install.
{ "pile_set_name": "StackExchange" }
Q: subclassing float to force fixed point printing precision in python [Python 3.1] I'm following up on this answer: class prettyfloat(float): def __repr__(self): return "%0.2f" % self I know I need to keep track of my float literals (i.e., replace 3.0 with prettyfloat(3.0), etc.), and that's fine. But whenever I do any calculations, prettyfloat objects get converted into float. What's the easiest way to fix it? EDIT: I need exactly two decimal digits; and I need it across the whole code, including where I print a dictionary with float values inside. That makes any formatting functions hard to use. I can't use Decimal global setting, since I want computations to be at full precision (just printing at 2 decimal points). @Glenn Maynard: I agree I shouldn't override __repr__; if anything, it would be just __str__. But it's a moot point because of the following point. @Glenn Maynard and @singularity: I won't subclass float, since I agree it will look very ugly in the end. I will stop trying to be clever, and just call a function everywhere a float is being printed. Though I am really sad that I can't override __str__ in the builtin class float. Thank you! A: I had a look at the answer you followed up on, and I think you're confusing data and its representation. @Robert Rossney suggested to subclass float so you could map() an iterable of standard, non-adulterated floats into prettyfloats for display purposes: # Perform all our computations using standard floats. results = compute_huge_numbers(42) # Switch to prettyfloats for printing. print(map(prettyfloat, results)) In other words, you were not supposed to (and you shouldn't) use prettyfloat as a replacement for float everywhere in your code. Of course, inheriting from float to solve that problem is overkill, since it's a representation problem and not a data problem. A simple function would be enough: def prettyfloat(number): return "%0.2f" % number # Works the same. Now, if it's not about representation after all, and what you actually want to achieve is fixed-point computations limited to two decimal places everywhere in your code, that's another story entirely. A: that because prettyfloat (op) prettyfloat don't return a prettyfloat example: >>> prettyfloat(0.6) 0.60 # type prettyfloat >>> prettyfloat(0.6) + prettyfloat(4.4) 5.0 # type float solution if you don't want to cast every operation result manually to prettyfloat and if you still want to use prettyfloat is to override all operators. example with operator __add__ (which is ugly) class prettyfloat(float): def __repr__(self): return "%0.2f" % self def __add__(self, other): return prettyfloat(float(self) + other) >>> prettyfloat(0.6) + prettyfloat(4.4) 5.00 by doing this i think you will have also to change the name from prettyfloat to uglyfloat :) , Hope this will help
{ "pile_set_name": "StackExchange" }
Q: Get exactly the same image sizes horizontally and vertically (Special case) I want to create a special image gallery. All images should have the same size, but some are in portrait format, and some are in landscape format. Example: If the landscape format image is 500px wide and 300px high, the portrait format image should be 300px wide and 500px high. But the layout shouldn't be based on pixel values, and also not on vw or vh. In the last hours, I tried to get the correct dimensions with percentage adjustments. But it's always a bit different in different browsers and browser sizes. What I need: The (flexible) height of .vertical should be the width of .image. So it should impact the same pixel value. Is that possible with CSS? Or maybe with jQuery? Ah, and it's important to keep this width: calc(50% - 28px);. Would be very thankful for help! .image-gallery { width: 70%; display: flex; flex-direction: column; flex-wrap: nowrap; align-items: center; align-content: flex-start; background: darkgrey; } .image { width: calc(50% - 28px); margin: 20px; } .vertical { width: calc(72.3% - 28px); /* Instead of this, I need here the (flexible) height of ".image" */ } img { width: 100%; float: left; } <div class="image-gallery"> <div class="image"> <img src="https://cassandraladru.com/wp-content/uploads/2018/03/AnnieRob_FINALS-434.jpg" /> </div> <div class="image vertical"> <img src="https://cassandraladru.com/wp-content/uploads/2018/03/AnnieRob_SP-43-1616x1080.jpg" /> </div> </div> A: Please try the following code. .image-gallery { width: 70vw; display: flex; flex-direction: column; flex-wrap: nowrap; align-items: center; align-content: flex-start; background: darkgrey; } .image { width: calc(50% - 28px); margin: 20px; } .vertical { width: auto; } img { width: 100%; float: left; } .vertical img{ max-height: 100%; width: auto; } Since all images will have same size, vertical image will have width of image as height. According to your css, normal image (portrait image) will have (35vw - 28px) width because .image-gallery has 70vw width. So vertical image will have 35vw-28px as height. Please try my code and if you have any question, please comment me. UPDATE Added jQuery code. <script> $(window).resize(function(){ $('.vertical').height($('.image:not(.vertical)').width()); }).trigger('resize'); </script>
{ "pile_set_name": "StackExchange" }
Q: Can 128bit/64bit hardware unsigned division be faster in some cases than 64bit/32bit division on x86-64 Intel/AMD CPUs? Can a scaled 64bit/32bit division performed by the hardware 128bit/64bit division instruction, such as: ; Entry arguments: Dividend in EAX, Divisor in EBX shl rax, 32 ;Scale up the Dividend by 2^32 xor rdx,rdx and rbx, 0xFFFFFFFF ;Clear any garbage that might have been in the upper half of RBX div rbx ; RAX = RDX:RAX / RBX ...be faster in some special cases than the scaled 64bit/32bit division performed by the hardware 64bit/32bit division instruction, such as: ; Entry arguments: Dividend in EAX, Divisor in EBX mov edx,eax ;Scale up the Dividend by 2^32 xor eax,eax div ebx ; EAX = EDX:EAX / EBX By "some special cases" I mean unusual dividends and divisors. I am interested in comparing the div instruction only. A: You're asking about optimizing uint64_t / uint64_t C division to a 64b / 32b => 32b x86 asm division, when the divisor is known to be 32-bit. The compiler must of course avoid the possibility of a #DE exception on a perfectly valid (in C) 64-bit division, otherwise it wouldn't have followed the as-if rule. So it can only do this if it's provable that the quotient will fit in 32 bits. Yes, that's a win or at least break-even. On some CPUs it's even worth checking for the possibility at runtime because 64-bit division is so much slower. But unfortunately current x86 compilers don't have an optimizer pass to look for this optimization even when you do manage to give them enough info that they could prove it's safe. e.g. if (edx >= ebx) __builtin_unreachable(); doesn't help last time I tried. For the same inputs, 32-bit operand-size will always be at least as fast 16 or 8-bit could maybe be slower than 32 because they may have a false dependency writing their output, but writing a 32-bit register zero-extends to 64 to avoid that. (That's why mov ecx, ebx is a good way to zero-extend ebx to 64-bit, better than and a value that's not encodeable as a 32-bit sign-extended immediate, like harold pointed out). But other than partial-register shenanigans, 16-bit and 8-bit division are generally also as fast as 32-bit, or not worse. On AMD CPUs, division performance doesn't depend on operand-size, just the data. 0 / 1 with 128/64-bit should be faster than worst-case of any smaller operand-size. AMD's integer-division instruction is only a 2 uops (presumably because it has to write 2 registers), with all the logic done in the execution unit. 16-bit / 8-bit => 8-bit division on Ryzen is a single uop (because it only has to write AH:AL = AX). On Intel CPUs, div/idiv is microcoded as many uops. About the same number of uops for all operand-sizes up to 32-bit (Skylake = 10), but 64-bit is much much slower. (Skylake div r64 is 36 uops, Skylake idiv r64 is 57 uops). See Agner Fog's instruction tables: https://agner.org/optimize/ div/idiv throughput for operand-sizes up to 32-bit is fixed at 1 per 6 cycles on Skylake. But div/idiv r64 throughput is one per 24-90 cycles. See also Trial-division code runs 2x faster as 32-bit on Windows than 64-bit on Linux for a specific performance experiment where modifying the REX.W prefix in an existing binary to change div r64 into div r32 made a factor of ~3 difference in throughput. And Why does Clang do this optimization trick only from Sandy Bridge onward? shows clang opportunistically using 32-bit division when the dividend is small, when tuning for Intel CPUs. But you have a large dividend and a large-enough divisor, which is a more complex case. That clang optimization is still zeroing the upper half of the dividend in asm, never using a non-zero or non-sign-extended EDX. I have failed to make the popular C compilers generate the latter code when dividing an unsigned 32-bit integer (shifted left 32 bits) by another 32-bit integer. I'm assuming you cast that 32-bit integer to uint64_t first, to avoid UB and get a normal uint64_t / uint64_t in the C abstract machine. That makes sense: Your way wouldn't be safe, it will fault with #DE when edx >= ebx. x86 division faults when the quotient overflows AL / AX / EAX / RAX, instead of silently truncating. There's no way to disable that. So compilers normally only use idiv after cdq or cqo, and div only after zeroing the high half, unless you use an intrinsic or inline asm to open yourself up to the possibility of your code faulting. In C, x / y only faults if y = 0 (or for signed, INT_MIN / -1 is also allowed to fault1). GNU C doesn't have an intrinsic for wide division, but MSVC has _udiv64. (With gcc/clang, division wider than 1 register uses a helper function which does try to optimize for small inputs. But this doesn't help for 64/32 division on a 64-bit machine, where GCC and clang just use the 128/64-bit division instruction.) Even if there were some way to promise the compiler that your divisor would be big enough to make the quotient fit in 32 bits, current gcc and clang don't look for that optimization in my experience. It would be a useful optimization for your case (if it's always safe), but compilers won't look for it. Footnote 1: To be more specific, ISO C describes those cases as "undefined behaviour"; some ISAs like ARM have non-faulting division instructions. C UB means anything can happen, including just truncation to 0 or some other integer result. See Why does integer division by -1 (negative one) result in FPE? for an example of AArch64 vs. x86 code-gen and results. Allowed to fault doesn't mean required to fault.
{ "pile_set_name": "StackExchange" }
Q: Display and grab the value listed in the DropDownList My COntroller class; in the following example returnAllHuman(); will return List<SelectListItem> public ActionResult Index() { var list = returnAllHuman(); // List<SelectListItem> ViewData["all_Human"] = list; return View(); } In the View @Html.DropDownList("all_Human") 1.) The values don't get displayed 2.) I need to grab the selected value and display it in a text field. How can i do this ? UPDATE: I removed the exception handling part from the below code public List<SelectListItem> returnAllHuman() { var i = new List<SelectListItem>(); using (SqlCommand com = new SqlCommand("SELECT * FROM Names", con)) { con.Open(); SqlDataReader s = com.ExecuteReader(); while (s.Read()) { i.Add(new SelectListItem { Value = s.GetString(0), Text = s.GetString(1) }); } con.Close(); return i; } A: Start by defining a view model: public class MyViewModel { [Required] public string SelectedHuman { get; set; } public IEnumerable<SelectListItem> AllHumans { get; set; } } and then have your controller populate this model and pass to the view: public class HomeController: Controller { public ActionResult Index() { var model = new MyViewModel(); model.AllHumans = returnAllHuman(); // List<SelectListItem> return View(model); } [HttpPost] public ActionResult Index(MyViewModel model) { if (!ModelState.IsValid) { // there was a validation error => for example the user didn't make // any selection => rebind the AllHumans property and redisplay the view model.AllHumans = returnAllHuman(); return View(model); } // at this stage we know that the model is valid and model.SelectedHuman // will contain the selected value // => we could do some processing here with it return Content(string.Format("Thanks for selecting: {0}", model.SelectedHuman)); } } and then in your strongly typed view: @model MyViewModel @using (Html.BeginForm()) { @Html.DropDownListFor(x => x.SelectedHuman, Model.AllHumans, "-- Select --") @Html.ValidationFor(x => x.SelectedHuman) <button type="submit">OK</button> }
{ "pile_set_name": "StackExchange" }
Q: Redirect contact page to the same page and add message too I use magento 1.9.x version, I add a new contact form in product view page, but after I press Submit button the magento is redirect me to the Contact page how I can stop this redirect and remain in the same page. I try to put this code in contact controller Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.')); if(Mage::helper('core/http')->getHttpReferer(true)){ $this->_redirectUrl(Mage::helper('core/http')->getHttpReferer(true)); } else{ $this->_redirect('*/*/'); } is work is stay in the same page but I don't see that success message: "Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us." How I can add that message too? A: Make sure you have put global_messages block on your page. <?php echo $this->getChildHtml('global_messages') ?> Also try with below code. Mage::getSingleton('core/session')->addSuccess( Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
{ "pile_set_name": "StackExchange" }
Q: mac/ios setting up webrtc from the command line and creating a .bash_profile I am trying to implement webrtc in a native ios app. I am following this tutorial http://ninjanetic.com/how-to-get-started-with-webrtc-and-ios-without-wasting-10-hours-of-your-life/ The tutorial starts from using the command line and creating a file .bash_profile Step 2 states 2) Download the Chromium depot tools Switch into your working directory and grab the Chromium depot_tools repository with git: git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git These are a bunch of tools used during the build process, and they will need to be in your path so you will need to modify your .bash_profile (or other shell file) and modify the PATH line like so: export PATH=/a_bunch_of_stuff:/working_directory/depot_tools:$PATH I am a little confused as what to put into the .bash_profile, what goes inside of /a_bunch_of_stuff:/, and is there anything else I should be adding to this .bash_profile? A: You are just adding one more location to the $PATH. /a_bunch_of_stuff:/ just means all the stuff that is already in your $PATH. The one new location you are adding is the location of your depot_tools.
{ "pile_set_name": "StackExchange" }
Q: Why is this lua gsub not working? I have some lua code that is part of a rest api. I'm extending it to handle redirects. However, I'm having trouble with a gsub. msg=POST /v2/keys/message?recursive=true&value=hello%20world HTTP/1.1 Host: 172.17.8.101:4001 Content-Length: 0 Accept: */*, application/json, application/x-www-form-urlencoded, text/plain I want to replace path = "blabla" msg = msg:gsub("^%w* ([^\r\n]*)\r\n.*", path .. " HTTP/1.1") So that the result is: msg=POST blabla HTTP/1.1 Host: 172.17.8.101:4001 Content-Length: 0 Accept: */*, application/json, application/x-www-form-urlencoded, text/plain But everything I've tried didn't match and didn't replace. I think I just fundamentally misunderstand how lua gsub and it's pattern matching works. What's wrong with the gsub? A: For starters you are over-matching. You don't need to match the entire string with your pattern. Just the bits you want to modify. Is msg= part of the string or a variable assignment? I'm going to assume that's a variable assignment (especially given msg = msg:gsub(...). Given that try: msg = msg:gsub("^(%w*%s*)([^%s]*)", "%1"..path)
{ "pile_set_name": "StackExchange" }
Q: Hiding the navbar toggle button for large and medium scale device I am trying to develop a responsive website using bootstrap, in which I am designing a navbar which contains a toggle button that should only show up when the browser is squeezed to -sm scale device. I tried to hide it by giving my button a class as visible-sm, it didn't work. The toggle button is always visible no matter whatever be the screen size, I want this button only to be visible in small screen size. <button class="navbar-toggler visible-sm" data-toggle="collapse" data-target="#navbarMenu"> <span class="navbar-toggler-icon"></span> </button> my jfiddle link: https://jsfiddle.net/t1yodsxf/ A: To show the button only on sm screen size you can use the classes d-none d-sm-block d-md-none. The button is now only visible on sm screen size, not on smaller (xs) or larger (>= md) screen sizes: <button class="navbar-toggler d-none d-sm-block d-md-none" data-toggle="collapse" data-target="#navbarMenu"> <span class="navbar-toggler-icon"></span> </button> To show the button only on the xs screen size you can use the classes d-block d-sm-none: <button class="navbar-toggler d-block d-sm-none" data-toggle="collapse" data-target="#navbarMenu"> <span class="navbar-toggler-icon"></span> </button> The visible-sm class is not available on Bootstrap. There is only a visible and invisible class to set the visibility of an element.
{ "pile_set_name": "StackExchange" }
Q: How to return object of the protocol in the method I would like to return an object of the protocol in the method. Any quicker way to achieve this? Thanks. #import "OverlayView.h" @protocol ErrorOverlayDelegate <NSObject> - (void)errorOverlayOKButtonAction:(UIButton*)sender; @end @interface ErrorOverlay : UIView @property (nonatomic, weak) id<ErrorOverlayDelegate> delegate; @end A: Just add one more parameter to your method, preferably the first argument, like the example below: - (void)errorOverlay:(ErrorOverlay *)overlay OKButtonAction:(UIButton *)sender; Then pass self as the argument.
{ "pile_set_name": "StackExchange" }
Q: Dynamic expandable and collapsed table view cells? I developed expandable and collapsed table view for dynamic data comes from the server. I'm displaying state names in header view successfully, but I can't displaying child data that is districts related to state names. I followed Link for this http://www.iostute.com/2015/04/expandable-and-collapsable-tableview.html My data is _response = @{@"Response":@{@"status":@"SUCCESS",@"error_code":@"0",@"message":@"SUCCESS",@"Array":@[ @{@"state_id":@"0",@"state_name":@"null",@"district_id":@"0",@"district_name":@"null"}, @{@"state_id":@"01",@"state_name":@"State1",@"district_id":@"001",@"district_name":@"State1District1"}, @{@"state_id":@"02",@"state_name":@"State2",@"district_id":@"004",@"district_name":@"State2District1"}, @{@"state_id":@"02",@"state_name":@"State2",@"district_id":@"005",@"district_name":@"State3District1"}, @{@"state_id":@"01",@"state_name":@"State1",@"district_id":@"002",@"district_name":@"State1District2"}, @{@"state_id":@"01",@"state_name":@"State1",@"district_id":@"003",@"district_name":@"State1District3"}, @{@"state_id":@"03",@"state_name":@"State3",@"district_id":@"006",@"district_name":@"State3District1"}, @{@"state_id":@"04",@"state_name":@"State4",@"district_id":@"008",@"district_name":@"State4District1"}, @{@"state_id":@"04",@"state_name":@"State4",@"district_id":@"009",@"district_name":@"State4District2"}, @{@"state_id":@"04",@"state_name":@"State4",@"district_id":@"010",@"district_name":@"State4District3"}, @{@"state_id":@"05",@"state_name":@"State5",@"district_id":@"011",@"district_name":@"State5District1"}, @{@"state_id":@"05",@"state_name":@"State5",@"district_id":@"012",@"district_name":@"State5District2"}, @{@"state_id":@"03",@"state_name":@"State3",@"district_id":@"007",@"district_name":@"State3District2"}]}, @"count":@"6"}; My code is if ([[[_response objectForKey:@"Response"] objectForKey:@"status"] isEqualToString:@"SUCCESS"] && (!(_integer == 0))) { _stateID = [[NSMutableArray alloc] init]; _stateName = [[NSMutableArray alloc] init]; _districtID = [[NSMutableArray alloc] init]; _districtName = [[NSMutableArray alloc] init]; _stateIdStateNameDic = [[NSMutableDictionary alloc]init]; //Add arrays to array to remove null values dynamically NSArray *arr = [[NSArray alloc]initWithObjects:_stateID, _stateName, _districtID, _districtName, nil]; for (int i=0; i<_integer; i++) { [_stateID addObject:[[[[_response objectForKey:@"Response"] objectForKey:@"Array"] objectAtIndex:i] objectForKey:@"state_id"]]; [_stateName addObject:[[[[_response objectForKey:@"Response"] objectForKey:@"Array"] objectAtIndex:i] objectForKey:@"state_name"]]; [_districtID addObject:[[[[_response objectForKey:@"Response"] objectForKey:@"Array"] objectAtIndex:i] objectForKey:@"district_id"]]; [_districtName addObject:[[[[_response objectForKey:@"Response"] objectForKey:@"Array"] objectAtIndex:i] objectForKey:@"district_name"]]; //Remove null values for (int j=0; j<arr.count; j++) { for (NSMutableArray *ar in arr) { if ([[ar objectAtIndex:i] isKindOfClass:[NSNull class]] || [[ar objectAtIndex:i] isEqualToString:@"null"] || [[ar objectAtIndex:i] isEqualToString:@"0"]) { [ar addObject:@""]; [ar removeObjectAtIndex:i]; } } } } //Add arrays to mutable array to remove empty objects NSMutableArray *marr = [[NSMutableArray alloc]initWithObjects:_stateID, _stateName, _districtID, _districtName, nil]; //Remove empty objects from all arrays for (int j=0; j<marr.count; j++) { for (int i=0; i<[[marr objectAtIndex:j] count]; i++) { if ([[[marr objectAtIndex:j] objectAtIndex:i] isEqualToString:@""]) { [[marr objectAtIndex:j] removeObjectAtIndex:i]; } } } //Remove duplicates from state names array _stateName = [_stateName valueForKeyPath:@"@distinctUnionOfObjects.self"]; NSString *districtName = @""; NSString * superater = @"&&"; _mdic = [[NSMutableDictionary alloc]init]; for (int j=0; j<_stateName.count; j++) { for (int i=0; i<_integer; i++) { if ([[_stateName objectAtIndex:j] isEqualToString:[[[[_response objectForKey:@"Response"] objectForKey:@"Array"] objectAtIndex:i] objectForKey:@"state_name"]]) { //Remove district name if empty or null if ([districtName isEqualToString:@""] || [districtName isEqual:[NSNull null]]) { districtName = [[[[_response objectForKey:@"Response"] objectForKey:@"Array"] objectAtIndex:i] objectForKey:@"district_name"]; if ([districtName isEqual:[NSNull null]] || [districtName isEqualToString:@"null"]) { districtName = @""; } } else { //Add all districts with superater && districtName = [districtName stringByAppendingString:[NSString stringWithFormat:@"%@%@", superater, [[[[_response objectForKey:@"Response"] objectForKey:@"Array"] objectAtIndex:i] objectForKey:@"district_name"]]]; } } } //Create district names dictionary with state name keys [_mdic setValue:districtName forKey:[_stateName objectAtIndex:j]]; districtName = @""; } NSLog(@"_mdic %@", _mdic); _arrayForBool=[[NSMutableArray alloc]init]; //Save bool value " NO " based on sectionTitleArray count. for (int i=0; i<[_stateName count]; i++) { [_arrayForBool addObject:[NSNumber numberWithBool:NO]]; } dispatch_async(dispatch_get_main_queue(), ^{ [_availableOrdersTableView reloadData]; }); } else { } // TableView delegates - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [_mdic count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Number of rows in each section if ([[_arrayForBool objectAtIndex:section] boolValue]) { NSLog(@"%@", [_stateName objectAtIndex:section]); NSLog(@"%@", _mdic); NSArray *mdicKeys = [_mdic allKeys]; for (int i=0; i<_mdic.count; i++) { if ([[mdicKeys objectAtIndex:i] isEqualToString:[_stateName objectAtIndex:section]]) { NSString *str = [_mdic objectForKey:[_stateName objectAtIndex:section]]; NSLog(@"%@", str); _subDistrictArr = [str componentsSeparatedByString:@"&&"]; } } NSLog(@"_subDistrictIDArr %@", _subDistrictArr); return _subDistrictArr.count; } else { return 0; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //Create cell static NSString *cellid=@"cell"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellid]; if (cell==nil) { cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid]; } BOOL manyCells = [[_arrayForBool objectAtIndex:indexPath.section] boolValue]; /********** If the section supposed to be closed *******************/ if(!manyCells) { cell.backgroundColor=[UIColor clearColor]; cell.textLabel.text=@""; } /********** If the section supposed to be Opened *******************/ else { cell.textLabel.text=[_subDistrictArr objectAtIndex:indexPath.row]; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { cell.textLabel.font=[UIFont systemFontOfSize:20.0f]; } else { cell.textLabel.font=[UIFont systemFontOfSize:15.0f]; } cell.backgroundColor=[UIColor whiteColor]; cell.selectionStyle=UITableViewCellSelectionStyleNone ; } cell.textLabel.textColor=[UIColor blackColor]; /********** Add a custom Separator with cell *******************/ UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(15, 48, _availableOrdersTableView.frame.size.width-15, 1)]; separatorLineView.backgroundColor = [UIColor blackColor]; [cell.contentView addSubview:separatorLineView]; return cell; } - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *sectionView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, _availableOrdersTableView.frame.size.width, 50)]; sectionView.backgroundColor = [UIColor clearColor]; sectionView.tag=section; UILabel *viewLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, _availableOrdersTableView.frame.size.width, sectionView.frame.size.height)]; viewLabel.backgroundColor=[UIColor clearColor]; viewLabel.textColor=[UIColor blackColor]; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { viewLabel.font=[UIFont systemFontOfSize:25]; } else { viewLabel.font=[UIFont systemFontOfSize:15]; } viewLabel.text=[NSString stringWithFormat:@"%@", [_stateName objectAtIndex:section]]; _stateIDString = [_stateID objectAtIndex:section]; NSLog(@"stateIDString %@", _stateIDString); [sectionView addSubview:viewLabel]; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(sectionView.frame.size.width-45, (sectionView.frame.size.height-25)/2, 18, 17)]; imgView.tag = section; imgView.image = [UIImage imageNamed:@"DA"]; [sectionView addSubview:imgView]; } else { UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(sectionView.frame.size.width-35, (sectionView.frame.size.height-25)/2, 18, 17)]; imgView.tag = section; imgView.image = [UIImage imageNamed:@"DA"]; [sectionView addSubview:imgView]; } /********** Add a custom Separator with Section view *******************/ UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, sectionView.frame.size.height, _availableOrdersTableView.frame.size.width, 1)]; separatorLineView.backgroundColor = [UIColor blackColor]; [sectionView addSubview:separatorLineView]; /********** Add UITapGestureRecognizer to SectionView **************/ UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionHeaderTapped:)]; [sectionView addGestureRecognizer:headerTapped]; return sectionView; } - (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer { NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag]; // _gestureInteger = gestureRecognizer.view.tag; if (indexPath.row == 0) { BOOL collapsed = [[_arrayForBool objectAtIndex:indexPath.section] boolValue]; for (int i=0; i<[_stateName count]; i++) { if (indexPath.section==i) { [_arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:!collapsed]]; } } [_availableOrdersTableView reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic]; // [_availableOrdersTableView reloadData]; } } A: I have two solution for this (1) initially you put numberofrow for any section is zero and after click on any section you can add row for for clicked section. (2) number of section will be one and you need to use two cell "cellwithheaderonly" and "cellwithheaderandsubpart" initially you will use "cellwithheaderonly" and when user will click on any cell you need to use "cellwithheaderandsubpart" You can take reference from following URL Expanding and Collapsing table view cells in ios https://www.anexinet.com/blog/expandable-collapsible-uitableview-sections/
{ "pile_set_name": "StackExchange" }
Q: AngularJS to Rails MassAssignmentSecurity::Error Whilst using AngularJS with Rails I keep getting the MassAssignmentSecurity error whilst updating. I know this is due to passing attributes such as 'created_at' and 'updated_at' along with the data. To get around this I've been contructing some json which just passes the attributes in the form. This does create more maintenance through the whole program. Is there a better way to do this? Here is an example: AngularJS $scope.contruct_json = -> { name: $scope.client.name surname: $scope.client.surname } # -------------------------------------------------------------------------------- # Update # -------------------------------------------------------------------------------- $scope.update = -> Client.update id: $stateParams['id'] , client: $scope.contruct_json() , (response) -> $location.path "/clients/#{$stateParams['id']}" Update Changed my AngularJS code to this # Remove keys from hash to make it acceptable for Rails to update $scope.remove_keys = (hash) -> new_hash = {} angular.forEach(hash, (value,key) -> if(key!='id' && key!='created_at' && key!='updated_at') new_hash[key]=value , new_hash) return new_hash # -------------------------------------------------------------------------------- # Update # -------------------------------------------------------------------------------- $scope.update = -> Client.update id: $stateParams['id'] , client: $scope.remove_keys($scope.client) , (response) -> $location.path "/clients/#{$stateParams['id']}" A: maybe you should consider allowing mass assignment for the attributes on your Client model with attr_accessible ?
{ "pile_set_name": "StackExchange" }
Q: Extrair dados de um array em javascript Tenho um array, e em seus índices tem um valor serializado. Gostaria de separar esses valores e colocar cada valor em um outro array (com índices devidamente separados). Segue meu código: data = ["["RibS7K/JS+ZTYtjDxqh5hg==","lO/CWn5lb3eqCkDhm9PpwA=="]", "["teste a","teste b"]", "[24351,24352]", "["png","png"]", "["teste a","teste b"]", "[7,6]", "[107.0,99.0]"] newObject.idCrip = data[0]; Quando vou colocar em newObject.idCrip recebe data[0], ele fica com ["RibS7K/JS+ZTYtjDxqh5hg==","lO/CWn5lb3eqCkDhm9PpwA=="] e não com dois valores separados e isto está me atrapalhando. Alguma solução? A: Não posso afirmar com certeza porque o código que você postou é inválido (falta escapar várias aspas), mas imagino que você esteja atrás disto aqui: newObject.idCrip = JSON.parse(data[0]); Isso funciona se você tem aquela primeira array como string dentro da array de fora. Faltou converter para objeto. Demonstração
{ "pile_set_name": "StackExchange" }
Q: Можно ли реализовать будильник который сработал бы даже если девайс выключен? Возможно ли это, если да то как? Я не смог найти примеров в интернете. У меня уже есть будильник, который работает после перезагрузки устройства но не в то время, когда девайс выключен. A: Некоторые android-устройства могут включаться самостоятельно по будильнику. Например, у Huawei это реализовано, но такую функцию должен реализовать производитель на аппаратном уровне и уровне драйверов системы. Программно, на любом android-устройстве, сторонним разработчиком, реализовать такое невозможно. Если производителем данная функция поддерживается, то устройство будет включаться по будильнику из полностью выключенного состояния без дополнительных действий со стороны стороннего разработчика, как и в случае с включенным устройством, если не поддерживается - повлиять на это сторонний разработчик никак не может.
{ "pile_set_name": "StackExchange" }
Q: Retrieve data based on categories in Firebase I'm new with Firebase and I have a question about retrieving some data. Lets say I'm having the following data structure: The goal of my query is for a given country name I want to retrieve all the users that their destinations array contain this country. For example: for the query of "Jordan" it will retrieve: user2 and user3. Anybody know how can I do such a query with Firbase Angular? A: Firebase doesn't have a query operator that matches items in an array. In fact: Firebase recommends against using arrays for situations like the one you have. Instead, store the data like this: advisors-countries: { user1: { destinations: { Angola: true, Australia: true } }, user2: { destinations: { Angola: true, Austria: true, Jordan: true } }, user3: { destinations: { Austria: true Egypt: true, Jordan: true } } } Now you can query users that have destination Jordan with: var users = ref.child('advisors-countries').orderByChild('destinations/Jordan') .equalTo(true); And then bind this to your AngularJS scope with: $scope.users = $firebaseArray(users); This type of data structure is called an index and you'll often find you need to add specific indexes to your NoSQL database to fit the querying requirements of your app. See this article on NoSQL data modeling for a good introduction on the topic.
{ "pile_set_name": "StackExchange" }
Q: How to customize Collections.sort() to sort strings in order of their numerical prefix I have a List<String> containing below values: [1h, 0h, 2h, 10h, 4h, 9h, 3h, 7h, 8h, 6h, 5h] When I sort it using Collections.sort(), the order becomes: [0h, 10h, 1h, 2h, 3h, 4h, 5h, 6h, 7h, 8h, 9h] Instead, it should be: [0h, 1h, 2h, 3h, 4h, 5h, 6h, 7h, 8h, 9h, 10h] How can I achieve this? A: The output you quoted in your question is normal. If you look at the API description of Collection.sort you'll see: Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list). By natural ordering they mean the ordering specified by their compareTo-method (the interface Comparable only has the method compareTo) which tells wether the this-object is is greater (return strict positive integer), or are equal (return 0), less(return strict negative integer) than the object passed as an argument in the ordering. To know if an object a should get before object b, it just calls a.compareTo(b). If it's result is strict positive (> 0) the sort method will set a after b in the sorted array. If it's result is strict negative (< 0) the sort method will set a before b in the sorted array. If it's result is 0 the sort method won't change the order they are in. I would refer to the API of the compareTo method in the String class, it is explained in detail there how strings are ordered and what the method returns. What it does is just iterating character per character over each string and compare the characters at the same position untill a difference is found. If at that difference, the character of the this-string has a higher Unicode value, it will return a strict positive integer (the this stringer is greater) else it will return a strict negative integer (the this-string is lower than the argument). If no difference can be found it will return 0 (the this-string and the argument have same "order value"). Now the problem in your case(and for many people who order strings for the first time) is that integers can't be ordered with that Unicode-ordering because it goes character per character. If it has to sort String s1 = "19" and String s2 = "1119" it will call s1.compareTo(s2). The first difference is at the second character s1 has 9 and s2 has 1 at that position. Since 1 comes before 9 in the Unicode-table (1 has value hexadecimal value 31 and 9 has hexadecimal value 39), s1.compareTo(s2) will return a strict positive integer (see the link to the API to see which value). Thus it will put s2 before s1 in the sorted array even if 1119 > 19! So now you know why it sorts like that, let's see what solutions we have: Map your array-elements to the decimal value of their begin-part using the Integer.parseInt method, sort these decimal values and map the resulting sorted arrays back to your original elements. I wouldn't really recommand this solution because of the extra collections and the extra code due to the mapping. Create your own Comparator-object, specify in there how you want your strings to be ordered (for example using the Integer.parseInt method) and pass it as argument to the Collections.sort method. By passing it as an argument, you tell the sort methode to use your Comparator-object instead of the classic compareTo methode. This link shows how a Comparator is used to sort an array. It's quite the same as using it to sort an arraylist. Hope it helps! Good luck
{ "pile_set_name": "StackExchange" }
Q: import error while using python and Django I am making a website using the django api. Problem is I am getting a weird import error. I have a function in a file which calls another function in another file which in turn calls back a third function in the first file. Problem is during that third function. When I try to import it I get an error cannot import deletefromS3. A full stack trace is given below http://dpaste.com/1288190/ Here are the snippets of the two modules: topichandler.py: from sdbhandler.mediahandler import deleteMediaParent def deletefromS3(itemid,folder): itemid=folder+itemid bucket = connect_s3() for key in bucket: fname=key.split(".")[0] if(fname==itemid): bucket.delete_key(key) return [] def deleteTopic(itemid,parentId='NULL'): sdb=connect() domain= sdb.get_domain(DOMAIN) rootitem = domain.get_item(itemid) if(parentId=='NULL'): query= 'select * from ' + DOMAIN + ' where itemName()="'+itemid+'"' rs = domain.select(query) else: rs = [rootitem] for item in rs: deleteMediaParent(item.name) deletefromS3(item.name,'topicsK2/') domain.delete_attributes(item.name) deleteMediaParent(rootitem.name) deletefromS3(rootitem.name,'topicsK2/') domain.delete_attributes(rootitem.name) mediahandler.py: from sdbhandler.topichandler import deletefromS3 def deleteMediaParent(parentid): sdb=connect() domain = sdb.get_domain(DOMAIN) query = 'select * from '+ DOMAIN + 'where ' +FIELD_TopicID + ' = "' + parentid + '"' rs = domain.select(query) for item in rs: deleteQuestionParent(item.name) deletefromS3(item.name,'mediaK2/') domain.delete_attributes(item.name) There are more dependencies but I cannot post my whole code that would be way too much. Can I not import from the file from which a method was called? A: The import is impossible because a module has to finish loading before things can be imported from it. When the topichandler module loads, it tries to import deleteMediaParent from mediahandler. But mediahandler tries to import deletefromS3 from topichandler, which triggers another attempt to load topichandler. Python catches the infinite loop that’s about to happen and raises an error instead. Let’s look at this with a simpler example. Here is foo.py: #!/usr/bin/env python2.7 x = 3 from bar import y print x, y and here is bar.py: from foo import x y = x This gives the same error you got, for the same reason. Although the best solution is probably to restructure your code into more coherent standalone modules, there is a workaround. You can delay the import by moving it into a function, as in: #!/usr/bin/env python2.7 x = 3 from bar import y print x, y() bar.py: def y(): from foo import x return x Note that if you run this the print will actually be imported twice… again, you probably are better off moving related functions into the same module.
{ "pile_set_name": "StackExchange" }
Q: Does HTTPS Everywhere defend me against sslsniff-like attacks? http://www.thoughtcrime.org/software/sslsniff/ If I have a domain on my HTTPS Everywhere list, so that theoretically it could be only visited via an HTTPS connection in my Firefox, then could an sslsniff attack be successful against me? Could the attacker get information because the sslsniff degraded the connection from HTTPS to HTTP? Or I am "fully safe" from these kind of attacks when using HTTPS Everywhere? UPDATE: and what happens if I have the domain whitelisted in HTTPS Everywhere? [xml files could be created]. So the domain would be only available via HTTPS. A: The short answer is: No, not always. I have studied this topic in depth and please read this entire post before forming a conclusion. SSLSniff is a proof of concept exploitation platform to leverage flaws in the PKI, such as vulnerabilities in OCSP or the (ingenious) null-prefix certificate attack. If you are using a fully patched system, and you understand what an SSL error means then you are immune to MOST (but not all) of these attacks without the need for HTTPS Everywhere. If you are not patched against the null-prefix certificate attack then the certificate will appear valid and HTTPS everywhere will be useless. If you don't understand what an SSL error means, then HTTPS Everywhere is useless against SSLSniff. What I think is more concerning than SSLSniff is SSLStrip, which is also written by Moxie Marlinspike and introduced in his talk New Tricks For Defeating SSL In Practice. This tool won't cause ssl errors. This is exploiting, HTTP/HTTPS the application layer. If you load a page over HTTP, it will rewrite the page removing HTTPS links. It will go a step further and change the favicon.ico file to a picture of a lock, to fool novice users. Simple enough, but absolutely devastating consequences. In response to this attack Google introduced the Strict Transport Layer Security (STS), which is a lot like HTTPS Everywhere but built into the browser. It should also be noted that HTTPS Everywhere is really good an defending against the SSLStrip attack. In fact this is the EFF's solution to attacks like SSL strip as well as careless OWASP a9 - Insufficient Transport Layer Protection violations. So when does HTTPS Everywhere AND STS fail? How about https://stackoverflow.com. If you notice, they are using a self signed certificate. Jeff Atwood himself doesn't care about this issue. Because this website is using a self signed certificate, HTTP Everywhere will forcibly use HTTPS, but the attacker can still use SSLSniff to deliver their own self signed certificate and therefore HTTPS Everywhere would fail to protect someone from hijacking your StackOverflow account. Okay, so at this point you probably are saying to yourself. "Well that's why we have a PKI!". Well, except the PKI isn't perfect. One of the creators of HTTPS said "The PKI was more of a last minute handwave" (See: SSL And The Future Of Authenticity). In this talk Moxie asked a great question, is a PKI really the best solution? I mean we are having problems with CAs like DigiNotor being hacked. When a CA is hacked, then the attacker can create a valid certificate, and then HTTPS Everywhere is totally useless, an attacker can still use SSLSniff because he has a "valid" certificate. The EFF's SSL observatory demonstrates what a tangled mess the PKI system is. I mean really, what is stopping China from creating a certificate for gmail.com? Well the EFF is proposing the Sovereign Keys Project and I think it's a great idea. Besides the fact that Sovereign keys don't exist as of yet, there is another problem, Sovereign keys don't help self-signed certificates like the one being used by https://stackoverflow.com! However Moxie thought of this situation and came up with a solution that he calls Convergence. Convergence is relying upon the masses for trust. The host will be contracted from multiple connections around the planet, if any one of them sees a different self-signed certificate, then you know a MITM attack is taking place. Having a warning that something is wrong is a lot better than nothing. In summation, there are fundamental problems HTTPS Everywhere. When there is a vulnerability in software used to validate certificates. When the user doesn't understand the repercussions of an SSL failure. When a self-signed certificate is used. Then finally, when our compromised PKI is used against you. This is a serious problem and intelligent people working on fixing it, this includes the EFF and the author of SSLStrip, Moxie Marlinspike. A: "HTTPS Everywhere" is only about using SSL whenever it is possible -- i.e. automatically using the SSL version of a site if it exists, even if the link you typed or followed is for the non-SSL site of the same name. That's all "HTTPS Everywhere" does. "sslsniff" is an attack tool to hijack SSL connections. It requires two things: A way to intercept incoming and outgoing low-level traffic between the attacked client and server; sslsniff primarily relies on ARP spoofing for that, so the attacker must be on the same LAN than either the client or the server. Insertion in the client browser of a root CA that the attacker controls, or exploit of a security hole in the certificate validation code in the client browser. The SSL security model relies on the client validating the certificate with regards to its a priori known root CA certificates; sslsniff is about using a fake certificate generated on the fly, but that certificate must still be acceptable to the client. So there is really no connection between sslsniff and HTTPS Everywhere. sslsniff does not degrade HTTPS connections to HTTP; from the point of view of both the client and the server, it is still SSL all the way, and HTTPS Everywhere would feel perfectly happy with it. sslsniff is "just" a tool to leverage breaches in the certificate validation model that SSL uses to ensure security. A: ...then could an sslsniff attack be successfull against me? Yes. Could the attacker get informations because the sslsniff degraded the connection from HTTPS to HTTP? Yes. Let me add that your description does not exactly fit to how "sslsniff" works. SSLsniff acts more like a proxy intercepting SSL traffic, instead of simply degrading your connection. In other words: SSLsniff messes with the certificates more than with the HTTPS connection itself. This means your "addon" might actually think everything is fine, while in fact your connection is as unsecure as it can get and you would not know about it. Or I am "fully safe" from these kind of attacks when using HTTPS Everywhere? No. Never expect a "browser addon" to provide "system protection". To give you a human perspective: You wouldn't send boyscouts to war either, would you? Of course not, since they would not be fit and able enough to handle the job. Well, neither is a simple browser addon when it comes to SSL security. Think about it: anyone messing with your browser could mess with the addon. In a worst-case scenario, the addon could be modified to not even warn you that you've "lost" your secure ssl connection while browsing and you would not know about it. Any virus, malware or even new browser exploit would be able (depending on it's individual malicious purpose) to mess with your system... including the software on your system (which includes your web-browser and it's addons and plugins). UPDATE: and what happens if I have the domain whitelisted in HTTPS Everywhere? [xml files could be created]. So the domain would be only available via HTTPS. Getting back to your case and example: you're worrying about the HTTPS connection. Your browser might use that connection, but it can not be sure the data it's sending or receiving is not being intercepted and neither can any addon. Actually, detecting such an "interception" can already be pretty hard even when you're using "tools of the trade". Your webbrowser and all the addons out there do not provide ANY means to detect such an "attack". Not yet anyway... SSLsniff was made to show the weakness of HTTPS connections (which not only influences webbrowsers). It is yet to be seen if browser-vendors will be able to find a solid "fix" to such vulnerabilities. Especially, since it's less of a browser issue, but more of a "connection" and "network security" problem. And when you've checked http://www.thoughtcrime.org/software/sslsniff/, you'll have seen that there's already more trouble waiting for us around the corner. This is displayed by the additional functionality the SSLsniff tool has gained... just to display related problems like the one you've recently learned about and were hoping to fix by using your browser addon. Anyway, let me keep it short by repeat myself: Never expect a "browser addon" to provide "system protection". You may or may not like it, but that's the shortest answer to your question, wrapping it all up in a single line of understandable text. The rest of my rather long answer is merely some useful decoration information to provide some insights where needed.
{ "pile_set_name": "StackExchange" }
Q: Throws declarations and interface methods Here's some code from an FTP application I'm working on. The first method comes from an interface which is being triggered by a class which is monitoring server output. @Override public void responseReceived(FTPServerResponse event) { if (event.getFtpResponseCode() == 227) { try { setupPassiveConnection(event.getFullResponseString()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } It invokes the second setupPassiveConnection() which throws some Exceptions. public void setupPassiveConnection(String serverReplyString) throws UnknownHostException, IOException { String passiveInfo[] = serverReplyString.substring( serverReplyString.indexOf("(") + 1, serverReplyString.indexOf(")")).split(","); int port = (Integer.parseInt(passiveInfo[4]) * 256) + (Integer.parseInt(passiveInfo[5])); String ip = passiveInfo[0] + "." + passiveInfo[1] + "." + passiveInfo[2] + "." + passiveInfo[3]; passiveModeSocket = new Socket(ip, port); if( passiveModeSocket != null ) isPassiveMode(); } As the Exceptions can't be rethrown through the first method what would be a proper way to rewrite this? A: Do you mean that the first code block is inside a class that implements an interface that specifies responseReceived with no throws clause, so you can't rethrow? In that case, your class must store the result and provide an API via which clients can retrieve the response, i.e. a getResponseCode() method. Take a look at java.util.concurrent classes ExecutorService and Future.
{ "pile_set_name": "StackExchange" }
Q: How to Optimize the URL in R can anybody help me through the URL optimization in R. Actually I need to get multiple organization related CSV file from URL. I have to just change the one parameter in url to get that particular organization CSV table. So mainly I was writing a function to extract that. Example: data<-function("bank"){table<-read.csv(url("*://.....=string.....")} can you guide me on this. A: Is that what you are looking for? Data <- function(string){ table <- read.csv(url(paste("https://.....=", string, "...", sep=""))) # ... } # then you can change the parameter with function call # (also dynamically using apply or a loop ) Data(string="bank")
{ "pile_set_name": "StackExchange" }
Q: What names for standard website user roles? What are the standard user role names that a majority of sites could all use? Below is a list of the best roles that I could think of (in order of importance), but I am hoping to find at least ten role names for a user system I am working on. admin: Manage everything manager: Manage most aspects of the site editor: Scheduling and managing content author: Write important content contributors: Authors with limited rights moderator: Moderate user content member: Special user access subscriber: Paying Average Joe user: Average Joe Another thing that I'm interested in, is whether or not these names translate over correctly into other languages. A: Old question, answer already given, but hell, why not? critic: can rate and review content, but not create original content ambassador: site rep for external communications, has access to site email, PR materials guest: duh emeritus: retired key users who no longer contribute, but whose contributions are honored A: To get to the aspect of content production: editors: Doing some stuff beyond writing: scheduling and managing content contributors: Authors with limited rights
{ "pile_set_name": "StackExchange" }
Q: How to display error (text/html) response to an AJAX/getJSON request? My situation is, I'm developing a little web app where the server provides dynamic JSON responses. The server is built on cherrypy. Sometimes, there is a bug in the code creating the JSON data, which throws, and cherrypy catches it and serves back a 500-error with a full HTML page detailing the exception. (That is, the response has everything: <!doctype..><html><head>...</head><body>...</body></html>) But because the request is AJAX, it doesn't get displayed. I can intercept this error easily enough, and look at it in the dev tools; but what I'd like to do (to ease debugging) is open a new page (as if user had followed a link) and display that response in the browser. I tried window.open('', '_self'); $(document).html(jqXHR.responseText); but I just get a blank page. I suppose I could store the error text and serve it up in a second request to the server, but is there a cleaner way? To follow up, the final code that worked was this: .error(function(jqXHR, textStatus, errorThrown) { $(window).bind('unload', function() { document.write(jqXHR.responseText); } ); var win = window.open('', '_self'); return false; }); Not sure if that final return false is necessary but it seems good form. Following up again: the above code worked reliably in Opera. I thought I had seen it working in Webkit as well, but I started noticing that it wasn't; and on further testing, it wasn't working for Firefox either. What I found that worked in all three platforms was this: document.open('text/html', true); document.write(jqXHR.responseText); document.close(); Don't have to open another window or bind events; just re-open the document and stuff the text in there. Well, here I am again. The above technique either stopped working or I was tripping when I said it ever worked at all. Chrome, in particular, doesn't seem to have document.open defined. But! I just found a nifty technique that seems to work everywhere: errtext = 'data:text/html;base64,' + window.btoa(jqXHR.responseText); window.open(errtext, '_self'); This simply converts the response into a fully self-contained data: URL and opens it in the window. A: Try this: var win = window.open('', '_self'); win.document.getElementsByTagName('Body')[0].innerText = jqXHR.responseText;
{ "pile_set_name": "StackExchange" }
Q: Globalization in ASP.net MVC (Resource file per View vs Domain) What is the best practice for keeping Resource files when it comes to ASP.net MVC globalization ? For Example, we have order processing system if we try to keep our resource files for domain i.e order.resx, customer.resx, etc or else we could try to keep resource files per view i.e OrderProcessingView.resx, CustomerView.resx, etc Common strings such as "Add", "Edit", "Delete" can handle by using common.resx file. Or Are there any other approaches to keep the resource files ? We are using some client side rendering (Jquery templates, Kendo templates) also. A: One of the localizability best practices is to not reuse translations in different contexts. That's because you want to allow the translator to use different translations for one same piece of English text in different contexts. Why? Because different languages have different rules (e.g. depending on gender, an adjective can take a different form) and also because of context-specific constaints such as space limitations (e.g. a translator may be forced to shorten a string to make it fit somewhere, but shouldn't have to when it's not necessary). For this reason, having one .resx per view is good practice. If you had just one big .resx, it would be hard to determine what view a string goes into (and you'd also be more tempted to reuse strings in different contexts). You'll also typically need a global .resx for the application for anything that is view-independent, which should be rare.
{ "pile_set_name": "StackExchange" }
Q: Correct way to require modules to prevent eslint erroring I've recently started using eslint, and I'm finding that all my code is erroring where I have required modules, as it says that the function names aren't assigned. mymodule.js module.exports = { one: function() { console.log(1); }, two: function() { console.log(2); } } index.js require('./mymodule.js'); one(); // eslint says 'one is not defined' Should I be declaring 'one' as a variable beforehand, is that the correct way of doing it? Or is there a better way? A: I can't run your example "index.js" at all (Node 8.15) as the node interpreter itself tells me the same thing eslint is telling you ReferenceError: one is not defined. Stuff you export/import from a module doesn't magick itself into the global namespace. I'd do either of the following: A) Import the whole of mymodule const mymodule = require('./mymodule'); mymodule.one(); B) Import the fun parts of mymodule by name const { one /* , two, three, etc */ } = require('./mymodule'); one(); C) Import a single member of mymodule const one = require('./mymodule').one; one();
{ "pile_set_name": "StackExchange" }
Q: How can I set a default value for the country in an addressfield? I'm trying to set the default value for a country in an addressfield (caught in hook_form_alter) and ensure that the associated fields (administrative area, etc.) are refreshed properly. How can I do this? A: Finally figured it out. The idea is to emulate the code in addressfield_field_widget_form(). Here's the recipe: /** * Implements hook_form_FORMID_alter() for `commerce_checkout_form_checkout`. */ function mymodule_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) { // Get the addressfield element we're modifying. // Adapted from addressfield.module/addressfield_field_widget_form() $element =& $form['customer_profile_shipping']['commerce_customer_address'][LANGUAGE_NONE][0]; $element_key = $element['element_key']['#value']; $field = $form_state['field']['commerce_customer_address'][LANGUAGE_NONE]['field']; $instance = $form_state['field']['commerce_customer_address'][LANGUAGE_NONE]['instance']; $delta = $element['#delta']; $settings = $instance['widget']['settings']; $langcode = $element['#language']; $items = array($delta => $element['#address']); // Get the default address used to build the widget form elements, looking // first in the form state, then in the stored value for the field, and then // in the default values of the instance. $address = array(); if (!empty($form_state['addressfield'][$element_key])) { // Use the value from the form_state if available. $address = $form_state['addressfield'][$element_key]; } elseif (!empty($items[$delta]['country'])) { // Else use the saved value for the field. $address = $items[$delta]; } else { // Otherwise use the instance default. $address = (array) $instance['default_value'][0]; } // Merge in default values to provide a value for every expected array key. $countries = _addressfield_country_options_list($field, $instance); $address += addressfield_default_values($countries); // Set our default country. // THAT'S THE PAYLOAD! if ($address['country'] != $my_default_country) { $address['country'] = $my_default_country; $address['administrative_area'] = ''; } // Add the form elements for the standard widget, which includes a country // select list at the top that reloads the available address elements when the // country is changed. if ($instance['widget']['type'] == 'addressfield_standard') { // Generate the address form. $context = array( 'mode' => 'form', 'field' => $field, 'instance' => $instance, 'langcode' => $langcode, 'delta' => $delta, ); $element = array_merge($element, addressfield_generate($address, $settings['format_handlers'], $context)); // Mark the form element as required if necessary. $element['#required'] = $delta == 0 && $instance['required']; } }
{ "pile_set_name": "StackExchange" }
Q: Arduino Delivering less power I connected 4x716 Coreless DC Motors on pin 13,12,11,10 and 1xGY-521 to Arduino Pro Mini 328, 5v but speed of propellers is not enough to produce enough torque to lift the quad whereas when i connect then directly to 3.3v LiPo battery the quad has lift but because of no flight control it moves randomly. I checked the voltage of pin 13,12... they have output as 0.5-0.6v, I think this is the reason quad is not lifting. I am using following code // MPU-6050 Short Example Sketch // By Arduino User JohnChi // August 17, 2014 // Public Domain #include<Wire.h> const int MPU=0x68; // I2C address of the MPU-6050 int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; int p1 = 13; int p2 = 12; int p3 = 11; int p4 = 10; void setup(){ Wire.begin(); Wire.beginTransmission(MPU); Wire.write(0x6B); // PWR_MGMT_1 register Wire.write(0); // set to zero (wakes up the MPU-6050) Wire.endTransmission(true); pinMode(p1, OUTPUT); pinMode(p2, OUTPUT); pinMode(p3, OUTPUT); pinMode(p4, OUTPUT); digitalWrite(p1, 0); analogWrite(p2, 0); analogWrite(p3, 0); analogWrite(p4, 0); Serial.begin(9600); } void loop(){ Wire.beginTransmission(MPU); Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) Wire.endTransmission(false); Wire.requestFrom(MPU,14,true); // request a total of 14 registers AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L) AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L) AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L) Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L) GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L) GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L) GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L) Serial.print("AcX = "); Serial.print(AcX); Serial.print(" | AcY = "); Serial.print(AcY); Serial.print(" | AcZ = "); Serial.print(AcZ); Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53); //equation for temperature in degrees C from datasheet Serial.print(" | GyX = "); Serial.print(GyX); Serial.print(" | GyY = "); Serial.print(GyY); Serial.print(" | GyZ = "); Serial.println(GyZ); digitalWrite(p1, HIGH); analogWrite(p2, 250); analogWrite(p3, 255); analogWrite(p4, 255); delay(333); } A: Atmega328 output pins are rated at 40 mA absolute-maximum current, and the 328's total current through Vcc and ground pins is 200 mA absolute max. Eg, see table 29.1 in the Atmega328 specs. Although some sources rate a high-speed 716 coreless dc motor at 40 mA, other sources rate it at 100 mA. In either case, it exceeds normal I/O pin capability. You should use FETs or other drivers between Arduino output pins and the motors rather than trying to drive the motors directly from digital output pins. Edit: Regarding the comment, “But most projects i've seen don't use any drivers, Why so ?” I replied: Perhaps they are using slightly higher voltage to the Pro Mini, eg 3.7 V up to 5 V, which after accounting for voltage drop in the i/o pin circuits may deliver enough voltage to the motors. Note that a driverless circuit ie direct drive from the i/o pins operates the 328 out of its safe operating area (SOA), but it may be close enough to the safe area to usually work. For example, some of the 716-based quadcopter pages I looked at say they used 4.2 V LiPo batteries. Also note, 716 seems to be a fairly generic motor designation; it refers to the motor's 7 mm diameter and 16 mm length. As a generic designation it has been used for several different motors, some of which produce less power. For example, in thread #1710948 on rcgroups.com, people refer to different RPMs, less lift, etc. for various motors, and the importance of shaving grams off of the copter's weight to allow it to fly. Another item that matters when drawing high current from an Atmega328 is which ports are used; and for some devices, it matters whether drive is high-side or low-side, ie whether current is sourced or sunk. The Atmega328 spec sheet (Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf) says “Each output buffer has symmetrical drive characteristics with both high sink and source capability”, but for several kinds of drivers less voltage is lost with low-side drive than with high-side. Ie, you could try connecting the motor's V+ lead to Vcc and its V- lead to the i/o pin, and inverting the on-off logic in the sketch. (I don't know if this will make any difference at all in how well things work.) Regarding which ports are used, the footnotes to Table 30-1, “Common DC characteristics”, spell out various combinations of ports where total current draw must not exceed a limit (100 mA in some cases, 150 mA in others). On the Uno and Pro-Mini, digital outputs marked 10 through 13 (as used for motor control in the question's sketch) are port B Atmega pins, with a footnoted total-current limit for the group. If you move two of the motor drives to outputs marked 2...4 or D2...D4, then a different total-current limit will apply. (Again, I don't know if this will make any difference at all in how well things work.) Refer to Table 30-1 footnotes for details. As noted in Gerben's comment, having flyback-diodes for the motor circuits is a good idea. This consists of placing power diodes across the motors, cathode to V+, anode to V-, to prevent energy stored in the motor's inductance from producing extreme i/o pin voltages each time the motor is turned off. Edit 2: Regarding “which diode, FET to use and where [to] learn about them”, electronics-tutorials.ws is an accurate and helpful presentation about FET digital circuits. In particular, see the section called “An example of using the MOSFET as a switch”. Which FETs to consider depends in part on your electronic-circuits fabrication skills. Note that surface mount devices (SMD parts) usually weigh less than other versions of parts, which is important for a lightweight quadcopter. However, some people find SMD parts difficult to work with. In my opinion, the main difficulty is holding parts in their proper places while soldering them, due to small size. (Eg, a SOT-23 SMD transistor package is on the order of 3mm x 2mm x 1mm, and a diode may be half as big.) If you have good soldering skills and a way to hold parts in place while soldering, you should be ok, either using a printed circuit board or air-wiring parts using wire-wrap wire (ie, 30 AWG wire, about 0.25mm diameter). Some typical logic-level-input SMD FETs are shown in mouser.com's online catalog. Note that in that list, RDS_on decreases a bunch as unit price increases slightly. For example, the FDN359BN would have under 0.1 ohm resistance when operated with Vcc = 3.7 V and currents < 100 mA. Voltage drop running a 40 mA motor should be about 4 millivolts. Some typical SMD Schottky diodes also are shown in mouser.com's online catalog. I think even the cheapest of these would work ok. Of course you'll need to adapt all these suggestions to your own skills, sources of parts supply, and budget.
{ "pile_set_name": "StackExchange" }
Q: How to call generic class from generic repository I want to use a generic class for pagination list query. I found a solution from this URL: https://dotnetcultist.com/paging-in-entity-framework-core/?unapproved=181&moderation-hash=c64d661435dc84a39f046cc786888855#comment-181 How can I call this static class "CreateAsync" from PaginationList public class PaginatedList<T> { public int CurrentPage { get; private set; } public int From { get; private set; } public List<T> Items { get; private set; } public int PageSize { get; private set; } public int To { get; private set; } public int TotalCount { get; private set; } public int TotalPages { get; private set; } public PaginatedList(List<T> items, int count, int currentPage, int pageSize) { CurrentPage = currentPage; TotalPages = (int)Math.Ceiling(count / (double)pageSize); TotalCount = count; PageSize = pageSize; From = ((currentPage - 1) * pageSize) + 1; To = (From + pageSize) - 1; Items = items; } public bool HasPreviousPage { get { return (CurrentPage > 1); } } public bool HasNextPage { get { return (CurrentPage < TotalPages); } } public static async Task<PaginatedList<T>> CreateAsync( IQueryable<T> source, int currentPage, int pageSize, string sortOn, string sortDirection) { var count = await source.CountAsync(); if (!string.IsNullOrEmpty(sortOn)) { if (sortDirection.ToUpper() == "ASC") source = source.OrderBy(sortOn); else source = source.OrderByDescending(sortOn); } source = source.Skip( (currentPage - 1) * pageSize) .Take(pageSize); var items = await source.ToListAsync(); return new PaginatedList<T>(items, count, currentPage, pageSize); } } And how can I add this class to generic repository class. public abstract class RepositoryBase<T> : PaginatedList<T>, IRepositoryBase<T> where T : class { protected EasyDoctorContext RepositoryContext { get; set; } protected PaginatedList<T> PaginatedList { get; set; } public RepositoryBase(EasyDoctorContext repositoryContext) { this.RepositoryContext = repositoryContext; } public IQueryable<T> FindAll() { return this.RepositoryContext.Set<T>(); } public IQueryable<T> FindByCondition(Expression<Func<T, bool>> expression) { return this.RepositoryContext.Set<T>() .Where(expression); } public void Create(T entity) { this.RepositoryContext.Set<T>().Add(entity); } public void Update(T entity) { this.RepositoryContext.Set<T>().Update(entity); } public void Delete(T entity) { this.RepositoryContext.Set<T>().Remove(entity); } public async Task<Boolean> SaveAsync() { try { await this.RepositoryContext.SaveChangesAsync(); return true; } catch(DbUpdateException e) { string model = typeof(T).ToString(); DBExeptionLogger.SetDbErrorLog(model, e.InnerException.Message); return false; } } } A: Try whether code below meet your requirement: public class RepositoryBase<T> : IRepositoryBase<T> where T : class { protected ApplicationDbContext RepositoryContext { get; set; } public RepositoryBase(ApplicationDbContext repositoryContext) { this.RepositoryContext = repositoryContext; } public async Task<PaginatedList<T>> FindAll() { return await PaginatedList<T>.CreateAsync(this.RepositoryContext.Set<T>(),1,2,null, null); } }
{ "pile_set_name": "StackExchange" }
Q: Remove columns when line matches a condition I am trying to remov certain columns from a text file on lines that match a string, but then leave the rest of the lines untouched. Say I have a file (thousand of lines in reality) 10 12 a USA John TGCAGG USA John TGCATG 5 2 b CAN Tom TGCACG CAN Tom TGCAAC .... And I want to create a new file that removes the 2nd column in lines that contain TGCA but leaves all other lines intact. I would like to see: 10 12 a USA TGCAGG USA TGCATG 5 2 b CAN TGCACG CAN TGCAAC I can modify which columns print on lines that match using a regexp to start awk or sed, but I cant get the other lines (which are not modified) to print, or to preserve the order of those lines. Do I need to use an if statement in awk? Tried using next but I dont think I have that right. A: I would say: $ awk '/TGCA/ {$2=$3; NF--} 1' file 10 12 a USA TGCAGG USA TGCATG 5 2 b CAN TGCACG CAN TGCAAC That is: when the line contains TGCA, replace the 2nd column with the 3rd and decrease the number of fields. That is, remove the 2nd column.
{ "pile_set_name": "StackExchange" }
Q: Will data binding unregister listeners from a ViewModel implementing Observable? I have some more complex logic for data provided by my ViewModel to the UI, so simply exposing the data via LiveData won't do the job for me. Now I've seen in the Android docs that I can implement Observable on my ViewModel to get the fine-grained control I need. However in the documentation it also says: There are situations where you might prefer to use a ViewModel component that implements the Observable interface over using LiveData objects, even if you lose the lifecycle management capabilities of LiveData. How intelligent is the built-in Android data binding? Will it automatically unregister it's listeners when necessary (e.g. on configuration changes where the View is destroyey) so that I don't have to care about the lost lifecycle capabilities? Or do I have to watch the Lifecycle of the View and unregister it's listeners? (=do manually what LiveData normally does for me). A: How intelligent is the built-in Android data binding? Will it automatically unregister it's listeners when necessary (e.g. on configuration changes where the View is destroyey) so that I don't have to care about the lost lifecycle capabilities? Or do I have to watch the Lifecycle of the View and unregister it's listeners? (=do manually what LiveData normally does for me). So I did some tests. I implemented androidx.databinding.Observable on my ViewModel and did a configuration change with the following log calls: override fun removeOnPropertyChangedCallback( callback: androidx.databinding.Observable.OnPropertyChangedCallback?) { Log.d("APP:EVENTS", "removeOnPropertyChangedCallback " + callback.toString()) } override fun addOnPropertyChangedCallback( callback: androidx.databinding.Observable.OnPropertyChangedCallback?) { Log.d("APP:EVENTS", "addOnPropertyChangedCallback " + callback.toString()) } I saw that addOnPropertyChangedCallback was invoked for each time my viewmodel was referenced in a layout binding expression. And not once did I see removeOnPropertyChangedCallback invoked. My initial conclusion is that AndroidX databinding is dumb and does not automagically remove the listener. FYI: the callback type was ViewDataBinding.WeakPropertyListener However, I took a peek at ViewDataBinding.java source code and found that it is using Weak References to add the listener. So what this implies, is that upon a configuration change, Android OS should be able to garbage collect your Activity/Fragment because the viewmodel does not have a strong reference. My advice: Don't add the boilerplate to unregister the listeners. Android will not leak references to your activities and fragments on configuration changes. Now, if you choose not to use LiveData, consider making your viewmodel implement LifecycleObserver so that you can re-emit the most recent value when your Activity/Fragment goes into the active state. This is the key behavior you lose by not using LiveData. Otherwise, you can emit notifications by using the PropertyChangeRegistry.notifyCallbacks() as mentioned in the documentation you shared at some other time. Unfortunately, I think this can only be used to notify for all properties. Another thing... while I've not verified the behavior the source code seems to indicate that weak references are used for ObservableField, ObservableList, ObservableMap, etc. LiveData is different for a couple of reasons: The documentation for LiveData.observe says that a strong reference is held to both the observer AND the lifecycle owner until the lifecycle owner is destroyed. LiveData emits differently than ObservableField. LiveData will emit whenever setValue or postValue are called without regard to if the value actually changes. This is not true for ObservableField. For this reason, LiveData can be used to send a somewhat "pseudo-event" by setting the same value more than once. An example of where this can be useful can be found on the Conditional Navigation page where multiple login failures would trigger multiple snackbars.
{ "pile_set_name": "StackExchange" }
Q: If $a_n=n\left(1-\frac{1}{n}\right)^{n[\log n]}$, prove $1\leqslant \liminf a_n$ and $\limsup a_n\leqslant e.$ Prove that: $$\limsup n\left(1-\frac{1}{n}\right)^{n[\log n]} \leqslant e$$ and $$\liminf n\left(1-\frac{1}{n}\right)^{n[\log n]} \geqslant 1.$$ Attempt. Since for $n>2$: $$1<[\log n]<\log n+1\leqslant n,$$ we would get: $$n\left(1-\frac{1}{n}\right)^{n[\log n]}\leqslant n\left(1-\frac{1}{n}\right)^n \to +\infty,$$ $$n\left(1-\frac{1}{n}\right)^{n[\log n]}\geqslant n\left(1-\frac{1}{n}\right)^{n^2} \to 0,$$ so the above estimates are not convenient. Thanks for the help. A: First, note that $\log n-1 < [\log n] \leq \log n$. Now, $0<1- \frac{1}{n}<1$, so we have $$ n \left( 1- \frac{1}{n} \right)^{n \log n} \leq n \left( 1- \frac{1}{n} \right)^{n [\log n]} < n \left( 1- \frac{1}{n} \right)^{n (\log n - 1)}. $$ We now want to use the fact that $\left(1- \frac{1}{n}\right)^{n} \to e^{-1}$ as $n \to \infty$ to simplify the above inequalities. To make the computation easier, write this as $n\log(1- \frac{1}{n}) \to -1$, which can be sharpened to $n\log(1- \frac{1}{n}) = -1 - \frac{1}{2n} + O\left( \frac{1}{n^2} \right)$ using the Taylor series for $\log(1-x).$ Now, $$\log \left(n \left( 1- \frac{1}{n} \right)^{n \log n} \right) = \log n \left( 1 + n \log \left(1 - \frac{1}{n} \right) \right) = \log n\left(- \frac{1}{2n} + O\left( \frac{1}{n^2}\right) \right) \to 0$$ as $n \to \infty$, and similarly $$ \log \left( n \left( 1- \frac{1}{n} \right)^{n (\log n - 1)} \right) = \log n \left( 1 + n \log \left(1 - \frac{1}{n} \right) \right) - n \log\left( 1- \frac{1}{n} \right) \to 1$$ as $n\to\infty.$ Taking the exponentials of both of these inequalities gives the desired result.
{ "pile_set_name": "StackExchange" }
Q: Can you use 希望 for actions in the past? For example, if I want to say "I wish I learned Chinese when I was little", is it ok to say "我希望我小的时候学中文"? If not, is there another word I could use instead? Possibly "我最好小的时候学中文"? Or do I need to entirely rephrase and say something like "我小的时候学中文更好" A: As a 老外 saying this, maybe: 我希望从小就开始学中文了。 Using 希望 is good.
{ "pile_set_name": "StackExchange" }
Q: Using PHP Simple DOM Parser to get image from Wordpress Post I am using the open source PHP library known as PHP Simple HTML DOM Parser to scrape the first image of a Wordpress Post. If I call the main website: $html = file_get_html('http://iadorefood.com/'); I get a response, an object of the DOM that I can manipulate. But if I request the URL of a specific post, my object returns NULL. Here is my command: $html = file_get_html('http://iadorefood.com/articles/tuscany-san-gimignano/'); Why does my object return NULL? Is there something wrong with the URL? A: Try this include('simple_html_dom.php'); $html = file_get_html('http://iadorefood.com/articles/tuscany-san-gimignano'); $element = $html->find('div.content p img'); echo '<img src=' . $element[0]->src . ' />'; It's tested and working, notice the trailing / at the URL, I've removed it and works fine.
{ "pile_set_name": "StackExchange" }
Q: Проблема с поиском числа инверсий в массиве через алгоритм MergeSort Есть рабочий алгоритм MergeSort. Нужно модифицировать его так, чтобы он по совместительству находил и число инверсий в массиве. Инверсией считается пара чисел массива, если выполняется условие A[left] > A[right]. И так же все оставшиеся элементы левой части тоже будут больше, т.к. левая и правая часть отсортированы. Поэтому количество инверсий нужно увеличить на количество оставшихся элементов + 1 (текущий элемент). Проблема заключается в том, что, например, в таком наборе чисел «145, 179, 232, 307, 588, 792, 22, 233, 279, 336, 863, 866» кол-во инверсий равно числу 14, а на выводе 15. Хотя при другом наборе, например, «1, 5, 8, 3, 7, 10» выводит правильное число, это 3. Вот моя наработка: public static void MargeSort(int[] array, int l, int r) { if ((r - l) < 2) return; MargeSort(array, l, (l + r) / 2); MargeSort(array, (l + r) / 2, r); Marge(array, l, r); } private static int inversionsCount = 0; public static void Marge(int[] array, int l, int r) { int middle = (l + r) / 2; int left = l; int right = middle; int index = 0; int[] buff = new int[r - l]; while ((left < middle) && (right < r)) { if (array[left] > array[right]) { buff[index++] = array[left++]; // здесь идет подсчет кол-ва инверсий inversionsCount += middle - left; } else buff[index++] = array[right++]; } while (left < middle) buff[index++] = array[left++]; while (right < r) buff[index++] = array[right++]; index = 0; while (index < buff.Length) array[l + index] = buff[index++]; } Не могу понять в чем проблема. A: Разобрался с проблемой. Прикол в том, что нужно было просто исключить из числа инверсий все повторения входных чисел. То есть. Например, при наборе чисел «7, 4, 1, 9, 1», результатом должно быть 6. А по старому алгоритму считало 7. Достичь правильного результата в данном примере можно двумя путями: 1) Добавить такое условие: if(array[left] != array[right]) inversionsCount += middle - left; Но с другими примерами результат будет неверным! Поэтому лучше воспользоваться пунктом 2. 2) Вот оно, универсальное решение. while ((left < middle) && (right < r)) { if (array[left] <= array[right]) buff[index++] = array[left++]; else { inversionsCount += middle - left; buff[index++] = array[right++]; } } В первом if нужно поставить <= вместо <.
{ "pile_set_name": "StackExchange" }
Q: Java SQL get all rows from column I want to get the number of rows from my database How can I create a method that returns the number of rows as an int? Here's what I got but it only returns number 1 public int getAllId() { SQLiteDatabase db = this.getWritableDatabase(); int x=0; String where = null; Cursor c = db.rawQuery("SELECT COUNT (*) FROM " + TABLE_PRODUCTS, null); while (c.isAfterLast() == false) { c.moveToNext(); } db.close(); return c.getCount(); A: I found the way to do it thanks to SQLite Query in Android to count rows Here's the code I came up with: public int getRowCount() throws Exception { SQLiteDatabase db = this.getWritableDatabase(); Cursor mCount= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_PRODUCTS, null); mCount.moveToFirst(); int rows= mCount.getInt(0); mCount.close(); return rows; }
{ "pile_set_name": "StackExchange" }
Q: Calculate $\sum\limits_{n=1}^\infty \frac{1}{(n+2)(n+4)^2}$ Calculate the sum of the series $$\sum_{n=1}^\infty \frac{1}{(n+2)(n+4)^2}$$ I have tried partial fraction decomposition. $$\sum_{n=1}^\infty\frac{1}{4(n+2)}- \sum_{n=1}^\infty\frac{1}{4(n+4)}-\sum_{n=1}^\infty\frac{1}{2(n+4)^2}$$ Is this correct? What is the sum? A: Your partial fraction decomposition looks OK, but it should be written as $$\sum_{n=1}^\infty\left({1\over4(n+2)}-{1\over4(n+4)}\right)-\sum_{n=1}^\infty{1\over2(n+4)^2}$$ instead of being split into three infinite series. That's because $\sum_{n=1}^\infty{1\over4(n+2)}$ and $\sum_{n=1}^\infty{1\over4(n+4)}$ are each divergent. But combined they give the convergent, telescoping series $$\left({1\over4\cdot3}-{1\over4\cdot5}\right)+\left({1\over4\cdot4}-{1\over4\cdot6}\right)+\left({1\over4\cdot5}-{1\over4\cdot7}\right)+\left({1\over4\cdot6}-{1\over4\cdot8}\right)+\cdots\\={1\over4\cdot3}+{1\over4\cdot4}={7\over48}$$ The other series you need to recognize as $${1\over2}\left({1\over5^2}+{1\over6^2}+\cdots\right)={1\over2}\sum_{n=1}^\infty{1\over n^2}-{1\over2}\left(1+{1\over2^2}+{1\over3^2}+{1\over4^2}\right)={1\over2}\left(\pi^2\over6\right)-{1\over2}\left(205\over144\right)$$ The trick is understanding the hat that the $\pi^2/6$ rabbit came from, but I'm assuming you've seen it somewhere. I'll leave it to you to put the pieces together. A: First note that your series has the same convergence as $\sum \frac{1}{n^3}$ by the limit comparison test. And the latter series converges absolutely by the $p$-series test or the integral test, so therefore so does your series. Next, to find the value the sum converges to, trying partial fractions, we get $$\frac{1}{(n+2)(n+4)(n+4)}=\frac{1}{4}\frac{1}{n+2}-\frac{1}{4}\frac{1}{n+4}-\frac{1}{2}\frac{1}{(n+4)^2}$$ If we break it into three series as you have attempted, then all three are divergent, and difference of divergent is indeterminate, so we cannot proceed. Instead, treat the first two terms together, and note that $\sum_{n=1}^\infty \frac{1}{n+2}-\frac{1}{n+4}$ is a telescoping series, its sum will converge to $1/3+1/4$, the uncanceled parts of the first two terms. For the final term, rememeber by the Basel problem $\sum_{n=1}^\infty\frac{1}{n^2}=\frac{\pi^2}{6}$ so by reindexing we have $\sum_{n=5}^\infty\frac{1}{n^2}=\sum_{n=1}^\infty\frac{1}{(n+4)^2}=\frac{\pi^2}{6}-\frac{1}{16}-\frac{1}{9}-\frac{1}{4}-1$. Putting it all together we have $$\sum_{n=1}^\infty\frac{1}{(n+2)(n+4)(n+4)}=\frac{1}{4}\left(\sum_{n=1}^\infty\frac{1}{n+2}-\frac{1}{n+4}\right)-\frac{1}{2}\sum_{n=1}^\infty\frac{1}{(n+4)^2} \\=\frac{1}{4}\left(\frac{1}{3}+\frac{1}{4}\right)-\frac{1}{2}\left(\frac{\pi^2}{6}-\frac{1}{16}-\frac{1}{9}-\frac{1}{4}-1\right) = \frac{7}{48} -\frac{\pi^2}{12}+\frac{205}{288}=\frac{247}{288}-\frac{\pi^2}{12} $$
{ "pile_set_name": "StackExchange" }
Q: How to remove line based on Delimeter in perl / Shell? Can anyone help to remove the line in file based on delimeter(Comma), Incase if line contain less number of columns or Bad records , Need to delete those. Input File: a,b,c,d a,b,d,f c,d a,v,b,h d,e,v,n In the above file if the delimeter is less than 4 than i have to delete the line from the file. Output File : a,b,c,d a,b,d,f a,v,b,h d,e,v,n The below command gives me number of delimeter in a line , How can i delete if that not equal to 4, egrep -iv '"' file.csv | awk -F',' '{print NF}' Thanks. A: Another perl: print a line if there are 3 commas. perl -i.bak -ne 'print if tr/,/,/==3' file The tr operator returns the number of characters transliterated. A: You can use awk: awk -F',' 'NF==4' file If you can use gawk version >= 4.1.0 you can use inplace, more info. So it could be: gawk -i inplace -v INPLACE_SUFFIX=.bak -F',' 'NF==4' file A: With perl: $ perl -F, -i.bak -ane 'print if @F > 3' file With perl > 5.20, you can use -F without -a and -n (-F implies -a and -a implies -n). Or you can use sed: $ sed -i.bak -e '/\([^,]*,\)\{3,\}/!d' file
{ "pile_set_name": "StackExchange" }
Q: Exclude multiple elements in .not, including $this The following hides all table rows, excluding rows with class .accordion or .course_header. $('#course_list').find("tr").not('.accordion, .course_header').hide(); How do I exclude $(this).next("tr") table row as well? That is assuming this is a tr that was just clicked. Full details I'm working on a table with an accordion effect using this solution. With the solution as-is, if I click on a row, its child stays expanded. Notice when you click a row in the jsfiddle, it expands the child correctly, but I want it to close the child when I click that same row again. What I have currently: var $course_list = $('#course_list'); $course_list.find("tr").not('.accordion, .course_header').hide(); $course_list.find("tr").eq(0).show(); $course_list.find(".accordion").click(function(){ $course_list.find("tr").not('.accordion, .course_header').hide(); $(this).next("tr").fadeToggle('fast'); }); Here is the table layout: <table id="course_list"> <thead> <tr class="course_header"> <th>Date</th> <th>Presenter</th> <th>Title</th> </tr> </thead> <tbody> <tr class="accordion"> <td>09.26.14</td> <td>Arthur Dent</td> <td>Example Course</td> </tr> <tr> <td colspan="4"> COURSE DETAILS GO HERE </td> </tr> <tr class="accordion"> <td>09.30.14</td> <td>Winston Smith</td> <td>Another Example</td> </tr> <tr> <td colspan="4"> COURSE DETAILS GO HERE </td> </tr> </tbody> </table> A: Have you tried to append it to the chain: var next = $(this).next("tr"); $course_list.find("tr").not('.accordion, .course_header').not(next).hide();
{ "pile_set_name": "StackExchange" }
Q: Do i need to set constrains? We have this product in which we started long time ago with the older Xcode 5 . In this project, there is a separate storyboard for iPhones, and iPads. When the program starts we chose the right storyboard according to the device . With the new Xcode6,when we open the same project, we have the old storyboard for iPads, in which now the option "auto layout" and "use size class", are not checked for it(iPads) . What happens is that the app is running on all iPads,with this storyboard,which does not have constrains,or auto layout, and it works perfectly on all iPads screens. For the iPhone storyboard,we do set auto layout and constrains,so there is not problem. Question is, do we have to set auto layout and constrains to the iPad storyboard although it works great on all iPad sizes without it ? In general, how is that it works on all screens without auto layout? is it because the aspect ration is the same for all iPads ? is it safe ? I have read here http://www.informit.com/articles/article.aspx?p=2041295 and he says that without auto layout the autorisizingmask will take control over the different sizes. so the question becomes more relevant - WHY DO I NEED AUTO-LAYOUT HEADACHE ? A: You don't need. If everything works and looks OK, leave it alone. Auto-layout will be useful, when you add some dynamic behavior: resizing, content height changing, etc. Finally auto-layout is not as painful as you think. Working with UIScrollView and UITableView dynamic height cells is much easier at the latest SDK. After all, you do not have to set EVERY constraint. You are able to setup constraints for specific controllers and views only.
{ "pile_set_name": "StackExchange" }
Q: How can i sort a mysql result by a list of prioritised ids? I have a large products database, and every sunday, my script is activating 50 new products. the thing is, based on some rules in my script, im finding some products i should prioritize activating. (for your example, lets say it should always prioritize activating products with the name 'hello kitty' and 'meshuggah' in them, before everything else) my db table contains info about the product, and unique id. lets say that the script finds 5 of these ids, having hello kitty in the title. so, how can i make the query, so that the prioritized items will come on top, and then followed by id desc? here some pseudocode of what im after: SELECT * FROM products order by (id='59', id='47', id='28', id='29', id='20'), id desc limit 50 the result should give me id 59, 47, 28, 29 and 20 first, then followed by other ids in the products table sorted by id descending. is that possible in one query? A: use FIELD SELECT * FROM products order by FIELD(id,59,47,28,29,20), id desc limit 50 Ordering by specific field values with MySQL
{ "pile_set_name": "StackExchange" }
Q: Solaris Containers on Xen Setting aside the "why?" for a moment, would it be possible to install a Xen hypervisor and have a Solaris DomU with several Zones / Containers running? Just one of those hypothetical questions that occurs at random times, not actually thinking of trying it out just yet. A: I see no reason why not, as long as you can get Xen to host Solaris -- I use this exact setup with several different versions of VMware with no issues. In my environment, I have Sol10 VM's with anywhere from 1 to 30 zones running on top of ESX, ESXi or Fusion. The zones live on a secondary (or more) disks, either as virutalised disks or raw LUN's presented from a SAN, formed into a zpool.
{ "pile_set_name": "StackExchange" }
Q: Moving fixed nodes in d3 force layout I am using D3's forced layout to display a graph. Now, I require that the nodes change their positions when any node is clicked. I looked up other related StackOverflow questions but that didn't help me. The code for render is as follows : var render = function(graph){ /* var loading = svg.append("text") .attr("x", width / 2) .attr("y", height / 2) .attr("dy", ".35em") .style("text-anchor", "middle") .text("Simulating. One moment please…");*/ force .nodes(graph.nodes) .links(graph.links) .start(); var link = svg.selectAll(".link") .data(graph.links); //Enter phase for links. link.enter().append("line"); //Update phase for links link .attr("class", "link") .style("stroke-width", function(d) { return Math.sqrt(d.value); }); var node = svg.selectAll(".node") .data(graph.nodes,function(d){return d.name;}); //Enter phase for nodes var node_g = node.enter() .append("g") .attr("class","node") .on("dblclick",nodeClick) .call(force.drag); //Update phase for nodes node_g.append("text") .attr("class","NodeLabel") .text(function(d){ return d.name; }); var nodeCirlce = node_g.append("circle"); nodeCirlce .attr("r", 5) .style("fill", function(d) { return color(d.group); }) node_g.append("title") .text(function(d) { return d.name; }); force.on("tick", function() { link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node_g.attr("transform",function(d){ return "translate("+ d.x+","+ d.y+")"; }); //TODO : Add attr change for node text as well. }); And the code for the node click handler looks like this : var nodeClick = function(d,i){ //Translate the graph to center around the selected node. var x_trans = x_cent - d.x; var y_trans = y_cent - d.y; var nodes = oldGraph.nodes; for(var i=0;i<nodes.length;i++){ var node = nodes[i]; node.x = node.x + 1000; node.y = node.y + 1000; node.fixed = true; } //oldGraph.nodes = updateNodes(nodes,oldGraph.links); render(oldGraph); //setTimeout(function(){layout("json/HUMAN-1g.json");},000); }; However, the node positions don't get updated. A: After changing the data, you need to run the code that updates the positions in the DOM. This is exactly what you have in the tick event handler function: link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node_g.attr("transform",function(d){ return "translate("+ d.x+","+ d.y+")"; I recommend pulling this out into a separate function and then setting it as the tick handler function and calling it from your nodeClick() function. To be clear, you don't need to call render() from the nodeClick() function.
{ "pile_set_name": "StackExchange" }
Q: Add current date in inputmask placeholder How, if its possible, add in inputmask's placeholder current date: $('#call_order_date').inputmask( mask: '99 99 9999', placeholder: "dd mm yyyy", ); Instead dd mm yyyy writing 02.05.2107. A: I think that on the UX side, it is wrong to show the current date as a placeholder. the placeholder should describe the user what the input mean to be and in 2nd to February the date will be 02 02 2XXX.. any way i think that you just can take the current date and show each number where you want to: var now = new Date(); $('#call_order_date').inputmask( mask: '99 99 9999', placeholder: now.getDay() + " " + (now.getMonth() + 1) + " " + (1900 + now.getYear()) );
{ "pile_set_name": "StackExchange" }
Q: Simple tkinter application that choose a random string I am really new to programming, and I made this simple tkinter app in python. Please tell me what can be improved and how to use classes correctly in combination with tkinter. Github to clone if you want #!/usr/bin/env python # --------------------------------- # @author: apoc # @version: 0.1 # --------------------------------- # importing from tkinter import * import csv from random import randint class LRG(object): def __init__(self,master): # variables with open('data/champs.csv','r') as f: reader = csv.reader(f) self.champ_list = list(reader) # layout self.randombutton = Button(master,text='Random',command=self.scan) self.infofield = Text(master,height=20,width=50) # layout self.randombutton.grid(row=0,column=1,sticky=E,pady=2,padx=5) self.infofield.grid(row=1,columnspan=4,sticky=W,column=0,pady=4) def scan(self): self.infofield.delete('1.0',END) self.infofield.insert(END,self.champ_list[ randint(0,len(self.champ_list)) ]) if __name__ == "__main__": master = Tk() LRG(master) master.title("LRG") master.mainloop() A: Standards Follow the PEP8 coding standard. One violation that immediately is obvious is the lack of a space following a comma. For example, (row=0, column=1, sticky=E, pady=2, padx=5) is much easier to read. Use pylint (or similar) to check your code style against the recommended standard. Import grouping My personal preference is to keep import ... statements together, and from ... import ... statements together, not interleave them. Private class members "Private" members should be prefixed with an underscore. Such as self._champ_list and def _scan(self):. This doesn't actually make them private, but some tools will use the leading underscore as a key to skip generating documentation, not offer the member name in autocomplete, etc. Remove useless members self.randombutton is only used in the constructor; it could just be a local variable, instead of a member. Use correct comments The # layout comment above the Button and Text construction is misleading; it is not doing any layout. Self documenting names Use understandable names. I have no idea what LRG is. Good variable names go a long way towards creating self-documenting code. Use Doc-Strings Add """doc-strings""" for files, public classes, public members, and public functions. Using LRG as a class name could be fine (in may be a common acronym at your company), but adding a doc-string for the class could spell out what the acronym stands for at least once. Avoid hard-coded information You have hard-coded reading the data/champs.csv file into the constructor. Consider making it more flexible, such as passing in a filename with that as a default. class LRG: """Literal Random Generator""" def __init__(self, master, csv_filename="data/champs.csv"): # ...etc... Or, move the reading of the data outside of the class, and pass the champ_list in as a constructor argument.
{ "pile_set_name": "StackExchange" }
Q: How to make td full height of row? Angular material I'm using ng-repeat to create a table with schedule blocks, but some are smaller than tr height, and I need that all of them have the same heigh. In each td I have a modified md-checkbox: Missing space I'v created a codepen: Schedule <div id="main" ng-app="MyApp" layout> <div ng-view layout="column" flex></div> <script type="text/ng-template" id="template.html"> <md-toolbar class="" layout="row"> <center>toolbar</center> </md-toolbar> <md-content class="content" > <table class="vistaTabla" cellspacing="0" cellpadding="0"> <tr ng-repeat="hora in bloques[0]"> <td class="vistaBloque" ng-repeat="bloque in hora"> <md-checkbox class=" text-longshadow md-whiteframe-1dp bloque dotted" > {{bloque.materia}} {{bloque.nombre}}</td> </md-checkbox> </tr> </table> </md-content> </script> </div> A: Solution for your problem is the block that is inside <td>. <td> elements are always the size of their <tr> parents. The md-checkbox element is the one that is messing with you. Define rule for element .md-whiteframe-1dp: .md-whiteframe-1dp { height: 100%; }
{ "pile_set_name": "StackExchange" }
Q: javascript for changing link's href in html page My problem is the following: I have a page with many links Some of them have a specific pattern : http://www.example.com/.../?parameter1=...&parameter2=PARAMETER2 What i want to do is to change these links' href to the value of the parameter2 using JavaScript. For example if i have a link like : <a href="http://www.example.com/.../?parameter1=...&parameter2=PARAMETER2">text here</a> what i want to do after the script runs is to have a link like this: <a href="PARAMETER2">text here</a> Any suggestion would be truly appreciated!!! Thank you all in advance!!! A: If you are using jquery then use the following code $(function() { $("a[href^='www.example.com']").each(function(){ var ele = $(this); var href = ele.attr("href");console.log(href); var index = href.lastIndexOf("parameter2"); var param_2 = href.substring((index + 11)); ele.attr("href", param_2); }); });
{ "pile_set_name": "StackExchange" }
Q: How to connect to my server from AWS device farm when limiting the device farm ip range to 54.244.50.32/27? We have a classic load balanser that's configured to allow TCP traffic on port 444. We have a security group configured that allows TCP traffic from 54.244.50.32/27. If we open up the traffic to the entire internet (0.0.0.0/0), then we can connect fine but as soon as we limit traffic to the device farm's ip range of 54.244.50.32/27, we fail to connect. We have a VPN and can connect just fine from our local network so the problem seem to be between the device farm and our server. Anyone know what we are missing? A: Couple of things to look at: Can you verify from the Device Farm that it's really using that IP range? E.g. access https://ifconfig.co from the Device Farm and see what it comes back with. If the Device Farm and the ELB are in the same VPC you may need to permit access to the ELB from the VPC IP range (e.g. 172.31.0.0/16). Enable ELB access logs while the access is open to 0.0.0.0/0 and look at the logs from which IPs the devices are connecting. If none of that works enable VPC Flow Logs and investigate where the traffic is coming from. Hope some of it helps :)
{ "pile_set_name": "StackExchange" }
Q: Check Uniform convergence of $f_{n}\left(x\right)=\ln\left(1+\frac{1}{nx^2}\right)$ on $(0,1]$ Check Uniform convergence of $f_{n}\left(x\right)=\ln\left(1+\frac{1}{nx^2}\right)$ on $(0,1]$. Attempt: $$f(x)=\lim _{n\to \infty}\ln\left(1+\frac{1}{nx^2}\right)=\ln(1)=0$$ now I need to find if : $$\lim _{n\to \infty}\sup_{x\in (0,1]}|f_{n}(x)-f(x)|=0$$ and here I stuck I don't know if $f(x)$ that I found is correct and how to continue from here ? I thought of $g(x)=\ln(1+\frac{1}{nx^2})$ so $g'(x)=0$... but I don't think this will help. Thanks. A: the convergence cannot be uniform $$\lim _{n\to \infty }\sup_{x\in (0,1]}|f_{n}(x)|\overset{x=1/n}{\ge} \lim _{n\to \infty } f(1/n)=\lim _{n\to \infty }\ln(1+n))=\infty$$ or alternatively $$\lim _{n\to \infty }\sup_{x\in (0,1]}|f_{n}(x)|\overset{x=1/\sqrt{n}}{\ge} \lim _{n\to \infty } f(1/\sqrt{n}) =\ln 2$$ but rather the convergence is uniform on any other compact subset of $(0,1]$ since $$\sup_{[a,1]}|f_n(x)|\le |f_n(a)|\to0,~~a>0$$
{ "pile_set_name": "StackExchange" }
Q: SQL condition where 2 values share common character I'm trying to create a query that lists staffID, staffName and staffDOB, but only of staff that first and last names begin with the same letter. So I have both staffFirst and staffLast as individual columns, will join them together. I will not be customising staffID and staffDOB. I would like it to return the name of staff like adam apple = a apple, so the output would look like: staffID | staffName | staffDOB ------------------------------ 1 | A Apple | 12/10/99 .... | .... | .... All columns are in the same table "N_Staff". I am using HeidiSQL which I believe uses MySQL. I know how to grab the data of each column, though it is selecting the first letters of both first and last names and comparing them which is confusing me as it is not an specific letter I am looking for but any letter that is common on both tables of index [0]. Thus far: SELECT staffID FROM N_Staff, SELECT staffFirst, staffLast AS staffName FROM N_Staff WHERE ... , --perhaps should be using LEFT ? SELECT staffDOB from N_Staff; A: How about: SELECT staffID, CONCAT(LEFT(staffFirst,1), ' ', staffLast) AS staffName, staffDOB FROM N_Staff WHERE LEFT(staffFirst,1) = LEFT(staffLast,1)
{ "pile_set_name": "StackExchange" }
Q: Unit Testing Marten I'm putting together an implementation of IdentityServer4, using PostgreSQL as the database, Marten as the ORM, and GraphQL as the API. So far, it's working great at runtime. However, I'm also trying to get unit tests in place, and am running into an issue. I have a custom implementation of IdentityServer4's IClientStore interface, where the implementation of the FindClientByIdAsync method looks thus: public async Task<Client> FindClientByIdAsync(string clientId) { var client = await _documentSession.Query<dbe.Client>().FirstOrDefaultAsync(c => c.ClientId == clientId); return _mapper.Map<Client>(client); // AutoMapper conversion call } This works great at runtime. However, I have the following test that I'm trying to put in place to exorcise this code: [Fact] public async Task FindClientByIdReturnsClient() { var clients = new [] { new dbe.Client { ClientId = "123" } }.AsQueryable(); var queryable = new MartenQueryable<dbe.Client>(clients.Provider); // _documentSession is a Moq Mock _documentSession.Setup(x => x.Query<dbe.Client>()).Returns(queryable); var store = new ClientStore(_documentSession.Object, _mapper); var result = await store.FindClientByIdAsync("123"); Assert.NotNull(result); Assert.Equal("123", result.ClientId); } The error I get happens when the test tries to execute the FindClientByIdAsync method: System.InvalidCastException : Unable to cast object of type 'System.Linq.EnumerableQuery`1[StaticSphere.Persona.Data.Entities.Client]' to type 'Marten.Linq.IMartenQueryable'. If anyone is familiar with Marten can could provide some insight, that would be great! I've done my Google time, and haven't found anything concrete on the subject. A: A quote from the creator of Marten which could be relevant here (context): You can mock a bit of IDocumentSession (Load, Store, SaveChanges, maybe query by compiled query), but you’re gonna be in a world of hurt if you try to mock the Linq support. So one solution would be to do integration tests for which you can find some code from the official Marten's repository or here.
{ "pile_set_name": "StackExchange" }
Q: Quickest framework to develop a Facebook App - CakePHP vs. Ruby on Rails So I know this has been asked before here: How to start facebook app? But I am banking on it being a little old and also hoping I have something slightly more specific to ask. So here goes: I want to build a basic Facebook app, that would require a basic database, a simple front page, and obviously the ability to share/Like over the feed. Now my main concern is I want to do this quickly and easily, without having to deal with as many mundane details as I can avoid. I was thus looking at CakePHP and Ruby on Rails as frameworks. However, I am not familiar with either of these technologies (I do have a software background, but it is mostly C/C++/Java). So which do you think would be best for me to pick up for this project that will enable me to quickly and easily just 'build' something like this for Facebook? (Also note that I need a free hosting provider as I don't have money to finance this hobby now, so I'll need to know which hosting companies support these frameworks for free). Any help is appreciated! A: Rails, definitely, there are infinitely more and better resources available to learn from and you can get fantastic free hosting (for small scale apps, plus easily scale for cheap) on Heroku. To get started, see: Rails for Zombies (free) Rails 3 Tutorial Railscasts I was in the same situation as you last fall, I knew a fair amount of PHP but had never worked with an MVC web framework before. I tried to learn CakePHP, struggled for a while, then thought I'd spend just one weekend giving Rails a chance. I had never touched Ruby before, but I was so curious about Rails that I picked up a copy of Beginning Rails 3, and I figured I would just take one weekend and see how hard it was to learn some basic Ruby and get an idea for how Rails works. I thought going into that weekend that there was really no way learning a whole new language could be worth it, even if the framework suited me better. I'm so, so glad I gave it a chance. Ruby is awesome, the community behind it is phenomenal, and the amount of documentation, screencasts, tutorials, etc. are out of this world. Ruby is also a lot of fun to work with, and very easy to learn. Try for yourself and see what you think. Rails is definitely the way to go (vs CakePHP at least). A: The answers so far only scratch the surface! CakePHP is to PHP what Rails is to Ruby. From the onset, CakePHP was developed to mimic the "Rails" way on things, and has done really well so far; but if you're starting from scratch; you need to remember you have to: Set up a development environment, which in turn involves Install the language (PHP / Ruby) and Database (MySQL?) Learning some basic server configuration(s) Choosing which one is right for you, and setting it up (Apache, Nginx, Passenger etc) Get the framework up and running Learn the underlying language Learn the framework Learn the Facebook API, and their developer guidelines Actually Build the application Test it, debug and submit for approval Launch it Having developed in both CakePHP and RoR - if you're coming with no web development background and you're looking to start; dive in with either. Honestly, it'll be the same learning curve for you! You will find the setup, learning, development and deployment easier in CakePHP - PHP is one of the most popular languages. If you want to learn a language and framework also to improve your skills as a programmer and developer, then you want RoR - it's got strict conventions that do twist your mind but once you get the hang of it, there's no looking back (and these are the same conventions that CakePHP is trying to bring to the PHP world!). The official documentation for both is excellent, they have amazing (and very active!) communities where even the silliest question is answered. There are also excellent (free) hosting platforms available, that make use of Git and make deployment a snap (PHPFog and Heroku). It might be worth mentioning that RoR is considered the new boy on the scene, the trendy framework thats bringing with it a lot of rapid changes in development methodologies, and that RoR developers also are in very high demand. Also - considering the simplicity of the App - have you considered using Sinatra (a very minimal framework for Ruby)? You may find that the easiest, and it'll be an excellent stepping stone if you later wanted to get into Ruby on Rails. A: OK, this thread is about 1 1/2 years old by the time I write this. But wanted to add something to the discussion for anyone finding this, as I did doing a search on RoR vs CakePHP. As of this date, and during the last 12 months, RoR is trending about 3 times what CakePHP is, according to Google Trends. Now, this is just RoR vs CakePHP. When I add Facebook into the mix, RoR/Facebook is still about 3 times CakePHP/Facebook, but if you look at the last 3 months, CakePHP/Facebook drops to zero. Link. Right now, the trending languages for Facebook apps are C, Java, & C++. Link.
{ "pile_set_name": "StackExchange" }
Q: Dirichlet's proof of the convergence of Fourier series Where can I find Dirichlet's proof of the convergence of Fourier series? A: Dirichlet's proof of the convergence of the Fourier series was nearly identical to a proof that Fourier offered in his original treatise on Heat Conduction. The reason this seems to have gone unnoticed is that Fourier's original manuscript was banned from publication for over a decade. Dirichlet was Fourier's student, and probably had access to the unpublished manuscript. H.S. Carslaw notes this in the Historical Introduction to his 1906 book Introduction to the Theory of Fourier’s series and integrals: "However, it is a mistake to suppose that Fourier did not establish in a rigorous and conclusive manner that a quite arbitrary function (meaning by this any function capable of being represented by an arc of a continuous curve or by successive portions of different continuous curves), could be represented by the series with his name, and it is equally wrong to attribute the first rigorous demonstration of this theorem to Dirichlet, whose earliest memoir was published in 1829. A closer examination of Fourier’s work will show that the importance of his investigations merits the fullest recognition, and Darboux, in the latest complete edition of Fourier’s mathematical works points out that the method he employed in the final discussion of the general case is perfectly sound and practically identical with that used later by Dirichlet in his classical memoir. In this discussion Fourier followed the line of argument which is now customary in dealing with infinite series. He proved that when the values $a_n,b_n$ are inserted in the terms of the series" $$a0 + (a1 \cos x + b1 \sin x) + (a2 \cos 2x + b2 \sin 2x) + …,$$ the sum of the terms up to $\cos(nx)$ and $\sin(nx)$ is $$\frac{1}{\pi}\int_{-\pi}^{\pi} f(x')\frac{ \sin \frac{1}{2}(2n + 1)(x'−x) }{\sin \frac{1}{2}(x'−x)} dx'$$ He then discussed the limiting value of this sum as n becomes infinite, and thus obtained the sum of the series now called Fourier’s Series." A: The first line and footnote of this answer link Dirichlet’s paper (in French) as well as a translation and expositions in English and German.
{ "pile_set_name": "StackExchange" }
Q: C# database interaction What would be the most generic way to handle user-database interaction in C# I expect being able to easilly swap the database drivers (data providers). I also think (not sure if it's possible) that it would be great if I could switch the data source from something DB-like (for example, plain MySQL database) to something absolutely another - like data serialized into xml or arbitrary binary file. I suspect the last case would require writing some Query-File interaction wrapper or something like that. So - could someone share a way to achieve the described behavior? I can definitely use LINQ for my queries and it does introduce some abstraction - but is it enough to make the data sources interchangeable? If yes, then what should I actually do to bring this to life and how would my development pipeline look? Thanks. A: Here's a small Respository Pattern Walkthrough using the EF Framework: someRepository.Find.Where(something => something.IsRed && something.IsBig) Create a generic interface called 'IRepository' of type T containing all the methods for data access. It could look like this: interface IRepository<T> where T : class { IEnumerable<T> FindAll(Expression<Func<T, bool>> exp); T FindSingle(Expression<Func<T, bool>> exp); // And many more! } Create an abstract 'Repository' class implementing this interface: class Repository<T> : IRepository<T> where T : class { TestDataContext _dataContext = TestDataContext(); // Would be your EF Context public IEnumerable<T> FindAll(Expression<Func<T, bool>> exp) { _dataContext.GetTable<T>().Where<T>(exp); } public T FindSingle(Expression<Func<T, bool>> exp) { _dataContext.GetTable<T>().Single(exp); } // And many more! } We can now create an interface for the ModelClass table/objects which implements our 'IRepository' and a concrete class extending the abstract 'Repository' class and implementing the 'IModelClassInterface': interface IModelClassRepository : IRepository<ModelClass> { } And the matching repository to implement it: class ModelClassRepository : Repository<ModelClass>, IModelClassRepository { } I would suggest using this approach as it gives you a lot of flexibility as well as enough power to control all the tiny entities you have. Calling those methods will be super easy that way: ModelClassRepository _repo = new ModelClassRepository(); _repo.Find.Where(something => something.IsRed && something.IsBig) Yes, it means that you have to do some work but it is hell easier for you to change the data source later on. You can even switch the EF Framework with any dataprovider of your choice. Be it XML, db4o or plain old Txt.
{ "pile_set_name": "StackExchange" }
Q: Multiple IDs returning values in another table - mysql, php I have two tables, one called Teams and the other called Scores Teams id - team_name 1 - Reds 2 - Blues 3 - Greens 4 - Yellows Scores home_team_id - away_team_id 1 - 2 3 - 4 I'm looking to get the team names returned in my php file by comparing the IDs for both home and away teams and returning the team name for them from Teams. I've used: SELECT * from scores, teams WHERE scores.home_team_id=teams.id OR scores.away_team_id=teams.id and also a LEFT JOIN that brings back similar values, but these only return duplicates. Is anyone able to assist so that the IDs shown for both home and away teams are reflected as per the team_name in Teams. A: You need to join scores with teams one time for home_team, and join another time for the away_team: select b.team_name home, c.team_name away from scores a join teams b on a.home_team_id = b.id join teams c on a.away_team_id = c.id
{ "pile_set_name": "StackExchange" }
Q: Laravel nginx default file I try to configure my laravel installation on a digital ocean instance with nginx running. The default config looks like this: server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /var/www/mfserver/public; index index.php index.html index.htm; server_name IPADDRESS; location / { try_files $uri $uri/ /index.php$is_args&args =404; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /var/www/mfserver/public; } location ~ \.php$ { try_files $uri $uri/ /index.php$is_args&args =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; fastcgi_intercept_errors off; fastcgi_buffer_size 16k; fastcgi_buffers 4 16k; } } The problem is, that when I call a route like /v1/aeds I get an error 404. Is the config not setup properly? The route file: Route::group(['domain' => 'SERVERIP', 'namespace' => 'API'], function() { Route::group(['prefix' => 'v1', 'namespace' => 'v1'], function() { // AED ROUTES Route::get('/aeds', 'AED\APIAEDController@index'); Route::post('/aeds', 'AED\APIAEDController@store'); Route::get('/aeds/{aeds}', 'AED\APIAEDController@show'); } A: Try replacing this: location / { try_files $uri $uri/ /index.php$is_args&args =404; } With this: location / { try_files $uri $uri/ /index.php?$query_string; } error_page 404 /index.php;
{ "pile_set_name": "StackExchange" }
Q: Docker Swarm host cannot resolve hosts on other nodes I am following this very excellent tutorial: https://github.com/binblee/springcloud-swarm When I deploy a stack to a Docker swarm that contains a single node (just the manager node), it works perfectly. docker stack deploy -c all-in-one.yml springcloud-demo I have four docker containers, one of them is Eureka service discovery, which all the other three containers register with successfully. The problem is when I add a worker node to the swarm, then two of the containers will be deployed to the worker, and two to the manager, and the services deployed to the worker node cannot find the Eureka server. java.net.UnknownHostException: eureka: Name does not resolve This is my compose file: version: '3' services: eureka: image: demo-eurekaserver ports: - "8761:8761" web: image: demo-web environment: - EUREKA_SERVER_ADDRESS=http://eureka:8761/eureka zuul: image: demo-zuul environment: - EUREKA_SERVER_ADDRESS=http://eureka:8761/eureka ports: - "8762:8762" bookservice: image: demo-bookservice environment: - EUREKA_SERVER_ADDRESS=http://eureka:8761/eureka Also, I can only access the Eureka Service Discovery server on the host on which it is deployed to. I thought that using "docker stack deploy" automatically creates an overlay network, in which all exposed ports will be routed to a host on which the respective service is running: From https://docs.docker.com/engine/swarm/ingress/ : All nodes participate in an ingress routing mesh. The routing mesh enables each node in the swarm to accept connections on published ports for any service running in the swarm, even if there’s no task running on the node. This is the output of docker service ls: manager:~/springcloud-swarm/compose$ docker service ls ID NAME MODE REPLICAS IMAGE PORTS rirdysi0j4vk springcloud-demo_bookservice replicated 1/1 demo-bookservice:latest 936ewzxwg82l springcloud-demo_eureka replicated 1/1 demo-eurekaserver:latest *:8761->8761/tcp lb1p8nwshnvz springcloud-demo_web replicated 1/1 demo-web:latest 0s52zecjk05q springcloud-demo_zuul replicated 1/1 demo-zuul:latest *:8762->8762/tcp and of docker stack ps springcloud-demo: manager:$ docker stack ps springcloud-demo ID NAME IMAGE NODE DESIRED STATE CURRENT STATE o8aed04qcysy springcloud-demo_web.1 demo-web:latest workernode Running Running 2 minutes ago yzwmx3l01b94 springcloud-demo_eureka.1 demo-eurekaserver:latest managernode Running Running 2 minutes ago rwe9y6uj3c73 springcloud-demo_bookservice.1 demo-bookservice:latest workernode Running Running 2 minutes ago iy5e237ca29o springcloud-demo_zuul.1 demo-zuul:latest managernode Running Running 2 minutes ago UPDATE: I successfully added another host, but now I can't add a third. I tried a couple of times, following the same steps, (installing docker, opening the requisite ports, joining the swarm) - but the node cannot find the Eureka server with the container host name). UPDATE 2: In testing that the ports were opened, I examined the firewall config: workernode:~$ sudo ufw status Status: active To Action From -- ------ ---- 8080 ALLOW Anywhere 4789 ALLOW Anywhere 7946 ALLOW Anywhere 2377 ALLOW Anywhere 8762 ALLOW Anywhere 8761 ALLOW Anywhere 22 ALLOW Anywhere However - when I try to hit port 2377 on the worker node from the manager node, I can't: managernode:~$ telnet xx.xx.xx.xx 2377 Trying xx.xx.xx.xx... telnet: Unable to connect to remote host: Connection refused A: Let us break the solution into parts. Each part tries to give you an idea about the solution and is interconnected with each other. Docker container network Whenever we create a container without specifying network, docker attaches it to default bridge network. According to this,. Service discovery is unavailable in the default network. Hene in order to maker service discovery work properly we are supposed to create a user-defined network as it provides isolation, DNS resolution and many more features. All these things are applicable when we use docker run command. When docker-compose is used to run a container and network is not specified, it creates its own bridge network. which has all the properties of the user-defined networks. These bridge networks are not attachable by default, But they allow docker containers in the local machine to connect to them. Docker swarm network In Docker swarm and swarm mode routing mesh Whenever we deploy a service to it without specifying an external network it connects to the ingress network. When you specify an external overlay network you can notice that the created overlay network will be available only to the manager and not in the worker node unless a service is created and is replicated to it. These are also not attachable by default and does not allow other containers outside swarm services to connect to them. So you don't need to declare a network as attachable until you connect a container to it outside swarm. Docker Swarm As there is no pre defined/official limit on no of worker/manager nodes, You should be able to connect from the third node. One possibility is that the node might be connected as a worker node but you might try to deploy a container in that node which is restricted by the worker node if the overlay network is not attachable. And moreover, you can't deploy a service directly in the worker node. All the services are deployed in the manager node and it takes care of replicating and scaling the services based on config and mode provided. Firewall As mentioned in Getting started with swarm mode TCP port 2377 for cluster management communications TCP and UDP port 7946 for communication among nodes UDP port 4789 for overlay network traffic ip protocol 50 (ESP) for encrypted overlay network These ports should be whitelisted for communication between nodes. Most firewalls need to be reloaded once you make changes. This can be done by passing reload option to the firewall and it varies between Linux distributions. ufw doesn't need to be reloaded but needs commit if rules are added in file. Extra steps to be followed in firewall Apart from whitelisting the above ports. You may need to whitelist docker0,docker_gw_bridge,br-123456 ip address with netmask of 16. Else service discovery will not work in same host machine. i.e If you are trying to connect to eureka in 192.168.0.12 where the eureka service is in same 192.168.0.12 it will not resolve as firewall will block the traffic. Refer this (NO ROUTE TO HOST network request from container to host-ip:port published from other container) Java Sometimes Java works weird such that it throws java.net.MalformedURLException and similar exceptions. I've my own experience of such case with the solution as well. Here ping resolved properly but Java rmi was throwing an error. So, You can define your own custom alias when you attach to a user-defined network. Docker service discovery By default, you can resolve to a service by using container name. Apart from that, you can also resolve a service as <container_name>.<network_name>. Of course, you can define alias as well. And even you can resolve it as <alias_name>.<network_name>. Solution So you should create a user-defined overlay network after joining the swarm and then should deploy services. In the services, You should mention the external network as defined here along with making changes in the firewall. If you want to allow external containers to connect to the network you should make the network attachable. Since you haven't provided enough details on what's happening with third server. I assume that you are trying to deploy a container there which is denied by docker overlay network as the network is not attachable.
{ "pile_set_name": "StackExchange" }
Q: How to program a loop in python that sums numbers I am trying to write a loop that calculates the total of the following series of numbers: 1/30 +2/29+3/28+…+30/1. I'm having trouble figuring out how to add, because the program below just displays the total as 0.033333333.... def main(): A=1 B=30 sum=(A/B) while A<=30: A+=1 B-=1 print('Total:',sum) main() A: Create two lists of the desired numbers, compute the value of each fraction, then sum then. sum(( a/b for a,b in zip(range(1,31),range(30,0,-1)))) A: You are not adding anything to sum on each iteration. You must add sum = sum + A / B inside the while loop. But you have to initialize sum with zero: sum = 0 Note: Don't use sum as name of a variable because it's a built-in function of Python. You can call that variable result, my_sum, ... Code: def main(): A = 1 B = 30 result = 0 while A <= 30: print A, B result += (A / B) A += 1 B -= 1 print('Total:', result) main() Also: You can see that in each term of the sum, A + B == 31, so B == 31 - A. Therefore, the code can be simplified: def main(): A = 1 result = 0 while A <= 30: result += (float(A) / (30 - A + 1)) A += 1 print('Total:', result)
{ "pile_set_name": "StackExchange" }
Q: Using RenderTargetBitmap to save a portion of the displayed images I have a simple WPF application where I display one very large image (9000x2875) and on top of it, many small images (64x64). To do this, I have a Canvas with one Image, then I programatically add the small images as they arrive. Now I am trying to save portions of the composite image as png files. I thought I would use a RenderTargetBitmap to render the portion of the Canvas that I wanted. My problem is that I cannot find a good way to save the right portion of the image. Here is a my current hack: private static void SaveImage(Canvas canvas, string file, int x, int y, int width, int height) { //changing 0,0 on the canvas so RenderTargetBitmap works as expected. canvas.RenderTransform = new MatrixTransform(1d, 0d, 0d, 1d, -x, -y); canvas.UpdateLayout(); RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d, Pixelformats.Pbgra32); bmp.Render(canvas); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); using(Stream s = File.Create(file)) { encoder.Save(s); } } The obvious problem with this is that the display will change due to the RenderTransform. It also makes the application slower. I did try to do a RenderTargetBitmap of the entire canvas, but that was much slower than doing this. So my questions are: Is there an easier way to save just a portion of the viewed image? If not, does someone have a suggestion for a better way to go about this? (I already tried a single WriteableBitmap, but that was about as slow as doing the RenderTargetBitmap of the entire canvas. A: What you want to use is a CroppedBitmap, which will allow you to save a cropped portion of your image. // (BitmapSource bmps) CroppedBitmap crop = new CroppedBitmap(bmps, new Int32Rect(selRect.X, selRect.Y, selRect.Width, selRect.Height)); Edit: Since there seems to be no way to get this to perform the way you want in WPF I would suggest pre-cropping the large image using GDI+ (without displaying it) and loading the region of it you want onto a smaller canvas.
{ "pile_set_name": "StackExchange" }
Q: All vagrant commands fail with "Bundler, the underlying system used to manage Vagrant plugins" Whenever I run any vagrant command, it fails, with the following error message, regardless of whether or not I'm in a vagrant folder, or any other folder. What's the problem? $ vagrant box list Bundler, the underlying system used to manage Vagrant plugins, is reporting that a plugin or its dependency can't be found. This is usually caused by manual tampering with the 'plugins.json' file in the Vagrant home directory. To fix this error, please remove that file and reinstall all your plugins using `vagrant plugin install`. A: I'm not exactly sure which file was causing the issue, but I simply removed my ~/.vagrant.d folder, and that fixed it for me. I suspect you could possibly just remove the ~/.vagrant.d/plugins.json file and that might work as well. You could of course just try renaming the above instead of deleting them to try it out yourself!
{ "pile_set_name": "StackExchange" }
Q: htaccess with Laravel on shared hosting I need your help. I have deployed Laravel app on shared hosting, and I have added htaccess file in order to redirect all traffic to public dir. Structure of directories is following: public_html | -------my_website | -------.htaccess I know, I should not do this and the right way is to put Laravel's public dir content in public_html and the rest of Laravel app should be outside of it, but in this case I am not in position to do it because of some reasons (not code related). And now I have a problem because anyone can access sensitive parts of website by hitting direct url, for example: http://mywebsite.com/my_website/database/database.sqlite I do not have extensive knowledge about htaccess, and have spent a lot of time searching how to protect sensitive files, but I was not able to accomplish this. My htaccess file currently looks like this: RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?mywebsite.com$ RewriteCond %{REQUEST_URI} !^/mywebsite/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /mywebsite/public/$1 RewriteCond %{HTTP_HOST} ^(www.)?mywebsite.com$ RewriteRule ^(/)?$ mywebsite/public/index.php [L] RewriteRule ^/?$ "https\:\/\/www\.mywebsite\.com" [R=301,L] RewriteCond %{HTTPS} !=on RewriteRule .* https://mywebsite.com%{REQUEST_URI} [R,L] Any help would be appreciated. A: Just as an example, because you show a link to an sqlite file, consider this: RewriteRule ^mywebsite/database - [F,L] This would keep HTTP requests to that sqlite file from being permitted. You can also add other directories to that, so if you also want to protect directory foo, then: RewriteRule ^mywebsite/(database|foo) - [F,L] This is a really common technique for protecting directories of PHP applications running on Apache
{ "pile_set_name": "StackExchange" }
Q: Sort on array elements inside the documents in MongoDB? I have a collection that looks like this: { "_id" : "customer1", "verarray" : [ "10.5.0-50_0", "11.5.0-30_0" ] } { "_id" : "customer2", "verarray" : [ "11.0.0-30_0", "11.5.0-80_0", "12.5.0-111_0", "13.3.0.21_0.31125", "13.5.0-20_0" ] } { "_id" : "customer3", "verarray" : [ "11.5.0-95_0", "12.6.0.131_0.33392", "10.0.0-5_0", "11.5.0.20_0.22028", "12.6.0.131_0.33392" ] } As you can see, the 3rd customer array is not in order. I want to sort each verarray. How do I do that? Thank you A: You can use $unwind to unwind array, sort it & then re-create the same array by grouping on condition _id. db.collection.aggregate([ { $unwind: "$verarray" }, { $sort: { verarray: 1 } }, // Using 1 for asc & use -1 for desc order { $group: { _id: "$_id", verarray: { $push: "$verarray" } } } ]) Test : mongoplayground Ref : aggregation
{ "pile_set_name": "StackExchange" }
Q: How To make Label like below image in swift I have working on chatting app and i have try to make label like bellow image but i can't done anyone can help me. A: In Xcode go to your assets, select your bubble image and click on show slicing. Slicing enable your image to stretch with the given slices without deforming.
{ "pile_set_name": "StackExchange" }
Q: Get value of property with reflection in C# i need to get value of property in C# with reflection . i need to find lenght of string and compare to max . i write this code : public static bool ValidateWithReflection(T model) { bool validate = false; var cls = typeof(T); PropertyInfo[] propertyInfos = cls.GetProperties(); foreach (PropertyInfo item in propertyInfos) { var max = item.GetCustomAttributes<MaxLenghtName>().Select(x => x.Max).FirstOrDefault(); if (max != 0) { var lenght = item.GetType().GetProperty(item.Name).GetValue(cls, null); if ((int)lenght > max) { return validate = true; } } } return validate; } and this for get value of property : var lenght = item.GetType().GetProperty(item.Name).GetValue(cls, null); but it show me this error : Message "Object does not match target type." string now whats the problem ? how can i solve this problem ? A: What is item.GetType().GetProperty(item.Name) supposed to do? item is a PropertyInfo instance. You're not looking to get properties of that, but of your model. So simplify your code to this: var value = item.GetValue(model) as string; if (value?.Length > max) { return validate = true; }
{ "pile_set_name": "StackExchange" }
Q: When plotting with tmap is it better to have the final SpatialPolygonsDataFrame or changes should be made within tmap options? I have downloaded a Spatial Polygons Data Frame from gadm.org but the map is slightly outdated and the names of the regions are in Latin. I need to change the names to Cyrillic and merge some of the regions. Is this something that would be better done on the Spatial Polygons Data Frame or in tmap while plotting? So far I have tried to extract separate data frames from the Spatial Polygons Data Frame and make the changes there, but I feel like I'm not going down the right path. I know I can plot those with ggplot2 as explained here, but I can't find any reference about using the same method being possible with tmap. A: It is difficult to quantify "better" - but the work you describe will be certainly easier and faster if you used the sf package format, rather than Spatial Polygons from sp package. It is available on the GADM site as well. The sf spatial objects are modified data frames, meaning you could apply to them the standard data wrangling methods - such as dplyr::mutate() to manipulate the names etc. As for the merging of regions you could use a workflow based on sf::st_union() that I described a while back in a blog post: https://www.jla-data.net/eng/dissolving-polygons-in-sf-environment/ - it even uses tmap as a plotting tool, so you should find the workflow familiar. And lastly a warning with regards to the five years old question about plotting maps with ggplot you linke: the approach using fortify() is by now obsolete, you will get much better results using the geom_sf() function of the current ggplot.
{ "pile_set_name": "StackExchange" }
Q: Change private static final field using Java reflection I have a class with a private static final field that, unfortunately, I need to change it at run-time. Using reflection I get this error: java.lang.IllegalAccessException: Can not set static final boolean field Is there any way to change the value? Field hack = WarpTransform2D.class.getDeclaredField("USE_HACK"); hack.setAccessible(true); hack.set(null, true); A: Assuming no SecurityManager is preventing you from doing this, you can use setAccessible to get around private and resetting the modifier to get rid of final, and actually modify a private static final field. Here's an example: import java.lang.reflect.*; public class EverythingIsTrue { static void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); } public static void main(String args[]) throws Exception { setFinalStatic(Boolean.class.getField("FALSE"), true); System.out.format("Everything is %s", false); // "Everything is true" } } Assuming no SecurityException is thrown, the above code prints "Everything is true". What's actually done here is as follows: The primitive boolean values true and false in main are autoboxed to reference type Boolean "constants" Boolean.TRUE and Boolean.FALSE Reflection is used to change the public static final Boolean.FALSE to refer to the Boolean referred to by Boolean.TRUE As a result, subsequently whenever a false is autoboxed to Boolean.FALSE, it refers to the same Boolean as the one refered to by Boolean.TRUE Everything that was "false" now is "true" Related questions Using reflection to change static final File.separatorChar for unit testing How to limit setAccessible to only “legitimate” uses? Has examples of messing with Integer's cache, mutating a String, etc Caveats Extreme care should be taken whenever you do something like this. It may not work because a SecurityManager may be present, but even if it doesn't, depending on usage pattern, it may or may not work. JLS 17.5.3 Subsequent Modification of Final Fields In some cases, such as deserialization, the system will need to change the final fields of an object after construction. final fields can be changed via reflection and other implementation dependent means. The only pattern in which this has reasonable semantics is one in which an object is constructed and then the final fields of the object are updated. The object should not be made visible to other threads, nor should the final fields be read, until all updates to the final fields of the object are complete. Freezes of a final field occur both at the end of the constructor in which the final field is set, and immediately after each modification of a final field via reflection or other special mechanism. Even then, there are a number of complications. If a final field is initialized to a compile-time constant in the field declaration, changes to the final field may not be observed, since uses of that final field are replaced at compile time with the compile-time constant. Another problem is that the specification allows aggressive optimization of final fields. Within a thread, it is permissible to reorder reads of a final field with those modifications of a final field that do not take place in the constructor. See also JLS 15.28 Constant Expression It's unlikely that this technique works with a primitive private static final boolean, because it's inlineable as a compile-time constant and thus the "new" value may not be observable Appendix: On the bitwise manipulation Essentially, field.getModifiers() & ~Modifier.FINAL turns off the bit corresponding to Modifier.FINAL from field.getModifiers(). & is the bitwise-and, and ~ is the bitwise-complement. See also Wikipedia/Bitwise operation Remember Constant Expressions Still not being able to solve this?, have fallen onto depression like I did for it? Does your code looks like this? public class A { private final String myVar = "Some Value"; } Reading the comments on this answer, specially the one by @Pshemo, it reminded me that Constant Expressions are handled different so it will be impossible to modify it. Hence you will need to change your code to look like this: public class A { private final String myVar; private A() { myVar = "Some Value"; } } if you are not the owner of the class... I feel you! For more details about why this behavior read this? A: If the value assigned to a static final boolean field is known at compile-time, it is a constant. Fields of primitive or String type can be compile-time constants. A constant will be inlined in any code that references the field. Since the field is not actually read at runtime, changing it then will have no effect. The Java language specification says this: If a field is a constant variable (§4.12.4), then deleting the keyword final or changing its value will not break compatibility with pre-existing binaries by causing them not to run, but they will not see any new value for the usage of the field unless they are recompiled. This is true even if the usage itself is not a compile-time constant expression (§15.28) Here's an example: class Flag { static final boolean FLAG = true; } class Checker { public static void main(String... argv) { System.out.println(Flag.FLAG); } } If you decompile Checker, you'll see that instead of referencing Flag.FLAG, the code simply pushes a value of 1 (true) onto the stack (instruction #3). 0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 3: iconst_1 4: invokevirtual #3; //Method java/io/PrintStream.println:(Z)V 7: return A: A little curiosity from the Java Language Specification, chapter 17, section 17.5.4 "Write-protected Fields": Normally, a field that is final and static may not be modified. However, System.in, System.out, and System.err are static final fields that, for legacy reasons, must be allowed to be changed by the methods System.setIn, System.setOut, and System.setErr. We refer to these fields as being write-protected to distinguish them from ordinary final fields. Source: http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.4
{ "pile_set_name": "StackExchange" }
Q: Event Management Calendar for Drupal? I run a church website and we have an event calendar page. We've been using Google Calendar for this - but there isn't a way to make everyone have the same default calendar - so some people are adding entries to their personal calendars and these are never showing up on the public calendar. I've been thinking about moving to either a hosted or a drupal solution (the site itself is drupal). I can't believe the process it takes to get a calendar up and running using the Date / Calendar modules. I'm wondering if there is an easier way to do this (with Drupal) or if anyone can recommend alternative systems that might be a better fit? A: If you feel unconfortable with Drupal's philosophy of "many small highly focused modules together make applications (aka the Unix way)" you are, indeed best off not seeking your solution in Drupal. The Drupal Way, would be to install CCK, Date and Views. These come with a lot of example views, and documentation that make running an even-calendar possible. Agreed, it is not easy, it is not a turnkey solution. But this is the way Drupal prefers things to be handled. However, on top of Drupal you can run a system like "features". Such a feature is actually a bundle of many dependencies and portable pre-configurations. In other words: you enable the "calendar" feature: and boom: you have a views, CCK and Date-based calendar, but turnkey. I am not aware of a public "feature" for calendars. And would think that running "features" on top of your Drupal is rather complex at the moment. You may, however, want to look at the Drupal-based distribution OpenAtrium, which uses features extensively to run calendars, wiki, and so on.
{ "pile_set_name": "StackExchange" }
Q: Calculate the displacement coordinates of a semi-articulated truck As shown in the image below, I'm creating a program that will make a 2D animation of a truck that is made up of two articulated parts. The truck pulls the trailer. The trailer moves according to the docking axis on the truck. Then, when the truck turns, the trailer should gradually align itself with the new angle of the truck, as it does in real life. I would like to know if there is any formula or algorithm that does this calculation in an easy way. I've already seen inverse kinematics equations, but I think for just 2 parts it would not be so complex. Can anybody help me? A: Let A be the midpoint under the front axle, B be the midpoint under the middle axle, and C be the midpoint under the rear axle. For simplicity assume that the hitch is at point B. These are all functions of time t, for example A(t) = (a_x(t), a_y(t). The trick is this. B is moving directly towards A with the component of A's velocity in that direction. Or in symbols, dB/dt = (dA/dt).(A-B)/||A-B|| And similarly, dC/dt = (dB/dt).(B-C)/||B-C|| where . is the dot product. This turns into a non-linear first-order system in 6 variables. This can be solved with normal techniques, such as https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods. UPDATE: Added code Here is a Python implementation. You can replace it with https://rosettacode.org/wiki/Runge-Kutta_method for your favorite language and your favorite linear algebra library. Or even hand-roll that. For my example I started with A at (1, 1), B at (2, 1) and C at (2, 2). Then pulled A to the origin in steps of size 0.01. That can be altered to anything that you want. #! /usr/bin/env python import numpy # Runga Kutta method. def RK4(f): return lambda t, y, dt: ( lambda dy1: ( lambda dy2: ( lambda dy3: ( lambda dy4: (dy1 + 2*dy2 + 2*dy3 + dy4)/6 )( dt * f( t + dt , y + dy3 ) ) )( dt * f( t + dt/2, y + dy2/2 ) ) )( dt * f( t + dt/2, y + dy1/2 ) ) )( dt * f( t , y ) ) # da is a function giving velocity of a at a time t. # The other three are the positions of the three points. def calculate_dy (da, A0, B0, C0): l_ab = float(numpy.linalg.norm(A0 - B0)) l_bc = float(numpy.linalg.norm(B0 - C0)) # t is time, y = [A, B, C] def update (t, y): (A, B, C) = y dA = da(t) ab_unit = (A - B) / float(numpy.linalg.norm(A-B)) # The first term is the force. The second is a correction to # cause roundoff errors in length to be selfcorrecting. dB = (dA.dot(ab_unit) + float(numpy.linalg.norm(A-B))/l_ab - l_ab) * ab_unit bc_unit = (B - C) / float(numpy.linalg.norm(B-C)) # The first term is the force. The second is a correction to # cause roundoff errors in length to be selfcorrecting. dC = (dB.dot(bc_unit) + float(numpy.linalg.norm(B-C))/l_bc - l_bc) * bc_unit return numpy.array([dA, dB, dC]) return RK4(update) A0 = numpy.array([1.0, 1.0]) B0 = numpy.array([2.0, 1.0]) C0 = numpy.array([2.0, 2.0]) dy = calculate_dy(lambda t: numpy.array([-1.0, -1.0]), A0, B0, C0) t, y, dt = 0., numpy.array([A0, B0, C0]), .02 while t <= 1.01: print( (t, y) ) t, y = t + dt, y + dy( t, y, dt )
{ "pile_set_name": "StackExchange" }
Q: similar string from two data frame with a count number I have two data that I am trying to find similar strings between them with their position. df1 <- structure(list(split = structure(c(7L, 6L, 8L, 3L, 2L, 4L, 9L, 4L, 9L, 5L, 10L, 1L), .Label = c("America1", "corea", "coreanorth1", "gdyijq", "gqdtr", "india-2", "india1", "india3", "udyhfs", "USA" ), class = "factor"), count = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 4L, 5L, 5L)), .Names = c("split", "count"), row.names = c(NA, -12L), class = "data.frame") it looks like this split count india1 1 india-2 1 india3 1 coreanorth1 2 corea 2 gdyijq 3 udyhfs 3 gdyijq 4 udyhfs 4 gqdtr 4 USA 5 America1 5 I have another data with the same structure, df2<- structure(list(split = structure(c(3L, 2L, 1L), .Label = c("America1", "gdyijq", "india1"), class = "factor"), count = 1:3), .Names = c("split", "count"), class = "data.frame", row.names = c(NA, -3L)) split count india1 1 gdyijq 2 America1 3 I want to check whether from df2 any string exist in df1 and put the count with a comma seperated for example india1 is in the df2 and is similar to india1 in df1, so the output is india1 1,1 if it appears more than once, each time with a semicolon seperated like gdyijq The output looks like below india1 1,1 gdyijq 2,3;2,4 America1 3,5 A: you want something like merge or join from dplyr: library(dplyr) (DF <- inner_join(df1, df2, by = "split") Now we have to combine all entries for one split: DF %>% group_by(split) %>% summarize(counts = paste0(count.x, ",", count.y, collapse = ";")) Results in # A tibble: 3 × 2 split counts <chr> <chr> 1 America1 5,3 2 gdyijq 3,2;4,2 3 india1 1,1
{ "pile_set_name": "StackExchange" }
Q: redhat 7 + systemctl verification I have try this on redhat 7 systemctl list-unit-files --type=service|grep iptables or systemctl list-unit-files --type=service|grep firewall but not get any output - is this mean the iptables/firewall deleted from systemctl ? I see also that iptables installed on my linux redhat # rpm -qa |grep iptables iptables-1.4.21-16.el7.x86_64 A: the command systemctl list-unit-files --type=service|grep iptables Not display the iptables because iptables-services is not installed! To installed the iptables service need to perform yum install iptables-services yum install iptables-services Loaded plugins: product-id, search-disabled-repos, subscription-manager This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register. Resolving Dependencies --> Running transaction check ---> Package iptables-services.x86_64 0:1.4.21-16.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================================================================================================ Package Arch Version Repository Size ================================================================================================================================================================ Installing: iptables-services x86_64 1.4.21-16.el7 updates 50 k Transaction Summary ================================================================================ ================================================================================ Install 1 Package Total download size: 50 k Installed size: 24 k Is this ok [y/d/N]: y Downloading packages: iptables-services-1.4.21-16.el7.x86_64.rpm | 50 kB 00:00:00 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : iptables-services-1.4.21-16.el7.x86_64 1/1 Verifying : iptables-services-1.4.21-16.el7.x86_64 1/1 Installed: iptables-services.x86_64 0:1.4.21-16.el7 Complete! now systemctl show it -:) # systemctl list-unit-files --type=service|grep iptables iptables.service disabled
{ "pile_set_name": "StackExchange" }
Q: Google Calendar api v3 using asp.net I am planing to integrate google calendar v3 api. i have Install the NuGet package Google.Apis.calendar.v3 package and i got the sample from the google Dim credential As UserCredential Using stream As New FileStream("client_secrets.json", FileMode.Open, FileAccess.Read) credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None, New FileDataStore("Calendar.VB.Sample")).Result End Using there they specified to give the client and secret id in the client_secrets.josn file. while executing the code it take me to the browser and ask for login details. After login it show me the error as invalid return url. is there any other way to specify the call back url. A: After you create a project in the Google API Console there you must have created an oAuth2.0 clientID where you defined the RedirectUri. So go in the Google API Console (http://code.google.com/apis/console) and change it to the correct Uri. NB If working in the development environment make sure you use a fixed IP port otherwise you have to change the Uri every time you build and run your project.
{ "pile_set_name": "StackExchange" }
Q: Как аналогично сделать на jquery? Есть несколько прослушек на JS, как сделать аналогичное на JQuery? Объясните, кто хорошо понимает: почему переменные inp и nameFscrn не равны? И как заменить addEventListener на аналогичное с JQuery? var inp = document.getElementById('name-f-scrn'); var nameFscrn = $('#name-f-scrn'); inp.addEventListener('invalid', function(event){ event.preventDefault(); if (!event.target.validity.valid){ $('.notify').addClass('error').text('Введите имя в одном из следующих форматов: Имя, Фамилия Имя, Фамилия Имя Отчество'); nameFscrn.addClass('invalid'); } }); inp.addEventListener('input', function(event){ if ($('.notify').css('display') == 'block'){ nameFscrn.removeClass('invalid'); $('.notify').removeClass('error'); } }); А также вот в следующем коде, как заменить строчку document.getElementById('bcaa-f-scrn').checked на аналогичную на JQuery? $('#bcaa-f-scrn').change(function(){ if(document.getElementById('bcaa-f-scrn').checked){ bcaaVal = $('#bcaa-quantity').val() * 1; bcaaWeight = $('#bcaa-quantity option:selected').data('weight') * 1; }else{ bcaaVal = 0; bcaaWeight = 0; } }); Буду очень благодарен! A: Эти функции можно заменить с помощью on. var inp = document.getElementById('name-f-scrn'); var nameFscrn = $('#name-f-scrn'); nameFscrn.on('invalid', function(event) { event.preventDefault(); if (!event.target.validity.valid) { $('.notify').addClass('error').text('Введите имя в одном из следующих форматов: Имя, Фамилия Имя, Фамилия Имя Отчество'); nameFscrn.addClass('invalid'); } }); nameFscrn.on('input', function() { if($('.notify').css('display') == 'block') { nameFscrn.removeClass('invalid'); $('.notify').removeClass('error'); }; }); Выводит оно не одно и тоже потому, что document.getElementById выводит определённый элемент, а $('#...') выводит лист элементов с таким ID. Что бы к этой записи можно было применять функции JS, нужно указать индекс элемента: $('#...')[индекс] или $('#...').get(индекс). Для ID, индекс всегда 0 Все значения типа checked прописываются и проверяются через функцию prop: $('#bcaa-f-scrn').change(function() { if ( $('#bcaa-f-scrn').prop('checked') ) { bcaaVal = $('#bcaa-quantity').val() * 1; bcaaWeight = $('#bcaa-quantity option:selected').data('weight') * 1; } else { bcaaVal = 0; bcaaWeight = 0; } });
{ "pile_set_name": "StackExchange" }
Q: mysqli bind_result/fetch problem I am learning how to use prepared statements with php 5 mysqli objects and I am having trouble getting the basic result binding to work. I am following the example code from php.net but something isn't working, the bound results are always NULL. Here is what I have /* prepare statement */ if ($stmt = $DB->mysqli->prepare("SELECT `alias`,`nameFirst`,`nameLast`,`email`,`access_level` FROM `users` WHERE `alias` LIKE CONCAT('%',?,'%') LIMIT 20;")) { $stmt->bind_param('s',$alias); $stmt->execute(); /* bind variables to prepared statement */ $stmt->bind_result($col1, $col2); /* fetch values */ while ($stmt->fetch()) { echo "COL 1=".$col1." | COL2=".$col2."<br />"; } /* close statement */ $stmt->close(); } else echo "NO DICE"; A: Ooops, I missed the note right on the php docs: Note that all columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch(). Found the answer here: Prepared Statement not returning anything
{ "pile_set_name": "StackExchange" }