prompt
stringlengths
49
4.73k
ground_truth
stringlengths
238
35k
Number prime with c++, what is wrong with the code and how to optimize? I'm trying to figure this problem <http://www.urionlinejudge.com.br/judge/problems/view/1032>, where I need to find the prime numbers between 1 to 3501 the fastest way, since the time limit may not exceed 1 second. The way I'm calculating these prime numbers is to check if they are prime until their square root, then eliminating the multiple of the first prime numbers [2, 3, 5, 7] to improve the performance of the algorithm. Yet, the time exceeds. My code (takes 1.560s as the internal testing of the submission system) ``` #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <iostream> #include <set> using namespace std; set<int> circ; set<int> primes; /* Calculate List Primes */ void n_prime(int qtd){ int a, flag=1, l_prime = 1; float n; for(int i=0;i<qtd;i++){ switch (l_prime){ case 1: l_prime = 2; break; case 2: l_prime = 3; break; default: while(1){ flag=1; l_prime+=2; if(l_prime>7) while(l_prime%2==0||l_prime%3==0||l_prime%5==0||l_prime%7==0) l_prime++; n=sqrt(l_prime); for(a=2;a<=n;a++){ if(l_prime%a==0){ flag=0; break; } } if(flag) break; } } primes.insert(l_prime); } } /* Initialize set with live's */ void init_circ(int t){ circ.clear(); for(int a=0;a<t;a++){ circ.insert(a+1); } } /* Show last live*/ void show_last(){ for(set<int>::iterator it=circ.begin(); it!=circ.end(); ++it) cout << *it << "\n"; } int main(){ int n = 0; clock_t c1, c2; c1 = clock(); n_prime(3501); while(scanf("%d", &n)&&n!=0){ init_circ(n); int idx=0, l_prime,count = 0; set<int>::iterator it; set<int>::iterator np; np=primes.begin(); for(int i=0;i<n-1;i++){ l_prime=*np; *np++; idx = (idx+l_prime-1) % circ.size(); it = circ.begin(); advance(it, idx); circ.erase(it); } show_last(); } c2 = clock(); printf("\n\nTime: %.3lf", (double)(c2-c1)/CLOCKS_PER_SEC); return 0; } ```
The easiest way is the [sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), here's my implementation: ``` //return the seive of erstothenes std::vector<int> generate_seive(const ulong & max) { std::vector<int> seive{2}; std::vector<bool> not_prime(max+1); ulong current_prime = seive.back(); bool done = false; while(!done){ for (int i = 2; i * current_prime <= max;i++) { not_prime[i*current_prime]=true; } for (int j = current_prime+1;true;j++) { if (not_prime[j] == false) { if( j >= max) { done = true; break; } else { seive.push_back(j); current_prime = j; break; } } } } return seive; } ``` Generates all the prime numbers under max, BTW these are the times for my sieve and 3501 as the max number. ``` real 0m0.008s user 0m0.002s sys 0m0.002s ```
text mode cursor doesn't appear in qemu vga emulator I have a problem with the function that updates cursor position in text mode the function definition and declaration are ``` #include <sys/io.h> signed int VGAx = 0,VGAy=0; void setcursor() { uint16_t position = VGAx+VGAy*COLS; outb(0x0f, 0x03d4); outb((position<<8)>>8,0x03d5); outb(0x0e,0x03d4); outb(position>>8,0x03d5); } ``` and the file sys/io.h ``` static inline unsigned char inb (unsigned short int port) { unsigned char value; asm ("inb %0, %%al":"=rm"(value):"a"(port)); return value; } static inline void outb(unsigned char value, unsigned short int port) { asm volatile ("outb %%al, $0"::"rm"(value), "a"(port)); } ``` before using the function the cursor sometimes was blinking underscore and sometimes didn't appear while after using the function no cursor appeared here is the main function that runs ``` #include <vga/vga.h> int kmain(){ setcursor() setbgcolor(BLACK); clc(); setforecolor(BLUE); terminal_write('h'); setcursor(); return 0; } ``` I tried using this function ``` void enable_cursor() { outb(0x3D4, 0x0A); char curstart = inb(0x3D5) & 0x1F; // get cursor scanline start outb(0x3D4, 0x0A); outb(0x3D5, curstart | 0x20); // set enable bit } ``` which is provided [here](https://stackoverflow.com/questions/25321608/moving-text-mode-cursor-not-working) but I got this error `inline asm: operand type mismatch for 'in'` any help is appreciated **EDIT** I tried to fix the wrong `inb` and `outb`: ``` static inline unsigned char inb (unsigned short int port) { unsigned char value; asm volatile("inb %1, %0" : "=a"(value) : "Nd"(port)); return value; } static inline void outb(unsigned char value, unsigned short int port) { asm volatile ("outb %%al, $0"::"Nd"(value), "a"(port)); } ``` I guess this is the right definition but still no cursor appeard **EDIT 2** I followed the given answer and defined the `io.h` file as the following ``` static inline unsigned char inb (unsigned short int port) { unsigned char value; asm volatile ("inb %1, %0" : "=a"(value) : "Nd"(port)); return value; } static inline void outb(unsigned char value, unsigned short int port) { asm volatile ("outb %0, %1"::"a"(value), "Nd"(port)); } ``` I would like to mention that I also added`enable_cursor();` to the beginning of kmain now the compile time error is fixed but no cursor appeared (which is the main problem) **EDIT 3** I would like to point out that a version of the whole code is availabe on [gihub](http://github.com/oddcoder/opal101) if any one want access to pieces of code that are no available in the question
# inb and outb Function Bugs This code for `inb` is incorrect: ``` static inline unsigned char inb (unsigned short int port) { unsigned char value; asm ("inb %0, %%al":"=rm"(value):"a"(port)); return value; } ``` A few problems with it: - It seems you have the parameters to `inb` reversed. See the [instruction set reference](http://x86.renejeschke.de/html/file_module_x86_id_139.html) for `inb`. Remember that in AT&T syntax (that you are using in your GNU Assembler code) the operands are reversed. The instruction set reference shows them in Intel format. - The port number is either specified as an immediate 8 bit value or passed in the *DX* register. The proper constraint for specifying the `DX` register or an immediate 8 bit value for inb/outb is `Nd`. See my Stackoverflow [answer](https://stackoverflow.com/a/32792177/3857942) here for an explanation of the constraint `Nd`. - The destination that the value read is returned in is either *AL/AX/EAX* so a constraint `=rm` on the output that says an available register or memory address is incorrect. It should be `=a` in your case. Your code should be something like: ``` static inline unsigned char inb (unsigned short int port) { unsigned char value; asm volatile ("inb %1, %0" : "=a"(value) : "Nd"(port)); return value; } ``` Your assembler template for `outb` is incorrect: ``` static inline void outb(unsigned char value, unsigned short int port) { asm volatile ("outb %%al, $0"::"rm"(value), "a"(port)); } ``` A couple problems with it: - The port number is either specified as an immediate 8 bit value or passed in the *DX* register. The proper constraint for specifying the `DX` register or an immediate 8 bit value for inb/outb is `Nd`. See my Stackoverflow [answer](https://stackoverflow.com/a/32792177/3857942) here for an explanation of the constraint `Nd`. - The value to output on the port has to be specified in *AL/AX/EAX* so a constraint `rm` on the value that says an available register or memory address is incorrect. It should be `a` in your case. See the [instruction set reference](http://x86.renejeschke.de/html/file_module_x86_id_222.html) for `outb` The code should probably look something like: ``` static inline void outb(unsigned char value, unsigned short int port) { asm volatile ("outb %0, %1"::"a"(value), "Nd"(port)); } ``` # Enabling and Disabling the Cursor I had to look up the VGA registers about the cursor and found this [document](http://web.stanford.edu/class/cs140/projects/pintos/specs/freevga/vga/crtcreg.htm#0A) on the *cursor start register* which says: > > > ``` > Cursor Start Register (Index 0Ah) > > ------------------------------------------------- > | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | > ------------------------------------------------- > | | | CD | Cursor Scan Line Start | > ------------------------------------------------- > > ``` > > CD -- Cursor Disable > > > This field controls whether or not the text-mode cursor is displayed. Values are: > > > > > > > 0 -- Cursor Enabled > > > > > > 1 -- Cursor Disabled > > > > > > > > > Cursor Scan Line Start > > > An important thing is that the cursor is **disabled** when the *bit 5* is **set**. In your *github* `setcursor` function you do this: ``` outb(curstart | 0x20, 0x3D5); ``` `curstart | 0x20` **sets** *bit 5* (0x20 = 0b00100000). If you want to **clear** *bit 5* and **enable** the cursor, then you bitwise *NEGATE*(~) the bitmask and bitwise *AND* (&) that with `curstart`. It should look like this: ``` outb(curstart & ~0x20, 0x3D5); ``` # VGA Function Bugs Once you have the cursor properly enabled it will render the cursor in the foreground color (attribute) for the particular video location it is currently over. One thing I noticed is that your `clc` routine does this: ``` vga_deref_80x24(VGAx,VGAy) = \ vga_encode_80x24(' ',BgColor,BgColor); ``` The thing to observe is that you set the attribute for the foreground and background colors to `BgColor` . If you set the `bgcolor` to black before calling `clc` it will flash a black underline cursor on a black background rendering it invisible on any screen location. For the cursor to be visible it must be on a screen location where the foreground and background are different colors. One way to see if this works is to change the code to: ``` vga_deref_80x24(VGAx,VGAy) = \ vga_encode_80x24(' ',BgColor,ForeColor); ``` I think it is a bug that you are clearing it with encoding `vga_encode_80x24(' ',BgColor,BgColor);` I think you mean to use `vga_encode_80x24(' ',BgColor,ForeColor);` Now in your `kmain` function you need to set a *ForeColor* and *BgColor* before calling `clc` and they both must be different color to make the cursor visible. You have this code: ``` setbgcolor(BLACK); clc(); setforecolor(BLUE); ``` It should now be: ``` setbgcolor(BLACK); setforecolor(BLUE); clc(); ``` Now if the cursor is rendered anywhere on an unwritten location on the screen it will flash BLUE underline on BLACK background. This should solve your cursor problem. However, I noticed that you also use `encode vga_encode_80x24(' ',BgColor,BgColor);` in your VGA `scrolldown` and `terminal_control` functions. I think this is a bug as well, and I think you should use `encode vga_encode_80x24(' ',BgColor,ForeColor);` instead. You do seem to set it properly in `terminal_write`. If you want to change the color of the cursor at any location you could write a function that changes the foreground attribute under the cursor location without changing the background color. Make sure the two attributes (Foreground and background color) are different for the cursor to be visible. If you wish to hide the cursor you can set foreground and background color the same color for the screen location the cursor is currently at.
Up vote and down vote in Laravel eloquent I want to create an up vote and down vote system for my website where a unique user can vote up/down for one post and next time he only allow to opposite to get off from database and after that he again can up or down vote. In this case I have: users table : ``` id name ``` debates table : ``` id post ``` upvotes table: ``` id user_id debate_id ``` and similarly downvote table: ``` id user_id debate_id ``` Is that a good way to manage and track up vote and down vote concept?
I think, you can use a single table to track the `votes` and the structure could be something like this Table : **votes** ``` id | user_id | debate_id | vote ``` Here, `vote` field could be `tinyInt` with defauld `null`. And, in `vote` field, you just keep two different values depending on the vote type, for example, if a user up votes then insert a value of `1` in the `vote` field and for down vote, insert the value of `0`. So, your table may look something like this ``` id | user_id | debate_id| vote 1 | 10 | 4 | 1 <-- up 2 | 11 | 4 | 0 <-- down 3 | 12 | 4 | 1 <-- up ``` In this case, two users with `id = 10` and `id = 12` up voted the post whose `debate_id = 4` and another user with `user_id = 11` down voted on the same post. IN this case, you may find out how many up or down votes a post got by counting the `vote` field's value, for example, you may count for up votes for `debate_id = 4` using something like this ``` $count = Debate::where('debate_id', '=', 4)->where('vote', '=', 1)->count(); ``` Also, you may use something [Query Scope](http://laravel.com/docs/eloquent#query-scopes), this is just an idea and it's not possible to make an answer which covers everything in this scope. You should start using some basic idea and if you stuck at a certain point, then you may ask specific questions with your code. Also, I would like to mention that, if you find a user id in the `votes` table with a certain `debate_id` then this user has voted on this post and to find out the vote type, just check the `vote` field `1 or 0`.
Search on a particular line using Regular Expression in Java I am new with Regular Expression and might be my question is very basic one. I want to create a regular expression that can search an expression on a particular line number. eg. I have data ``` "\nerferf erferfre erferf 12545" + "\ndsf erf" + "\nsdsfd refrf refref" + "\nerferf erferfre erferf 12545" + "\ndsf erf" + "\nsdsfd refrf refref" + "\nerferf erferfre erferf 12545" + "\ndsf erf" + "\nsdsfd refrf refref" + "\nerferf erferfre erferf 12545" + ``` And I want to search the number 1234 on 7th Line. It may or may not be present on other lines also. I have tried with ``` "\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\d{4}" ``` but am not getting the result. Please help me out with the regular expression.
Firstly, your `newline` character should be placed at the end of the lines. That way, picturing a particular line would be easier. *Below explanation is based on this modification.* Now, to get to 7th line, you would first need to skip the first 6 line, that you can do with `{n,m}` quantifier. You don't need to write `.*\n` 6 times. So, that would be like this: ``` (.*\n){6} ``` And then you are at 7th line, where you can match your required digit. That part would be something like this: ``` .*?1234 ``` And then match rest of the text, using `.*` So, your final regex would look like: ``` (?s)(.*\n){6}.*?1234.* ``` So, just use [`String#matches(regex)`](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches%28java.lang.String%29) method with this regex. P.S. `(?s)` is used to enable single-line matching. Since dot`(.)` by default, does not matches the newline character. To print something you matched, you can use capture groups: ``` (?s)(?:.*\n){6}.*?(1234).* ``` This will capture `1234` if matched in *group 1*. Although it seems unusual, that you capture an exact string that you are matching - like capturing `1234` is no sense here, as you know you are matching `1234`, and not against `\\d`, in which case you might be interested in exactly what are those digits.
using bash to read pdf content I have several ebooks which are not always named after the title of the book. Would it be possible to use bash commands to read the pdf's first page (and do a trivial grep etc) and rename the file accordingly ? thanks -a
[Poppler Library](http://poppler.freedesktop.org/) provides a set of command line tools to extract text and metadata from PDF files. To extract metadata you could use `pdfinfo` For example ``` :~> pdfinfo ProAdminGuide.pdf 2>/dev/null | \ grep Title: | sed 's/Title:[ ]*//' ``` Outputs ``` Professional Administrator’s Guide ``` Sometimes the PDF file does not contain complete metadata. In this case you might try your luck to extract the title from the text of the title page. To extract the text of the title page you could use `pdftotext` ``` :~> pdftotext ProAdminGuide.pdf - | head -3 ``` Outputs ``` A division of Professional Administrator’s Guide, published by ``` In any case it is worth first checking that you can extract the titles from the pdf file before renaming them automatically ``` for book in *.pdf ; do title=$(pdfinfo "$book" 2>/dev/null | grep Title: | sed 's/Title:[ ]*//') [[ "$title" ]] || continue mv "$book" "${title}.pdf" done ``` **Edit:** added a nice idiom suggested by Charles Duffy in the comments as a precaution
Wondering About GeoDjango and Mapping Services I'm trying to build my first GIS app with GeoDjango and I have a few questions before I begin: First: What exactly is GeoDjango for in relation to Google Maps? Is it simply for processing the information, which is then passed to a service like Google Maps? If this is true, what's the advantage of using GeoDjango vs simply storing lat/long points in a db and passing them to Google Maps? Assuming all of the above is true, if I suddenly want to change map providers (from Google to Bing, lets say), does GeoDjango make this much easier and more modular? I'm having a little trouble understanding the relationship between GeoDjango and mapping services, if someone could clarify this for me with some examples, that'd be awesome. Next: If I have an existing project in GeoDjango that I want to integrate that uses MySQL, should I move everything over to PostgreSQL because GeoDjango doesn't work well with MySQL? What should I do in terms of databases?
As said in [documentation](https://docs.djangoproject.com/en/dev/ref/contrib/gis/tutorial/#introduction): > > GeoDjango is an add-on for Django that turns it into a world-class > geographic Web framework. GeoDjango strives to make it as simple as > possible to create geographic Web applications, like location-based > services. Some features include: > > > - Django model fields for OGC geometries. > - Extensions to Django’s ORM for the querying and manipulation of spatial data. > - Loosely-coupled, high-level Python interfaces for GIS geometry operations and data formats. > - Editing of geometry fields inside the admin. > > > You can easily process GeoDjango information to Google Maps via Google Maps Javascript API. Advantages of GeoDjango are special tools for dealing with geometry types of informations. For example such kinds of [fields](https://docs.djangoproject.com/en/dev/ref/contrib/gis/model-api/): - GeometryField - PointField - LineStringField - PolygonField - MultiPointField - MultiLineStringField - MultiPolygonField - GeometryCollectionField And base-level integration with [spacial databases](https://docs.djangoproject.com/en/1.3/ref/contrib/gis/install/#spatial-database) and [geospacial libraries](https://docs.djangoproject.com/en/1.3/ref/contrib/gis/install/#geospatial-libraries): - GEOS - PROJ.4 - GDAL - GeoIP - PostGIS - SpatiaLite If you want to keep ability to change map provider in future it's recommended to use frontend(map) - backend(GeoDjango) architecture. In this case you can change frontend or switch between different maps easily. I recommend also migrate to postgres because it has a various tools, such GEOS, PROJ.4, PostGIS libraries that may be useful for dealing with spacial data. MySQL has limited functionality as said in documentation.
Why does variable declaration work well as the condition of for loop? What's the return value/type of a declaration like `int i = 5`? Why doesn't compile this code: ``` #include <iostream> void foo(void) { std::cout << "Hello"; } int main() { int i = 0; for(foo(); (int i = 5)==5 ; ++i)std::cout << i; } ``` while this does ``` #include <iostream> void foo(void) { std::cout << "Hello"; } int main() { int i = 0; for(foo(); int i = 5; ++i)std::cout << i; } ```
The [for](http://en.cppreference.com/w/cpp/language/for#Syntax) loop requires *condition* to be either an expression or a declaration: > > condition - either > > > - an expression which is contextually convertible to bool. This expression is evaluated before each iteration, and if it yields false, > the loop is exited. > - a declaration of a single variable with a brace-or-equals initializer. the initializer is evaluated before each iteration, and > if the value of the declared variable converts to false, the loop is > exited. > > > The 1st code doesn't work because `(int i = 5)==5` is not a valid [expression](http://en.cppreference.com/w/cpp/language/expressions) at all. (It's not a declaration either.) The operand of `operator==` is supposed to be an expression too, but `int i = 5` is a declaration, not an expression. The 2nd code works because `int i = 5` matches the 2nd valid case for *condition*; a declaration of a single variable with a equals initializer. The value of `i` will be converted to `bool` for judgement; which is always `5`, then leads to an infinite loop.
TypeScript allow for optional arguments - overloading methods I have this method signature on a class: ``` lock(key: string, opts: any, cb?: LMClientLockCallBack): void; ``` if a user uses it like so: ``` lock('foo', null, (err,val) => { }); ``` they will get the right typings. However, if they omit the options argument and do this: ``` lock('foo', (err,val) => { }); ``` then `tsc` sees the callback function as type `any`, just like this: [![enter image description here](https://i.stack.imgur.com/ONspp.png)](https://i.stack.imgur.com/ONspp.png) Is there any way to allow users to avoid passing an empty object or null as the second argument, and shift the callback over? I tried overloading the method, into two definitions: ``` lock(key: string, cb: LMClientLockCallBack, n?: LMClientLockCallBack) : void; lock(key: string, opts: any, cb?: LMClientLockCallBack) { ... } ``` but it still doesn't compile, there are new problems: [![enter image description here](https://i.stack.imgur.com/Lktmo.png)](https://i.stack.imgur.com/Lktmo.png) and if I try this: ``` lock(key: string, cb: LMClientLockCallBack) : void; lock(key: string, opts: any, cb?: LMClientLockCallBack) { ... } ``` I get this: [![enter image description here](https://i.stack.imgur.com/rq2ED.png)](https://i.stack.imgur.com/rq2ED.png) Surely there must be a solution to this one?
When overloading the method in TypeScript, the implementation doesn't count as one of overloads. You should thus create three function definitions: two ones for different overloads, as you've already done, and the third - with optional argument and real implementation, which is in your code erroneously connected to the second overload definition. So you'll have: ``` lock(key: string, cb: LMClientLockCallBack) : void; lock(key: string, opts: any, cb: LMClientLockCallBack): void; lock(key: string, opts: any, cb?: LMClientLockCallBack) { ... } ``` So, if the second argument is a callback - user will get the first overload typings, if it is anything else, but the third argument is a callback - the second overload typings. But in both cases they will call the same implementation, just like it would be in pure JavaScript.
How to handle pct\_change with negative values I am calculating percentage change for a panel dataset, which has both positive and negative values. If both values of n and n+1 date are negative and values of n > n+1, for instance, n=-2, n+1=-4. The calculated percentage change is ((n+1)-n)/n=((-4)-(-2))/-2=1. As you can see the change should be a downtrend, which is expected to be negative but the result is the opposite. I normally set the denominators the absolute values ((n+1)-n)/abs(n) in other software to ensure the direction of the trend. Just wondering if I can do so in Python pandas pct\_change to set up the denominator to be absolute values. Many thanks. I have solved the question based on the answer from Leo. Here is a data example if one wants to play around. ``` import pandas as pd df= {'id':[1,1,2,2,3,3],'values':[-2,-4,-2,2,1,5]} df=pd.DataFrame(data=df) df['pecdiff']=(df.groupby('id')['values'].apply(lambda x:x.diff()/x.abs().shift() )).fillna(method=bfill) ```
If I understood correctly, the line for `expected change` should solve your problem. For comparison, I put side by side pandas' method and what you need. The following code: ``` import pandas as pd df = pd.DataFrame([-2,-4,-2,2,1], columns = ['Values']) df['pct_change'] = df['Values'].pct_change() # This should help you out: df['expected_change'] = df['Values'].diff() / df['Values'].abs().shift() df ``` Gives this output. Note that the signs are different for lines 1 through 3 ``` Values pct_change expected_change 0 -2 NaN NaN 1 -4 1.0 -1.0 2 -2 -0.5 0.5 3 2 -2.0 2.0 4 1 -0.5 -0.5 ```
How to Import Excel file into mysql Database from PHP Lets say, i want to import/upload excel file to mysql from PHP My HTML is like below ``` <form enctype="multipart/form-data" method="post" role="form"> <div class="form-group"> <label for="exampleInputFile">File Upload</label> <input type="file" name="file" id="file" size="150"> <p class="help-block">Only Excel/CSV File Import.</p> </div> <button type="submit" class="btn btn-default" name="Import" value="Import">Upload</button> </form> ``` PHP code is like below ``` <?php if(isset($_POST["Import"])) { //First we need to make a connection with the database $host='localhost'; // Host Name. $db_user= 'root'; //User Name $db_password= ''; $db= 'product_record'; // Database Name. $conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error()); mysql_select_db($db) or die (mysql_error()); echo $filename=$_FILES["file"]["tmp_name"]; if($_FILES["file"]["size"] > 0) { $file = fopen($filename, "r"); //$sql_data = "SELECT * FROM prod_list_1 "; while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) { //print_r($emapData); //exit(); $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')"; mysql_query($sql); } fclose($file); echo 'CSV File has been successfully Imported'; header('Location: index.php'); } else echo 'Invalid File:Please Upload CSV File'; } ?> ``` Excel file is like below ![excel file picture](https://i.stack.imgur.com/e5iDu.png) I want to import only the 2nd row values into my table. Please help me how can i solve it or give me any resource. I was able to upload the excel file but it is not correctly formatted. i want to upload 4 column in mysql's 4 column but it is uploading all 4 column in mysql's 1 column. am i missing something ?
For >= 2nd row values insert into table- ``` $file = fopen($filename, "r"); //$sql_data = "SELECT * FROM prod_list_1 "; $count = 0; // add this line while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) { //print_r($emapData); //exit(); $count++; // add this line if($count>1){ // add this line $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')"; mysql_query($sql); } // add this line } ```
Find Max Id from list which has children of same list I have a list of Persons which has children [same type]. I get the list from xml file. **Scenario :** Person : Id, Name, Gender, Age, Children [Class with fields] If personList has 1,2,5 Ids, 2 and 5 with children 3,4 and 6,7,8 respectively. I have to get the max id as 8. How do i get the max of Id from PersonList using lambda expression?
You could try a combination of [`Concat`](http://msdn.microsoft.com/en-us/library/bb302894.aspx) and [`SelectMany`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx) (that's assuming it's only nested one level): ``` var maxId = personList.Concat(personList.SelectMany(p => p.Children)).Max(p => p.Id); ``` **UPDATE** If you have multiple nesting levels, you could also write an extension method to make `SelectMany` recursive: ``` public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector) { if (source == null) { yield break; } foreach (var item in source) { yield return item; foreach (var selected in selector(item).SelectManyRecursive(selector)) { yield return selected; } } } ``` That doesn't handle circular references and it behaves differently than `SelectMany` by also returning the items in the source collection itself (so you might want to change the name), but otherwise i think it does the job. You could use it quite easily: ``` var maxId = personList.SelectManyRecursive(p => p.Children).Max(p => p.Id); ```
MySQL Limit Rows / Group By I have searched a lot of different posts about this and i didn't find something that works for me. This [Using LIMIT within GROUP BY to get N results per group?](https://stackoverflow.com/questions/2129693/using-limit-within-group-by-to-get-n-results-per-group) and <http://www.sqlines.com/mysql/how-to/get_top_n_each_group> didn't work for me. I have a simple MySQL Table with the following columns ``` id , package, user_id, date ``` I want to perform a query in which i will get > > X Rows / user\_id WHERE date > Number Order By date ASC > > > In short, we want to perform a `Group By user_id` with `LIMIT of X rows / group` but have in mind the statement using the `date column` **Example Full Table**: ``` id , package, user_id, date 1, full, 1 , 1447003159 2, full, 1 , 1447003055 3, full, 1 , 1447002022 4, full, 1 , 1447001013 5, full, 1 , 1447000031 6, mid, 2 , 1447003159 7, mid, 2 , 1447003055 8, mid, 2 , 1447002022 9, mid, 2 , 1447001013 10, mid, 2 , 1447000031 ``` From the above table we want to Select only 2 rows / user\_id but where date >= 1447000031 (But make `ORDER BY date ASC` first) **Expected Output**: ``` 4, full, 1 , 1447001013 3, full, 1 , 1447002022 9, mid, 2 , 1447001013 8, mid, 2 , 1447002022 ```
E.g.: ``` SELECT x.* FROM my_table x JOIN my_table y ON y.id >= x.id AND y.user_id = x.user_id WHERE y.date > 1447000031 GROUP BY x.id HAVING COUNT(*) <= 2; ``` or, faster, but more typing... ``` SELECT id , package , user_id , date FROM ( SELECT x.* , CASE WHEN @prev_user = user_id THEN @i:=@i+1 ELSE @i:=1 END rank , @prev_user := user_id FROM my_table x , ( SELECT @prev_user = 0,@i:=1 ) vars WHERE date > 1447000031 ORDER BY user_id , date ) a WHERE rank <= 2; ```
How do I launch the HLSL debugger in Visual Studio 2017? I cant find the option to launch the HLSL Debugger in Visual Studio 2017. The Microsoft document instructs to launch it from Graphics Pipeline Stages window or Graphics Pixel History <https://msdn.microsoft.com/en-us/library/hh873197.aspx> However, I have no idea what those are or how to get to them When I set a breakpoint in hlsl code in visual studio IDE directly, it just shows "`The Breakpoint will not currently be hit`" over the empty red circle. I assume I need to open the hlsl code in the hlsl debugger for it to break on the line. I'm running a new project template `DirectX 11 App(Universal Windows)` in x64 debug mode and setting breakpoints in both vertex and pixel shaders. Thanks,
1. Make sure that your shaders are compiled with debug support - with `/Zi` option if you are using HLSL compiler. 2. Make sure that DX device is created with debug enabled (`D3D11_CREATE_DEVICE_DEBUG` flag). 3. Start GFX debugging session by going to Main menu -> Debug -> Graphics -> Start Graphics debugging. This will make a window asking for elevated privileges to pop up, launch your program and show diag session window with "Capture frame" button and timeline. 4. Now make your application display desired image and capture a frame(s) of iterest using corresponding button. Captured frame screenshot will appear in the list. 5. Close your application. This will trigger finalization (some postprocessing) of diag session which will take some time. 6. Click on the frame name (blue) in the list of captured frames. This will open VS graphics analyzer window - this is where you actually debug graphics. 7. In the middle there will be a (reproduced) frame render screenshot - you can click anywhere on it and at the pixel history window there should be a list of draw calls modifying that pixel. By expanding this list you should be able to locate invocation of shader of interest. It should have "Play" triangle button starting shader debugging and jumping into shader code where you can inspect variables, set breakpoints and other stuff. 8. Alternatively on the left there will be Event list that contains all the pipeline modification and draw (marked with brush) calls. Locate a draw call of interest there and select it. In the Pipeline stages window there should be a diagram with screenshots of products of each stage with a corresponding shader link and "Play" button that starts shader debugging.
Numba function No matching definition for argument type(s) ListType[array(float64, 2d, C)] error I have a function in `Numba` that uses a `List(float64[:,::1])` type, this is a dummy function to try out the type, I will do a lot of operations under the for loop. It has an strange behavior, while the to arr lists have the same excatly numba.typeof() signature, one works and the other does not and tells me it is not matching type. This is definitely a type of object error, but I can figure it out. this is the file test.npy to load: <https://drive.google.com/file/d/1guAe1C2sKZyy2U2_qXAhMA1v46PfeKnN/view?usp=sharing> **Error** ``` raise TypeError(msg) TypeError: No matching definition for argument type(s) ListType[array(float64, 2d, C)] ``` **Code** ``` import numpy as np import numba from numba.typed import List branches = np.load('test.npy', allow_pickle=True).item() @numba.njit('List(int64)(List(float64[:, ::1]))') def not_test(branches): a_list = [] for branch in branches: for i in range(len(branch)): a_list.append(i) return a_list # this does not work arr = [] for branch in branches.features[:2]: arr.append(np.asarray(branch.geometry.coordinates).copy()) arr = List(arr.copy()) print(numba.typeof(arr)) no_test(arr) # this works arr = List([np.array([np.array([7.0,7.3]), np.array([7.4,8.6])])]) print(numba.typeof(arr)) no_test(arr) ```
For anybody stuck in something trivial like this, turns out the correct signature type is: ``` @numba.njit('List(int64)(ListType(float64[:, ::1]))') ``` I do not understand the differences between `List` and `ListType` and I could not find it on the `Numba` official website. I could be really helpfull to have a cheatsheet for types in decorators as is not easy to infer how they should be written just from the available data type found in the arguments of the function. Also, it could really be of great help to have a parser function based on numba.typeof() return, and been able to create the string of the decorator just of off this. Plus, the conversion to List() is pretty slow, I found a post on Numba GitHub that talks about this this problem. This is the original post [improve performance of numba.typed.List constructor with Python list as arg](https://github.com/numba/numba/issues/7727) ``` def convert2(x, dtype=np.float64): try: # Try and convert x to a Numpy array. If this succeeds # then we have reached the end of the nesting-depth. y = np.asarray(x, dtype=dtype) except: # If the conversion to a Numpy array fails, then it can # be because not all elements of x can be converted to # the given dtype. There is currently no way to distinguish # if this is because x is a nested list, or just a list # of simple elements with incompatible types. # Recursively call this function on all elements of x. y = [convert2(x_, dtype=dtype) for x_ in x] # Convert Python list to Numba list. y = numba.typed.List(y) return y ``` **EDIT** I found a super helpfull line to get the type signatures off of a numba function ``` print(not_test.inspect_types()) #not_test (ListType[array(float64, 2d, C)], array(float64, 1d, A)) ```
Why is the oneric-backport repository enable by default on 11.10? I installed Xubuntu 11.10 and Ubuntu 11.10 in both the oneric-backport is enabled by default. Any ideas why?
This was a decision they made to help people get the best drivers for their systems. There was a bug created here: - <https://bugs.launchpad.net/ubuntu/+source/software-properties/+bug/840135> And here was the spec discussion: - <https://blueprints.launchpad.net/ubuntu/+spec/foundations-o-backports-bof> And here is the quote from [the release notes](https://wiki.ubuntu.com/OneiricOcelot/ReleaseNotes): > > ## Backports are now more easily accessible > > > To enable users to more easily receive new versions of software, the Ubuntu Backports repository is now enabled by default. Packages from backports will not be installed by default — they must explicitly be selected in package management software. However, once installed, packages from backports will automatically be upgraded to newer versions. > > >
What does a single exclamation mark do in YAML? I'm working with the [YamlDotNet](http://sourceforge.net/projects/yamldotnet/) library and I'm getting this error when loading a YAML file: > > While parsing a tag, did not find expected tag URI. > > > The YAML file is supposed to be well-formed because it comes [right from RoR](https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en-GB.yml). The error seems to be triggered by this code: ``` formats: default: ! '%d-%m-%Y' long: ! '%d %B, %Y' short: ! '%d %b' ``` I'm not an expert, but I see from the YAML spec that you can use an exclamation mark to indicate a custom object/type, and two exclamation marks to indicate an explicit built-in type. ``` obj1: !custom # whatever obj2: !!str "My string" ``` However I haven't been able to find any reference to an exclamation mark used as above. What does that mean, and why the YAML library I use doesn't seem able to parse it? Note that if I remove those exclamation marks, the file is parsed fine.
That `!` is the **non-specific tag**. The [YAML specification 1.2](http://www.yaml.org/spec/1.2/spec.html#id2784064) (as well as the previous [1.1](http://yaml.org/spec/1.1/#id900262)) says that : > > By explicitly specifying a “!” non-specific tag property, the node > would then be resolved to a “vanilla” sequence, mapping, or string, > according to its kind. > > > Take a look [here](http://yaml.org/refcard.html) to the tag "grammar": > > > ``` > none : Unspecified tag (automatically resolved by application). > '!' : Non-specific tag (by default, "!!map"/"!!seq"/"!!str"). > '!foo' : Primary (by convention, means a local "!foo" tag). > '!!foo' : Secondary (by convention, means "tag:yaml.org,2002:foo"). > '!h!foo': Requires "%TAG !h! <prefix>" (and then means "<prefix>foo"). > '!<foo>': Verbatim tag (always means "foo"). > > ``` > > Why is YamlDotNet throwing a error? I can't be 100% sure, but I think you found a bug. YamlDotNet is a port of [LibYAML](http://pyyaml.org/wiki/LibYAML), so it's easy to compare sources. Line 2635 of scanner.c (LibYAML): ``` /* Check if the tag is non-empty. */ if (!length) { ``` Line 2146 of Scanner.cs (YamlDotNet ): ``` // Check if the tag is non-empty. if (tag.Length == 0) ``` I know, both looks very similar, but at this point `length` is 1 and `tag.Length` is 0. Original C code takes care of the initial "!" (whole length) but C# doesn't do it (just the tag "name" length). File an issue to the project.
Why is TextEditingController always used in Stateful widgets? While reading the Flutter documentation, I came across this article that shows [how to handle changes to a text field](https://flutter.dev/docs/cookbook/forms/text-field-changes). What I found interesting is that in this and all other articles regarding `TextEditingController`, the `TextEditingController` is always used in a **Stateful widget** regardless of whether that widget needs to be stateful or not. What is the reason that `TextEditingController` is always used with Stateful widgets?
## Long answer short You need to *dispose* your `TextEditingController` in [`State.dispose`](https://api.flutter.dev/flutter/widgets/State/dispose.html): ``` TextEditingController textEditingController; @override void dispose() { textEditingController.dispose(); // You need to do this. super.dispose(); } ``` ## Explanation A [`TextEditingController`](https://api.flutter.dev/flutter/widgets/TextEditingController-class.html) is a [`ChangeNotifier`](https://api.flutter.dev/flutter/foundation/ChangeNotifier-class.html) as `TextEditingController` inherits from `ValueNotifier` and `ValueNotifier` extends `ChangeNotifier`. Having said that, `TextEditingController`s need to be **disposed** in order to not leak any resources. Anytime you want to **dispose** something, you will want to make use of the [`StatefulElement.unmount`](https://api.flutter.dev/flutter/widgets/StatefulElement/unmount.html). This is exposed via [`State`](https://api.flutter.dev/flutter/widgets/State-class.html) and with that [`StatefulWidget`](https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html). See above for how to implement this. --- Ideally, you will set up your controller in `initState`: ``` @override void initState() { super.initState(); textEditingController = ..; } ```
How do I call a function handle from cell array? What I try to do is keep a cell-array of function handles, and then call one of them in a loop. It doesn't work, and it seems to me that what I get is just a 1x1 cell array, and not the function handle within it. I am not fixed on using cell arrays, so if another collection works it's fine by me. This is my code: ``` func_array = {@(x) x, @(x) 2*x } a = func_array(1) %%% a = @(x) x a(2) %%% (error-red) Index exceeds matrix dimensions. a(0.2) %%% (error-red) Subscript indices must either be real positive integers or logicals. ``` Thank you Amir
The problem is in this line: ``` a = func_array(1) ``` you need to access the content of the cell array, not the element. ``` a = func_array{1} ``` and everything works fine. The visual output in the command window looks the same, which is truly a little misleading, but have a look in the workspace to see the difference. As mentioned by **chappjc** in the comments, the intermediate variable is not necessary. You could call your functions as follows: ``` func_array{2}(4) %// 2*4 ans = 8 ``` --- Explanation of errors: ``` a(2) %%% (error-red) Index exceeds matrix dimensions. ``` `a` is still a cell array, but just with one element, therefore `a(2)` is out of range. ``` a(0.2) %%% (error red) Subscript indices must either be real positive ... ``` ... and arrays can't be indexed with decimals. But that wasn't your intention anyway ;)
Do strong-named assemblies in .NET ensure the code wasn't tampered with? I'm trying to understand the point of strong-naming assemblies in .NET. While googling about it I noticed that everywhere it is said that it ensures that the code comes from me and wasn't tampered with. So I tested it. I created a simple DLL, signed it with a newly created PFX key and referenced it by my WPF application. And ok, everything works. When I compile the DLL with another PFX file I get an error, so it's ok. BUT when I decompile the DLL by ildasm, modify it and recompile it by ilasm the WPF application still works without any error. So I tampered the strongly-named DLL and changed it manually with the old one and the application still works with the tampered DLL. The PublicKeyToken is the same. So what is the point of strong-naming? It doesn't ensure the code hasn't been tampered with since I strong-named it.
It used to check for tampering, but the overhead of checking every strong-name-signed assembly at application startup was too high, so [Microsoft disabled this behaviour by default a number of years ago](https://blogs.msdn.microsoft.com/shawnfa/2008/05/14/strong-name-bypass/) (way back when ".NET Framework version 3.5 Service Pack 1" was released). This is called the ***Strong-Name bypass feature***. You can disable the feature (i.e. make Windows check for tampering) for a particular application by adding the following to its ".config" file: ``` <configuration> <runtime> <bypassTrustedAppStrongNames enabled="false" /> </runtime> </configuration> ``` You can enable strong-name checking for ALL applications by editing the registry (which is clearly not a feasible solution!). For more details, see the following page: <https://learn.microsoft.com/en-us/dotnet/framework/app-domains/how-to-disable-the-strong-name-bypass-feature> The advice nowadays is to use a full code-signing certificate for your executable and DLLs if you want to prevent code tampering.
VB.NET: Abort FormClosing() I have a code snippet that I want to run when the app is closing. So, I used `FormCLosing` event. But now i wanna place a confirmation message for exiting. Like, if the user clicks the Exit(`X`) button, there'll be a prompt, if he clicks NO, then the app will not close and revert to previous state. Now I find that hard to achieve using `FormClosing` event. because it'll get executed no matter what button the user clicks. Any remedy for that? I mean, I need an even like `ExitButtonPressed()`..
You could try something like ``` Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing If (MessageBox.Show("Close?", "", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No) Then e.Cancel = True End If End Sub ``` Have a look at [FormClosingEventArgs Class](http://msdn.microsoft.com/en-us/library/system.windows.forms.formclosingeventargs.aspx) And [CancelEventArgs.Cancel Property](http://msdn.microsoft.com/en-us/library/system.componentmodel.canceleventargs.cancel.aspx) > > The event can be canceled by setting > the Cancel property to true. > > >
bit field declaration in a c++ struct I was reading over the ISO standard of c++ and I came over this bit-field declarations. The following code is not well clear to me ``` struct { char a; int b:5, c:11, :0, d:8; struct {int ee:8;} e; } ``` Here it is specified that the fields a, d and e.ee have different memory locations and they can be modified independently using multiple threads. The bitfields b and c uses same memory locations so they cant be modified concurrently. I dont understand the significance of using two bit fields for c i.e, `c:11,:0,`. can anybody clear my vision about this? thank you
You asked; > > I dont understand the significance of using two bit fields for c i.e, c:11,:0,. can anybody clear my vision about this? > > > `c` is not defined using two bit-fields. The second one is an unnamed bit-field. Unnamed bit-fields with width of zero have special significance. This is what the standard says about unnamed bit-field. > > A declaration for a bit-field that omits the identifier declares an unnamed bit-field. Unnamed bit-fields are not members and cannot be initialized. [ Note: An unnamed bit-field is useful for padding to conform to externally-imposed layouts. — end note ] As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary. Only when declaring an unnamed bit-field may the value of the constant-expression be equal to zero. > > >
How to optimize Neo4j Cypher queries with multiple node matches (Cartesian Product) I am currently trying to merge three datasets for analysis purposes. I am using certain common fields to establish the connections between the datasets. In order to create the connections I have tried using the following type of query: ``` MATCH (p1:Person),(p2:Person) WHERE p1.email = p2.email AND p1.name = p2.name AND p1 <> p2 CREATE UNIQUE (p1)-[IS]-(p2); ``` Which can be similarly written as: ``` MATCH (p1:Person),(p2:Person {name:p1.name, email:p1.email}) WHERE p1 <> p2 CREATE UNIQUE (p1)-[IS]-(p2); ``` Needless to say, this is a very slow query on a database with about 100,000 Person nodes, specially given that Neo4j does not process single queries in parallel. Now, my question is whether there is any better way to run such queries in Neo4j. I have at least eight CPU cores to dedicate to Neo4j, as long as separate threads don't tie up by locking each others' required resources. The issue is that I don't know how Neo4j builds its Cypher execution plans. For instance, let's say I run the following test query: ``` MATCH (p1:Person),(p2:Person {name:p1.name, email:p1.email}) WHERE p1 <> p2 RETURN p1, p2 LIMIT 100; ``` Despite the LIMIT clause, Neo4j still takes a considerable amount of time to turn in the results, what makes me wonder whether even for such a limited query Neo4j produces the whole cartesian product table before considering the LIMIT statement. I appreciate any help, whether it addresses this specific issue or just gives me an understanding of how Neo4j generally builds Cypher execution plans (and thus how to optimize queries in general). Can legacy Lucene indexes be of any help here?
You can do a combination of a label scan for `p1` and then index lookup + comparison for `p2`: see here: ``` cypher 2.1 foreach (i in range(1,100000) | create (:Person {name:"John Doe"+str(i % 10000), email:"john"+str(i % 10000)+"@doe.com"})); +-------------------+ | No data returned. | +-------------------+ Nodes created: 100000 Properties set: 200000 Labels added: 100000 6543 ms neo4j-sh (?)$ CREATE INDEX ON :Person(name); +-------------------+ | No data returned. | +-------------------+ Indexes added: 1 28 ms neo4j-sh (?)$ schema Indexes ON :Person(name) ONLINE neo4j-sh (?)$ match (p1:Person) with p1 match (p2:Person {name:p1.name}) using index p2:Person(name) where p1<>p2 AND p2.email = p1.email return count(*); +----------+ | count(*) | +----------+ | 900000 | +----------+ 1 row 8206 ms neo4j-sh (?)$ match (p1:Person) with p1 match (p2:Person {name:p1.name}) using index p2:Person(name) where p1<>p2 AND p2.email = p1.email merge (p1)-[:IS]-(p2) return count(*); +----------+ | count(*) | +----------+ | 900000 | +----------+ 1 row Relationships created: 450000 40256 ms ```
Generating samples from singular Gaussian distribution Let random vector $x = (x\_1,...,x\_n)$ follow multivariate normal distribution with mean $m$ and covariance matrix $S$. If $S$ is symmetric and positive definite (which is the usual case) then one can generate random samples from $x$ by first sampling indepently $r\_1,...,r\_n$ from standard normal and then using formula $m + Lr$, where $L$ is the Cholesky lower factor so that $S=LL^T$ and $r = (r\_1,...,r\_n)^T$. What about if one wants samples from singular Gaussian i.e. $S$ is still symmetric but not more positive definite (only positive semi-definite). We can assume also that the variances (diagonal elements of $S$) are strictly positive. Then some elements of $x$ must have linear relationship and the distribution actually lies in lower dimensional space with dimension $<n$, right? It is obvious that if e.g. $n=2, m = \begin{bmatrix} 0 \\ 0 \end{bmatrix}, S = \begin{bmatrix} 1 & 1 \\ 1 & 1\end{bmatrix}$ then one can generate $x\_1 \sim N(0,1)$ and set $x\_2=x\_1$ since they are fully correlated. However, is there any good methods for generating samples for general case $n>2$? I guess one needs first to be able identify the lower dimensional subspace, then move to that space where one will have valid covariance matrix, then sample from it and finally deduce the values for the linearly dependent variables from this lower-dimensional sample. But what is the best way to that in practice? Can someone point me to books or articles that deal with the topic; I could not find one.
The singular Gaussian distribution is the push-forward of a nonsingular distribution in a lower-dimensional space. Geometrically, you can take a standard Normal distribution, rescale it, rotate it, and embed it isometrically into an affine subspace of a higher dimensional space. Algebraically, this is done by means of a Singular Value Decomposition (SVD) or its equivalent. --- Let $\Sigma$ be the covariance matrix and $\mu$ the mean in $\mathbb{R}^n$. Because $\Sigma$ is non-negative definite and symmetric, the SVD will take the form $$\Sigma = U \Lambda^2 U^\prime$$ for an orthogonal matrix $U\in O(n)$ and a *diagonal* matrix $\Lambda$. $\Lambda$ will have $m$ nonzero entries, $0\le m \le n$. Let $X$ have a standard Normal distribution in $\mathbb{R}^m$: that is, each of its $m$ components is a standard Normal distribution with zero mean and unit variance. Abusing notation a little, extend the components of $X$ with $n-m$ zeros to make it an $n$-vector. Then $U\Lambda X$ is in $\mathbb{R}^n$ and we may compute $$\text{Cov}(U\Lambda X) = U \Lambda\text{Cov}(X) \Lambda^\prime U^\prime = U \Lambda^2 U^\prime = \Sigma.$$ Consequently $$Y = \mu + U\Lambda X$$ has the intended Gaussian distribution in $\mathbb{R}^n$. It is of interest that this works when $n=m$: that is to say, this is a (standard) method to generate multivariate Normal vectors, in any dimension, for any given mean $\mu$ and covariance $\Sigma$ by using a univariate generator of standard Normal values. --- As an example, here are two views of a thousand simulated points for which $n=3$ and $m=2$: ![View 1](https://i.stack.imgur.com/6mj1V.png) ![View 2](https://i.stack.imgur.com/5OTel.png) The second view, from edge-on, demonstrates the singularity of the distribution. The `R` code that produced these figures follows the preceding mathematical exposition. ``` # # Specify a Normal distribution. # mu <- c(5, 5, 5) Sigma <- matrix(c(1, 2, 1, 2, 3, 1, 1, 1, 0), 3) # # Analyze the covariance. # n <- dim(Sigma)[1] s <- svd((Sigma + t(Sigma))/2) # Guarantee symmetry s$d <- abs(zapsmall(s$d)) m <- sum(s$d > 0) #$ # Generate a standard Normal `x` in R^m. # n.sample <- 1e3 # Number of points to generate x <- matrix(rnorm(m*n.sample), nrow=m) # # Embed `x` in R^n and apply the square root of Sigma obtained from its SVD. # x <- rbind(x, matrix(0, nrow=n-m, ncol=n.sample)) y <- s$u %*% diag(sqrt(s$d)) %*% x + mu # # Plot the results (presuming n==3). # library(rgl) plot3d(t(y), type="s", size=1, aspect=TRUE, xlab="Y1", ylab="Y2", zlab="Y3", box=FALSE, col="Orange") ```
Electron + React + Typescript + Visual Studio Code? Debug? Can I debug an electron-react app in visual studio? Using some boiler plate code, I am able to get my electron app to work in visual studio code. I can hit the breakpoint for main.js, but not for any of my typescript/React code. I am using webpack to build, but am not married to it. How do I wire up the debugger for the React stuff? I started with these walk-throughs: [medium.com](https://medium.com/@paulirwin/getting-started-with-electron-and-visual-studio-code-typescript-and-react-36d41b68fadb) and [typescriptlang.org](https://www.typescriptlang.org/docs/handbook/react-&-webpack.html) Here are my configuration files launch.js ``` { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "preLaunchTask": "webpack", "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron", "program": "${workspaceFolder}/main.js", "runtimeArgs": [ ".", "--enable-logging" ] } ] } ``` tasks.js ``` { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "webpack", "command": "webpack", "args": [] } ] } ``` tsconfig.json ``` { "compilerOptions": { "outDir": "./", "sourceMap": true, "noImplicitAny": true, "module": "commonjs", "target": "es5", "jsx": "react" }, "include": [ "./src/**/*" ] } ``` webpack.config.js ``` module.exports = { entry: "./src/index.tsx", output: { filename: "./bundle.js", //path: __dirname + "/dist" }, mode: "production" , // Enable sourcemaps for debugging webpack's output. devtool: "source-map", resolve: { // Add '.ts' and '.tsx' as resolvable extensions. extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".json"] }, module: { rules: [ // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. { test: /\.tsx?$/, loader: "awesome-typescript-loader" }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. { enforce: "pre", test: /\.js$/, loader: "source-map-loader" } ] }, // When importing a module whose path matches one of the following, just // assume a corresponding global variable exists and use that instead. // This is important because it allows us to avoid bundling all of our // dependencies, which allows browsers to cache those libraries between builds. externals: { // "react": "React", // "react-dom": "ReactDOM" }, }; ```
I solved it! Found the answer [from Microsoft](https://github.com/Microsoft/vscode-recipes/tree/master/Electron). Install [Debugger for Chrome](https://github.com/Microsoft/vscode-chrome-debug); change tasks.json to the following, and start one project and then the other. **It works with Typescript, Webpack, and React beautifully!** ``` { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Electron: Main", "preLaunchTask": "webpack", "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron", "program": "${workspaceFolder}/main.js", "runtimeArgs": [ ".", "--enable-logging", "--remote-debugging-port=9223", ] }, { "name": "Electron: Renderer", "type": "chrome", "request": "attach", "port": 9223, "webRoot": "${workspaceFolder}", "timeout": 30000 } ], "compounds": [ { "name": "Electron: All", "configurations": [ "Electron: Main", "Electron: Renderer" ] } ] } ```
The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication > > The communication object, System.ServiceModel.Channels.ServiceChannel, > cannot be used for communication because it is in the Faulted state. > > > What is this error all about, and how would I go about solving it?
You get this error because you let a .NET exception happen on your server side, and you didn't catch and handle it, and didn't convert it to a SOAP fault, either. Now since the server side "bombed" out, the WCF runtime has "faulted" the channel - e.g. the communication link between the client and the server is unusable - after all, it looks like your server just blew up, so you cannot communicate with it any more. So what you need to do is: - **always** catch and handle your server-side errors - **do not** let .NET exceptions travel from the server to the client - **always** wrap those into interoperable SOAP faults. Check out the WCF [IErrorHandler](http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx) interface and implement it on the server side - if you're about to send a second message onto your channel from the client, make sure the channel is not in the faulted state: ``` if(client.InnerChannel.State != System.ServiceModel.CommunicationState.Faulted) { // call service - everything's fine } else { // channel faulted - re-create your client and then try again } ``` If it is, all you can do is dispose of it and re-create the client side proxy again and then try again
QuadTree find neighbor I'm searching for a algorithm to find neighbors of a quadtree, in the example image, I got the red node, how to find the blue nodes. Any ideas? ![example](https://i.stack.imgur.com/R3Oiz.png)
There are some known algorithms. Check them out. 1. [Kunio Aizawa et al.](http://www.lcad.icmc.usp.br/%7Ejbatista/procimg/quadtree_neighbours.pdf) - Constant Time Neighbor Finding in Quadtrees: An Experimental Result 2. [Kasturi Varadarajan](http://homepage.divms.uiowa.edu/%7Ekvaradar/sp2012/daa/ann.pdf) - All Nearest Neighbours via Quadtrees 3. [Robert Yoder, Peter Bloniarz](http://web.archive.org/web/20120907211934/http://ww1.ucmss.com/books/LFS/CSREA2006/MSV4517.pdf) - A Practical Algorithm for Computing Neighbors in Quadtrees, Octrees, and Hyperoctrees
How to unnest column-list? I have a tibble like: ``` tibble(a = c('first', 'second'), b = list(c('colA' = 1, 'colC' = 2), c('colA'= 3, 'colB'=2))) # A tibble: 2 x 2 a b <chr> <list> 1 first <dbl [2]> 2 second <dbl [2]> ``` Which a would like to turn into this form: ``` # A tibble: 2 x 4 a colA colB colC <chr> <dbl> <dbl> <dbl> 1 first 1. NA 2. 2 second 3. 2. NA ``` I tried to use `unnest()`, but I am having issues preserving the elements' names from the nested values.
You can do this by coercing the elements in the list column to data frames arranged as you like, which will unnest nicely: ``` library(tidyverse) tibble(a = c('first', 'second'), b = list(c('colA' = 1, 'colC' = 2), c('colA'= 3, 'colB'=2))) %>% mutate(b = invoke_map(tibble, b)) %>% unnest() #> # A tibble: 2 x 4 #> a colA colC colB #> <chr> <dbl> <dbl> <dbl> #> 1 first 1. 2. NA #> 2 second 3. NA 2. ``` Doing the coercion is a little tricky, though, as you don't want to end up with a 2x1 data frame. There are various ways around this, but a direct route is `purrr::invoke_map`, which calls a function with `purrr::invoke` (like `do.call`) on each element in a list.
How to extract chains from a PDB file? I would like to extract chains from pdb files. I have a file named pdb.txt which contains pdb IDs as shown below. The first four characters represent PDB IDs and last character is the chain IDs. ``` 1B68A 1BZ4B 4FUTA ``` I would like to 1) read the file line by line 2) download the atomic coordinates of each chain from the corresponding PDB files. 3) save the output to a folder. I used the following script to extract chains. But this code prints only A chains from pdb files. ``` for i in 1B68 1BZ4 4FUT do wget -c "http://www.pdb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId="$i -O $i.pdb grep ATOM $i.pdb | grep 'A' > $i\_A.pdb done ```
The following BioPython code should suit your needs well. It uses `PDB.Select` to only select the desired chains (in your case, one chain) and `PDBIO()` to create a structure containing just the chain. ``` import os from Bio import PDB class ChainSplitter: def __init__(self, out_dir=None): """ Create parsing and writing objects, specify output directory. """ self.parser = PDB.PDBParser() self.writer = PDB.PDBIO() if out_dir is None: out_dir = os.path.join(os.getcwd(), "chain_PDBs") self.out_dir = out_dir def make_pdb(self, pdb_path, chain_letters, overwrite=False, struct=None): """ Create a new PDB file containing only the specified chains. Returns the path to the created file. :param pdb_path: full path to the crystal structure :param chain_letters: iterable of chain characters (case insensitive) :param overwrite: write over the output file if it exists """ chain_letters = [chain.upper() for chain in chain_letters] # Input/output files (pdb_dir, pdb_fn) = os.path.split(pdb_path) pdb_id = pdb_fn[3:7] out_name = "pdb%s_%s.ent" % (pdb_id, "".join(chain_letters)) out_path = os.path.join(self.out_dir, out_name) print "OUT PATH:",out_path plural = "s" if (len(chain_letters) > 1) else "" # for printing # Skip PDB generation if the file already exists if (not overwrite) and (os.path.isfile(out_path)): print("Chain%s %s of '%s' already extracted to '%s'." % (plural, ", ".join(chain_letters), pdb_id, out_name)) return out_path print("Extracting chain%s %s from %s..." % (plural, ", ".join(chain_letters), pdb_fn)) # Get structure, write new file with only given chains if struct is None: struct = self.parser.get_structure(pdb_id, pdb_path) self.writer.set_structure(struct) self.writer.save(out_path, select=SelectChains(chain_letters)) return out_path class SelectChains(PDB.Select): """ Only accept the specified chains when saving. """ def __init__(self, chain_letters): self.chain_letters = chain_letters def accept_chain(self, chain): return (chain.get_id() in self.chain_letters) if __name__ == "__main__": """ Parses PDB id's desired chains, and creates new PDB structures. """ import sys if not len(sys.argv) == 2: print "Usage: $ python %s 'pdb.txt'" % __file__ sys.exit() pdb_textfn = sys.argv[1] pdbList = PDB.PDBList() splitter = ChainSplitter("/home/steve/chain_pdbs") # Change me. with open(pdb_textfn) as pdb_textfile: for line in pdb_textfile: pdb_id = line[:4].lower() chain = line[4] pdb_fn = pdbList.retrieve_pdb_file(pdb_id) splitter.make_pdb(pdb_fn, chain) ``` --- One final note: **don't write your own parser** for PDB files. The format specification is ugly (*really ugly*), and the amount of faulty PDB files out there is staggering. Use a tool like BioPython that will handle parsing for you! Furthermore, instead of using `wget`, you should use tools that interact with the PDB database for you. They take FTP connection limitations into account, the changing nature of the PDB database, and more. I should know - I [updated `Bio.PDBList`](https://github.com/biopython/biopython/commit/7ebf6e9ecbebdf4fd093110f8d8eb218b02f6b1b) to account for changes in the database. =)
How to get BeautifulSoup 4 to respect a self-closing tag? This question is specific to [BeautifulSoup4](http://www.crummy.com/software/BeautifulSoup/bs4/doc/), which makes it different from the previous questions: [Why is BeautifulSoup modifying my self-closing elements?](https://stackoverflow.com/questions/1567402/why-is-beautifulsoup-modifying-my-self-closing-elements) [selfClosingTags in BeautifulSoup](https://stackoverflow.com/questions/2211589/selfclosingtags-in-beautifulsoup) Since `BeautifulStoneSoup` is gone (the previous xml parser), how can I get `bs4` to respect a new self-closing tag? For example: ``` import bs4 S = '''<foo> <bar a="3"/> </foo>''' soup = bs4.BeautifulSoup(S, selfClosingTags=['bar']) print soup.prettify() ``` Does not self-close the `bar` tag, but gives a hint. What is this tree builder that bs4 is referring to and how to I self-close the tag? ``` /usr/local/lib/python2.7/dist-packages/bs4/__init__.py:112: UserWarning: BS4 does not respect the selfClosingTags argument to the BeautifulSoup constructor. The tree builder is responsible for understanding self-closing tags. "BS4 does not respect the selfClosingTags argument to the " <html> <body> <foo> <bar a="3"> </bar> </foo> </body> </html> ```
[To parse XML you pass in “xml” as the second argument to the BeautifulSoup constructor.](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#xml) ``` soup = bs4.BeautifulSoup(S, 'xml') ``` [You’ll need to have lxml installed.](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#parsing-xml) You don't need to pass `selfClosingTags` anymore: ``` In [1]: import bs4 In [2]: S = '''<foo> <bar a="3"/> </foo>''' In [3]: soup = bs4.BeautifulSoup(S, 'xml') In [4]: print soup.prettify() <?xml version="1.0" encoding="utf-8"?> <foo> <bar a="3"/> </foo> ```
c++14 Variadic lambda capture for function binding I'm currently reading a few books to get caught up on c++14 features. I am trying to use a variadic template to bind arguments to a function. I know how to do this using std::bind, but I would also like to implement this function with a c++14 lambda expression, just for common knowledge and understanding, and for any possible performance benefits. I've read that lambdas can be inlined while std::bind cannot inline because it takes place through a call to a function pointer. Here is the code from myFunctions.h: ``` #include <functional> int simpleAdd(int x, int y) { return x + y; } //function signatures template<class Func, class... Args> decltype(auto) funcBind(Func&& func, Args&&...args); template<class Func, class... Args> decltype(auto) funcLambda(Func&& func, Args&&...args); ///////////////////////////////////////////////////////////////// //function definitions template<class Func, class... Args> inline decltype(auto) funcBind(Func&& func, Args&&... args) { return bind(forward<Func>(func), forward<Args>(args)...); } template<class Func, class ...Args> inline decltype(auto) funcLambda(Func && func, Args && ...args) { //The error is caused by the lambda below: return [func, args...]() { forward<Func>(func)(forward<Args>(args)...); }; } ``` Here is the main code I am running: ``` #include<iostream> #include<functional> #include "myFunctions.h" using namespace std; int main() { cout << "Application start" << endl; cout << simpleAdd(5,7) << endl; auto f1 = funcBind(simpleAdd,3, 4); cout << f1() << endl; //error is occurring below auto f2 = funcLambda(simpleAdd, 10, -2); cout << f2() << endl; cout << "Application complete" << endl; ``` Error C2665 'std::forward': none of the 2 overloads could convert all the argument types Error C2198 'int (\_\_cdecl &)(int,int)': too few arguments for call I think the error might be occurring when the variadic arguments are getting forwarded to the lambda, but I'm not really sure. My question is how do I properly formulate this code so that I can use a lambda to capture the function and its arguments, and call it later.
> > I've read that lambdas can be inlined while std::bind cannot inline > because it takes place through a call to a function pointer. > > > If you pass `simpleAdd` to something that then binds the arguments, then whether you use `bind` or not doesn't matter. What do you think the lambda captures with `func`? It's a function pointer. The lambda-vs-function-pointer case is about writing `bind(simpleAdd, 2, 3)` vs. `[] { return simpleAdd(2, 3); }`. Or binding a lambda like `[](auto&&...args) -> decltype(auto) { return simpleAdd(decltype(args)(args)...); }` vs. binding `simpleAdd` directly (which will use a function pointer). --- In any event, implementing it is surprisingly tricky. You can't use by-reference capture because things can easily get dangling, you can't use a simple by-value capture because that would always copy the arguments even for rvalues, and you can't do a pack expansion in an init-capture. This follows `std::bind`'s semantics (invoking the function object and passing all bound arguments as lvalues) except that 1) it doesn't handle placeholders or nested binds, and 2) the function call operator is always `const`: ``` template<class Func, class ...Args> inline decltype(auto) funcLambda(Func && func, Args && ...args) { return [func = std::forward<Func>(func), args = std::make_tuple(std::forward<Args>(args)...)] { return std::experimental::apply(func, args); }; } ``` [cppreference](http://en.cppreference.com/w/cpp/experimental/apply) has an implementation of `std::experimental::apply`. Note that this does unwrap `reference_wrapper`s, like `bind`, because `make_tuple` does it. Your original code breaks down because `args` are `const` in the lambda's function call operator (which is `const` by default), and the `forward` ends up attempting to cast away constness.
R shiny mouseover text for table columns How can I create `mouseover text` for column names in R shiny data table display. I'm trying to provide some text for users to understand the column names. I checked in DT package also and I couldn't find a solution. I can create labels for column names and display all of them when a user checks a box, this takes a lot of real estate and I don't want that. Any tips?
To expand my comment above, here is an example showing what I meant by using the `title` attributes: ``` library(DT) sketch = htmltools::withTags(table( class = 'display', thead( tr( th('', title = 'Row Names'), th('Sepal.Length', title = 'The Sepal Length'), th('Sepal.Width', title = 'The Sepal Width'), th('Petal.Length', title = 'The Petal Length'), th('Petal.Width', title = 'The Petal Width'), th('Species', title = 'Iris Species') ) ) )) datatable(iris, container = sketch) ``` And here is another approach using JavaScript (jQuery) to add the `title` attributes: ``` library(DT) datatable(iris, callback = JS(" var tips = ['Row Names', 'The Sepal Length', 'The Sepal Width', 'The Petal Length', 'The Petal Width'], header = table.columns().header(); for (var i = 0; i < tips.length; i++) { $(header[i]).attr('title', tips[i]); } ")) ```
echo \\\* - bash backslash escape behavior, is it evaluated backwards? So in bash, When I do ``` echo \* * ``` This seems right, as \* is escaped and taken literally. But I can't understand that, when I do ``` echo \\* \* ``` I thought the first backslash escaped the second one thus two backslash "\\" will give me one "\" in literal. and \* followed carrying its special meaning. I was expecting: ``` echo \\* \file1 file2 file3 ``` ANSWER SUMMARY: Since \ is taken literally, `echo \*` will behave just as `echo a*`, which will find any file that starts with literal "a". Follow up question, If I want to print out exactly like ``` \file1 file2 file3 ``` What command should I use? e.g. like the following but I want no space ``` echo \\ * \ file1 file2 file3 ```
If you don't have a file in the current directory whose name starts with a backslash, this is expected behaviour. Bash [expands `*` to match any existing file names, but](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13_03): > > If the pattern does not match any existing filenames or pathnames, the pattern string shall be left unchanged. > > > Because there was no filename starting with `\`, the pattern was left as-is and `echo` is given the argument `\*`. This behaviour is often confusing, and some other shells, such as `zsh`, do not have it. You [can change it in Bash using `shopt -o failglob`](https://www.gnu.org/software/bash/manual/bashref.html#The-Shopt-Builtin), which will then give an error as `zsh` does and help you diagnose the problem instead of misbehaving. The `*` and `?` pattern characters can appear anywhere in the word, and characters before and after are matched literally. That is why `echo \\*` and `echo \\ *` give such different output: the first matches anything that starts with `\` (and fails) and the second outputs a `\`, and then all filenames. --- The most straightforward way of getting the output you want safely is probably to use [printf](https://www.gnu.org/software/bash/manual/bashref.html#index-printf): ``` printf '\\'; printf "%s " * ``` `echo *` is unsafe in the case of unusual filenames with `-` or `\` in them in any case.
Are functions mutable in multiple dispatch systems? Have I understood correctly that in (most? some?) multiple dispatch languages each method gets added to the function **at some point in time of program's execution**. Can I then conclude that multiple dispatch as a feature forces functions to be mutable? Is there a multiple dispatch language, where all methods are attached to a (generic)function together (at load time?), so that it's not possible to see the function in different states at different points in time?
> > at some point in time of program's execution. > > > In Common Lisp the methods get added/replaced when the method definitions are executed - for a compiled system this is typically at load-time of the compiled code - not necessarily during the program's execution. Remember, that Common Lisp has an *object system* (CLOS, the Common Lisp Object System), which is defined by its behaviour. It's slightly different from a *language* or a *language extension*. Common Lisp allows runtime modification of the object system. For example also adding/removing/replacing methods. Common Lisp also may *combine* more than one applicable method into an *effective method*, which then gets executed. Typical example: all applicable `:before` methods and the most specific applicable primary method will be combined into one *effective method*. There exist extensions for CLOS in some implementations, which *seal* a generic function against changes. For a longer treatment of the idea of an *object system* see: [The Structure of a Programming Language Revolution](http://www.dreamsongs.com/Files/Incommensurability.pdf) by Richard P. Gabriel.
Strange UTF8 string comparison I'm having this problem with UTF8 string comparison which I really have no idea about and it starts to give me headache. Please help me out. Basically I have this string from a xml document encoded in UTF8: 'Mina Tidigare anställningar' And when I compare that string with the exactly the same string which I typed myself: 'Mina Tidigare anställningar' (also in UTF8). And the result is FALSE!!! I have no idea why. It is so strange. Can someone help me out?
[This seems somewhat relevant](https://stackoverflow.com/questions/1089966/utf8-filenames-in-php-and-different-unicode-encodings/1934029#1934029). To simplify, there are several ways to get the same text in Unicode (and therefore UTF8): for example, this: `ř` can be written as one character `ř` or as two characters: `r` and the *combining* `ˇ`. Your best bet would be the [normalizer class](http://us2.php.net/manual/en/class.normalizer.php) - normalize both strings to the same normalization form and compare the results. In one of the comments, you show these hex representations of the strings: ``` 4d696e61205469646967617265 20 616e7374 c3a4 6c6c6e696e676172 // from XML 4d696e61205469646967617265 c2a0 616e7374 61cc88 6c6c6e696e676172 // typed ^^-----------------^^^^1 ^^^^^^2 ``` Note the parts I marked, apparently there are two parts to this problem. - For the first, observe [this question on the meaning of byte sequence "c2a0"](https://stackoverflow.com/questions/2774471/what-is-c2a0-in-mime-encoded-quoted-printable-text/2774507#2774507) - for some reason, your typing is translated to a non-breakable space where the XML file has a normal space. Note that there's a normal space in both cases after "Mina". Not sure what to do about *that* in PHP, except to replace all whitespace with a normal space. - As to the second, that is the case I outlined above: `c3a4` is [`ä`](http://www.decodeunicode.org/en/u+00e4) (U+00E4 "LATIN SMALL LETTER A WITH DIAERESIS" - one character, two bytes), whereas `61` is [`a`](http://www.decodeunicode.org/en/u+0061) (U+0061 "LATIN SMALL LETTER A" - one character, one byte) and `cc88` would be the combining umlaut [`"`](http://www.decodeunicode.org/en/U+0308) (U+0308 "COMBINING DIAERESIS" - two characters, three bytes). Here, the [normalization library](http://us2.php.net/manual/en/class.normalizer.php) should be useful.
Switching between Fragments in a single Activity I want to create an `Activity` which shows a sort of menu a user can go through. By clicking an item, a new screen is shown, allowing the user more options (wizard-like). I wanted to implement this using `Fragment`s, but it's not working for me. Right now I have: `main.xml`: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:id="@+id/main_fragmentcontainer" > <fragment android:id="@+id/mainmenufragment" android:name="com.myapp.MainMenuFragment" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <fragment android:id="@+id/secondmenufragment" android:name="com.myapp.SecondMenuFragment" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> ``` `MainMenuFragment` with an `OnClickListener`: ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.mainmenu, container, false); setupButton(view); return view; } /* Button setup code omitted */ @Override public void onClick(View v) { SherlockFragment secondRunMenuFragment = (SherlockFragment) getSherlockActivity().getSupportFragmentManager().findFragmentById(R.id.secondmenufragment); FragmentTransaction transaction = getSherlockActivity().getSupportFragmentManager().beginTransaction(); transaction.replace(android.R.id.content, secondMenuFragment); //also crashes with R.id.main_fragmentcontainer transaction.addToBackStack(null); transaction.commit(); } ``` Now when I press the button, the application crashes with this logcat: > > 06-27 01:45:26.309: E/AndroidRuntime(8747): java.lang.IllegalStateException: Can't change container ID of fragment SecondMenuFragment{405e2a70 #1 id=0x7f060029}: was 2131099689 now 2131099687 > > 06-27 01:45:26.309: E/AndroidRuntime(8747): at android.support.v4.app.BackStackRecord.doAddOp(Unknown Source) > > 06-27 01:45:26.309: E/AndroidRuntime(8747): at android.support.v4.app.BackStackRecord.replace(Unknown Source) > > 06-27 01:45:26.309: E/AndroidRuntime(8747): at android.support.v4.app.BackStackRecord.replace(Unknown Source) > > 06-27 01:45:26.309: E/AndroidRuntime(8747): at com.myapp.MainMenuFragment$MyButtonOnClickListener.onClick(MainMenuFragment.java:52) > > > What am I doing wrong?
Personally, I would not have any `<fragment>` elements. Step #1: Populate your activity layout with a `<FrameLayout>` for the variable piece of the wizard, plus your various buttons. Step #2: In `onCreate()` of the activity, run a `FragmentTransaction` to load the first wizard page into the `FrameLayout`. Step #3: On the "next" click, run a `FragmentTransaction` to replace the contents of the `FrameLayout` with the next page of the wizard. Step #4: Add in the appropriate smarts for disabling the buttons when they are unusable (e.g., back on the first wizard page). Also, you will want to think about how the BACK button should work in conjunction with any on-screen "back" button in the wizard. If you want them to both behave identically, you will need to add each transaction to the back stack and pop stuff off the back stack when you handle the "back" button. Someday, if nobody beats me to it, I'll try to create a wizard-by-way-of-fragments example, or perhaps a reusable component.
how to send an SMS without users interaction in flutter? I am actually trying to send SMS from my flutter app without user's interaction. I know I can launch the SMS app using url\_launcher but I actually want to send an SMS without user's interaction or launching SMS from my flutter app. Please can someone tell me if this is possible. Many Thanks, Mahi
Actually to send an SMS programatically, you'll need to implement a platform channel and use `SMSManager` to send SMS. Example: Android Part: First add appropriate permissions to `AndroidManifest.xml`. ``` <uses-permission android:name="android.permission.SEND_SMS" /> ``` Then in your `MainActivity.java`: ``` package com.yourcompany.example; import android.os.Bundle; import android.telephony.SmsManager; import android.util.Log; import io.flutter.app.FlutterActivity; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { private static final String CHANNEL = "sendSms"; private MethodChannel.Result callResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(this); new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler( new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(MethodCall call, MethodChannel.Result result) { if(call.method.equals("send")){ String num = call.argument("phone"); String msg = call.argument("msg"); sendSMS(num,msg,result); }else{ result.notImplemented(); } } }); } private void sendSMS(String phoneNo, String msg,MethodChannel.Result result) { try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNo, null, msg, null, null); result.success("SMS Sent"); } catch (Exception ex) { ex.printStackTrace(); result.error("Err","Sms Not Sent",""); } } } ``` Dart Code: ``` import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter/services.dart'; void main() { runApp(new MaterialApp( title: "Rotation Demo", home: new SendSms(), )); } class SendSms extends StatefulWidget { @override _SendSmsState createState() => new _SendSmsState(); } class _SendSmsState extends State<SendSms> { static const platform = const MethodChannel('sendSms'); Future<Null> sendSms()async { print("SendSMS"); try { final String result = await platform.invokeMethod('send',<String,dynamic>{"phone":"+91XXXXXXXXXX","msg":"Hello! I'm sent programatically."}); //Replace a 'X' with 10 digit phone number print(result); } on PlatformException catch (e) { print(e.toString()); } } @override Widget build(BuildContext context) { return new Material( child: new Container( alignment: Alignment.center, child: new FlatButton(onPressed: () => sendSms(), child: const Text("Send SMS")), ), ); } } ``` Hope this helped! \*\* Note: 1.The example code dosen't show how to handle permission on android devices with version `6.0` and above. If using with `6.0` implement the right permission invoking code. 2.The example also dosen't implement choosing sim incase of dual sim handsets. If no default sim is set for sms on dual sim handsets, sms might not be sent.
How can I shorten my URLs in Zend For example I am using following URLs for user profile/dashboard: ``` example.com/person/person/profile example.com/person/person/dashboard ``` Where **person** is **module**, 2nd **person** is **controller** and **profile** and **dashboard** are **actions**. But I want that If user go to following URLs then they should point the same URLs respectively mentioned above: ``` example.com/person/profile example.com/person/dashboard ``` Is there any way that I always remove the module name from URL? Remember I want to keep the current directory structure. Thanks
You can do this using routes, in your bootstrap add this ``` protected function _initRoutes() { $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/routes.ini'); $router = new Zend_Controller_Router_Rewrite(); $router->addConfig($config, 'routes'); Zend_Controller_Front::getInstance()->setRouter($router); } ``` Then in your config director create a file called `routes.ini`, this will contain your custom routes, try these ``` routes.person_profile.route = "person/profile" routes.person_profile.defaults.controller = person routes.person_profile.defaults.action = profile routes.person_profile.defaults.module = person routes.person_dashboard.route = "person/dashboard" routes.person_dashboard.defaults.controller = person routes.person_dashboard.defaults.action = dashboard routes.person_dashboard.defaults.module = person ``` Here we define two routes, remeber to give each a unique name I have called these `person_profile` and `person_dashboard`. The `route` value is the URI which will be overwritten by the `controller`, `action` and `module` values, for example the route `person/profile` will be automatically dispatched to the `person` controller, the `person` module and the `profle` action. Hope that helps.
Moving all fields from one object into another Can I somehow move all field values from one object to another **without** using reflection? So, what I want to do is something like this: ``` public class BetterThing extends Thing implements IBetterObject { public BetterThing(Thing t) { super(); t.evolve(this); } } ``` So, the `evolve` method would evolve one class to another. An argument would be `<? extends <? extends T>>` where `T` is the class of the object, you're calling `evolve` on. I know I can do this with reflection, but reflection hurts performance. In this case `Thing` class is in external API, and there's no method that would copy all the required fields from it to another object.
As @OliverCharlesworth points out, it can't be done directly. You will either have to resort to reflection (though I wouldn't recommend it!) or a series of field-by-field assignments. Another option though, would be to switch from inheritance to composition: ``` public class BetterThing implements IBetterObject { Thing delegate; public BetterThing(Thing t) { this.delegate = t; } // Thing methods (delegate methods) String thingMethodOne() { return delegate.thingMethodOne(); } // BetterThing methods } ``` This is commonly referred to as the [decorator pattern](https://en.wikipedia.org/?title=Decorator_pattern). See: [Prefer composition over inheritance?](https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance)
Replace last occurrence of character in string I've got the following string : 01/01/2014 blbalbalbalba blabla/blabla I would like to replace the last slash with a space, and keep the first 2 slashes in the date. The closest thing I have come up with was this kind of thing : ``` PS E:\> [regex] $regex = '[a-z]' PS E:\> $regex.Replace('abcde', 'X', 3) XXXde ``` but I don't know how to start from the end of the line. Any help would be greatly appreciated. Editing my question to clarify : I just want to replace the last slash character with a space character, therefore : 01/01/2014 blbalbalbalba blabla/blabla becomes 01/01/2014 blbalbalbalba blabla blabla Knowing that the length of "blabla" varies from one line to the other and the slash character could be anywhere. Thanks :)
Using the following string to match: ``` (.*)[/](.*) ``` and the following to replace: ``` $1 $2 ``` # Explanation: `(.*)` matches anything, any number of times (including zero). By wrapping it in parentheses, we make it available to be used again during the replace sequence, using the placeholder `$` followed by the element number (as an example, because this is the first element, `$1` will be the placeholder). When we use the relevant placeholder in the replace string, it will put all of the characters matched by this section of the regex into the resulting string. In this situation, the matched text will be `01/01/2014 blbalbalbalba blabla` `[/]` is used to match the forward slash character. `(.*)` again is used to match anything, any number of times, similar to the first instance. In this case, it will match `blabla`, making it available in the `$2` placeholder. Basically, the first three elements work together to find a number of characters, followed by a forward slash, followed by another number of characters. Because the first "match everything" is greedy (that is, it will attempt to match as many character as possible), it will include all of the other forward slashes as well, up until the last. The reason that it stops short of the last forward slash is that including it would make the regex fail, as the `[/]` wouldn't be able to match anything any more.
Should you reuse a PHP exception's code when wrapping it? When catching and wrapping an exception in PHP, assuming the new exception doesn't have a meaningful code of its own, should you also use the caught exception's code value? or the default value? In other words... Should I do this? ``` try { do_something(); } catch (GenericOrThirdParty_CaughtException $e) { // Reuse the caught exception's code: throw new MyCustom_WrappingException('Message', $e->getCode(), $e); } ``` Or this? ``` try { do_something(); } catch (GenericOrThirdParty_CaughtException $e) { // Use the default exception code: throw new MyCustom_WrappingException('Message', 0, $e); } ``` I could imagine arguments in favor of either approach, but I'm unaware of an accepted best practice. Is there any? What are the pros and cons of each approach? Is there another approach I haven't considered?
As a general rule, I'd say that **no, you do not need to keep the code**. The exception code is hardly ever relevant; when was the last time you had to handle the exception based on the given code? Unless you're connecting to SOAP servers, the answer might just be "never". It's usually better to split off your exceptions into multiple classes instead. Also, the wrapped exception can be accessed using [`$exception->getPrevious()`](https://www.php.net/manual/en/exception.getprevious.php). So if the code does turn out to be relevant, it's not irrecoverably lost, assuming you indeed wrap the old exception when raising the new one. Consider these examples: ``` class defaultException extends \Exception {} class connectionRefusedException extends defaultException {} class authorizationFailedException extends defaultException {} try { // code } catch (connectionRefusedException $e) { // ... } catch (authorizationFailedException $e) { // ... } catch (defaultException $e) { // ... } ``` Versus: ``` class defaultException extends \Exception {} try { // code } catch (defaultException $e) { switch ($e->getCode()) { case 1: // ... break; case 2: // ... break; default: // ... } } ``` The first example is, in my opinion, cleaner, easier to read and understand, and more language-agnostic. It does not require the exception code to be set. Setting it anyway implies that the code *is* relevant somehow, which might lead others to misinterpret your intent and write their own code-based exception handler. **To summarize: If you're able, define specialized exceptions, and do not rely on exception codes. When wrapping exceptions, there's hardly ever a reason to copy the code in the original exception, since you probably won't (read: shouldn't) use it.**
How to intercept connection and subscription with Spring Stomp I need to control connection/disconnection and subscriptions/unsubscriptions of stomp clients in my websocket spring server. This is the main configuration class: ``` @Configuration @ComponentScan(basePackages = "com.test") @EnableWebSocketMessageBroker @EnableWebMvc public class Config extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/queue", "/topic"); config.setApplicationDestinationPrefixes("/app"); config.setUserDestinationPrefix("/user"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/stomp").setAllowedOrigins("*").addInterceptors(getInterceptot()); } private HandshakeInterceptor getInterceptot() { return new HandshakeInterceptor(){ @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { return true; //TODO } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {} }; } } ``` I could intercept the connection event with `beforeHandshake` method, but I don't know if this is the best way. Moreover I need to check all disconnections, subscription and unsubscriptions, I tried to use `@SubscribeMapping("/**")` annotation but it doesn't work for me. I tried this: ``` @Component public class StompEventListener { @EventListener private void handleSessionConnected(SessionConnectEvent event) { } @EventListener private void handleSessionDisconnect(SessionDisconnectEvent event) { } @EventListener private void handleSessionSubscribeEvent(SessionSubscribeEvent event) { } @EventListener private void handleSessionUnsubscribeEvent(SessionUnsubscribeEvent event) { } } ``` It works, but I need to intercept this request and I should deny/grant all operations, for example I can decide to deny the connection but with `@EventListener` I cannot do this because it is called after the connection.
With a `HandshakeInterceptor` you won't be able to get CONNECT / DISCONNECT frames. You have to implement a [ChannelInterceptor](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/messaging/support/ChannelInterceptor.html) (or extend ChannelInterceptorAdapter) and add it to the `clientInboundChannel`. The `preSend` method allows you to add your logic before the message is processed: ``` public class FilterChannelInterceptor extends ChannelInterceptorAdapter { @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { StompHeaderAccessor headerAccessor= StompHeaderAccessor.wrap(message); if (StompCommand.SUBSCRIBE.equals(headerAccessor.getCommand()) { // Your logic } return message; } } ``` Check out the Spring Security interceptor, which might be a good starting point: <https://github.com/spring-projects/spring-security/blob/master/messaging/src/main/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptor.java>
Is there an official website containing a list of all apt packages with descriptions? I wonder is there a website for apt packages similar to <https://www.npmjs.com/> where I can read description of all available packages? I read some manuals how to install some software and it's written there to run `sudo apt install something`, but I have no idea what that `something` is needed for. How can I get that information?
## Website Yes, there is one. <http://packages.ubuntu.com> You can search for packages for all supported versions of Ubuntu. For example, to quickly search for the package `gimp`, you can go to <http://packages.ubuntu.com/gimp> ## Directly using apt Alternatively, you can search from the package in `apt` itself. `apt search something` shows all packages which has `something` in its name and description. `apt show exact-packagename-of-something` shows all details (description, dependencies, recommended packages, name of the packager) of the package. ## Manual pages As mentioned in the comment by @codlord, you can go to <http://manpages.ubuntu.com/> to search for manual pages (user guides) for any package.
No service for type Identity.UserManager when using multiple identity users **My setup** Currently, I have two models that inherit from `ApplicationUser`, which inherits `IdentityUser`. The user classes are: ``` public abstract class ApplicationUser : IdentityUser { [PersonalData] public string FirstName { get; set; } [PersonalData] public string LastName { get; set; } [NotMapped] public string FullName => $"{FirstName} {LastName}"; } public class StudentUser : ApplicationUser { [PersonalData] [Required] public string StudentNumber { get; set; } // A user belongs to one group public Group Group { get; set; } } public class EmployeeUser : ApplicationUser { } ``` The `ApplicationUser` contains *shared* properties, like the First and Last name. Both `StudentUser` and `EmployeeUser` have their **own** properties and relationships. This structure follows the [Table Per Hierarchy (TPH)](https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/inheritance?view=aspnetcore-2.0#options-for-mapping-inheritance-to-database-tables) inheritance. Ideally, I want to follow the [Table Per Type (TPT)](https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/inheritance?view=aspnetcore-2.0#options-for-mapping-inheritance-to-database-tables) inheritance, because the SQL structure is better. ASP.NET Core only supports TPH natively, so that is why I follow the TPT approach. **The problem** I added the Identity service in `Startup.cs`: ``` services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); ``` When I call `UserManager<StudentUser>` or `UserManager<EmployeeUser>`, I get the following error: > > No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[ClassroomMonitor.Models.StudentUser]' has been registered. > > > **My question** Unfortunately, I can't find much about this error combined with this implementation. Is it (even) possible to make it work this way? Any help or thoughts are welcome. **Update 1** Manually adding the `StudentUser` or `EmployeeUser` as a scoped services does not seem to work (mentioned as the first [answer](https://stackoverflow.com/a/52698155/3625118)). ``` services.AddScoped<UserManager<ApplicationUser>, UserManager<ApplicationUser>>(); // or.. services.AddScoped<UserManager<ApplicationUser>>(); ``` This throws the following error: > > InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore1[ClassroomMonitor.Models.StudentUser]' > > > **Update 2** Here is a [Gist](https://gist.github.com/matthijs110/94a55df9d4df35f2fb6596b54dedff25) to give you a better picture of the project structue:
Ideally you would call the same identity setup for the derived user types as for the base user type. Unfortunately [`AddIdentity`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.identityservicecollectionextensions.addidentity?view=aspnetcore-2.1) method contains some code that prevents of using it more than once. Instead, you could use [`AddIdentityCore`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.identityservicecollectionextensions.addidentitycore?view=aspnetcore-2.1). The role services are already registered by the `AddIdentity`, the only difference is that `AddIdentityCore` registers `UserClaimsPrincipalFactory<TUser>`, so in order to match `AddIdentity` setup it needs to be replaced with `UserClaimsPrincipalFactory<TUser, TRole>` via [`AddClaimsPrincipalFactory`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.identitybuilder.addclaimsprincipalfactory?view=aspnetcore-2.1) method. The code looks like something like this: ``` services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders() .AddDefaultUI(); services.AddIdentityCore<StudentUser>() .AddRoles<IdentityRole>() .AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<StudentUser, IdentityRole>>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders() .AddDefaultUI(); services.AddIdentityCore<EmployeeUser>() .AddRoles<IdentityRole>() .AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<EmployeeUser, IdentityRole>>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders() .AddDefaultUI(); ``` Of course you could move the common parts in a custom extension methods. **Update:** Although the role services are already configured, you still need to call `AddRoles` in order to set correctly the `Role` property of the `IndentityBuilder`, which then is used by the `AddEntityFrameworkStores`.
Ruby modules - included do end block There is a module `MyModule`: ``` module MyModule extend ActiveSupport::Concern def first_method end def second_method end included do second_class_method end module ClassMethods def first_class_method end def second_class_method end end end ``` When some class `include`s this module, it will have 2 methods exposed as instance methods (`first_method` and `second_method`) and 2 class methods (`first_class_method` and `second_class_method`) - it is clear. It is said, that > > `included` block will be executed within the context of the class that > is including the module. > > > What does it mean exactly? Meaning, when exactly would this method (`second_class_method`) be executed?
Here's a practical example. ``` class MyClass include MyModule end ``` When you will include the module in a class, the `included` hook will be called. Therefore, `second_class_method` will be called within the scope of `Class`. What happens here is 1. `first_method` and `second_method` are included as instance-methods of `MyClass.` ``` instance = MyClass.new instance.first_method # => whatever returned value of first_method is ``` 2. The methods of `ClassMethods` are automatically mixed as class methods of `MyClass`. This is a common Ruby pattern, that `ActiveSupport::Concern` encapsulates. The non-Rails Ruby code is ``` module MyModule def self.included(base) base.extend ClassMethods end module ClassMethods def this_is_a_class_method end end end ``` Which results in ``` MyClass.this_is_a_class_method ``` or in your case ``` MyClass.first_class_method ``` 3. `included` is a hook that is effectively to the following code ``` # non-Rails version module MyModule def self.included(base) base.class_eval do # somecode end end end # Rails version with ActiveSupport::Concerns module MyModule included do # somecode end end ``` It's mostly "syntactic sugar" for common patterns. What happens in practice, is that when you mix the module, that code is executed in the context of the mixer class.
functions call in sequence # How this stuff works? > > $object->foo1()->foo2()->foo3(); > > > I'm working in [Magento](http://www.magentocommerce.com/) php framework. In Magento functions are called as sequence.But, I don't understand how it works.Can anyone explain.
``` $object->foo1()->foo2()->foo3(); ``` First, PHP will get a pointer to the `foo1` method from the `$object` variable. It calls this method, which then returns another object. This second object (we shall call it `$object2`) has a method `foo2()`, which is also called. `foo2()` returns another object (`$object3`), which has a method `foo3()`, which returns whatever it likes. In some cases, `$object`, `$object2` and `$object3` are just pointers to the same object. This means that you can keep calling methods on the same class in a nice sequence. You can achieve this quite easily: ``` class Foo { public function nicely() { return $this; } public function formatted() { return $this; } public function chained() { return $this; } public function calls() { return $this; } } $foo = new Foo(); $foo->nicely()->formatted()->chained()->calls(); ```
ODDS RATIO- META ANALYSIS-Reversing the reference category Reversing the reference category Hello! I am doing a meta-analysis. I explain the problem with an example: All the study included in the meta-analysis have reference B (OR) except one that has reference A (OR). For this study, unfortunately, I do not have the data available to calculate the Odds Ratio inverted directly from Table 2X2. Is there any possibility of getting OR B vs A directly from OR A vs B? Thanks in advance!
Using standard notation of: - $a$ being number of events in non-reference group - $b$ being number of non-events in non-reference group - $c$ being number of events in reference group - $d$ being number of non-events in reference group we have $$ OR = \frac{ad}{bc} $$. Switching groups means switching roles of $a$ and $c$ and of $b$ and $d$, so $$ OR\_{switch} = \frac{bc}{ad} = \frac{1}{OR} $$. For meta-analysis you probably need to re-calculate SE as well. Recall that $$ SE(log(OR)) = \sqrt{\frac{1}{a}+\frac{1}{b}+\frac{1}{c}+\frac{1}{d}} $$ so $$ SE(log(OR)) =SE(log(OR\_{switch})) $$ For SE without logarithm, see [this](https://stats.stackexchange.com/questions/156597/how-to-calculate-se-of-an-odds-ratio) post and Maarten Buis answer. By delta method $$ SE(OR) = SE(log(OR)) \cdot OR $$ so $$ SE(OR\_{switch}) = SE(log(OR\_{switch})) \cdot OR\_{switch} = \frac{SE(log(OR))}{OR} = \frac{SE(OR)}{OR^2}$$ If you wish to work exclusively on log-scale (as @mdewey suggested) it's even more straightforward: $$ SE(log(OR\_{switch})) =SE(log(OR)) $$ and since $$ OR\_{switch} = \frac{1}{OR} $$ we have that $$ log(OR\_{switch}) = log(\frac{1}{OR}) = -log(OR)$$
How to unittest the sequence of function calls made insde a fuction [python] I would like to unittest a fuction and assert if the sequence of function calls made inside the function workflow(). Something like, ``` [1st called] fetch_yeargroup_ls() [2nd called] invoke_get_links()....... ``` I searched across many discussions but never found one answering my question.
If you are using [`mock`](https://pypi.python.org/pypi/mock) you can create mocks as attributes of a parent mock, when patching out those functions: ``` try: # Python 3 from unittest.mock import MagicMock, patch, call except ImportError: # Python 2, install from PyPI first from mock import MagicMock, patch, call import unittest from module_under_test import function_under_test class TestCallOrder(unittest.TestCase): def test_call_order(self): source_mock = MagicMock() with patch('module_under_test.function1', source_mock.function1), \ patch('module_under_test.function2', source_mock.function2), \ patch('module_under_test.function3', source_mock.function3) # the test is successful if the 3 functions are called in this # specific order with these specific arguments: expected = [ call.function1('foo'), call.function2('bar'), call.function3('baz') ] # run your code-under-test function_under_test() self.assertEqual(source_mock.mock_calls, expected) ``` Because the 3 functions are attached to `source_mock`, all calls to them are recorded on the parent mock object in the [`Mock.mock_calls`](https://docs.python.org/dev/library/unittest.mock.html#unittest.mock.Mock.mock_calls) attribute and you can make assertions about their call order. I attached the 3 function mocks simply by looking them up as attributes on the `source_mock` object, but you could also use the [`Mock.attach_mock()` method](https://docs.python.org/dev/library/unittest.mock.html#unittest.mock.Mock.attach_mock) to attach mocks you created in a different way to a parent.
Forward functors with minimal copying I'd like to forward functor call and copy that functor only when absolutely necessary. Here is my generic wrapper function and functor: ``` template <typename F> void wrapper (F func) { func (); } struct Functor { Functor() {} void operator() () { /* do some work */ } }; ``` I can call wrapper with 1. *rvalue reference*: wrapper( Functor() ); 2. *lvalue reference*: Functor f; wrapper(f); 3. *const lvalue reference*: const Functor f; wrapper(f); 4. *const rvalue reference*: const Functor make\_functor (); wrapper (make\_functor ()); I want to copy wrapper's arg only when const references was passed. So I come to such wrapper implementation: ``` using safe_mutual_handler_type = typename std::conditional< std::is_reference<F>::value , typename std::conditional< std::is_const<typename std::remove_reference<F>::type>::value , typename std::remove_const<typename std::remove_reference<F>::type>::type , F& >::type , F& >::type; template <typename F> void wrapper (F&& func) { safe_mutual_handler_type<F> tmp = func; tmp (); } ``` Not very nice and misses (not very typical) const-rvalue-reference case, but basically do its work. But I may also have Functor with const operator() ``` struct Functor { Functor() {} void operator() () const {} }; ``` And in that case I do not need to copy wrapper's arg at all. The question is: how may I check in wrapper if **Functor** has const parenthesis operator? The other question is if the **wrapper** may be implemented in more smart and compact way without huge number of lines of type traits typedefs? (actually I'm worrying not about code size but about code readability).
If you simply want to use references if the call with them is valid, use expression SFINAE: ``` template <typename F> auto wrapper_ (F&& func, int) -> decltype(func()) { func (); } template <typename F> void wrapper_ (F func, ...) { func (); } template <typename F> void wrapper (F&& f) { wrapper_(std::forward<F>(f), 0); } ``` If you only want to copy/move it when you pass a mutable reference (and only then): ``` template <typename F> auto wrapper_ (F&& func, std::true_type) { func (); } template <typename F> void wrapper_ (F func, std::false_type.) { func (); } template <typename F> void wrapper (F&& f) { wrapper_(std::forward<F>(f), std::is_const<typename std::remove_reference<F>::type>()); } ```
Create Jquery Plugin I creating jquery Plugin with simple alert option. I did this way see below is my code.But it doesn't work. **Below code is the seperate js file.** ``` (function($) { $.fn.gettingmessage = function() { var element = this; $(element).load(function() { alertingcontent(); function preventnextpage() { return false; } function alertingcontent() { alert("nicely done"); }); }; })(jQuery); ``` **I called this function as this way** ``` $(function(){ $("body").gettingmessage(); }); ``` I am not sure how can i fix this any suggestion would be great. **[JSFIDDLE](http://jsfiddle.net/vicky081/WTNLq/1/)** Thanks
- First, you're missing a closing bracket. - Second, the [`load()`](http://api.jquery.com/load-event/) function doesn't do what you're searching for, use [`ready()`](http://api.jquery.com/ready/) instead of. Updated code : ``` (function($) { $.fn.gettingmessage = function() { var element = this; $(element).ready(function() { alertingcontent(); function preventnextpage() { return false; } function alertingcontent() { alert("nicely done"); } }); }; })(jQuery); $(function(){ $("body").gettingmessage(); }); ``` [Updated jsFiddle](http://jsfiddle.net/zessx/WTNLq/4/)
Is returning references of member variables bad practice? The following is said to be better than having First() and Second() as public members. I believe this is nearly as bad. ``` // Example 17-3(b): Proper encapsulation, initially with inline accessors. Later // in life, these might grow into nontrivial functions if needed; if not, then not. template<class T, class U> class Couple { public: Couple() : deleted_(false) { } void MarkDeleted() { deleted_ = true; } bool IsDeleted() { return deleted_; } private: T first_; U second_; bool deleted_; T& First() { return first_; } U& Second() { return second_; } }; ``` If you're giving a way to access a private variable outside of the class then what's the point? Shouldn't the functions be ``` T First(); void(or T) First(const T&) ```
There are several reasons why returning references (or pointers) to the internals of a class are bad. Starting with (what I consider to be) the most important: 1. **Encapsulation** is breached: you leak an implementation detail, which means that you can no longer alter your class internals as you wish. If you decided not to store `first_` for example, but to compute it on the fly, how would you return a reference to it ? You cannot, thus you're stuck. 2. **Invariant** are no longer sustainable (in case of non-const reference): anybody may access and modify the attribute referred to at will, thus you cannot "monitor" its changes. It means that you cannot maintain an invariant of which this attribute is part. Essentially, your class is turning into a blob. 3. **Lifetime** issues spring up: it's easy to keep a reference or pointer to the attribute after the original object they belong to ceased to exist. This is of course undefined behavior. Most compilers will attempt to warn about keeping references to objects on the stack, for example, but I know of no compiler that managed to produce such warnings for references returned by functions or methods: you're on your own. As such, it is usually better not to give away references or pointers to attributes. *Not even const ones!* For small values, it is generally sufficient to pass them by copy (both `in` and `out`), especially now with move semantics (on the way in). For larger values, it really depends on the situation, sometimes a Proxy might alleviate your troubles. Finally, note that for some classes, having public members is not so bad. What would be the point of encapsulating the members of a `pair` ? When you find yourself writing a class that is no more than a collection of attributes (no invariant whatsoever), then instead of getting all OO on us and writing a getter/setter pair for each of them, consider making them public instead.
What webcam apps are available and how to check if your webcam is working? What software is available for using webcams or ways of checking if my webcam is working correctly after installing Ubuntu.
# [Cheese](http://projects.gnome.org/cheese/) [Install Cheese](http://apt.ubuntu.com/p/cheese) ![enter image description here](https://i.stack.imgur.com/wezVP.jpg) > > Cheese uses your webcam to take photos > and videos, applies fancy special > effects and lets you share the fun > with others. It was written as part of > Google's 2007 Summer of Code lead by > daniel g. siegel and mentored by > Raphaël Slinckx. Under the hood, > Cheese uses GStreamer to apply fancy > effects to photos and videos. With > Cheese it is easy to take photos of > you, your friends, pets or whatever > you want and share them with others. > > >
converting an HTML table in Pandas Dataframe I am reading an HTML table with pd.read\_html but the result is coming in a list, I want to convert it inot a pandas dataframe, so I can continue further operations on the same. I am using the following script ``` import pandas as pd import html5lib data=pd.read_html('http://www.espn.com/nhl/statistics/player/_/stat/points/sort/points/year/2015/seasontype/2',skiprows=1) ``` and since My results are coming as 1 list, I tried to convert it into a data frame with ``` data1=pd.DataFrame(Data) ``` and result came as 0 ``` 0 0 1 2 3 4... ``` and because of result as a list, I can't apply any functions such as rename, dropna, drop. I will appreciate every help
I think you need add `[0]` if need select first item of list, because [`read_html`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html) return `list of DataFrames`: So you can use: ``` import pandas as pd data1 = pd.read_html('http://www.espn.com/nhl/statis‌​tics/player/‌​_/stat/point‌​s/sort/point‌​s/year/2015&‌​#47;seasontype/2‌​',skiprows=1)[0] ``` ``` print (data1) 0 1 2 3 4 5 6 7 8 9 \ 0 RK PLAYER TEAM GP G A PTS +/- PIM PTS/G 1 1 Jamie Benn, LW DAL 82 35 52 87 1 64 1.06 2 2 John Tavares, C NYI 82 38 48 86 5 46 1.05 3 3 Sidney Crosby, C PIT 77 28 56 84 5 47 1.09 4 4 Alex Ovechkin, LW WSH 81 53 28 81 10 58 1.00 5 NaN Jakub Voracek, RW PHI 82 22 59 81 1 78 0.99 6 6 Nicklas Backstrom, C WSH 82 18 60 78 5 40 0.95 7 7 Tyler Seguin, C DAL 71 37 40 77 -1 20 1.08 8 8 Jiri Hudler, LW CGY 78 31 45 76 17 14 0.97 9 NaN Daniel Sedin, LW VAN 82 20 56 76 5 18 0.93 10 10 Vladimir Tarasenko, RW STL 77 37 36 73 27 31 0.95 11 NaN PP SH NaN NaN NaN NaN NaN NaN NaN 12 RK PLAYER TEAM GP G A PTS +/- PIM PTS/G 13 NaN Nick Foligno, LW CBJ 79 31 42 73 16 50 0.92 14 NaN Claude Giroux, C PHI 81 25 48 73 -3 36 0.90 15 NaN Henrik Sedin, C VAN 82 18 55 73 11 22 0.89 16 14 Steven Stamkos, C TB 82 43 29 72 2 49 0.88 17 NaN Tyler Johnson, C TB 77 29 43 72 33 24 0.94 18 16 Ryan Johansen, C CBJ 82 26 45 71 -6 40 0.87 19 17 Joe Pavelski, C SJ 82 37 33 70 12 29 0.85 20 NaN Evgeni Malkin, C PIT 69 28 42 70 -2 60 1.01 21 NaN Ryan Getzlaf, C ANA 77 25 45 70 15 62 0.91 22 20 Rick Nash, LW NYR 79 42 27 69 29 36 0.87 23 NaN PP SH NaN NaN NaN NaN NaN NaN NaN 24 RK PLAYER TEAM GP G A PTS +/- PIM PTS/G 25 21 Max Pacioretty, LW MTL 80 37 30 67 38 32 0.84 26 NaN Logan Couture, C SJ 82 27 40 67 -6 12 0.82 27 23 Jonathan Toews, C CHI 81 28 38 66 30 36 0.81 28 NaN Erik Karlsson, D OTT 82 21 45 66 7 42 0.80 29 NaN Henrik Zetterberg, LW DET 77 17 49 66 -6 32 0.86 30 26 Pavel Datsyuk, C DET 63 26 39 65 12 8 1.03 31 NaN Joe Thornton, C SJ 78 16 49 65 -4 30 0.83 32 28 Nikita Kucherov, RW TB 82 28 36 64 38 37 0.78 33 NaN Patrick Kane, RW CHI 61 27 37 64 10 10 1.05 34 NaN Mark Stone, RW OTT 80 26 38 64 21 14 0.80 35 NaN PP SH NaN NaN NaN NaN NaN NaN NaN 36 RK PLAYER TEAM GP G A PTS +/- PIM PTS/G 37 NaN Alexander Steen, LW STL 74 24 40 64 8 33 0.86 38 NaN Kyle Turris, C OTT 82 24 40 64 5 36 0.78 39 NaN Johnny Gaudreau, LW CGY 80 24 40 64 11 14 0.80 40 NaN Anze Kopitar, C LA 79 16 48 64 -2 10 0.81 41 35 Radim Vrbata, RW VAN 79 31 32 63 6 20 0.80 42 NaN Jaden Schwartz, LW STL 75 28 35 63 13 16 0.84 43 NaN Filip Forsberg, C NSH 82 26 37 63 15 24 0.77 44 NaN Jordan Eberle, RW EDM 81 24 39 63 -16 24 0.78 45 NaN Ondrej Palat, LW TB 75 16 47 63 31 24 0.84 46 40 Zach Parise, LW MIN 74 33 29 62 21 41 0.84 10 11 12 13 14 15 16 0 SOG PCT GWG G A G A 1 253 13.8 6 10 13 2 3 2 278 13.7 8 13 18 0 1 3 237 11.8 3 10 21 0 0 4 395 13.4 11 25 9 0 0 5 221 10.0 3 11 22 0 0 6 153 11.8 3 3 30 0 0 7 280 13.2 5 13 16 0 0 8 158 19.6 5 6 10 0 0 9 226 8.9 5 4 21 0 0 10 264 14.0 6 8 10 0 0 11 NaN NaN NaN NaN NaN NaN NaN 12 SOG PCT GWG G A G A 13 182 17.0 3 11 15 0 0 14 279 9.0 4 14 23 0 0 15 101 17.8 0 5 20 0 0 16 268 16.0 6 13 12 0 0 17 203 14.3 6 8 9 0 0 18 202 12.9 0 7 19 2 0 19 261 14.2 5 19 12 0 0 20 212 13.2 4 9 17 0 0 21 191 13.1 6 3 10 0 2 22 304 13.8 8 6 6 4 1 23 NaN NaN NaN NaN NaN NaN NaN 24 SOG PCT GWG G A G A 25 302 12.3 10 7 4 3 2 26 263 10.3 4 6 18 2 0 27 192 14.6 7 6 11 2 1 28 292 7.2 3 6 24 0 0 29 227 7.5 3 4 24 0 0 30 165 15.8 5 8 16 0 0 31 131 12.2 0 4 18 0 0 32 190 14.7 2 2 13 0 0 33 186 14.5 5 6 16 0 0 34 157 16.6 6 5 8 1 0 35 NaN NaN NaN NaN NaN NaN NaN 36 SOG PCT GWG G A G A 37 223 10.8 5 8 16 0 0 38 215 11.2 6 4 12 1 0 39 167 14.4 4 8 13 0 0 40 134 11.9 4 6 18 0 0 41 267 11.6 7 12 11 0 0 42 184 15.2 4 8 8 0 2 43 237 11.0 6 6 13 0 0 44 183 13.1 2 6 15 0 0 45 139 11.5 5 3 8 1 1 46 259 12.7 3 11 5 0 0 ```
How do I enforce App Check in Cloud Firestore? I have set up App Check in my Firebase Project, for both my mobile app and my web app. Once I was done with that, I have enabled App Check in various Firebase products such as Cloud Functions and Cloud Storage, following the instructions [here](https://firebase.google.com/docs/app-check/web/recaptcha-provider#enable-enforcement). However those instructions don't mention Cloud Firestore. How do I enable App Check in Cloud Firestore? The link above doesn't provide any info and I could not find anything in the Cloud Firestore documentation.
*firebaser here* **Update** (November 10, 2021): Firebase just added support for App Check to Firestore. For this and all the latest releases, check: <https://firebase.googleblog.com/2021/11/whats-new-at-Firebase-Summit-2021.html#Strengthening> --- Old answer , you really should check the update ... According to the documentation on [Firebase App Check](https://firebase.google.com/docs/app-check): > > App Check currently works with the following Firebase products: > > > - Realtime Database > - Cloud Storage > - Cloud Functions (callable functions) > > > So Cloud Firestore does not yet support App Check. While we're definitely interested adding support for App Check to Firestore in the future, there is no timeline for when this will be available.
terraform eks setup - namespaces is forbidden: User cannot list resource I have been following a guide on how to setup AWS EKS using terraform. <https://learn.hashicorp.com/tutorials/terraform/eks> I am on the section where i need to authenticate the dashboard. <https://learn.hashicorp.com/tutorials/terraform/eks#authenticate-the-dashboard> 1. I have created the cluster roll binding ``` $ kubectl apply -f https://raw.githubusercontent.com/hashicorp/learn-terraform-provision-eks-cluster/master/kubernetes-dashboard-admin.rbac.yaml ``` 2. I have generated the token ``` kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep service-controller-token | awk '{print $1}') ``` 3. I have logged into the kubernetes dashboard using token. `kubectl proxy` However after im logged in and i try to click on any of the panels to see the resources, i get a set of errors that are similar to the following. > > namespaces is forbidden: User > "system:serviceaccount:kube-system:service-controller" cannot list > resource "namespaces" in API group "" at the cluster scope > > > cronjobs.batch is forbidden: User > "system:serviceaccount:kube-system:service-controller" cannot list > resource "cronjobs" in API group "batch" in the namespace "default" > > > The messages suggest to me the user im logged in as via the token does not have the permissions to view these resources. Although i am able to view them using `kubectl` cli tool. ``` kubectl describe clusterrole kubernetes-dashboard Name: kubernetes-dashboard Labels: k8s-app=kubernetes-dashboard Annotations: <none> PolicyRule: Resources Non-Resource URLs Resource Names Verbs --------- ----------------- -------------- ----- nodes.metrics.k8s.io [] [] [get list watch] pods.metrics.k8s.io [] [] [get list watch] ```
The following will log you in as an `admin-user`, which seems to be the behavior you're looking for. ``` $ ADMIN_USER_TOKEN_NAME=$(kubectl -n kube-system get secret | grep admin-user-token | cut -d' ' -f1) $ echo $ADMIN_USER_TOKEN_NAME admin-user-token-k4s7r # The suffix is auto-generated $ ADMIN_USER_TOKEN_VALUE=$(kubectl -n kube-system get secret "$ADMIN_USER_TOKEN_NAME" -o jsonpath='{.data.token}' | base64 --decode) $ echo "$ADMIN_USER_TOKEN_VALUE" eyJhbGciOiJ ... .....................-Tg # Copy this token and use it on the Kubernetes Dashboard login page ``` The Service Account that was used in the tutorial is `service-controller`, which seems to have a very few permissions ``` $ kubectl -n kube-system describe clusterrole system:controller:service-controller Name: system:controller:service-controller Labels: kubernetes.io/bootstrapping=rbac-defaults Annotations: rbac.authorization.kubernetes.io/autoupdate: true PolicyRule: Resources Non-Resource URLs Resource Names Verbs --------- ----------------- -------------- ----- events [] [] [create patch update] events.events.k8s.io [] [] [create patch update] services [] [] [get list watch] nodes [] [] [list watch] services/status [] [] [patch update] ``` Let me know if you have any issues.
What's the point of AMQP? As I understood AMQP 0.9.1, the main benefit was that you could send and receive messages and configure your exchanges / bindings / queues in a broker-independent way, thus you were able to switch your broker implementation without too much headache. Now, AMQP 1.0 only defines a wire-level protocol, so you actually have to know your broker specifics in order to implement most messaging patterns. Then why would I favour a message broker that is AMQP compliant over one that is not? If the broker implements AMQP 1.0, I'm still locked in with broker specific client code. With AMQP 0.9.1, I am theoretically broker independent but would most likely end up with RabbitMQ, since they seem to be the only ones to sincerely maintain the full support for AMQP 0.9.1.
Unfortunately, your concerns are very valid. [Pieter Hintjens has great post on that](http://hintjens.com/blog:28), claiming that "AMQP/1.0 will go down in history as a prime documented example of how to fail a standardization effort and hurt a lot of people in the process." To your question: "why would I favour a message broker that is AMQP compliant over one that is not?" Definitely not because you get the option to change your message broker provider, as it is now not required. There are only two situations, I would think of favouring AMQP message broker: 1) You are already used to that and have that broker easily available 2) AMQP still brings the advantage of having clients available in multiple programming languages. But [STOMP](http://en.wikipedia.org/wiki/Streaming_Text_Oriented_Messaging_Protocol) would serve here too.
switch case for parsing options I am writing a simple program which takes the arguments form the user and process them. I have the arguments in the argv which is two dimensional array. But when i ran the program, i get the garbage value and the segmentation fault error. I have tried with using argc as terminating condition and it works. But i want to do it using the pointer only. What am doing wrong with pointer here. ``` #include<stdio.h> int main( int argc, char *argv[]) { while (++(*argv)) { if ( **argv == '-' ) { switch (*argv[1]) { default: printf("Unknown option -%c\n\n", (*argv)[1]); break; case 'h': printf("\n option h is found"); break; case 'v': printf("option V is found"); break; case 'd': printf("\n option d is found"); break; } } printf("\n outside while : %s", *argv); } } ``` program run as: ``` ./a.out -h -v -d ``` Thank you
- If you want to iterate through program arguments looking for the terminating null pointer, your outer cycle should be ``` while (*++argv) ``` not the ``` while (++*argv) // <- incorrect! ``` that you have in your code. - Your `switch` expression is written incorrectly. While your intent is clear, your implementation ignores operator precedence. This ``` switch (*argv[1]) { // <- incorrect! ``` should actually be ``` switch ((*argv)[1]) { ``` - The previous `if` ``` if (**argv == '-') ``` is fine, but since it is equivalent to ``` if ((*argv)[0] == '-') // <- better ``` maybe you should rewrite it that way as well, just for consistency with `switch`.
Can I debug AngularJS and TypeScript in Eclipse? I have just started working with TypEcs and I am trying to create a webpage in Typescript and AngularJS which I want to debug in Eclipse. - Is it possible to debug a TypeScript and Angular page in Eclipse? If so then can you please guide me in the right direction? I've tried to debug a single typescript file with the TypeScript Standalone option and it works. But I also want to use AngularJS. I've created an index.html file and an app.ts file I have also imported angular.d.ts and angular.min.js among others into a script folder. Can I do this by using any of the TypEcs TypeScript debuggers? I have tried to run it, but I get an error at var app = angular.module... (ReferenceError: angular is not defined). My guess is that the angular.min.js file which I link to in the index file hasn't been loaded. Is it because app.ts is set to be main file in the TypeScript Standalone configuration? (I cannot choose the index.html) And/Or am I missing some code/settings? I hope you can help me. Thank you in advance! Here is some example code: index.html: ``` <html ng-app="helloworld"> <head> <title>Hello World!</title> </head> <body> <div class="container" ng-controller="HelloWorldCtrl"> <input type="text" class="form-control" value="{{message}}" /> </div> <script src="../scripts/angular.min.js"></script> <script src="app.js"></script> </body> </html> ``` app.ts: ``` /// <reference path="../scripts/typings/angularjs/angular.d.ts"/> module Sample.HelloWorld { export interface IHelloWorldScope extends ng.IScope { message: string; } export class HelloWorldCtrl { static $inject = ["$scope"]; constructor(private scope: IHelloWorldScope) { scope.message = "Hello World"; } } var app = angular.module("helloworld",["ui.bootstrap"]); app.controller("HelloWorldCtrl", HelloWorldCtrl); } ```
As Basarat mentioned it is possible to debug AngularJS and TypeScript using the "TypeScript Web Remote" debug option which is included in TypEcs How to debug the page: 1. Close all open chrome windows. 2. Open Chrome again with the command chrome.exe --remote-debugging-port=9222 3. Apply a debug configuration according to "Add TypeScript Debug for WebKit remote mode" at [TypEcs / 2.0 - New and Noteworthy](https://bitbucket.org/axmor/typecs/wiki/2.0%20-%20New%20and%20Noteworthy) 4. Open your start page (index.html) in the chrome window from point 1. 5. Go to debug view 6. Debug using the configuration from step 3 7. A dialog appears where you need to select the tab with the file that you wish to debug. 8. Now you can step through the code and add breakpoints to the app.ts file if you wish. (Click on Main thread if you don't see the step options) And if you get the error "Failed to get tabs for debugging connect timed out" close all chrome windows and reopen chrome with the chrome.exe --remote-debugging-port=9222 command.
To create a new directory and a file within it using Java I am trying to create a new directory and a file within this directory. Can any one tell me where am I going wrong? I am using a Windows system and I want the directory to be present in the folder my `.java` file is present. ``` import java.io.*; class PS_Task1 { public static void main(String[] args) { try { File file = new File("Library\\test.txt"); file.mkdir(); file.createNewFile(); } catch(Exception e) { System.out.println("ecception"); } } } ```
Basically, what's happening is, you are creating a directory called `Library\test.txt`, then trying to create a new file called the same thing, this obviously isn't going to work. So, instead of... ``` File file = new File("Library\\test.txt"); file.mkdir(); file.createNewFile(); ``` Try... ``` File file = new File("Library\\test.txt"); file.getParentFile().mkdir(); file.createNewFile(); ``` **Additional** `mkdir` will not actually throw any kind of exception if it fails, which is rather annoying, so instead, I would do something more like... ``` File file = new File("Library\\test.txt"); if (file.getParentFile().mkdir()) { file.createNewFile(); } else { throw new IOException("Failed to create directory " + file.getParent()); } ``` Just so I knew what the actual problem was... **Additional** The creation of the directory (in this context) will be at the location you ran the program from... For example, you run the program from `C:\MyAwesomJavaProjects\FileTest`, the `Library` directory will be created in this directory (ie `C:\MyAwesomJavaProjects\FileTest\Library`). Getting it created in the same location as your `.java` file is generally not a good idea, as your application may actually be bundled into a Jar later on.
cmake find sqlite3 library on windows I am having more trouble than I'd expect getting CMake to find the `sqlite3.dll` library on Windows 7 (64-bit if that matters). I have downloaded and placed the latest `sqlite3.dll` and `sqlite3.def` files to `C:\Windows\System32`. I am using the `FindSqlite3.cmake` module below: ``` IF( SQLITE3_INCLUDE_DIR AND SQLITE3_LIBRARY_RELEASE AND SQLITE3_LIBRARY_DEBUG ) SET(SQLITE3_FIND_QUIETLY TRUE) ENDIF( SQLITE3_INCLUDE_DIR AND SQLITE3_LIBRARY_RELEASE AND SQLITE3_LIBRARY_DEBUG ) FIND_PATH( SQLITE3_INCLUDE_DIR sqlite3.h ) FIND_LIBRARY(SQLITE3_LIBRARY_RELEASE NAMES sqlite3 ) FIND_LIBRARY(SQLITE3_LIBRARY_DEBUG NAMES sqlite3 sqlite3d HINTS /usr/lib/debug/usr/lib/ C:/Windows/System32/ ) IF( SQLITE3_LIBRARY_RELEASE OR SQLITE3_LIBRARY_DEBUG AND SQLITE3_INCLUDE_DIR ) SET( SQLITE3_FOUND TRUE ) ENDIF( SQLITE3_LIBRARY_RELEASE OR SQLITE3_LIBRARY_DEBUG AND SQLITE3_INCLUDE_DIR ) IF( SQLITE3_LIBRARY_DEBUG AND SQLITE3_LIBRARY_RELEASE ) # if the generator supports configuration types then set # optimized and debug libraries, or if the CMAKE_BUILD_TYPE has a value IF( CMAKE_CONFIGURATION_TYPES OR CMAKE_BUILD_TYPE ) SET( SQLITE3_LIBRARIES optimized ${SQLITE3_LIBRARY_RELEASE} debug ${SQLITE3_LIBRARY_DEBUG} ) ELSE( CMAKE_CONFIGURATION_TYPES OR CMAKE_BUILD_TYPE ) # if there are no configuration types and CMAKE_BUILD_TYPE has no value # then just use the release libraries SET( SQLITE3_LIBRARIES ${SQLITE3_LIBRARY_RELEASE} ) ENDIF( CMAKE_CONFIGURATION_TYPES OR CMAKE_BUILD_TYPE ) ELSEIF( SQLITE3_LIBRARY_RELEASE ) SET( SQLITE3_LIBRARIES ${SQLITE3_LIBRARY_RELEASE} ) ELSE( SQLITE3_LIBRARY_DEBUG AND SQLITE3_LIBRARY_RELEASE ) SET( SQLITE3_LIBRARIES ${SQLITE3_LIBRARY_DEBUG} ) ENDIF( SQLITE3_LIBRARY_DEBUG AND SQLITE3_LIBRARY_RELEASE ) IF( SQLITE3_FOUND ) IF( NOT SQLITE3_FIND_QUIETLY ) MESSAGE( STATUS "Found Sqlite3 header file in ${SQLITE3_INCLUDE_DIR}") MESSAGE( STATUS "Found Sqlite3 libraries: ${SQLITE3_LIBRARIES}") ENDIF( NOT SQLITE3_FIND_QUIETLY ) ELSE(SQLITE3_FOUND) IF( SQLITE3_FIND_REQUIRED) MESSAGE( FATAL_ERROR "Could not find Sqlite3" ) ELSE( SQLITE3_FIND_REQUIRED) MESSAGE( STATUS "Optional package Sqlite3 was not found" ) ENDIF( SQLITE3_FIND_REQUIRED) ENDIF(SQLITE3_FOUND) ``` This works fine on Linux, but not on Windows. I have spent a few hours now attempting small changes to other CMAKE variables with no luck. It seems like it should be straight forward getting CMake to find this `dll`. Could I get some help getting this to find the sqlite3 library on Windows?
There are some issues here and also some weird Windows stuff! First issue; when searching for a library on Windows with MSVC as the generator, CMake will always look for a ".lib" file - never a ".dll", even if you specify e.g. `sqlite3.dll` as the `NAMES` argument to `find_library`. This is unfortunately not properly documented, in fact the docs for [`CMAKE_FIND_LIBRARY_SUFFIXES`](http://www.cmake.org/cmake/help/v2.8.10/cmake.html#variable%3aCMAKE_FIND_LIBRARY_SUFFIXES) wrongly state: > > This specifies what suffixes to add to library names when the find\_library command looks for libraries. On Windows systems this is typically .lib and .dll, meaning that when trying to find the foo library it will look for foo.dll etc. > > > You can easily check this; simply add ``` message("CMAKE_FIND_LIBRARY_SUFFIXES: ${CMAKE_FIND_LIBRARY_SUFFIXES}") ``` to your CMakeLists.txt. You should see output like: > > > ``` > CMAKE_FIND_LIBRARY_SUFFIXES: .lib > > ``` > > [This thread](http://cmake.3232098.n2.nabble.com/FindLibrary-only-looks-for-lib-under-Windows-td5532822.html) from the CMake mailing list further confirms this behaviour. If you really need to find the dlls, you'll need to use the [`find_file`](http://www.cmake.org/cmake/help/v2.8.10/cmake.html#command%3afind_file) command, e.g: ``` find_file(SQLITE3_DLL_DEBUG NAMES sqlite3d.dll PATHS ...) ``` --- The next issue is a minor one. You should prefer `PATHS` to `HINTS` as the argument in `find_xxx` commands if it's a hard-coded guess. From the docs for [`find_library`](http://www.cmake.org/cmake/help/v2.8.10/cmake.html#command%3afind_library): > > `3`. Search the paths specified by the `HINTS` option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the `PATHS` option. > > > --- A slightly more serious issue is in the line: ``` FIND_LIBRARY(SQLITE3_LIBRARY_DEBUG NAMES sqlite3 sqlite3d ...) ``` You should specify sqlite3d *first* then sqlite3 or sqlite3 will incorrectly be chosen as the Debug library if both are available. --- And now the weirdness... On a Windows x64 system, the `find_xxx` partially ignores the C:\Windows\System32 directory in favour of the C:\Windows\SysWOW64 one. If you don't have the sqlite3.lib in C:\Windows\SysWOW64, then the `find_library` command will always fail, regardless of the `PATHS` argument. However, if you *do* have C:\Windows\SysWOW64\sqlite3.lib, then any combination of `C:/Windows/SysWOW64` and/or `C:/Windows/System32` as the `PATHS` argument finds the library, but sets the full path to `C:/Windows/System32/sqlite3.lib` *even if C:/Windows/System32/sqlite3.lib doesn't exist*! This is obviously useless if the library isn't there; a linker error will result. There is some further reading again from the CMake mailing list [here](http://www.cmake.org/pipermail/cmake/2010-June/037312.html). Having said that, if you're linking, you'll be using the .lib files, not the .dlls, and System32 & SysWOW64 aren't really the place for .lib files.
In Application Insights analytics how to query what percent of users are impacted by specific exception? I use this query to display exceptions: ``` exceptions | where application_Version == "xyz" | summarize count_=count(itemCount), impactedUsers=dcount(user_Id) by problemId, type, method, outerMessage, innermostMessage | order by impactedUsers ``` How to query what percent of users are impacted by specific exception? I would check all users by this query: ``` customEvents | where application_Version == "xyz" | summarize dcount(user_Id) ```
You're almost there with what you have, you just need to connect the two: 1. use `let` + `toscalar` to define the results of a query as a number 2. reference that in your query (i used `*1.0` to force it to be a float, otherwise you get 0, and used `round` to get 2 decimals, adjust that however you need) making your query: ``` let totalUsers = toscalar(customEvents | where application_Version == "xyz" | summarize dcount(user_Id)); exceptions | where application_Version == "xyz" | summarize count_=count(itemCount), impactedUsers=dcount(user_Id), percent=round(dcount(user_Id)*1.0/totalUsers*100.0,2) by problemId, type, method, outerMessage, innermostMessage | order by impactedUsers ```
Pre-Boot BIOS Setup Power Setting/Warning Currently when I startup my Dell Latitude 5400 I receive this message: [![enter image description here](https://i.stack.imgur.com/qhHf4l.jpg)](https://i.stack.imgur.com/qhHf4l.jpg) > > Alert! You have attached an undersized 60W power adapter to your system, which is less than the recommended 90W power adapter. To continue operating at peak performance, your system may also draw power from the battery. The battery charges only when the power provided by the adapter is greater than the needs of your. Use a Dell 90W (or greater) power adapter to enable charging during peak system performance. > > > Note: This warning can be disabled in BIOS setup. > > > Now, I am using the 90W power supply that was provided with laptop from the factory, so I am not worried performance or battery charge state (never had an issue with the battery draining with the work I do). I would like to focus on the last line "Note: This warning can be disabled in BIOS setup." I have been through the entire BIOS Setup menu and cannot find a setting or option that will disable this warning message. **Where can I find this setting/option?**
According to [the manual](https://www.dell.com/support/manuals/en-ae/latitude-14-5400-laptop/latitude_5400_setupspecs/post-behavior?guid=guid-d37ff18c-3501-42a9-86ed-bc2c55d43007&lang=en-us), you can find the option under *POST Behavior*. It is called *Adapter Warnings* and should be at the very top in this menu. On my Dell Precision 5560, the menu is called *Pre-boot Behavior*, the option is the same. --- You indicate you’re using a docking station. If it is a USB-C docking station with passthrough charging, you need a bigger power supply. General rule of thumb with Dell is one step bigger. So if your notebook requires 65 Watts, you’d use a 90 W PSU on the dock. If it requires 90 W, 130 W. 130, 180. 180, 240. It’s also important to keep in mind that Dell uses proprietary USB Power Delivery extensions. Use a Dell dock, if at all possible. Otherwise, you can always connect a PSU using the barrel plug, in addition to the docking station via USB-C.
Plotting a linear regression with dates in matplotlib.pyplot How would I plot a linear regression with dates in pyplot? I wasn't able to find a definitive answer to this question. This is what I've tried (courtesy of w3school's tutorial on linear regression). ``` import matplotlib.pyplot as plt from scipy import stats x = ['01/01/2019', '01/02/2019', '01/03/2019', '01/04/2019', '01/05/2019', '01/06/2019', '01/07/2019', '01/08/2019', '01/09/2019', '01/10/2019', '01/11/2019', '01/12/2019', '01/01/2020'] y = [12050, 17044, 14066, 16900, 19979, 17593, 14058, 16003, 15095, 12785, 12886, 20008] slope, intercept, r, p, std_err = stats.linregress(x, y) def myfunc(x): return slope * x + intercept mymodel = list(map(myfunc, x)) plt.scatter(x, y) plt.plot(x, mymodel) plt.show() ```
You first have to convert your dates into numbers to be able to do a regression (and to plot for that matter). Then you can instruct matplotlib to interpret the x-values as dates to get a nicely formatted axis: ``` import matplotlib.pyplot as plt from scipy import stats import datetime x = ['01/01/2019', '01/02/2019', '01/03/2019', '01/04/2019', '01/05/2019', '01/06/2019', '01/07/2019', '01/08/2019', '01/09/2019', '01/10/2019', '01/11/2019', '01/12/2019'] y = [12050, 17044, 14066, 16900, 19979, 17593, 14058, 16003, 15095, 12785, 12886, 20008] # convert the dates to a number, using the datetime module x = [datetime.datetime.strptime(i, '%M/%d/%Y').toordinal() for i in x] slope, intercept, r, p, std_err = stats.linregress(x, y) def myfunc(x): return slope * x + intercept mymodel = list(map(myfunc, x)) fig, ax = plt.subplots() ax.scatter(x, y) ax.plot(x, mymodel) # instruct matplotlib on how to convert the numbers back into dates for the x-axis l = matplotlib.dates.AutoDateLocator() f = matplotlib.dates.AutoDateFormatter(l) ax.xaxis.set_major_locator(l) ax.xaxis.set_major_formatter(f) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/ip5gR.png)](https://i.stack.imgur.com/ip5gR.png)
Use Emscripten with Fortran: LAPACK binding My goal is to use LAPACK with Emscripten. My question is: how to port LAPACK to JS? The are two ways I can think of: CLAPACK to JS where my question is: does anybody know an unofficial version that is later than 3.2.1? And the other way to think of is: how to port FORTRAN to JS? Emscripten is capable of transforming C code to JavaScript. But unfortunately, LAPACK 3.5.0 (<http://www.netlib.org/lapack/>) is only available in FORTRAN95. The CLAPACK project (<http://www.netlib.org/clapack/>) is basically what I want: a C version of LAPACK. But this one is outdated; the latest is 3.2.1. F2C only works up to FORTRAN 77. LAPACK 3.5.0 was written in FORTRAN 95. So my question now is: why is there no newer port of LAPACK to C? The optimal way would be to directly transform the FORTRAN95 code of LAPACK to javascript with clang and emscripten. But I just don't know where to start. Emscripten currently does not support FORTRAN. But it handles LLVM bitcode, so it should not be a problem to use clang to generate LLVM bc from a FORTRAN file. For testing purpose, I have this file: ``` program hello print *, "Hello World!" end program hello ``` It compiles just fine with "clang hello.f -o hello -lgfortran". I am not capable of transforming this into valid bitcode. ``` clang -c -emit-llvm hello.f clang -S -emit-llvm hello.f -o hello.bc -lgfortran ``` None of these approaches works, because emscripten keeps telling me ``` emcc -c hello.o -o hello.js hello.o is not valid LLVM bitcode ``` I am not sure anyways if this would be even possible, because LAPACK obviously needs libgfortran to work. And I can't merge a library into javascript code... Thanks in advance! Edit: I almost managed it to convert BLAS from LAPACK 3.5.0 to JS. I used dragonegg to accomplish this. ``` gfortran caxpy.f -flto -S -fplugin=/usr/lib/gcc/x86_64-linux-gnu/4.6/plugin/dragonegg.so gfortran cgerc.f ... ... ``` After gaining LLVM bitcode from that: ``` emcc caxpy.s.ll cgerc.s.ll cher.s.ll ... -o blas.js -s EXPORTED_FUNCTIONS="['_caxpy_', ... , '_ztpsv_']" ``` But emscripten still leaves me with the following errors: ``` warning: unresolved symbol: _gfortran_st_write warning: unresolved symbol: _gfortran_string_len_trim warning: unresolved symbol: _gfortran_transfer_character_write warning: unresolved symbol: _gfortran_transfer_integer_write warning: unresolved symbol: _gfortran_st_write_done warning: unresolved symbol: _gfortran_stop_string warning: unresolved symbol: cabs warning: unresolved symbol: cabsf AssertionError: Did not receive forwarded data in an output - process failed? ``` The problem is that lgfortran is precompiled I think.
Thank you for your reply! Indeed I did make progress on this. Finally it is working. I was very close, just follow these steps: ``` gfortran caxpy.f -S -flto -m32 -fplugin=dragonegg.so mv caxpy.s caxpy.ll llvm-as caxpy.ll -o caxpy.o ``` Note the "m32" flag which I missed earlier. Warnings like ``` warning: unresolved symbol: _gfortran_st_write ``` can be ignored safely. Emscripten creates empty functions in the JavaScript file with this name so if these functions are not called at all there is no problem. If they get called you can easily substitute them with your own functions; the names are somewhat descriptive. Additionally you can have a look at the libgfortran source code (be aware it is GPL). With this Emscripten source can be extended by hand to support Fortran files. Someday I may publish this on github!
What is the best way to handle nuances for different platforms? I'm working on a normal Java/SWT desktop application I'm planning on distributing to the three primary PC platforms (Windows, OSX, Linux). Obviously, there are slight differences between them, mainly having to do with files. What's the best way to keep those differences separate? I'm thinking three different SVN branches (win, osx, linux), and trunk for development, but then how do I update the branches without overwriting the differences? Do I need to define a platform constant instead at compile time? And then, of course, there are different versions of libraries (i.e. SWT in my case). How should those be handled? Where should I keep the compiled byte-code ".jars" files?
For the example you gave (file paths), you should use a configuration file. You can have one for each platform, or one big one with settings for all platforms. I'd lean toward the first option, because then you can just use that one file and all the paths would be set. Java has a rich set of methods to construct platform independent file paths; use things like `File.separator` rather than `\`. Generally in Java you don't need to have separate projects for separate platforms - that's why the JVM! Use specific components for *only those parts* of the application that are platform specific. In my experience, I have not seen anything in Java intself that needs to change for different platforms. Interacting with the filesystem is trickier, but there are ways around that as described above. That being said, you should still test on the platforms you intend to deploy on to be sure that everything does work - sometimes there are subtle differences in JVMs for specialized applications. My recommendation for jars and other platform specific components is to have a directory structure look something like this in your VCS: ``` /src /lib linux/ jars/ config/ windows/ jars/ config/ ``` Then in your build scripts, only include the folder you need for the platform you're building for. I'd include the folder as lib in your build, so for a Linux build you'd end up with (as a suggestion): ``` / *yourjar* *launchfiles* /lib jars/ config/ ``` Zip that whole thing up and unzip it where you want to install. That will avoid having to specify paths more than once in code at the expense of a slighly more complicated build process. You could probably put that in a windows installer, too.
Using \_cmd to perform method on main thread in objective c I came across this `_cmd` trick: ``` -(void)methodToBeRunOnMainThreadWithObj:(id)object { if (![NSThread isMainThread) { [self performSelectorOnMainThread:_cmd withObject:object] } else { // ... method body } } ``` Is this a reliable way to ensure a method is performed on the main thread?
This works, but is a bit of an anti-pattern. What I would do is throw an error if the thread the method is called on is not the main thread. It is the responsibility of the caller to make sure methods are called on the right threads, these sorts of hacks only encourage ugly code. Besides, if you rely on this, suddenly you're doubling the message dispatch overhead for every time you call this method. If you really cant change the caller's behavior, you can try the following: ``` -(void)methodToBeRunOnMainThreadWithObj:(id)object { dispatch_sync(dispatch_get_main_queue(), ^{ // code goes here }); } ``` this will cause all code inside the dispatch block to be executed on the main thread, and the method will not return until it is complete. If you want the method to return immediately, you can use `dispatch_async` instead. If you use `dispatch_sync`, you can use this trick even on methods that have non-void return types. This code also has the added benefit of supporting methods with arguments that are of non-object types (`int` etc). It also supports methods with an arbitrary number of arguments, whereas `performSelector:withObject:` and its sibling methods only support a limited number of arguments. The alternative is to set up `NSInvocation` objects and those are a pain. Note that this requires Grand Central Dispatch (GCD) on your platform.
How do I determine if a survival model with missing data is appropriate? Oversimplifying a bit, I have about a million records that record the entry time and exit time of people in a system spanning about ten years. Every record has an entry time, but not every record has an exit time. The mean time in the system is ~1 year. The missing exit times happen for two reasons: 1. The person has not left the system at the time the data was captured. 2. The person's exit time was not recorded. This happens to say 50% of the records The questions of interest are: 1. Are people spending less time in the system, and how much less time. 2. Are more exit times being recorded, and how many. We can model this by saying that the probability that an exit gets recorded varies linearly with time, and that the time in the system has a Weibull whose parameters vary linearly with time. We can then make a maximum likelihood estimate of the various parameters and eyeball the results and deem them plausible. We chose the Weibull distribution because it seems to be used in measuring lifetimes and is fun to say as opposed to fitting the data better than say a gamma distribution. Where should I look to get a clue as to how to do this correctly? We are somewhat mathematically savvy, but not extremely statistically savvy.
The basic way to see if your data is Weibull is to [plot](http://www.itl.nist.gov/div898/handbook/eda/section3/weibplot.htm) the log of cumulative hazards versus log of times and see if a straight line might be a good fit. The cumulative hazard can be found using the non-parametric Nelson-Aalen estimator. There are similar graphical [diagnostics](http://www.weibull.com/hotwire/issue71/relbasics71.htm) for Weibull regression if you fit your data with covariates and some references follow. The [Klein & Moeschberger](http://www.powells.com/biblio/72-9780387239187-0) text is pretty good and covers a lot of ground with model building/diagnostics for parametric and semi-parametric models (though mostly the latter). If you're working in R, [Theneau's book](http://www.powells.com/biblio/61-9780387987842-1) is pretty good (I believe he wrote the [survival](http://cran.r-project.org/web/views/Survival.html) package). It covers a lot of Cox PH and associated models, but I don't recall if it has much coverage of parametric models, like the one you're building. BTW, is this a million subjects each with one entry/exit or recurrent entry/exit events for some smaller pool of people? Are you conditioning your likelihood to account for the censoring mechanism?
Scala's "postfix ops" I've searched for a half-hour, and still cannot figure it out. In [SIP: Modularizing Language Features](http://docs.scala-lang.org/sips/pending/modularizing-language-features.html) there are a number of features which will require explicit "enabling" in Scala 2.10 (`import language.feature`). Amongst them there is `postfixOps`, to which I just cannot find a reference anywhere. What exactly does this feature allow?
It allows you to use operator syntax in postfix position. For example ``` List(1,2,3) tail ``` rather than ``` List(1,2,3).tail ``` In this harmless example it is not a problem, but it can lead to ambiguities. This will not compile: ``` val appender:List[Int] => List[Int] = List(1,2,3) ::: //add ; here List(3,4,5).foreach {println} ``` And the error message is not very helpful: ``` value ::: is not a member of Unit ``` It tries to call the `:::` method on the result of the `foreach` call, which is of type `Unit`. This is likely not what the programmer intended. To get the correct result, you need to insert a semicolon after the first line.
Git fails when pushing commit to github I cloned a git repo that I have hosted on github to my laptop. I was able to successfully push a couple of commits to github without problem. However, now I get the following error: ``` Compressing objects: 100% (792/792), done. error: RPC failed; result=22, HTTP code = 411 Writing objects: 100% (1148/1148), 18.79 MiB | 13.81 MiB/s, done. Total 1148 (delta 356), reused 944 (delta 214) ``` From here it just hangs and I finally have to `CTRL` + `C` back to the terminal.
I had the same issue and believe that it has to do with the size of the repo (edited- or the size of a particular file) you are trying to push. Basically I was able to create new repos and push them to github. But an existing one would not work. The HTTP error code seems to back me up it is a 'Length Required' error. So maybe it is too large to calc or greated that the max. Who knows. EDIT > > I found that the problem may be > files that are large. I had one update > that would not push even though I had > successful pushes up to that point. > There was only one file in the commit > but it happened to be 1.6M > > > So I added the following config change > > > > ``` > git config http.postBuffer 524288000 > > ``` > > To allow up to the file size 500M and > then my push worked. It may have been > that this was the problem initially > with pushing a big repo over the http > protocol. > > > END EDIT the way I could get it to work (EDIT before I modified postBuffer) was to tar up my repo, copy it to a machine that can do git over ssh, and push it to github. Then when you try to do a push/pull from the original server it should work over https. (since it is a much smaller amount of data than an original push).
How to get first four letters from string in Swift 3? I am trying to do IFSCCode validation in swift, but the problem I'm facing is I am not able to fetch the first four letters in string. IFSC Code example: > > ABCD0200000 > > > This is how an IFSC Code looks: 1. First four characters in IFSC Code are always alphabets 2. Fifth character is always a zero. 3. And rest can be anything 4. The length of IFSC Code should not be greater than or less than 11. It should 11 in length. I have written code for ifs code validation in Objective C, but I am not that familiar in Swift so getting a problem in replicating the same in Swift. The following is the code which I have written in Objective C: ``` - (BOOL)validateIFSCCode:(NSString*)ifsccode { if (ifsccode.length < 4) { return FALSE; } for (int i = 0; i < 4; i++) { if (![[NSCharacterSet letterCharacterSet] characterIsMember:[ifsccode characterAtIndex:i]]) { return FALSE; } } if (ifsccode.length < 10) { return FALSE; } if ([ifsccode characterAtIndex:4] != '0') { return FALSE; } else { return TRUE; } } ``` In Swift 3 ``` func validateIfscCode(_ ifscCode : String) -> Bool{ if(ifscCode.characters.count < 4){ return false; } for( _ in 0 ..< 4){ let charEntered = (ifscCode as NSString).character(at: i) } if(ifscCode.characters.count < 10){ return false; } let idx = ifscCode[ifscCode.index(ifscCode.startIndex, offsetBy: 4)] print("idx:%d",idx) if (idx == "0"){ } return true } ```
This is a simple validation using regular expression. The pattern represents: - `^` must be the beginning of the string - `[A-Za-z]{4}` = four characters A-Z or a-z - `0`one zero - `.{6}` six arbitrary characters - `$` must be the end of the string --- Updated to Swift 4 ``` func validateIFSC(code : String) -> Bool { let regex = try! NSRegularExpression(pattern: "^[A-Za-z]{4}0.{6}$") return regex.numberOfMatches(in: code, range: NSRange(code.startIndex..., in: code)) == 1 } ``` PS: To answer your question, you get the first 4 characters in Swift 3 with ``` let first4 = code.substring(to:code.index(code.startIndex, offsetBy: 4)) ``` and in Swift 4 simply ``` let first4 = String(code.prefix(4)) ```
typescript multiple type check function ## Background I'm making type checking function with typescript. ``` const checkType = <T>(value: unknown, isTypeFn: (value: unknown) => value is T): T => { if (!isTypeFn(value)) { console.error(`${isTypeFn} ${value} does not have correct type`); throw new Error(`${value} does not have correct type`); } return value; }; const isBoolean = (value: unknown): value is boolean => typeof value === 'boolean'; const isString = (value: unknown): value is string => typeof value === 'string'; const isNumber = (value: unknown): value is number => typeof value === 'number'; const isNull = (value: unknown): value is null => value === null; ``` And I can use it like below. ``` const a = await getNumber() // this should be number const numA: number = checkType(a, isNumber); // numA is number or throw Error! ``` ## Problem I want to extend the checkType function like below. ``` const b = await getNumberOrString(); const bNumOrString: number | string = checkType(b, isNumber, isString); const bNumOrBoolean: number | boolean = checkType(b, isNumber, isBoolean); const bStringOrNull: string | null = checkType(b, isString, isNull); ``` How to improve the checkType for it to work like this ?
The function `checkType` will need a rest parameter. Let's call it `isTypeFns`. `isTypeFns` is a generic type parameter `T` which will be an array of functions with type predicates. ``` const checkType = < T extends ((value: unknown) => value is any)[] >(value: unknown, ...isTypeFns: T): CheckType<T> => { if (isTypeFns.some(fn => fn(value))) { console.error(`${value} does not have correct type`); throw new Error(`${value} does not have correct type`); } return value as CheckType<T>; }; ``` The implementation is straight forward. You just need to check if one of the functions in `isTypeFns` returns `true` given the `value`. The return type gets trickier again. We need to take `T` and *infer* the union of type predicate types. ``` type CheckType<T extends ((value: unknown) => value is any)[]> = T[number] extends ((value: unknown) => value is infer U) ? U : never ``` We use this for the return type of the function. TypeScript does not understand this complex type when it comes to the `return` statement of the implementation. That's why I added an assertion there. ``` const b = "b" as number | string; const bNumOrString = checkType(b, isNumber, isString); // ^? const bNumOrString: string | number const bNumOrBoolean = checkType(b, isNumber, isBoolean); // ^? const bNumOrBoolean: number | boolean const bStringOrNull = checkType(b, isString, isNull); // ^? const bStringOrNull: string | null ``` --- [Playground](https://www.typescriptlang.org/play?jsx=0#code/LAKALgngDgpgBAYQBYwMYGsAq0YB5NwwAeYMAdgCYDOcAFLQG4CGANgK4wBccbZ6ZAewDuZAJRwAvAD44zdvACWNJmQiiA2gF0ZEuKDhxM6smwC2AIxgAnTYRLlqdRqw7de-YWMky5HOEv8yADNrOABVcX0DOAB+cL0QaLhuMhgGa1BQVAEyKjA4VBQMbFhJOFwogmJSShp6Xy4ePkERcWlZF0VlVQ1NUClneTdmzwAaOAA6KaUSmAAxXO5MUW5kNCwcfB0ZAG8ohSC6GZwFqgmqAVMYWiCybzhbwY5RF7g9xOjs3IEWGAnrKwCKy0AAGABIdg0AL5wCgCGA0QT5JBMdIFIFWND5SCwEGiADcUQMYCQgKEcFS5IAolZAcDwZDOjC4QiKQJkaj4NlaVi4DiYHjCR8oZkPpiwGwrHcGnAmDQ1sVNpgpEKoUKsjk8v4qAAhAQ-GAqMpPRruFpibgygLmfW-I3tfkCQ4yiSuuAAchtBpU7vVIC+WqUAGUwFYFGQAObGhrDDytS2dbVwPJhyP3R3OxOu3TulPhiO+0UB-JKAByZksVmjnVj5pWHXkSZMFlCDpwTobfmzHublcLIFAcogZFQD14qDAChycFMTHDtFE7wMxdlZQADHAAPSbvlIAJUJACNgsChwSwUisZD4r5sAQRSl6rukK61mtCY4zLj4JW53d6bj5wECu5knANJ0gAhKKUQruYZQAETwbKiKAQAPsmob5kKy6avk5jlqYADyVghqmUbPkUGywLQ5iflQBGVnRpH5gSUTbkkAB6MSgCKA4gEAA)
What is the difference between skew and kurtosis functions in pandas vs. scipy? I decided to compare skew and kurtosis functions in pandas and scipy.stats, and don't understand why I'm getting different results between libraries. As far as I can tell from the documentation, both kurtosis functions compute using Fisher's definition, whereas for skew there doesn't seem to be enough of a description to tell if there any major differences with how they are computed. ``` import pandas as pd import scipy.stats.stats as st heights = np.array([1.46, 1.79, 2.01, 1.75, 1.56, 1.69, 1.88, 1.76, 1.88, 1.78]) print "skewness:", st.skew(heights) print "kurtosis:", st.kurtosis(heights) ``` this returns: ``` skewness: -0.393524456473 kurtosis: -0.330672097724 ``` whereas if I convert to a pandas dataframe: ``` heights_df = pd.DataFrame(heights) print "skewness:", heights_df.skew() print "kurtosis:", heights_df.kurtosis() ``` this returns: ``` skewness: 0 -0.466663 kurtosis: 0 0.379705 ``` Apologies if I've posted this in the wrong place; not sure if it's a stats or a programming question.
The difference is due to different normalizations. Scipy by default does not correct for bias, whereas pandas does. You can tell scipy to correct for bias by passing the `bias=False` argument: ``` >>> x = pandas.Series(np.random.randn(10)) >>> stats.skew(x) -0.17644348972413657 >>> x.skew() -0.20923623968879457 >>> stats.skew(x, bias=False) -0.2092362396887948 >>> stats.kurtosis(x) 0.6362620964462327 >>> x.kurtosis() 2.0891062062174464 >>> stats.kurtosis(x, bias=False) 2.089106206217446 ``` There does not appear to be a way to tell pandas to remove the bias correction.
ReSharper Curiosity: "Parameter is only used for precondition check(s)." Why is ReSharper judging me for this code? ``` private Control GetCorrespondingInputControl(SupportedType supportedType, object settingValue) { this.ValidateCorrespondingValueType(supportedType, settingValue); switch(supportedType) { case SupportedType.String: return new TextBox { Text = (string)settingValue }; case SupportedType.DateTime: return new MonthPicker { Value = (DateTime)settingValue, ShowUpDown = true }; default: throw new ArgumentOutOfRangeException(string.Format("The supported type value, {0} has no corresponding user control defined.", supportedType)); } } private void ValidateCorrespondingValueType(SupportedType supportedType, object settingValue) { Type type; switch(supportedType) { case SupportedType.String: type = typeof(string); break; case SupportedType.DateTime: type = typeof(DateTime); break; default: throw new ArgumentOutOfRangeException(string.Format("The supported type value, {0} has no corresponding Type defined.", supportedType)); } string exceptionMessage = string.Format("The specified setting value is not assignable to the supported type, [{0}].", supportedType); if(settingValue.GetType() != type) { throw new InvalidOperationException(exceptionMessage); } } ``` The second method ValidateCorrespondingValueType's "settingValue" parameter is grayed out with the following message by ReSharper: "Parameter 'settingValue' is only used for precondition check(s)."
It's not judging, it's trying to help :) If ReSharper sees that a parameter is only used as a check to throw an exception, it greys it out, indicating that you're not actually using it for "real" work. This is most likely a mistake - why pass in a parameter you're not going to use? It usually indicates that you've used it in a pre-condition, but then forgotten (or no longer need) to use it elsewhere in the code. Since the method is an assertion method (that is, all it does is assert it's valid), you can suppress the message by marking the `ValidateCorrespondingValueType` as an assertion method, using ReSharper's [annotation attributes](https://www.jetbrains.com/resharper/webhelp/Reference__Code_Annotation_Attributes.html), specifically the `[AssertionMethod]` attribute: ``` [AssertionMethod] private void ValidateCorrespondingValueType(SupportedType supportedType, object settingValue) { // … } ```
How can I access Windows COM objects in R v3? Some time ago, you used to be able to install the [`rcom` package in R to use COM scripting](https://stackoverflow.com/questions/14862861/is-it-possible-call-a-com-object-from-within-r-if-the-com-object-is-exposed-fro) (eg, access to external programs.) Unfortunately, it [seems to be discontinued](http://cran.r-project.org/web/packages/rcom/index.html): > > Package ‘rcom’ was removed from the CRAN repository. > > > Formerly available versions can be obtained from the archive. > > > This depends on statconnDCOM, which nowadays restricts use, contrary > to the CRAN policy for a package with a FOSS licence. See > <http://rcom.univie.ac.at/> and <http://www.statconn.com/>. > > > Following the archive and statconn links and installing one of the older versions in R version 3 gives the error: > > “Error: package ‘rcom’ was built before R 3.0.0: please re-install > it”. > > > I am not very familiar with R, but there seems no way around this message - after all, it occurs when installing, so re-installing doesn't seem to be the answer. It appears as though `rcom` is simply not available for recent (3.0+) versions of R. I have also scanned the [package list](http://cran.r-project.org/web/packages/available_packages_by_name.html), although searching for "COM" there returns over a hundred results and it is possible I missed the right one when clicking through them. **How can I use the `rcom` package, or use COM from within R some other way?** (Note: I am asking this question on behalf of a colleague. I have no experience with R myself at all. Both of us, when searching for answers, could not find anything. I am sure that others are also using COM in the latest version of R, though!)
I looked at the rcom source code a few months ago. It seems I can get it to build and install OK on R3.0.1. Below is the procedure if it helps. - Get a checkout of the latest source code of rcom. I have rcom\_2.2-5.tar.gz locally. I can google something at the following address, but I have no idea of the provenance, so up to you to check it is legit. <http://cran.open-source-solution.org/web/packages/rcom/index.html> - in R do `install.packages('rscproxy')` - install Rtools as per the instructions on the R web site (<http://cran.r-project.org/bin/windows/Rtools>), - open a Windows command prompt i.e. run "CMD" - go to the folder containing the 'rcom' folder, and at the command prompt: ``` set R="c:\Program Files\R\R-3.0.1\bin\i386\R.exe" %R% CMD check --no-manual rcom ``` - check it passes without too many complaints. Your call as to the --no-manual option (if you have MiKTeX installed you may remove it) ``` %R% CMD INSTALL rcom ``` should result in ``` installing to c:/Rlib/rcom/libs/i386 ** R ** inst ** preparing package for lazy loading ** help *** installing help indices ** building package indices ** testing if installed package can be loaded rcom requires a current version of statconnDCOM installed. To install statconnDCOM type installstatconnDCOM() This will download and install the current version of statconnDCOM You will need a working Internet connection because installation needs to download a file. * DONE (rcom) ``` - in R: ``` library(rcom) installstatconnDCOM() ``` - I tried a `comRegisterRegistry() ; comRegisterServer() ; x<-comGetObject("Excel.Application")` but I get a NULL for `x`. I am not a user of rcom so while it all seems to compile fine; it may just not work anymore. If you happen to need to access .NET code, a viable option (and yes I have a vested interest in mentioning it) may be the [rClr](http://r2clr.codeplex.com) package. Hope this helps; I'd be interested to hear how you go.
If statements with comparison SSE in C I want to achieve this: ``` for (int i=0;i<n,i++){ if (x[i] > 2.0f || x[i] < -2.0f) a[i] += x[i]; } ``` I have gone this far but don't know what to do next: ``` __m128 P2f = _mm_set1_ps(2.0f); __m128 M2f = _mm_set1_ps(-2.0f); for(int i=0;i<n,i+=4){ __m128 xv = _mm_load_ps(x+i); __m128 av = _mm_load_ps(a+i); __m128 c1 = _mm_cmpgt_ps(xv, P2f); __m128 c2 = _mm_cmplt_ps(xv, M2f); __m128 or = _mm_or_ps(c1,c2); =???== av = _mm_add_ps(av, xv); _mm_store_ps(a+i, av); } ```
You're close: ``` const __m128 P2f = _mm_set1_ps(2.0f); const __m128 M2f = _mm_set1_ps(-2.0f); for (int i = 0; i < n; i += 4) { __m128 xv = _mm_load_ps(x + i); __m128 av = _mm_load_ps(a + i); __m128 c1v = _mm_cmpgt_ps(xv, P2f); __m128 c2v = _mm_cmplt_ps(xv, M2f); __m128 cv = _mm_or_ps(c1v, c2v); xv = _mm_and_ps(xv, cv); av = _mm_add_ps(av, xv); _mm_store_ps(a + i, av); } ``` The trick is to `OR` the two comparison results and then use this combined result as a mask to zero out the X values which do not pass the test using a bitwise `AND` operation. You then add the masked X vector, which will add 0 or the original X value to each element of A according to the mask. --- For the alternate version as mentioned in your comment below you'd do this: ``` const __m128 P2f = _mm_set1_ps(2.0f); const __m128 M2f = _mm_set1_ps(-2.0f); for (int i = 0; i < n; i += 4) { __m128 xv = _mm_load_ps(x + i); __m128 av = _mm_load_ps(a + i); __m128 c1v = _mm_cmpgt_ps(xv, P2f); __m128 c2v = _mm_cmplt_ps(xv, M2f); __m128 cv = _mm_or_ps(c1v, c2v); xv = _mm_and_ps(P2f, cv); // <<< change this line to get a[i] += 2.0f // instead of a[i] += x[i] av = _mm_add_ps(av, xv); _mm_store_ps(a + i, av); } ``` --- For the third version you mention in later comments below (`a[i] *= 2.0`) it's slightly trickier, but you can do it by thinking of the expression as `a[i] += a[i]`: ``` const __m128 P2f = _mm_set1_ps(2.0f); const __m128 M2f = _mm_set1_ps(-2.0f); for (int i = 0; i < n; i += 4) { __m128 xv = _mm_load_ps(x + i); __m128 av = _mm_load_ps(a + i); __m128 c1v = _mm_cmpgt_ps(xv, P2f); __m128 c2v = _mm_cmplt_ps(xv, M2f); __m128 cv = _mm_or_ps(c1v, c2v); xv = _mm_and_ps(av, cv)); // <<< change this line to get a[i] *= 2.0f (a[i] += a[i]) // instead of a[i] += x[i] av = _mm_add_ps(av, xv); _mm_store_ps(a + i, av); } ```
Relating an array of objects to an enumerator How would you relate the indexes of an array to an enumerator without leaving the chance of mismatch? Example ``` public enum difficulties { easy, medium, hard } public List<Lobby> easyLobbies = new List<Lobby>(); public List<Lobby> mediumLobbies = new List<Lobby>(); public List<Lobby> hardLobbies = new List<Lobby>(); public List<Lobby>[] lobbiesArray; public ClassConstructor(){ // Index order should match enumerator lobbiesArray = new List<Lobby>[] { easyLobbies, mediumLobbies, hardLobbies}; } List<Lobby> lobbies = lobbiesArray[difficulties.hard]; ``` Because this enumerator and array are seemingly unlinked, it is not obvious that the lobbiesArray should follow any order. What is a better way to approach this?
You are using a wrong data structure. In your case, you may use a dictionary where keys are the values from the enum, and the values are the actual lists: ``` var lobbies = new Dictionary<Difficulty, List<Lobby>> { { Difficulty.Easy, easyLobbies }, { Difficulty.Medium, mediumLobbies }, { Difficulty.Hard, hardLobbies }, }; var currentLobbies = lobbies[Difficulty.Hard]; ``` A few notes: 1. An array is mostly always a wrong data structure in C#. Don't use it, unless you are perfectly certain that you *need* the specific characteristics of an array. 2. Unless your team has a well-established style convention (and the inconsistencies in your code makes me think that there are none), stick with the standards. This means that `enum Difficulties`, with a capital `D`. The members of an enum start with a capital too. You can use [StyleCop](https://stylecop.codeplex.com/) to check for other violations (like the lack of a new line before the opening curly bracket.) 3. Since your enum doesn't contain flags, its name should be `Difficulty`, not `Difficulties`. When you use plural, it means that you can use multiple values at once. [More on flags here](https://stackoverflow.com/q/8447/240613). 4. `lobbiesArray` is a wrong name. You shouldn't have types in the names of the variables. Visual Studio makes it very easy to determine the type of a given variable, so you don't need Hungarian notation or similar constructs. 5. `ClassConstructor` is a misleading name for a method, because it makes the reader think that it's an actual constructor, while it's not (unless you actually called your class `ClassConstructor`, which is a strange name for a class.)
How can I save aside an object in awaitility callback? My code calls a server and get a `old-response`. Then I want to poll until I get a different response from the server (aka `new-response`). I I use while loop I can hold the `new-response` and use it after polling. If I use `awaitility` how can I get the `new-response` easily? Here is my code: ``` public Version waitForNewConfig() throws Exception { Version oldVersion = deploymentClient.getCurrentConfigVersion(appName); await().atMost(1, MINUTES).pollInterval(5, SECONDS).until(newVersionIsReady(oldVersion)); Version newVersion = deploymentClient.getCurrentConfigVersion(appName); } private Callable<Boolean> newVersionIsReady(Version oldVersion) { return new Callable<Boolean>() { public Boolean call() throws Exception { Version newVersion = deploymentClient.getCurrentConfigVersion(appName); return !oldVersion.equals(newVersion); } }; } ```
One way is to make a specialized Callable implementation that remembers it : ``` public Version waitForNewConfig() throws Exception { NewVersionIsReady newVersionIsReady = new NewVersionIsReady(deploymentClient.getCurrentConfigVersion(appName)); await().atMost(1, MINUTES).pollInterval(5, SECONDS).until(newVersionIsReady); return newVersionIsReady.getNewVersion(); } private final class NewVersionIsReady implements Callable<Boolean> { private final Version oldVersion; private Version newVersion; private NewVersionIsReady(Version oldVersion) { this.oldVersion = oldVersion; } public Boolean call() throws Exception { Version newVersion = deploymentClient.getCurrentConfigVersion(appName); return !oldVersion.equals(newVersion); } public Version getNewVersion() { return newVersion; } } ``` Another is to store it in a container (as an example I use an array) ``` public Version waitForNewConfig() throws Exception { Version[] currentVersionHolder = new Version[1]; Version oldVersion = deploymentClient.getCurrentConfigVersion(appName); await().atMost(1, MINUTES).pollInterval(5, SECONDS).until(() -> { Version newVersion = deploymentClient.getCurrentConfigVersion(appName); currentVersionHolder[0] = newVersion; return !oldVersion.equals(newVersion); }); return currentVersionHolder[0]; } ``` If you don't use java 8 yet, you can do it using an anonymous inner class as well.
Dealing with large numbers in R [Inf] and Python I am learning Python these days, and this is probably my first post on Python. I am relatively new to R as well, and have been using R for about a year. I am comparing both the languages while learning Python. I apologize if this question is too basic. I am unsure why R outputs `Inf` for something python doesn't. Let's take `2^1500` as an example. **In R:** ``` nchar(2^1500) [1] 3 2^1500 [1] Inf ``` **In Python:** ``` len(str(2**1500)) Out[7]: 452 2**1500 Out[8]: 3507466211043403874... ``` I have two questions: **a) Why is it that R provides `Inf` when Python doesn't.** **b)** I researched [How to work with large numbers in R?](https://stackoverflow.com/questions/22466328/how-to-work-with-large-numbers-in-r) thread. It seems that `Brobdingnag` could help us out with dealing with large numbers. However, even in such case, I am unable to compute `nchar`. **How do I compute above expression i.e. 2^1500 in R** ``` 2^Brobdingnag::as.brob(500) [1] +exp(346.57) > nchar(2^Brobdingnag::as.brob(500)) Error in nchar(2^Brobdingnag::as.brob(500)) : no method for coercing this S4 class to a vector ```
In answer to your questions: a) They use different representations for numbers. Most numbers in R are represented as double precision floating point values. These are all 64 bits long, and give about 15 digit precision throughout the range, which goes from -double.xmax to double.xmax, then switches to signed infinite values. R also uses 32 bit integer values sometimes. These cover the range of roughly +/- 2 billion. R chooses these types because it is geared towards statistical and numerical methods, and those rarely need more precision than double precision gives. (They often need a bigger range, but usually taking logs solves that problem.) Python is more of a general purpose platform, and it has types discussed in MichaelChirico's comment. b) Besides `Brobdingnag`, the `gmp` package can handle arbitrarily large integers. For example, ``` > as.bigz(2)^1500 Big Integer ('bigz') : [1] 35074662110434038747627587960280857993524015880330828824075798024790963850563322203657080886584969261653150406795437517399294548941469959754171038918004700847889956485329097264486802711583462946536682184340138629451355458264946342525383619389314960644665052551751442335509249173361130355796109709885580674313954210217657847432626760733004753275317192133674703563372783297041993227052663333668509952000175053355529058880434182538386715523683713208549376 > nchar(as.character(as.bigz(2)^1500)) [1] 452 ``` I imagine the `as.character()` call would also be needed with `Brobdingnag`.
Uri.EscapeUriString - How do I use it? I am new to C# so i appreciate your help. I have the following code which calls an API. I need to have the URL values encoded. Now i have no idea how to do this. I would appreciate your assistance. Thank you. ``` private void DeviceDetect_Load(object sender, EventArgs e) { var printerQuery = new ManagementObjectSearcher("Select * from Win32_Printer"); foreach (var printer in printerQuery.Get()) { var name = printer.GetPropertyValue("Name"); var status = printer.GetPropertyValue("Status"); var isDefault = printer.GetPropertyValue("Default"); var isNetworkPrinter = printer.GetPropertyValue("Network"); var description = printer.GetPropertyValue("Description"); var PortName = printer.GetPropertyValue("PortName"); var Location = printer.GetPropertyValue("Location"); var Comment = printer.GetPropertyValue("Comment"); string macAddress = string.Empty; System.Diagnostics.Process pProcess = new System.Diagnostics.Process(); pProcess.StartInfo.FileName = "arp"; pProcess.StartInfo.Arguments = "-a " + PortName; pProcess.StartInfo.UseShellExecute = false; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.CreateNoWindow = true; pProcess.Start(); string strOutput = pProcess.StandardOutput.ReadToEnd(); string[] substrings = strOutput.Split('-'); if (substrings.Length >= 8) { macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2)) + "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6] + "-" + substrings[7] + "-" + substrings[8].Substring(0, 2); } string currentuser = null; string appToken = null; string password = null; XDocument doc = XDocument.Load("config.xml"); XElement element = doc.Root.Elements("UserID").FirstOrDefault(); XElement element0 = doc.Root.Elements("Password").FirstOrDefault(); XElement element1 = doc.Root.Elements("AppToken").FirstOrDefault(); if (element1 != null) { currentuser = element.Value; appToken = element1.Value; password = element0.Value; try { string url = "https://mydomain.com/api/add?t=" + appToken + "&mac=" + macAddress + "&PortName=" + PortName + "&Name=" + name + "&Location=" + Location + "&Description=" + description + "&Comment=" + Comment + ""; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "POST"; Encoding enc = Encoding.GetEncoding(1252); HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse(); StreamReader loResponseStream = new StreamReader(httpWebResponse.GetResponseStream(), enc); } catch (Exception ex) { MessageBox.Show(ex.Message); label7.Text = "Status: Error"; } } } } ```
You probably want to use [HttpUtility.UrlEncode()](http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode(v=vs.110).aspx). Not `Uri.EscapeUriString()`.. ``` string url = string.Format("https://mydomain.com/api/add?t={0}&mac={1}&portName={2}&name={3}&location={4}&description={5}&comment={6}", HttpUtility.UrlEncode(appToken), HttpUtility.UrlEncode(macAddress), HttpUtility.UrlEncode(PortName), HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(Location), HttpUtility.UrlEncode(description), HttpUtility.UrlEncode(Comment)); ```
gcc /usr/bin/ld: cannot find -lglut32, -lopengl32, -lglu32, -lfreegut, but these are installed I'm trying to compile a demo project, what is using `OpenGL`. I'm getting this error message: [![Everything is missing, at least gcc says it](https://i.stack.imgur.com/A1jjr.png)](https://i.stack.imgur.com/A1jjr.png) But I have everything: [![but I have everything](https://i.stack.imgur.com/aW4ja.png)](https://i.stack.imgur.com/aW4ja.png) What is happening? If I have all of the dependencies, why does it not compile? I use Solus 3.
The meaning of `-lglut32` (as an example) is, load the library `glut32`. The result of the `ls` you execute showed that you have the **header file** for `glut32` In order to solve the problem of *cannot find -l-library-name* You need: 1. To actually have the library in your computer 2. Help gcc/the linker to find the library by providing the path to the library - You can add `-Ldir-name` to the `gcc` command - You can the library location to the `LD_LIBRARY_PATH` environment variable 3. Update the "[Dynamic Linker](https://www.lifewire.com/ldconfig-linux-command-4093742)": ``` sudo ldconfig ``` --- [man gcc](https://linux.die.net/man/1/gcc) > > > ``` > -llibrary > -l library > Search the library named library when linking. > -Ldir > Add directory dir to the list of directories to be searched for -l. > > ``` > >
Ambiguous call when using LINQ extension method on DbSet I am using a LINQ query on a `DbSet<T>`: ``` await _dbContext.Users.AnyAsync(u => u.Name == name); ``` However, the compiler outputs the following error: ``` Error CS0121: The call is ambiguous between the following methods or properties: 'System.Linq.AsyncEnumerable.AnyAsync<TSource>(System.Collections.Generic.IAsyncEnumerable<TSource>, System.Func<TSource, bool>)' and 'Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AnyAsync<TSource>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource, bool>>)' ``` A similar problem also occurs with other LINQ extension methods, like `.Where()`. I am using EF.Core 3.1 and have the `System.Linq.Async` package installed. How do I fix this issue?
The described problem is caused by using the `System.Linq.Async` package along with the `DbSet<TEntity>` class. Since `DbSet<TEntity>` implements both `IQueryable<TEntity>` and `IAsyncEnumerable<TEntity>`, importing the namespaces `System.Linq` and `Microsoft.EntityFrameworkCore` leads to the definition of the conflicting extension methods. Unfortunately, avoiding importing one of them is usually not practicable. This behavior is present beginning with EF.Core 3.0, and is discussed in [this issue](https://github.com/dotnet/efcore/issues/18124). In order to address this, EF.Core 3.1 adds two auxiliary functions `AsAsyncEnumerable()` and `AsQueryable()`, which explicitly return the respective interfaces `IAsyncEnumerable<TEntity>` or `IQueryable<TEntity>`. The given code sample is fixed by calling the desired disambiguation function: ``` await _dbContext.Users.AsQueryable().AnyAsync(u => u.Name == name); ``` or ``` await _dbContext.Users.AsAsyncEnumerable().AnyAsync(u => u.Name == name); ```
How can I get information around the full certificate chain with Nodejs? I'm creating a service in node to verify the statuses of all the certificates for all the domains our company depends upon. Initially we're just concerned with the expiration dates, but may need more information later. I can retrieve the appropriate details for the lowest level cert via ``` var https = require('https'); var options = { host: 'google.com', port: 443, method: 'GET' }; const request = https.request(options, function(res) { console.log(res.connection.getPeerCertificate()); }); request.end(); ``` but I'm looking to get the detailed information for every cert in the certificate chain. How is this possible in nodejs? i.e. For google.com, I'd like to get full detailed information for each of ``` Google Trust Services - GlobalSign CA-R2 -> GTS CA 101 -> www.google.com ``` I imagine I can recursively make calls to each cert's issuer but not quite sure how or if it's possible.
Per [the doc](https://nodejs.org/api/tls.html#tls_tlssocket_getpeercertificate_detailed), if you pass `true` like this: ``` res.connection.getPeerCertificate(true) ``` Then, you will get detail about the whole chain. When the full certificate chain is requested, each certificate will include an `issuerCertificate` property containing an object representing its issuer's certificate and you can follow the chain using it. Here's an example: ``` var https = require('https'); var options = { host: 'google.com', port: 443, method: 'GET' }; const request = https.request(options, function(res) { let cert = res.connection.getPeerCertificate(true); let list = new Set(); do { list.add(cert); console.log("subject", cert.subject); console.log("issuer", cert.issuer); console.log("valid_from", cert.valid_from); console.log("valid_to", cert.valid_to); cert = cert.issuerCertificate; } while (cert && typeof cert === "object" && !list.has(cert)); res.on('data', data => { //console.log(data.toString('utf8')); }); }); request.end(); ``` The doc does not explain how you know when you're at the end of the chain (I would have thought it would be denoted by a `null` issuer, but `console.log()` reported a circular reference so I added a `Set` to keep track of the certificates we'd seen so far in order to detect when the chain became circular to know when to stop following the chain.
Default destructor for pointers? Suppose I have a self-defined vector class and the destructor for the vector class is defined as below, ``` ~vector(void) { for (uint64_t i = 0; i<len_elem; i++) { //destruct each elem front[i].~T(); } ::operator delete(head); head = nullptr; capacity = 0; } ``` In my understanding, this destructor works fine for most cases. However if the vector is `vector<vector*> myVec`, will the code in the destructor execute correctly? To be specific, will the `front[i].~T();` correctly invoke the the destructor of vector class?
# TLDR: Your code is fine. Long answer: Yes and no. `front[i].~T()` will "correctly call the destructor for a pointer\*". However, a pointer's "destructor" does nothing at all. So this code *correctly* does nothing. If you wanted to *free* the things the pointers point at, that's an altogether different thing. The easiest thing to do in this case is to instead use `vector<std::unique_ptr<int>>` or whatever, so that this destructor will call the destructors of the `unique_ptr`, and *those* destructors free the memory. As a note, virtually every sequential container tries to destroy elements from back to front instead of the way you have it. Some classes can be a touch picky about the construction/destruction order. \* Built in types don't *technically* have members like destructors, but you can pretend they do for all intents and purposes except that you can't reference them by name.
How to get rid of the "blocks" message given by cpio? I'm trying to look through this: [How do I get the MD5 sum of a directory's contents as one sum?](https://unix.stackexchange.com/questions/35832/how-do-i-get-the-md5-sum-of-a-directorys-contents-as-one-sum), and so I'm trying: ``` $ find | LC_ALL=C sort | cpio -o | md5sum 25324 blocks 6631718c8856606639a4c9b1ef24d420 - ``` Hmm... I'd like just the hash, not anything else in the output... so assuming that "25324 blocks" has been printed to stderr, I try to redirect stderr to `/dev/null`: ``` $ find | LC_ALL=C sort | cpio -o | md5sum 2>/dev/null 25324 blocks 6631718c8856606639a4c9b1ef24d420 - ``` Nope, that's not it. Let's just for tests sake, try to redirect stdout to `/dev/null`: ``` $ find | LC_ALL=C sort | cpio -o | md5sum 1>/dev/null 25324 blocks ``` Ok, so the hash is gone as expected - but the "blocks" message is still there ?! Where the hell is this "25324 blocks" printed, via file descriptor 3 ?!: ``` $ find | LC_ALL=C sort | cpio -o | md5sum 3>/dev/null 25324 blocks 6631718c8856606639a4c9b1ef24d420 - ``` Nope, that's not it... In any case, I can get just the hash with awk: ``` $ find | LC_ALL=C sort | cpio -o | md5sum | awk '{print $1}' 25324 blocks 6631718c8856606639a4c9b1ef24d420 ``` but still the darn "blocks" message is printed... So how is it printed to terminal at all (as it seems not printed via either stdout or stderr), and how can I suppress that message? --- EDIT: found the answer, the "blocks" message is printed by `cpio` actually, so the right thing to do is: ``` $ find | LC_ALL=C sort | cpio -o 2>/dev/null | md5sum | awk '{print $1}' 6631718c8856606639a4c9b1ef24d420 ``` Now we have just the hash...
The message is printed by `cpio`, this avoids it: ``` find | LC_ALL=C sort | cpio -o 2> /dev/null | md5sum | awk '{print $1}' ``` You’ll lose any error messages printed by `cpio` if you use this approach. Some versions of `cpio` (at least GNU and FreeBSD) support a `quiet` option instead: ``` find | LC_ALL=C sort | cpio -o --quiet | md5sum | awk '{print $1}' ``` To avoid losing errors with a version of `cpio` which doesn’t support `--quiet`, you could log them to a temporary file: ``` cpiolog=$(mktemp); find | LC_ALL=C sort | cpio -o 2> "${cpiolog}" | md5sum | awk '{print $1}'; grep -v blocks "${cpiolog}"; rm -f "${cpiolog}" ```
Deploying to Glassfish classpath not set for com.mysql.jdbc.jdbc2.optional.MysqlXADataSource Glassfish is not loading the `com.mysql.jdbc.jdbc2.optional.MysqlXADataSource` package. The following error is thrown ``` javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Class name is wrong or classpath is not set for:com.mysql.jdbc.jdbc2.optional.MysqlXADataSource Error Code: 0 at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy (EntityManagerSetupImpl.java:517)... ``` I have copied the mysql-connector jar file to the `lib` directory of Glassfish but I still get the above error. How do I ensure that Glassfish can find my JDBC driver for my deployed application?
You will need to make the MySQL JDBC jar file available to Glassfish. <http://ushainformatique.com/blog/2010/03/19/jdbcwithglassfish/> EDIT: ## How do I use different JDBC drivers? Where should I copy the jar(s)? > > It is recommended to place JDBC drivers, that are used by all the > applications in the domain, in domain-dir/lib or > domain-dir/lib/classes. A restart of the application server instance > is required today so that the JDBC drivers are visible to applications > deployed in the domain. > > > From <https://blogs.oracle.com/sivakumart/entry/classloaders_in_glassfish_an_attempt> So move the jar file into the lib dir below the domain into which you are deploying your app. The default Glassfish domain is domain1. Restart Glassfish and this should work. There is a Maven Glassfish plugin which may be worth evaluating <http://maven-glassfish-plugin.java.net/> Using Maven and this plugin would help automate the deployment step. This would be more robust than doing manual deployments. Your call though of course.
How to read lines from a file into an array? I'm trying to read in a file as an array of lines and then iterate over it with zsh. The code I've got works most of the time, except if the input file contains certain characters (such as brackets). Here's a snippet of it: ``` #!/bin/zsh LIST=$(cat /path/to/some/file.txt) SIZE=${${(f)LIST}[(I)${${(f)LIST}[-1]}]} POS=${${(f)LIST}[(I)${${(f)LIST}[-1]}]} while [[ $POS -le $SIZE ]] ; do ITEM=${${(f)LIST}[$POS]} # Do stuff ((POS=POS+1)) done ``` What would I need to change to make it work properly?
``` #!/bin/zsh zmodload zsh/mapfile FNAME=/path/to/some/file.txt FLINES=( "${(f)mapfile[$FNAME]}" ) LIST="${mapfile[$FNAME]}" # Not required unless stuff uses it integer POS=1 # Not required unless stuff uses it integer SIZE=$#FLINES # Number of lines, not required unless stuff uses it for ITEM in $FLINES # Do stuff (( POS++ )) done ``` You have some strange things in your code: 1. Why are you splitting `LIST` each time instead of making it an array variable? It is just a waste of CPU time. 2. Why don’t you use `for ITEM in ${(f)LIST}`? 3. There is a possibility to directly ask zsh about array length: `$#ARRAY`. No need in determining the index of the last occurrence of the last element. 4. `POS` gets the same value as `SIZE` in your code. Hence it will iterate only once. 5. Brackets are problems likely because of 3.: `(I)` is matching against a pattern. Do read documentation.
Combining records from two sorted files I have two big files with more than six million records. Data in those two files can be correlated by [UID](https://en.wikipedia.org/wiki/Unique_identifier) (if ordering the file, should be at same row in both files). Eventually I need to get data from the first file concatenated with data in the second file. The issue is that executing the script is taking 10 hours for about 650,000 records!! I'd like to improve it. ``` UIDS=`cut -f1 -d',' sorted_UID_data1.txt` for record in $UIDS do echo `grep $record sorted_UID_data1.txt| awk -F ',' '{print $2}'`,`grep $record sorted_UID_data2.txt` >> data.txt done ``` In order to optimize it, I thought of ``` TOTAL_RECORDS=`wc -l < sorted_UID_data1.txt` recordId=1 while [ $recordId -le $TOTAL_RECORDS ] do echo `sed -n "${recordId}{p;q;}" sorted_UID_data1.txt| awk -F ',' '{print $2}'`,`sed -n "${recordId}{p;q;}" sorted_UID_data2.txt` >> data.txt recordId=$(( $recordId + 1 )) done ``` And this is also taking too much time. But then, I'm thinking: What if I always can grab the first line of the file? I've seen that this could be done by [sed](http://en.wikipedia.org/wiki/Sed), [tail](https://en.wikipedia.org/wiki/Tail_%28Unix%29), or [AWK](http://en.wikipedia.org/wiki/AWK), but this seems to be inefficient. How can I fix this problem?
To remove the first line use `tail` : ``` # seq 5 | tail -n +2 2 3 4 5 ``` And to only "grab the first line" use `head` : ``` # seq 5 | head -n 1 1 ``` But to join two files line by line use `paste` : ``` # seq 5 > nums # echo -e 'a\nb\nc\nd\ne' > chars # paste nums chars 1 a 2 b 3 c 4 d 5 e ``` And to join two files with matching common fileds use `join`: ``` # paste -d , <( seq 5 ) <( seq 11 15 ) > teens # paste -d , <( seq 5 ) <( seq 21 25 ) > twenties # join -t , teens twenties 1,11,21 2,12,22 3,13,23 4,14,24 5,15,25 ```
Docker nodejs not found When i run `docker build -t example .` on the below im getting an error ``` FROM ruby:2.1 RUN rm /bin/sh && ln -s /bin/bash /bin/sh ENV NVM_DIR /usr/local/nvm ENV NODE_VERSION 4.4.2 RUN curl https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash \ && source $NVM_DIR/nvm.sh \ && nvm install $NODE_VERSION \ && nvm alias default $NODE_VERSION \ && nvm use default ENV NODE_PATH $NVM_DIR/v$NODE_VERSION/lib/node_modules ENV PATH $NVM_DIR/v$NODE_VERSION/bin:$PATH RUN node -v ``` I get the following error: > > Step 9 : RUN node -v ---> Running in 6e3fac36d2fc /bin/sh: node: > command not found The command '/bin/sh -c node -v' returned a non-zero > code: 127 > > > Can't understand why node is not found in the path. i tried executing the nvm.sh file as well but it didnt have an effect.
Node version manager is an excellent application for switching versions of Node.js on your development machine, but Docker begs a specific kind of image/container design that is meant to be both ephemeral and stripped down to the bare essentials in order to support the "best practice" of microservices. Docker is just a fancy way to run a process, not a full VM. That last sentence has helped me a lot in how to think about Docker. And so here, you can make things easier on yourself by creating different versions of your image, instead of making one container with many versions of Node.js inside of it. This way, you can reference the Node version you want to run inside of your `docker run` command instead of trying to feed in environment variables trying to get NVM to select the right version. For example: ``` docker build -t=jamescharlesworth-node:4.x-latest . ``` And of course your Dockerfile will have in it the install command in your `RUN` directive that you mention in the comments: ``` RUN curl -sL https://deb.nodesource.com/setup_4.x | bash - RUN apt-get install -y nodejs ```
SQL Server Compact error: Unable to load DLL 'sqlceme35.dll'. The specified module could not be found I'm developing a [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) application using Visual Studio 2008 C# that uses an [SQL Server Compact](http://en.wikipedia.org/wiki/SQL_Server_Compact) 3.5 database on the client. The client will most likely be 32 bit Windows XP or Windows Vista machines. I'm using a standard Windows Installer project that creates an [MSI](http://en.wikipedia.org/wiki/Windows_Installer) file and setup.exe to install the application on a client machine. I'm new to SQL Server Compact, so I haven't had to distribute a client database like this before now. When I run the setup.exe (on new Windows XP 32 bit with SP2 and Internet Explorer 7) it installs fine, but when I run the application I get this error: > > Unable to load DLL 'sqlceme35.dll'. The specified module could not be found > > > I spent a few hours searching for this error already, but all I could find were issues relating to installing on 64 bit Windows and none relating to normal 32 bit that I'm using. The install application copies the all the dependent files that it found into the specified install directory, including the `System.Data.SqlServerCe.dll` file (assembly version 3.5.1.0). The database file is in a directory called 'data' off the application directory, and the connection string for it is ``` <add name="Tickets.ieOutlet.Properties.Settings.TicketsLocalConnectionString" connectionString="Data Source=|DataDirectory|\data\TicketsLocal.sdf" providerName="Microsoft.SqlServerCe.Client.3.5" /> ``` Some questions I have: - Should the application be able to find the DLL file if it's in the same directory, that is, local to the application, or do I need to install it in the [GAC](http://en.wikipedia.org/wiki/Global_Assembly_Cache)? (If so, can I use the Windows Installer to install a DLL file in the GAC?) - Is there anything else I need to distribute with the application in order to use a SQL Server Compact database? - There are other DLL files also, such as MS interop for exporting data to Excel on the client. Do these need to be installed in the GAC or will locating them in the application directory suffice?
You don't need it to be in the GAC for SQL Server Compact to run, and it will pick them up from the application directory. There are several ways to deploy an SQL Server Compact project. The two main ways are: 1. Deploying the SQL Server Compact redistributable installer with your project, but this way is painful and also can be unistalled by the end user, or upgraded by Windows updates and breaking your application. 2. Including the DLL files in your application folder. Depending on the features of SQL Server Compact you are using (replication or whatever), there is a handful of DLL files to deploy in your application folder. If you have SQL Server Compact installed on your machine, they are most likely located at "C:\Program Files\Microsoft SQL Server Compact Edition\v3.5". They can be added to the project in Visual Studio and then set their project output type to "copy always". And the main reference to `System.Data.SqlServerCe` that you have in your project references should have *copy local* set to true. - sqlceca35.dll - sqlcecompact35.dll - sqlceer35en.dll - sqlceoledb35.dll - sqlceqp35.dll - sqlcese35.dll If you have these all set, then in your installer project all you have to include is the project output of this project and you're good. In my opinion this is the only way to go. It is a simple deployment, of a couple of files and you are in control of what DLL versions your application uses. I hope that helps.
Is there emacs plugins to do Sublime-like completion and goto anything? In Sublime Text 2, I can enter `prnfunc[tab]` and then it completes to 'PrintFunction'. If I have a project, I can press `Cmd+P` and enter `srcpy/hello.py` and then it navigates to `source/python/hello_world.py`. Is there equivalents in emacs? p.s. I think ido in emacs is provides similar fuzzy completion but only in mini-buffer.
For completion, try [auto-complete](http://auto-complete.org/). To get intelligent completion, you may need "backend" for each programming language. For Python, try [Emacs-jedi](http://tkf.github.io/emacs-jedi/) (disclaimer: my project). Auto-complete supports case-insensitive completion. For project management, I recommend combination of [Helm](https://github.com/emacs-helm/helm) and [eproject](https://github.com/jrockway/eproject). With these two, you can find `source/python/hello_world.py` by something like `s rc py hello RET`. Helm is a framework for incremental completion and selection narrowing. So you can get not only project management but also other features. eproject is a project management plugin and it can act as backend of Helm. Setting up everything at once could be tough work so I suggest to just setup plain auto-complete and Helm first. Those two will give you a big improvement on your Emacs environment.
Remove trailing numbers Why I get trailing so many numbers when I run below code? ``` BigDecimal lat = new BigDecimal(0.0077); System.out.println(lat); ``` > > output >> > 0.00770000000000000024702462297909733024425804615020751953125 > > > I want to print exactly what I entered. How can I do this?
Most finite decimal fractions cannot be exactly represented by floating-point, so that is the approximation you get when you create the floating-point literal `0.0077`. To avoid the problem, use the constructor [`BigDecimal(String val)`](http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal%28java.lang.String%29) instead: ``` BigDecimal lat = new BigDecimal("0.0077"); ``` As @TimB points out, if you already have a `double` value, you can also use: ``` BigDecimal lat = BigDecimal.valueOf(doubleVal); ``` Also, here is the mandatory reference to [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html).
How to get returned data from mongoDB in Perl? I read <http://api.mongodb.org/perl/current/MongoDB/Examples.html> and seems to be only documentation from mongoDB on Perl. How do I get my query result from mongoDB in perl. Let us say into Hash. I have successfully made connection to the db so far. I managed to do inserts into collections. Now how do I issue select query and get its returned data into hash or something similar? Update: ``` Example of my data { "_id" : ObjectId("asdhgajsdghajgh"), "country" : "USA" "city" : "Boston" } { "_id" : ObjectId("asdhgajsdghajgh"), "country" : "USA" "city" : "Seattle" } { "_id" : ObjectId("asdhgajsdghajgh"), "country" : "Canada" "city" : "Calgary" } My code my $cursor = $my_collection ->find({ country => 1 }) ; while (my $row = $cursor->next) { print "$row\n"; } ``` This code is not resulting any output. I want to basically iterate through the entire collection and read document by document. Not sure what I am doing wrong. I used the code above. I changed $cur->next to $cursor->next I am guessing it was a typo. I appreciate all the answers so far.
That's not the official documentation. Head right to the CPAN: - [MongoDB::Tutorial](https://metacpan.org/module/MongoDB::Tutorial) - [MongoDB::Examples](https://metacpan.org/module/MongoDB::Examples) Iterating results is pretty similar to the DBI way: ``` use Data::Printer; use MongoDB; # no query is performed on initialization! my $cursor = $collection ->find({ active => 1, country => 'Canada' }) # filter "active" records from Canada ->sort({ stamp => -1 }) # order by "stamp" attribute, desc. ->limit(1000); # first 1000 records # query & iterate while (my $row = $cur->next) { # it is 'p', from Data::Printer! p $row; } ```
Eclipse Juno - Constant crash (805306369) when highlighting anything Whenever I mouse over any imported.. anything in Juno, Eclipse immediately hangs. Editing Java files - types, classes, annotations, the import itself - mousing over anything to view the javadoc will instantly hang eclipse. Also happens with auto-completes if the popup stays open for more than a second. Here's the error: ![Juno Error 805306369](https://i.stack.imgur.com/wjxlD.png) Running: ``` java version "1.7.0_15" Java(TM) SE Runtime Environment (build 1.7.0_15-b03) Java HotSpot(TM) 64-Bit Server VM (build 23.7-b01, mixed mode) ``` The latest Eclipse Juno (Java EE) 64bit Win7 x64. There shouldn't be any incompatibilities there (All x64). Looking around the proposed fixes are either related to Java 6, or say to delete `Mylyn`, which I've done but no fix. This error happens consistently every single time. Edit: And to make things more annoying, the log in the .metadata folder is empty. I'm assuming I'm missing something obvious as the *exact same setup* on my other laptop works fine. And searching just gets me unreadable mailing lists, or bug trackers saying it's fixed - when clearly it's not in this case.
**Warning**: *the solution described below corrected the problem on my computer, but the problem may not be the same on your computer... YMMV.* So, the incriminated popups are displaying an HTML snippet. This snippet is rendered using *mshtml.dll*. The same *mshtml.dll* is used to render HTML Help files (files with extension *.chm*). On my computer, i discovered that i was not able to open any HTML Help file: the HTML Help Executable (*hh.exe*) was crashing at launch. After some more research (i won't go through all the details of the search), it appeared that the drivers for my display adapter, which is an nVidia GeForce 540M, were at fault. They were outdated, and their installation got probably corrupted. After updating the drivers, the system was back to normal: i can open HTML Help files again, and Eclipse is no more crashing when displaying those little HTML filled popups ! So, the first step for you would be to check that you can open an HTML Help file correctly. Then you should check your display adapter driver installation... If it does not solve your problem, there can be many reasons for mshtml.dll file to crash, try to make something using mshtml.dll crash: this crash might give you more information than when eclipse brutally exits. (note that the corrupted drivers prevented the execution of the standard driver installer package downloaded from nVidia. I had to go to the device manager, open the properties for my display adapter, then click the "update driver" button. everything went smoothly, and automatically, from there) (note also that my system is running Windows 7 64-bit)
UISwipeGestureRecognizer blocked by UITapGestureRecognizer I have a view which needs to handle pan, tap, and swipe gestures. I have pan and tap working, but when I add swipe, it doesn't work. Curiously, it seems that tap somehow blocks the swipes because if I remove the tap, then swipe works fine. Here's how I create my gesture recognizers. ``` - (void) initGestureHandlers { UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeLeftGesture:)]; swipeLeftGesture.numberOfTouchesRequired = 1; swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft; [self addGestureRecognizer:swipeLeftGesture]; UISwipeGestureRecognizer *swipeRightGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeRightGesture:)]; swipeRightGesture.numberOfTouchesRequired = 1; swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight; [self addGestureRecognizer:swipeRightGesture]; UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]; [tapGesture setNumberOfTapsRequired:1]; [self addGestureRecognizer:tapGesture]; UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)]; [self addGestureRecognizer:panGesture]; } ``` A lot of blog suggest using requireGestureRecognizerToFail to handle the case where tap fires before the double tap fires, so I tried that, but it also didn't work. ``` [tapGesture requireGestureRecognizerToFail:swipeLeftGesture]; [tapGesture requireGestureRecognizerToFail:swipeRightGesture]; ``` How can I get tap and swipe in the same view?
comment or remove the lines ``` //[tapGesture requireGestureRecognizerToFail:swipeLeftGesture]; //[tapGesture requireGestureRecognizerToFail:swipeRightGesture]; ``` Also set the all the guesture objects delegate to self. like this ``` - (void) initGestureHandlers { UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeLeftGesture:)]; swipeLeftGesture.numberOfTouchesRequired = 1; swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft; swipeLeftGesture.delegate = self; [self addGestureRecognizer:swipeLeftGesture]; UISwipeGestureRecognizer *swipeRightGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeRightGesture:)]; swipeRightGesture.numberOfTouchesRequired = 1; swipeRightGesture = self; swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight; [self addGestureRecognizer:swipeRightGesture]; UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]; [tapGesture setNumberOfTapsRequired:1]; [self addGestureRecognizer:tapGesture]; tapGesture.delegate = self; UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)]; [self addGestureRecognizer:panGesture]; panGesture.delegate = self; } ``` Implement the delegate method like this ``` - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; } ```
Clear Editor Console logs from script This is my script and I tried to make "" in case it's not one of the cases: ``` private void OnCollisionEnter(Collision collision) { if (collision.gameObject.name == "Platform") Debug.Log("Touching Platform"); else Debug.Log(""); } private void OnTriggerEnter(Collider other) { if (other.gameObject.name == "OnTop Detector") { Debug.Log("On Top of Platform"); GameObject findGo = GameObject.Find("ThirdPersonController"); GameObject findGo1 = GameObject.Find("Elevator"); findGo.transform.parent = findGo1.transform; } else Debug.Log(""); } ``` But this "" not working. It's not deleting the text from the console while the game is running. And also when i stop the game and running it again it keep showing the last text of the Debug.Log. I want to clear it if none of the If's happen in my script. I saw this answer: [Answer](http://answers.unity3d.com/questions/707636/clear-console-window.html) But i'm not sure if this is what I need and how to use it. Make a new script ? And also what about errors. If I clear the Log in the console it will delete also erorrs if there will be some ? In this screenshot it's in state after I touched the platform and then moved away from it but the text still exist in the console log: [![Screenshot](https://i.stack.imgur.com/e3HSk.jpg)](https://i.stack.imgur.com/e3HSk.jpg)
The `Debug.ClearDeveloperConsole()` function is used when you clear logs from an application that was built while *Debug Build* is enabled in your project. There is *no* official API for clearing the Editor log. Most Editor functionality can be replicated with [`Reflection`](https://msdn.microsoft.com/en-us/library/mt656691.aspx) just like [*hiding Gizmos*](https://stackoverflow.com/a/37271944/3785314) and toggling the [*Stats Panel*](https://stackoverflow.com/a/40234614/3785314). I was going to write one but found [this](http://answers.unity3d.com/answers/956891/view.html) one. This should clear every log on the Console tab. ``` using System.Reflection; public void ClearLog() { var assembly = Assembly.GetAssembly(typeof(UnityEditor.ActiveEditorTracker)); var type = assembly.GetType("UnityEditorInternal.LogEntries"); var method = type.GetMethod("Clear"); method.Invoke(new object(), null); } ``` Now, you can call `ClearLog();` in your else statements. **EDIT**: This has changed recently in about ~Unity 2017. Since it is done with reflection, I consider it to change again anytime if any class, variable or function used in this code is renamed by Unity. Below is the new way to do this: ``` public void ClearLog() { var assembly = Assembly.GetAssembly(typeof(UnityEditor.Editor)); var type = assembly.GetType("UnityEditor.LogEntries"); var method = type.GetMethod("Clear"); method.Invoke(new object(), null); } ```
Forward variadic template args to several class members Is the following safe? Won't the `std::string` be `move`d after the first class member is initialised? It prints out ok but I'm not sure. ``` template <typename T> class Test { public: template <typename... Args> Test(Args&&... args) : m_one(new T(std::forward<Args>(args)...)), m_two(new T(std::forward<Args>(args)...)) // <- Here { } private: std::unique_ptr<T> m_one; std::unique_ptr<T> m_two; }; class C { public: C(int a, int b, const std::string& c) : m_a(a), m_b(b), m_c(c) { std::cout << "ctor a=" << m_a << ", b=" << m_b << ", c=" << m_c << "\n"; } int m_a; int m_b; std::string m_c; }; int main() { Test<C> t(1, 2, "3"); } ``` I guess it's ok since the third ctor param of `C` is `const std::string&`, but how do I prevent perfect forwarding in a class that takes an r-value ref, e.g. `C(int, int, std::string&&)` as then `m_two` will not receive the same ctor args as `m_one`? Changing the ctor of Test to ``` template <typename... Args> Test(Args&... args) ``` doesn't compile. Nor does removing the `std::forward<Args>(args)...` from `m_one` and `m_two` ctors.
You are going to want to use something like this: ``` #include <memory> #include <string> #include <iostream> #include <utility> template <typename T> class Test { public: template <typename... Args> Test(Args&&... args) : m_one(new T(args...)), // avoid moving the first time m_two(new T(std::forward<Args>(args)...)) // but allowing moving the last time { } private: std::unique_ptr<T> m_one; std::unique_ptr<T> m_two; }; class C { public: C(int a, int b, std::string c) // rule of thumb -- if you are going to copy an argument // anyway, pass it by value. : m_a(a), m_b(b), m_c(std::move(c)) // you can safely move here since it is the last use. { std::cout << "ctor a=" << m_a << ", b=" << m_b << ", c=" << m_c << "\n"; } int m_a; int m_b; std::string m_c; }; ``` For `m_one`, the arguments use lvalue references, so no moving will take place. For `m_two`, the `std::forward` will use rvalue references as appropriate. Taking the `std::string` argument to `C` by value and using `std::move` makes it work properly for either case. If you pass an lvalue reference, then the argument will be copy-constructed, but if you pass an rvalue reference, the argument will be move-constructed. In either case, you can move the argument into your `m_c` member for efficiency.
Lightest way to run GUI applications in Linux? I realized I can use a [window manager without a desktop environment](https://unix.stackexchange.com/q/1206/250) and don't lose any functionality I care about. Applications still work fine, I can still arrange application windows as I please. This pretty much eliminates the need for lightweight desktop environments such as LXDE and XFCE for use cases like mine. I wonder if that is the end of the list. Is there anything one can possibly cut out? As the minimum, I want something that can run GUI apps like Firefox. I imagine something with a terminal from which I can start other applications.
Did you have a look at some other "lighterweight" ;-) window managers? I'm completly happy with i3 for example: <http://i3wm.org/> It's just a tiling windowmanger with dmenu for launching applications. No desktop, no other special features and the binary is just some KBs. There are a lot others in this range: - evilwm - <http://www.6809.org.uk/evilwm/> - dwm - <http://dwm.suckless.org/> - ... The absolut minimum would be running your X-Server without any windowmanager and just with something like dmenu (<http://tools.suckless.org/dmenu/>) to launch applications. I'm not sure if this is really what you want, because you won't be able to resize the application windows, move them, etc.
Rich Push Notification - Video won't play in Notification Content Extension I am working on rich notification's `Notification Content Extension` and have able to load `images` and `gif` successfully like following screenshot: [![enter image description here](https://i.stack.imgur.com/ZBSq9.jpg)](https://i.stack.imgur.com/ZBSq9.jpg) Now i am trying to play video and i am doing following code for playing it. ``` - (void)didReceiveNotification:(UNNotification *)notification { //self.label.text = @"HELLO world";//notification.request.content.body; if(notification.request.content.attachments.count > 0) { UNNotificationAttachment *Attachen = notification.request.content.attachments.firstObject; NSLog(@"====url %@",Attachen.URL); AVAsset *asset = [AVAsset assetWithURL:Attachen.URL]; AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset]; AVPlayer *player = [AVPlayer playerWithPlayerItem:item]; AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player]; playerLayer.contentsGravity = AVLayerVideoGravityResizeAspect; player.actionAtItemEnd = AVPlayerActionAtItemEndNone; playerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); [self.VideoPlayerView.layer addSublayer:playerLayer]; [player play]; } } ``` In NSLog i get the file url of video as well. but that wont play. Kindly help if any one have that solution. Thanks.
It's Very small mistake i did with the code that. we must be check with `startAccessingSecurityScopedResource` if i do code like following ``` - (void)didReceiveNotification:(UNNotification *)notification { if(notification.request.content.attachments.count > 0) { UNNotificationAttachment *Attachen = notification.request.content.attachments.firstObject; if(Attachen.URL.startAccessingSecurityScopedResource) { NSLog(@"====url %@",Attachen.URL); AVAsset *asset = [AVAsset assetWithURL:Attachen.URL]; AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset]; AVPlayer *player = [AVPlayer playerWithPlayerItem:item]; AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player]; playerLayer.contentsGravity = AVLayerVideoGravityResizeAspect; player.actionAtItemEnd = AVPlayerActionAtItemEndNone; playerLayer.frame = CGRectMake(0, 0, self.VideoPlayerView.frame.size.width, self.VideoPlayerView.frame.size.height); [self.VideoPlayerView.layer addSublayer:playerLayer]; [player play]; } } } ``` And Video is playing. Boooom...
is there s possibility to get the variable name from within code in Android/Java or iPhone/objective-C for debugging I frequently use constants defined like: ``` private static final int myConstant_x = 1; private static final int myConstant_y = 2; private int anyVariable; anyVariable = myConstant_x ``` during debugging it would be really helpful to somehow access the name of the variable for log output instead of the value. ``` Log.i (TAG,"this is debug output of anyVariable with constant name: " + ????); ``` with output: **"this is debug output of anyVariable with constant name: myConstant\_x"** instead of ``` Log.i (TAG,"this is debug output of anyVariable with constant name: " + anyVariable); ``` with output: **"this is debug output of anyVariable with constant name: 1"** Is there any way? I know one can get the method name from within code but is there a way to get the variable name too somehow? Would be really helpful Thanks EDIT: updates/corrected the example code - sorry for the first misleading version
You could get the fields of a class using reflection and iterate over them. You'd then have access to the name and the value. Something like this: ``` public void logStaticFields( Class<?> clazz) throws IllegalAccessException { for( Field f : clazz.getDeclaredFields() ) { if( Modifier.isStatic( f.getModifiers() ) ) { boolean wasAccessible = f.isAccessible(); f.setAccessible(true); Log.i (TAG, "this is debug output of static field " + f.getName() + ": " + f.get( null ) ); f.setAccessible( wasAccessible ); } } } ``` If you want to only log constants (which normally are static final) you could check for `Modifier.isStatic( f.getModifiers() ) && Modifier.isFinal( f.getModifiers() )`. This method also temporarily disables access checks, otherwise `get()` might throw that `IllegalAccessException`. Note that this might still not work, depending on your JVM's `SecurityManager` configuration. Note that this only works for fields (class or instance variables) and method parameters, not for local variables within a method since theres no reflection information for those.
What can be done to decrease the number of live issues with applications? First off I have seen this post which is slightly similar to my question. : [What can you do to decrease the number of deployment bugs of a live website?](https://softwareengineering.stackexchange.com/questions/107851/what-can-you-do-to-decrease-the-number-of-deployment-bugs-of-a-live-website) Let me layout the situation for you. The team of programmers that I belong to have metrics associated with our code. Over the last several months our errors in our live system have increased by a large amount. We require that our updates to applications be tested by at least one other programmer prior to going live. I personally am completely against this as I think that applications should be tested by end users as end users are much better testers than programmers, I am not against programmers testing, obviously programmers need to test code, but they are most of the times too close to the code. The reason I specify that I think end users should test in our scenario is due to the fact that we don't have business analysts, we just have programmers. I come from a background where BAs took care of all the testing once programmers checked off it was ready to go live. We do have a staging environment in place that is a clone of the live environment that we use to ensure that we don't have issues between development and live environments this does catch some bugs. We don't do end user testing really at all, I should say we don't really have anyone testing our code except programmers, which I think gets us into this mess (Ideally, we would have BAs or QA or professional testers test). We don't have a QA team or anything of that nature. We don't have test cases for our projects that are fully laid out. Ok, I am just a peon programmer at the bottom of the rung, but I am probably more tired of these issues than the managers complaining about them. So, I don't have the ability to tell them you are doing it all wrong.....I have tried gentle pushes in the correct direction. Any advice or suggestions on how to alleviate this issue ?
> > We require that our updates to applications be tested by at least one > other programmer prior to going live. > > > That's a start, but you are writing here because you have proven this to be insufficient. > > Applications should be tested by end users > > > We used to joke that we'd let end-users test our code. The point of testing is to find bugs *before* the end-users do. That way, end-users have a good experience, and recommend, or buy more of the software. > > not [tested by] programmers > > > What's wrong with programmers testing? I think it's an important part of being a good programmer. Some schools of thought recommend that programmers write tests before even writing code! I think the problem that you are getting at is *only* having programmers do testing. > > staging environment in place that is a clone of the live environment > > > This is very good. But if it is truly a clone, then the learning you gain from installing from development to staging is not getting transferred from staging to production. One way or another, you aren't getting the full benefit of this system. Do you do your testing in the staging environment? > > We don't do end user testing really at all. > > > End user testing is usually about acceptance of new features, ease of use, and meeting the users needs. Not about finding bugs. End-users finding bugs = lost customers. > > We don't have a QA team or anything of that nature. We don't have test > cases for our projects that are fully laid out. > > > Eek! This is the root cause of your problems. A QA team would be fantastic, but even one eager and capable full-time tester would be an improvement. You could get a short-term contractor, but having someone on-board long-term who can weave testing into your whole development cycle would be much better. I work in a small company and we have a written regression test that we go through for every release. It is not fun, but it catches bugs. We take turns and just do it. Maybe you mean something different when you talk about end-users finding bugs. If so, you need to find a different way of expressing it, because that's a losing proposition if I've ever heard one. Specifically, it sounds like it loses customers. Advocate instead for: - A professional tester - A written regression test - Test-driven development - Establishing a culture of Quality. Each of those is a time-honored industry-standard solution to a real issue you are experiencing that is affecting your bottom line. If you keep metrics, then you should be able to estimate a dollar figure to the number of users who leave because of bugs, and the negative advertising the bugs generate. There is also an opportunity cost, where customers who don't find bugs are happier and more likely to recommend your product. If 80% of the total cost of the bugs to the company is enough to hire a tester, that's your whole business case right there. A slam-dunk really. Good luck!
Get date format in Python in Windows In a sample code given to me for my homework, this line appears: ``` date_format = locale.nl_langinfo(locale.D_FMT) ``` But in Windows that line returns the following error: ``` File "C:\Users\Shadark\Dropbox\IHM\P3\p3_files\www\cgi-bin\todolist.py", line 11, in <module> date_format = locale.nl_langinfo(locale.D_FMT) AttributeError: 'module' object has no attribute 'nl_langinfo' ``` I've read about using **localeconv** but I only read about it being used currency or numbers. Any idea on uses for the purpose of my code sample or other kind of function? Thanks in advance.
Your problem is probably the fact that `locale.nl_langinfo` doesn't appear to be available in Windows Python 2.7.x (I don't see it in my copy of Windows 64-bit Python 2.7.3). Looking at the docs at <http://docs.python.org/2.7/library/locale.html#locale.nl_langinfo>, they specifically say: > > This function is not available on all systems, and the set of possible options might also vary across platforms. > > > Once you've set the locale up with something along the lines of: ``` locale.setlocale(locale.LC_ALL, 'english') ``` Then calls to some\_date.strftime() will use correct locale specific formatting and strings. So if you want the date in string format, call `some_date.strftime('%x')` replace the `%x` with `%X` for time or `%c` for both. The full list of strftime formats are documented [here](http://docs.python.org/2.7/library/datetime.html#strftime-and-strptime-behavior). ``` >>> d = datetime.datetime.now() ... for loc in ('english', 'german', 'french'): ... locale.setlocale(locale.LC_ALL, loc) ... print loc, d.strftime('%c -- %x -- %X -- %B -- %A') english 11/15/2012 4:10:56 PM -- 11/15/2012 -- 4:10:56 PM -- November -- Thursday german 15.11.2012 16:10:56 -- 15.11.2012 -- 16:10:56 -- November -- Donnerstag french 15/11/2012 16:10:56 -- 15/11/2012 -- 16:10:56 -- novembre -- jeudi 14: 'French_France.1252' ```