text
stringlengths
14
21.4M
Q: Zero Sum Games and Weakly Dominated Strategies Can you eliminate weakly dominated strategies in a zero-sum game? If yes, why? Doesn't the order of elimination matter. (Normally, in ordinary games in strategic form, you can only eliminate strictly dominated strategies. And if you were to eliminate weakly dominated strategies, the order would matter) A: Here is a similar question where the accepted answer includes a zero sum game with a Nash Equilibrium where one player plays a weakly dominated strategy: Weakly dominated Nash equilibrium in a zero-sum game In case that gets taken down, here is the game: $$\begin{array}{r | c | c |} & L & R \\ \hline T & (1,-1) & (1,-1) \\ \hline B & (1,-1) & (0,0) \\ \hline \end{array}$$ We have that $(T,L)$ is a Nash Equilibrium even though $L$ is weakly dominated by $R$. A: How can this zero-sum game be solved?
Q: PHP get file contents for textarea I have a form that selects files from the server and then on change puts the filename and contents into text areas. This works fine if I have this in the base directory of /evo/ where everything is kept (as in /evo/users/username being where it pulls the files from) However when I moved this page deeper into the folder it has trouble parsing the files from the dropdown list. I had to add $_SERVER['DOCUMENT_ROOT'] To the file so it found the files to display in the dropdown correctly, however when it tries to put them into into the text area, it displays: Failed to load resource: the server responded with a status of 404 (Not Found) XHR finished loading: GET "http://mywebsite.site/home/revo/public_html/evo/users/Addiction/Addiction.html". Which means either my directory in how I'm finding them is wrong or (hopefully and likely) how I'm echoing it or using it in the function change at the bottom is. The textarea that isn't loading correctly is the "CodeValue" box that displays the files contents. <select size="1" name="CodeList" id="CodeList"><option selected disabled>(Select Your Code)</option> <?php $directory = $directory = $_SERVER['DOCUMENT_ROOT'] . '/evo/' . '/users/' . $_SESSION['username']; $filesContents = Array(); $files = scandir( $directory ) ; foreach( $files as $file ) { if ( ! is_dir( $file ) ) { $filesContents[$file] = file_get_contents($directory , $file); echo '<option value="'. $file .'">' . $file . '</option>'; } } ?> </select> <input type="hidden" name="CodeId" id="CodeId" value="0" /> <input type="hidden" name="CodeDescription" size="40" maxlength="50" id="CodeName" value="" /> <font color=#33A6A6>Code:</font>&nbsp;<input name="USER" value="" SIZE=40 name="CodeValue" id="CodeValue" />&nbsp;&nbsp;&nbsp;<input type=hidden name="ACTION" value="says to"><input type=hidden name="WHOTO" value="ALL"><input type=submit value="Enter"><font size="-1"><font color=#33A6A6>Entrance:&nbsp;</font><input name="SAYS" value="Enters the room..."><font color=#33A6A6>History:&nbsp;</font><input name="HISTORY" value="20" size=2><font size="-1"><font color=#33A6A6>No Pics:&nbsp;</font><input name="NOPIC" value="1" type="checkbox" checked></form> <script> $(document).ready(function(){ // apply a change event $('#CodeList').change(function() { // update input box with the currently selected value $('#CodeName').val($(this).val()); $.get( '<? echo $directory ?>' + '/' + $('#CodeName').val(), function( data ) { $( "#CodeValue" ).val( data ); }); }); }); </script> A: The error message says the AJAX request went to this URL: http://mywebsite.site/home/revo/public_html/evo/users/Addiction/Addiction.html Whereas I think you wanted it to go to: http://mywebsite.site/evo/users/Addiction/Addiction.html Since you said /evo/ is the base directory. The script being output is including the internal directory path on the server rather than the externally visible HTTP path. You can change this by doing this at the top: $httpPath = '/evo/' . '/users/' . $_SESSION['username']; $directory = $directory = $_SERVER['DOCUMENT_ROOT'] . $httpPath; and then this in the script output: $.get( '<? echo $httpPath ?>' + '/' + $('#CodeName').val(), function( data ) {
Q: Does Android Studio have an option to automatically scan inactive tabs for errors/warnings/lint etc? I would like to be able to have all tabs to automatically scan lint and other warnings while they are inactive. Currently, only the active tab will load. But I prefer Android Studio to load all the tabs while I am away alt tabbed or doing other stuff while waiting for Android Studio to load. Right now I have to manually click on the tab and wait, and then click the next tab and wait. My PC is slow so it takes awhile to load each tab. A: Analyze > Inspect Code... will probably cover your use case. Please see https://developer.android.com/studio/write/lint#manuallyRunInspections for more details.
Q: How to use Upload Endpoint plugin in Shrine? I want to use the shrine gem, I read a Shrine image cropping , Shrine Upload Endpoint plugin, then I refer to sample codes, First, I copied sample codes, but I happened ActionController::RoutingError (No route matches [GET] " /uploads/cache/47eee6dc368f20db1e26fa5176552136.jpg"): I think this error I couldn't send right path, I don't solve this error, i.e. I don't use Upload Endpoint plugin well, I could send a Post request but couldn't use get request someone teach me how to use get request in the shrine, please? form.html.erb: <div class ="container"> <div class ="row"> <%= form_with model: @photo, url: photos_new_path,local: true do |f| %> <div class="form-group"> <%= f.label :image %> <%= f.hidden_field :image, value: @photo.cached_image_data, class: "upload-data" %> <%= f.file_field :image, accept: ImageUploader::ALLOWED_TYPES.join(","), data: { upload_server: "upload_server", preview_element: "preview-photo", upload_result_element: "preview-photo-upload-result", }%> <div class="image-preview"> <!-- static link to the thumbnail generated on attachment --> <%= image_tag @photo.image_url.to_s, width: 300, class: "img-thumbnail file-upload-preview", id: "preview-photo" %> </div> </div> <%= f.submit "create", class: "btn btn-primary" %> <% end %> </div> routes.rb: Rails.application.routes.draw do get 'photos/new' mount ImageUploader.upload_endpoint(:cache) => "/app/assets/images/uploads" mount ImageUploader.derivation_endpoint => "/derivations/image" mount ImageUploader.presign_endpoint(:cache) => "/images/presign" get 'sessions/new' devise_for :users resources :users do resources :photos end # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end Plugin of Shrine.rb: require "shrine" require "shrine/storage/file_system" Shrine.storages = { cache: Shrine::Storage::FileSystem.new("app/assets/images", prefix: "uploads/cache"), # temporary store: Shrine::Storage::FileSystem.new("app/assets/images", prefix: "uploads"), # permanent } Shrine.plugin :pretty_location Shrine.plugin :determine_mime_type, analyzer: :marcel Shrine.plugin :activerecord # loads Active Record integration Shrine.plugin :cached_attachment_data # for retaining the cached file across form redisplays Shrine.plugin :restore_cached_data # re-extract metadata when attaching a cached file Shrine.plugin :validation_helpers Shrine.plugin :derivatives Shrine.plugin :derivation_endpoint, secret_key: "secret", expires_in: 10 Shrine.plugin :upload_endpoint, url: true Shrine.plugin :default_url Shrine.plugin :backgrounding Plugin of Image_uploader.rb: plugin :store_dimensions, analyzer: :ruby_vips, log_subscriber: nil plugin :derivatives plugin :derivation_endpoint, prefix: "derivations/image" plugin :presign_endpoint I checked path with console.log, so that response.uploadURL is /uploads/cache/47eee6dc368f20db1e26fa5176552136.jpg
Q: Strange date format from a text file into SAS date I have a text-file with a date that I would like to convert into a SAS date. The dates look like this 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z I know that if the date looked like date_in_string = '05May2013', then I could input(date_in_string,date9.); But, I have characters inside the string, and I have not been able to find any suitable formats. A: IS8601DZ. is the correct informat for that datetime, as that is an ISO 8601 datetime format with a timezone. data test; input dt IS8601DZ.; format dt datetime17.; datalines; 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z ;;;; run; To convert to a date-only you can read it in then use DATEPART, or you can use YYMMDD10. to read it in (remember, SAS will happily truncate it for you and ignore the junk at the end - as long as your MM/DD are zero padded). If they're not zero padded you have to parse it in some other fashion. data test; input dt YYMMDD10.; format dt date9.; datalines; 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z 2014-12-14T07:04:33Z ;;;; run;
Q: How to get selected item of NSOutlineView without using NSTreeController? How do I get the selected item of an NSOutlineView with using my own data source. I see I can get selectedRow but it returns a row ID relative to the state of the outline. The only way to do it is to track the expanded collapsed state of the items, but that seems ridiculous. I was hoping for something like: array = [outlineViewOutlet selectedItems]; I looked at the other similar questions, they dont seem to answer the question. A: NSOutlineView inherits from NSTableView, so you get nice methods such as selectedRow: id selectedItem = [outlineView itemAtRow:[outlineView selectedRow]]; A: Swift 5 NSOutlineView has a delegate method outlineViewSelectionDidChange func outlineViewSelectionDidChange(_ notification: Notification) { // Get the outline view from notification object guard let outlineView = notification.object as? NSOutlineView else {return} // Here you can get your selected item using selectedRow if let item = outlineView.item(atRow: outlineView.selectedRow) { } } Bonus Tip: You can also get the parent item of the selected item like this: func outlineViewSelectionDidChange(_ notification: Notification) { // Get the outline view from notification object guard let outlineView = notification.object as? NSOutlineView else {return} // Here you can get your selected item using selectedRow if let item = outlineView.item(atRow: outlineView.selectedRow) { // Get the parent item if let parentItem = outlineView.parent(forItem: item){ } } } A: @Dave De Long: excellent answer, here is the translation to Swift 3.0 @objc private func onItemClicked() { if let item = outlineView.item(atRow: outlineView.clickedRow) as? FileSystemItem { print("selected item url: \(item.fileURL)") } } Shown is a case where item is from class FileSystemItem with a property fileURL.
Q: Searchbar inside navbar calls an HTTP request, want returned data to populate in another component I am building a site that allows one to search for a beer and it returns data about that beer. The user clicks the search button, and it runs the http request I have setup on a service. All displays fine. But what I am trying to do is move my search form from the displaying component, to be inside the navbar. How do I link the search form on the navbar to the viewing component? here is the home.component where the search form currently sits(clicking search runs the "searchBeer" function below passing the beer name being searched for: @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(private beerSearchService:BeerSearchService) { } beerName:string; beers:{}; selectedBeer: {}; searchBeer(beerName){ this.beers=null; this.beerSearchService.searchBeer(beerName) .subscribe(data => console.log(this.beers=data)); this.selectedBeer=null; } onSelect(beer): void { this.selectedBeer = beer; console.log(beer); } ngOnInit() { } } EDIT... Had wrong service before..... beer-search.service: import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class BeerSearchService{ constructor(private http: HttpClient) { } searchBeer(name){ let data= { query: `{beerSearch(query:"`+name+`"){items{id, name, style {description}, description, overallScore, imageUrl, abv, brewer {name, facebook, web}}}}`, variables:"{}", operationName:null } return this.http.post('https://api.r8.beer/v1/api/graphql/', data, { headers:{ 'x-api-key': '<API-KEY>'} }); } } If I move the search bar to the navbar component, how do I call this searchBeer function? A: You store the results of API call to BehaviorSubject in the service, from navbar call the method to get beers from API and in component instead of subscribing to API result, subscribe to Observable (from BehaviorSubject of BeerS - your data): BeerSearchService export class BeerSearchService { private _beers = new BehaviorSubject<Beer[]>(null); constructor(private http: HttpClient) { } searchBeer(beerSearch?: string) { // do something with beerSearch parameter let data = { query: ` {topBeers{items{id, name, style {description}, description, overallScore, imageUrl, abv, brewer {name, facebook, web}}}}`, variables:"{}", operationName:null }; this.http.post('https://api.r8.beer/v1/api/graphql/', data, { headers: {'x-api-key': '<api-key>'} }).subscribe(data => { this._beers.next(data); }); } get beers$() { return this._beers.asObservable(); } } navbar.ts export class NavbarComponent implements OnInit { constructor(private beerSearchService: BeerSearchService) {} searchBeer(beerName) { this.beerSearchService.searchBeer(beerName); } } Component.ts export class HomeComponent implements OnDestroy { beers:{}; sub: Subscription; constructor(private beerSearchService: BeerSearchService) { this.sub = this.beerSearchService.beers$.subscribe(beers => { this.beers = beers; }); } ngOnDestroy() { this.sub.unsubscribe(); } }
Q: What is the difference between 'or' and '|' when programming in xslt? I have been working with xslt recently, and I have been having trouble understanding the difference between | and or and when I should use which. I understand I can just use the error messages to figure out which one I need to be using but I am interested in learning why I can't use one or the other. Would anyone be able to help point me in the right direction to someplace where I can learn the difference? A: | is concerned with nodes, or is concerned with "truth", that is, Boolean values. Explanation The | or union operator This operator returns the union of two sequences that, in this case, are interpreted as two sets of nodes. An interesting detail is that the union operator removes any duplicate nodes. Also, it only accepts operands of the type node()*, i.e. a sequence of nodes. The nodes are returned in document order. The or operator The technical term for this operator is Boolean Disjunction. It takes two arguments, both of which must evaluate to a Boolean value ("true" or "false") individually. Or, more precisely, the operands of or are jugded by their effective Boolean value by converting them to xs:boolean. All of this also applies to the and operator, by the way. Examples Use the union operator to enlarge a set of nodes, typically in a template match: <xsl:template match="Root|Jon"> Why not use the or operator here? Because the match attribute expects a set of nodes as its value. union returns a set of nodes, whereas the or operator returns a Boolean value. You cannot define a template match for a Boolean. Use the or operator to implement alternatives in XSLT code, mainly using xsl:if or xsl:choose: <xsl:if test="$var lt 354 or $var gt 5647"> If any of the two operands of this or operation evaluates to true, then the content of xsl:if will be evaluated, too. But not only comparisons like "less than" (lt) have a Boolean value, the following is also perfectly legal: <xsl:if test="$var1 or $var2"> The above expression only evaluates to true if at least one of the two variables is a non-empty sequence. This is because an empty sequence is defined to have the effective Boolean value of false. Coercion Note that because of the way XSLT coerces things to appropriate types, there are some contexts where either operator can be used. Consider these two conditionals: <xsl:if test="Root | Jon"> ... <xsl:if> <xsl:if test="Root or Jon"> ... <xsl:if> The first conditional tests whether the union of the set of children named Root and the set of children named Jon is non-empty. The expression Root | Jon returns a sequence of nodes, and then that sequence is coerced to a boolean value because if requires a boolean value; if the sequence is non-empty, the effective boolean value is true. The second conditional tests whether either of the two sets of children (children named Root and children named Jon) is non-empty. The expression Root or Jon returns a boolean value, and since the operator or requires boolean arguments, the two sets are each coerced to boolean, and then the or operator is applied. The outcome is the same, but (as you can see) the two expressions reach that outcome in subtly different ways. A: From Documentation | - The union operator. For example, the match attribute in the element <xsl:template match="a|b"> matches all <a> and <b> elements or - Tests whether either the first or second expressions are true. If the first expression is true, the second is not evaluated.
Q: How to add a button after each row of a table from sql? i have a table with three columns date , title , message. i will show only date and title in each table and want to add a seperate button after each row then i will show that message . i have tried <?php echo "<table style='border: solid 3px aqua;'>"; echo "<tr><th>Circular/Notice</th><th>DateGenerated</th></tr>"; class TableRows extends RecursiveIteratorIterator { function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); } function current() { return "<td style='width:150px;border:1px solid red;'>" . parent::current(). "</td>"; } function beginChildren() { echo "<tr>"; } function endChildren() { echo "</tr>" . "\n"; } } $servername = "localhost"; $username = "root"; $password = ""; $dbname = "er"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT title ,DateGenerated FROM messages"); $stmt->execute(); // set the resulting array to associative $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { echo $v; } } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; echo '<input type ="button" value = "View"/>'; echo "</table>"; ?> and the result am getting is only one button that too at top of the table. A: The <input> needs to be inside a <td>, which needs to be inside a <tr> Anything inside a HTML table that isn't in a row and cell, gets rendered outside the table. To have a button for each row, you need to put the code inside your TableRows loop. I would suggest editing the endChildren() function, as follows: function endChildren() { echo '<td><input type="button" value = "View"/></td>'; echo "</tr>" . "\n"; }
Q: Secrets as password format in AWS We are saving Secrets, keys in AWS secrets Manager and These can be retrieved later in programming. We can also define IAM policies who can access these values. We are able to see Keys and values combinations. For example I can save "AppPass=@123tx56tX". Admin user can see "AppPass" actual value, Is there any way it can be stored like secret "AppPass=**********" or any other AWS services, or any workaround. Just don`t want everyone (Who has access) to see the password values from Console. A: No, you cannot secret manager store a document (as text), but its not responsible of the format (could be XML, JSON, or anything) If you want to show what's the format of the secret without show the value, maybe do it in description. But most of the time, the developer that'll use the secret have to know it (or at least a mock with a similar structure) So either you can read the secret or you cannot, but you cannot access only a part of it A: If you want encryption different from AWS provides (KMS), you will need to use a custom encryption code.
Q: WPF Path Command So I have successfully implemented a button click with a custom background. Here is the xaml: <Button HorizontalAlignment="Left" Grid.Row="0" Grid.Column="0" Command="{Binding PreferencesClickedCmd}" > <Path Data="..." Stretch="Uniform" Fill="#FF070707" Width="16" Height="16" Margin="0,0,0,0" RenderTransformOrigin="0.5,0.5" > <Path.RenderTransform> <TransformGroup> <TransformGroup.Children> <RotateTransform Angle="0" /> <ScaleTransform ScaleX="1" ScaleY="1" /> </TransformGroup.Children> </TransformGroup> </Path.RenderTransform> </Path> </Button> Now, is there a way to implement a click command with MVVM on Path object itself. What I am looking for to have only an icon portion to be clickable (with no help of button object). With button, the entire generated background rectangle can be clicked in order to trigger an event for the Path. A: If you want only the filled Path area to be clickable, this will work (just swap in your own Path, transform, etc. stuff): <Button Command="{Binding PreferencesClickedCmd}" > <Button.Content> <Path Data="M 8,0 L 0,16 L 16,0 Z" Fill="SlateBlue" /> </Button.Content> <Button.Template> <ControlTemplate TargetType="Button"> <ContentPresenter /> </ControlTemplate> </Button.Template> </Button> The entire visual presentation of the button is replaced by just the content alone, and the parts of the button that aren't filled by the path are not clickable because they're transparent. If you want the whole thing to be clickable, just give the template a background that's not quite transparent: <ControlTemplate TargetType="Button"> <Grid Background="#01ffffff"> <ContentPresenter /> </Grid> </ControlTemplate> This is the MVVM Way of Doing Things: Button provides a Click event, and Command property, and some visual stuff; if all you want is the Click event and the Command Property, don't roll your own click event; use those parts of the Button while discarding the visual stuff. A: As per Brandley suggestion, here is how I managed to implement it with minimal coding changes. I set the button size to match icon size, set the background to transparent and border width to 0: <Button HorizontalAlignment="Left" Grid.Row="0" Grid.Column="0" Margin="5,0,0,0" Width="30" Height="30" BorderThickness="0" Background="Transparent" Command="{Binding PreferencesClickedCmd}"> <Path Data="..." Stretch="Uniform" Fill="#FF070707" Width="16" Height="16" Margin="0,0,0,0" RenderTransformOrigin="0.5,0.5"> <Path.RenderTransform> <TransformGroup> <TransformGroup.Children> <RotateTransform Angle="0" /> <ScaleTransform ScaleX="1" ScaleY="1" /> </TransformGroup.Children> </TransformGroup> </Path.RenderTransform> </Path> </Button>
Q: Translations with many components using ng2-translate Hi I have a problem with translations, I'm using ng2-translate and this theme: SB Admin Bootstrap 4 Angular 4 I have an header with a language select dropdown menù, if I change language only my header component is translated but not the entire page (I have correctly configured pipes in all my project and imported translatemodule in the correct module) My component.html is: <app-header></app-header> <app-sidebar></app-sidebar> <section class="main-container"> <router-outlet></router-outlet> </section> In my header I have this dropdown: <div> <label> {{ 'HOME.SELECT' | translate }} <select #langSelect (change)="translate.use(langSelect.value);setLang()"> <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option> </select> </label> </div> What is the way to change language at entire page if it's formed by many other components? A: You need to import the ng2-translate module in all your modules where you are using translate pipe. it better to install the next version ngx-translate/core. For ngx-translate/core need to import TranslateModule in all your sub-modules ... import {TranslateModule} from '@ngx-translate/core'; ... @NgModule({ imports: [ ..., TranslateModule //or TranslateModule.forChild() ]
Q: What is the counting sequence of a Binary String? I have a two part question dealing with the binary strings for Discrete Math and I am stuck on the meaning of the very last part. (a) List all binary strings of length 3. * *Since a binary string is just a sequence of 0 and 1s I got the answer: 2x2x2 or 2^3 (b) What is the counting sequence of binary strings? * *I want to say permutations or "arrangement type counting sequence", but I think the answer expects a mathematical response or generalization. Can someone show me how to correctly answer this question?
Q: Sap Webi Count Function Hello All i have a problem in count function. i have a table which is auto generated from Database. means online table. i want to create a summary according to data in that table. i need a count of a value which are same in some columns. As example given below. Example table This is auto generated table online. Ticket number has unique value. i want to know to get a count of "Restored within Time" by "Severity" and Region. i am using below formula. =count([TicketNumber] Where ([RestoredWithInTime] ="Yes" And [Severity]="High" And [Region]="Central")) In above formula it should give me a count like 2. but it is showing 0. if i use only one condition then it works. like, count([TicketNumber] Where ([RestoredWithInTime] ="Yes") Or =count([TicketNumber] Where ([Severity]="High" it gives me accurate output. but if there is more than one condition then it shows only 0 count. Formulas which i have used for this are... =count([TicketNumber] Where ([RestoredWithInTime] ="Yes" And [Severity]="High" And [Region]="Central");Distinct) =count([TicketNumber]) Where ([RestoredWithInTime] ="Yes" And [Severity]="High" And [Region]="Central") (It Shows #MULTIVALUE Error) =sum(count([TicketNumber]) Where ([RestoredWithInTime] ="Yes" And [Severity]="High" And [Region]="Central")) Is there anything related to measures or dimensions? Thanks In Advance... A: I guess, Where should be outside Count function. can you check this. =count([TicketNumber]) Where ([RestoredWithInTime] ="Yes" And [Severity]="High" And [Region]="Central")
Q: Click in pdf file goes to indicated place When we do compiling tex file, we have a pdf file. In some pdf file (In online there exists a lot of such files), if we click, for instance, tex formula in the context, then we moved into tex formula paragraph or page. Or in content page, if we click a section, then we move into the section page How do we write in tex file to do this ? I think that we need the some package But I can not programming. If you have package, then can you give me ? I usually use the following : \documentclass[10pt]{amsart}\usepackage[hmargin=0.5in, vmargin=0.2in]{geometry} \usepackage{color} \usepackage{graphicx} \usepackage{multimedia, hfont, hangul} \newtheorem{fac}{Fact} \newtheorem{idea}{IDEA}\newtheorem{cor}{Corollary} \newtheorem{con}{Conjecture}\newtheorem{exa}{Example}\newtheorem{exe}{Exercise} \newtheorem{thm}{Theorem}\newtheorem{defn}{Definition}\newtheorem{prop}{Proposition} \newtheorem{lem}{Lemma} \newtheorem{form}{Formula} \newtheorem{prf}{Proof} \newtheorem{rmk}{Remark} \begin{document} \end{document} In here we have a such fuctioning ? If so, please tell me about it. Thank in advace. A: First thank you for your consistent helps : Bolker, Bernard, cfr, Kormylo, Andrew Thank you for your comments. My old miktex is version 2.3 so that I may not be given from updating place, since it does not provide service. So fortunately I equip version 2.9 from web It works well with acrobat reader DC The following is my example. \documentclass[10pt]{amsart} \usepackage{color, hyperref} %%<- \usepackage{graphicx} \begin{document} Critical Point Theory 90 \eqref{exa1} %%<- Well known theory \eqref{thm1} %%<- \begin{exa}\label{exa1} %%<- In ... \end{exa} \begin{thm}\label{thm1} %%<- If ... \end{thm}
Q: Most effective way to implement problem based on large sequence and xor operation I have been given the following input: * *n where n is size of sequence *k is an integer *a sequence A[0] A[1] A[2] ............A[n-1] I need to perform for each i from 0 to (k-1) inclusive find a,b where a=A[i%n] and b=A[n-(i%n)-1] then set A[i%n]=a XOR b and output the final sequence space separated Order is given :- n<=10^4 k<=10^12 Ai<=10^7 for each i i have applied the naive approach n,k=map(int,input().split()) arr=list(map(int,input().split())) for i in range(k): t=i%n arr[t]=arr[t]^arr[n-(t)-1] for i in arr: print(i,end=" ") but it shows Time Limit exceeded for large test cases. Would like an efficient implementation suggestion for the above A: ** Re:Updated implementation approach for the problem ** After combining algorithm suggested my @AJNeufeld and @vujazzman Sequence remains same if loop is run up to any multiple of (N*3) so we can save the overhead of running for all values of k Rather find the closest multiple of (n*3) to K and then run loop for remaining value from the found multiple to k Note:- Odd number n case to be handled separately in advance by set A[n//2] = 0 so i have came up with the following implementation: for _ in range(int(input())): n,k=map(int,input().split()) arr=list(map(int,input().split())) if n % 2 and k > n//2 : #odd n case arr[ n//2 ] = 0 rem= k % ( 3*n ) closest_multiple_3n = ( k-rem ) for i in range( closest_multiple_3n,k ): t=i % n arr[t] ^= arr[-1-t] print(*arr) i have created some self made test cases like :- t=1 n=11 k=9999999998 A[] = 20 7 27 36 49 50 67 72 81 92 99 output:- 20 7 27 36 49 0 67 72 81 92 119 note :- closest_multiple_3n = 9999999966 rem = 32 (20^92=119) It works perfectly now in less than 1 sec
Q: Evaluate the limiting value using mean-value theorem Prove that $$\lim_{n\rightarrow\infty}\int_{n}^{n+ 1}\sin e^{x}{\rm d}x= 0$$ I already have a solution but I want to see a proof(s) using mean-value theorem, it will be travelled ! Now let me show $$\left | \int_{n}^{n+ 1}\sin e^{x}{\rm d}x \right |= \left | \int_{e^{n}}^{e^{n+ 1}}\frac{\sin x}{x}{\rm d}x \right |\leq\left | \left ( \frac{\cos e^{n}}{e^{n}}- \frac{\cos e^{n+ 1}}{e^{n+ 1}} \right )- \int_{e^{n}}^{e^{n+ 1}}\frac{\cos x}{x^{2}}{\rm d}x \right |\leq$$ $$\leq\left | \frac{\cos e^{n}}{e^{n}}- \frac{\cos e^{n+ 1}}{e^{n+ 1}} \right |+ \int_{e^{n}}^{e^{n+ 1}}\frac{{\rm d}x}{x^{2}}\leq\frac{1}{e^{n+ 1}}+ \frac{1}{e^{n}}+ \frac{1}{e^{n+ 1}}+ \frac{1}{e^{n}}\rightarrow 0\,{\rm as}\,n\rightarrow\infty$$ A: MVT for integrals: $|\displaystyle{\int_{e^n}^{e^{n+1}}}\dfrac{\sin x}{x}dx|=$ $|\dfrac{\sin t}{t}\displaystyle{ \int_{e^n}^{e^{n+1}}}1dx|=|\dfrac{\sin t}{t}(e^{n+1}-e^n)|$ where $t \in [e^n,e^{n+1}].$ Take the limit. There is a problem here : Taking the limit gives you an upper bound $(e-1)$, not the desired result.
Q: Pure CSS transform scale from current value When applying a CSS scale transform to an element, is it possible to set the 'from' value as the current scale? For example, consider the following 2 CSS keyframes used to apply separate growing and shrinking animation transforms: @-webkit-keyframes grow { from { -webkit-transform: scale(0,0); } to { -webkit-transform: scale(1,1); } } @-webkit-keyframes shrink { from { -webkit-transform: scale(1,1); } to { -webkit-transform: scale(0,0); } } This will successfully scale the element it's applied to, but always from 0 to 1 (or vice-versa). If the shrink keyframe gets applied before the grow keyframe has finished, it has the effect of 'jumping' the scale to 0 before the transform begins. You can see this effect in this jsFiddle showing CSS scale transform on mouseover Notice that if you mouse over the black square and then quickly mouse out, the scale transform is not smooth. What I'm essentially after is something like the following: @-webkit-keyframes grow { from { -webkit-transform: CURRENT_SCALE; } to { -webkit-transform: scale(1,1); } } A: Your animation makes the element go from 0% scale to 100% scale on hover, and from 100% to 0% scale on mouseOut. I think in this case, the solution could be setting the basic scale of the element according to its start point : #output { width: 200px; height: 200px; border-radius: 50%; background: #FF0000; display: inline-block; -ms-transform: scale(0,0); transform: scale(0,0); -webkit-transform: scale(0,0); } In this case, I would harldy recommend using pure CSS solution, using transition on :hover : http://jsfiddle.net/bg6aj/21/ You wont have any "jumping" effect : #output { width: 200px; height: 200px; border-radius: 50%; background: #FF0000; display: block; -ms-transform: scale(0,0); transform: scale(0,0); -webkit-transform: scale(0,0); transition: all .2s; -webkit-transition: all .2s; } #touchPad:hover + #output { -ms-transform: scale(1,1); transform: scale(1,1); -webkit-transform: scale(1,1); } At this point, you'll have no more jumping effect. Then : can we do something like : @-webkit-keyframes grow { from { -webkit-transform: scale(0,0); } to { -webkit-transform: scale(1,1); } } Answer : quite easy : @-webkit-keyframes grow { 0% { -webkit-transform: scale(1,1); } 50% { -webkit-transform: scale(0,0); } 100% { -webkit-transform: scale(1,1); } } Which means: take my element (as scale default is 100%), render it with 0% scale at 50% of the animation, and turn it back at 100%. Trying to set something like current_scale doesn't make sense. Considering that, I'll definitely choose the Transition solution.
Q: Magento 2 - No theme is loading After creating and deploying a new module following this article, no theme loaded anymore. I've tried to change the theme to luma or my custom theme, but there is no effect. What can I do to enable displaying any theme? A: I've found the solution by myself. I compared the \pub\static folder of two magento installations and saw that the htaccess file is missing. After pasting and deploying the static content the themes are displayed correctly.
Q: Redirecting a pageReference according to a picklist value I created a class and include a webservice method that will generate the pdf and attach it to a record, but it's not working when I choose a specific value in the picklist in order to generate the wanted PDF. Custom object: Certificate__c Picklist field: Object__c Any advice? global class AddPdfToRecord{ webservice static void addPDF(list<id> CertificateIds){ //Instantiate a list of attachment object list<attachment> insertAttachment = new list<attachment>(); List<Certificate__c> lstCertif = new List<Certificate__c>(); pageReference pdf; for (Certificate__c Certif: lstCertif){ for(Id CertifId: CertificateIds){ //create a pageReference instance of the VF page if(Certif.Object__c == 'Certificate of employement') { pdf = Page.VFPDF; } else { pdf = Page.VFDS; } //pass the Account Id parameter to the class. pdf.getParameters().put('id',CertifId); Attachment attach = new Attachment(); Blob body; body = pdf.getContent(); attach.Body = body; attach.Name = 'pdfName'+CertifId+'.pdf'; attach.IsPrivate = false; attach.ParentId = CertifId;//This is the record to which the pdf will be attached insertAttachment.add(attach); } } //insert the list insert insertAttachment; } } A: lstCertif is an empty list so the for loop below never executes. List<Certificate__c> lstCertif = new List<Certificate__c>(); pageReference pdf; for (Certificate__c Certif: lstCertif){ ... this code is never called.
Q: Simple image-editing program to add shapes/text to an image that are still editable after saving? If I add text boxes and shapes to an image using Preview.app, save that image, and then close the image window, the next time that I open the image in Preview, all additions are uneditable. Preview saves the edits directly to the image. I am looking for a basic program that can do the same thing as Preview.app (i.e., overlay shapes and text onto an image), except that I need the ability to edit or remove the new image elements later. Adobe Photoshop can accomplish this obviously, but I am looking for something more user-friendly and simple (à la Preview). A: All the software I would normally recommend are probably out of scope considering your comments about Adobe Photoshop, and the fact you're looking for something more user-friendly and simple. Since you just want to be able to annotate an image and then edit this again later, one option for this type of thing is to use MS PowerPoint (which you already have). I've shown many people over the years how they can use PowerPoint and most of them have been happy with the results, so give this a go before you dismiss it. Using MS PowerPoint One feature of MS PowerPoint 2011 and above is that you can group items on the slide and save them as a single image. So, you could do what you want as follows: * *Insert the image into your PowerPoint slide. *Use shapes etc to draw arrows, lines, etc. *Use text boxes to add in your comments. *Format them as necessary (color, line weights, etc). *Select all items (i.e. the image and any shapes, etc.). *Right-mouse-click on your selection and go to Grouping > Group to group them together. *Right-mouse-click on the grouped items and select 'save as picture'. *Select from PNG, JPEG, GIF and BMP for the image format you want (you can also select PDF as an option). *Now also save your PowerPoint presentation. And there you go - you've got yourself an edited (annotated) image you can use that is separate from the original file, and if you save the PowerPoint slide you have a way of going back and editing it again. PowerPoint also gives you some pro editing features such as the ability to arrange items (e.g. Forwards, Backwards, Front, Back) as well as adding shadows, transparencies, etc. If you take the time to really get to know it, you'd be surprised what you can do. I hope you don't mind, but I took the liberty of using your profile pic to do a quick edit with it in PowerPoint just to give you a taste of what's possible. A: You could press Pages or Keynote or PowerPoint into service but for layered document work on the Mac, my favorite apps are: * *Acorn - http://flyingmeat.com/acorn/ *Pixelmator - http://www.pixelmator.com/mac/ Pixelmator seems to be more of a photoshop replacement (which you can rent monthly if you prefer that option) but both are awesome and fully Mac like.
Q: Adaptive Layout of Master/Detail View in Windows 10 UWP I looked around for several days now to find an example on how to create a master/detail view for a Windows 10 UWP app which targets a Windows tablet as well as a Windows phone. The current view already contains a SplitView, which displays the menu on the left hand side. I would like to show the master/detail in the detail view of that SplitView so that on the left hand side there is a ListView/ListBox with all selectable items and a detail view with the details of the currently selected item. Is there a best practice? I'm using Caliburn Micro for my MVVM pattern. A: Template 10 is a complete package but its done almost entirely with the built-ins that Jerry and Co. have come up with over the last few months putting it together. They do have an example of MVVMLight usage with T10. But I understand the draw of using CM. CM is just now getting to the point where Master/Detail with UWP/ SplitView is possible with some of the bugs that came up during the release to 3.0.x sooner or later. There are some gotchas just keep an eye on the examples. I will probably be posting a PR for a Master/Detail shortly but I have a project to complete first. CM with Template 10, there is a huge amount of overlap that would need to be combed over before the would work nicely between each other. Would nice to see it; unfortunately it would be a massive undertaking to get the overlap gap closed.
Q: Using long query method instead of short method for creating database If I want to create a table Many programmers and many of the answers for creating SQLite database uses this method. 1st method private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + contacts + " (" + ID + " INTEGER PRIMARY KEY," + name + " TEXT," + age + " TEXT)"; private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + contacts; public class FeedReaderDbHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "db"; public FeedReaderDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } } using database helper class and etc etc. but I use this method 2nd method db=openOrCreateDatabase("Details",MODE_PRIVATE,null); db.execSQL("CREATE TABLE IF NOT EXISTS contacts(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,name VARCHAR,age VARCHAR,);"); db.execSQL("INSERT INTO contacts (name,age) VALUES('Deepak','age');"); Cursor v= db.rawQuery("Select * from contacts where name='Deepak'",null); Can anyone please tell that this 2nd query method will create any type of problem so that I will soon use the 1st long method.
Q: Show/Hide views I have added a UIView in IB (targetView) and have added 4 labels as subview to this. I have seen it in hierarchy as well. I also have an outlet for this @property (nonatomic, retain) IBOutlet UIView *targetView; I want to show hide this container view (to actually show/hide the 4 labels inside it) I am writing targetView.hidden = YES; But for some reason, it is not working. Please help me. A: More than likely you have not connected your IBOutlet to the UIView in interface builder.
Q: Spring RememberMe processAutoLoginCookie I'm using Spring Security 3.0.0 and persistent RememberMe. When the server restarts and a browser window is still open, we need to be able to continue using the application without having to login - if remember me is selected. I'm getting a org.springframework.security.web.authentication.rememberme.CookieTheftException: Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack, when I try to continue to use the application after a server restart. What I notice is that the processAutoLoginCookie method gets called twice. I'm not sure why. The behavior of the method itself seems to be correct, ie , update the token in the database and update the cookie in the client. Any help on this would be appreciated. Thank you. A: I was getting the exact same issue! The processAutoLoginCookie was getting called twice in succession so that the first call was successful, but the second call fails because the cookie is updated by the first call. My only solution was to subclass PersistentTokenBasedRememberMeServices and override the processAutoLoginCookie method. I had to copy the existing code for processAutoLoginCookie and comment out the throwing of the CookieTheftException. Note: My solution will open up a security hole! If you are happy to allow for Cookie Thefts to occur (my system is used internally and does not contain sensitive data) then this solution will work. Alternatively, you could also subclass PersistentTokenBasedRememberMeServices and add a more robust solution that still checks for Cookie Theft Exceptions but allows the two successive calls to processAutoLoginCookie to be made.
Q: how do i know when I can divide by the highest denominator power? When there are radicals in limits I understand you have to either first * *Divide by highest denominator power *multiply by conjugate $\lim _{x\to \infty }\left(\sqrt{x^2+5x}-x\right)$ solved by multiplying by conjugate $\lim _{t\to \infty \:}\left(\frac{\sqrt{t}+t^2}{6t-t^2}\right)$ solved by dividing by highest denominator power Is it because one has the x in both numerator and denominator? I want to be extra clear on that so I don't do the mistake I have done in the past where I did this... $\lim \:_{x\to \:\infty \:}\left(\sqrt{x^2+5x}-x\right)\:$ $=\:\lim \:_{x\to \:\infty \:}\left(\sqrt{\frac{x^2}{x^2}+\frac{5x}{x^2}}-\frac{x}{x}\right)\:$ $=\:\lim \:\:_{x\to \:\:\infty \:\:}\left(\sqrt{1+\frac{5}{x}}-1\right)\:$ $=\:\sqrt{1+0}-1\:=\:0$ And I was certain I did good :c Edit as im writed this I realized that since is not in a fraction im changing the result by dividing? but what about this? $=\:\lim \:\:_{x\to \:\:\infty \:\:}\left(\frac{\sqrt{\frac{x^2}{x^2}+\frac{5x}{x^2}}-\frac{x}{x}}{\frac{1}{x}}\right)\:$ A: There are many methods for evaluating limits, two of which you mention. Keep in mind you must multiply (or divide) both numerator and denominator by the same thing to preserve the same expression. In your (incorrect) example, you simply divided the whole thing through by $x$, which changes the expression. Here's the quick and dirty for the kinds of examples you mention, where you know one of those two approaches will work and are just trying to decide which one to use in evaluating $\lim_{x\rightarrow \infty}f(x)$: If plugging in $x=\infty$ into the expression gives $\infty-\infty$, then evaluate the limit by multiplying top and bottom by the conjugate. If plugging in $x=\infty$ into the expression gives $\pm \infty/\infty$, then evaluate the limit by dividing top and bottom by the highest degree term. However, I would like to point out there is no one good way to evaluate limits. Rather than memorize rules, just try different approaches; if one approach doesn't help you evaluate a limit, try another (as long as you don't change the original expression as you did in your example!)
Q: Android Application : How do I get touch event on Home Screen when the app in Background Action Using WindowManager, I make the app floaintView in home screen like Facebook Messenger. MotionEvent allows to move the Floated View. I'd like to set up WindowManager Flag and get a touch event for a screen other than Floating, but it's not working... When I touch the floating view, It works well. By calling OnTouchListener, ACTION_DOWN ACTION_UP, When I touch outside the Window( Home Screen), I Want it works well both Doing other Job(Touching other App) and Calling Listener Please anyone guide me how I can get touch event in my app so I can do some task. I used three all flags FLAG_WATCH_OUTSIDE_TOUCH FLAG_NOT_TOUCH_MODAL FLAG_NOT_FOCUSABLE * *FLAG_NOT_FOCUSABLE |FLAG_NOT_TOUCH_MODAL On the Home screen, it touchs of the rest of the window, but fails to invoke the touch of the OnClickListener. *FLAG_WATCH_OUTSIDE_TOUCH Touch other than Floating View is blocked. @SuppressLint("ClickableViewAccessibility") override fun onCreate() { super.onCreate() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startMyOwnForeground() else startForeground( 1, Notification() ) //Inflate the floating view layout we created mFloatingView = LayoutInflater.from(this).inflate(R.layout.test, null) val LAYOUT_FLAG: Int if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY } else { LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE } params = WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, LAYOUT_FLAG, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, PixelFormat.TRANSLUCENT ) //Specify the view position params!!.gravity = Gravity.TOP or Gravity.LEFT //Initially view will be added to top-left corner params!!.x = 0 params!!.y = 100 //Add the view to the window mWindowManager = getSystemService(WINDOW_SERVICE) as WindowManager mWindowManager!!.addView(mFloatingView, params) var test = mFloatingView!!.findViewById<RelativeLayout>(R.id.wrap_container) with(test) { setOnTouchListener(object : View.OnTouchListener { private var initialX = 0 private var initialY = 0 private var initialTouchX = 0f private var initialTouchY = 0f override fun onTouch(v: View?, event: MotionEvent): Boolean { Log.d("aa", "aa") when (event.action) { MotionEvent.ACTION_DOWN -> { Log.d("ACTION_DOWN", "ACTION_DOWN") //remember the initial position. initialX = params!!.x initialY = params!!.y //get the touch location initialTouchX = event.rawX initialTouchY = event.rawY return true } MotionEvent.ACTION_UP -> { Log.d("ACTION_UP", "ACTION_UP") val Xdiff = (event.rawX - initialTouchX).toInt() val Ydiff = (event.rawY - initialTouchY).toInt() //The check for Xdiff <10 && YDiff< 10 because sometime elements moves a little while clicking. //So that is click event. if (Xdiff < 10 && Ydiff < 10) { val intent = Intent(applicationContext, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK intent.putExtra("fromwhere", "ser") startActivity(intent) } return true } MotionEvent.ACTION_MOVE -> { Log.d("ACTION_MOVE", "ACTION_MOVE") //Calculate the X and Y coordinates of the view. params!!.x = initialX + (event.rawX - initialTouchX).toInt() params!!.y = initialY + (event.rawY - initialTouchY).toInt() //Update the layout with new X & Y coordinate mWindowManager!!.updateViewLayout(mFloatingView, params) return true } MotionEvent.ACTION_OUTSIDE -> { Log.d("ACTION_OUTSIDE", "ACTION_OUTSIDE") //Calculate the X and Y coordinates of the view. initialX = params!!.x initialY = params!!.y //get the touch location initialTouchX = event.rawX initialTouchY = event.rawY return true } } return false } }) } } '''
Q: Install Postman native app on Ubuntu 17.04 I am trying to install the Postman native app on a virtual machine with Ubuntu 17.04. I followed the istructions present here and the program won't start up. I installed libgconf-2-4 and now the program starts, but all I get is a black window. Am I missing something? A: It looks like that the problem is generated by chromium inside VirtualBox. Using postman --disable-gpu instead of simply postman solves the issue
Q: When does the long enumeration in this poem starts and ends? The Busy Heart by Rupert Brooke Now that we've done our best and worst, and parted, I would fill my mind with thoughts that will not rend. (O heart, I do not dare go empty-hearted) I'll think of Love in books, Love without end; Women with child, content; and old men sleeping; And wet strong ploughlands, scarred for certain grain; And babes that weep, and so forget their weeping; And the young heavens, forgetful after rain; And evening hush, broken by homing wings; And Song's nobility, and Wisdom holy, That live, we dead. I would think of a thousand things, Lovely and durable, and taste them slowly, One after one, like tasting a sweet food. When does the long enumeration in this poem starts and ends? It seems that the enumeration starts with "Love without end" and then ends with "and Wisdom holy that live, we dead" although I am not sure what "and Wisdom holy, that live, we dead". Can someone rewrite this part in simple English? A: I don't see mention of a 'long enumeration' in the poem. The closest thing to that would seem to be everything after "I'll think of..." up to "... wisdom holy...", i.e. the series of items separated by "and". All those items are direct objects of "I'll think of...". That collection of things amounts to a noun phrase. The poet is saying about those things that they live, although, or after, we are dead. A: None of the other answers have addressed the meaning of that live, we dead. I take it to mean " ... that live (even when) we (are) dead". "We dead" is an absolute clause. In prose it would probably read "we being dead": only in poetry can you get away with omitting the "being".
Q: Unity Android Build Issues I am trying to build a project for Android and just seem to encounter endless stream of errors. I've completely removed the editors, re-installed, updated and still the same issues. All builds for iOS ok and runs in the editor without issue, but I am getting at least 5 errors like this: Building Library/Bee/artifacts/Android/d8kzr/zqff_y-CSharp10.o failed with output: Stack dump: 0. Program arguments: /Applications/Unity/Hub/Editor/2021.3.8f1/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang++ -cc1 -triple aarch64-unknown-linux-android22 -emit-obj -mnoexecstack -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Assembly-CSharp10.cpp -mrelocation-model pic -pic-level 2 -mthread-model posix -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu generic -target-feature +neon -target-abi aapcs -mllvm -aarch64-fix-cortex-a53-835769=1 -fallow-half-arguments-and-returns -dwarf-column-info -debug-info-kind=limited -dwarf-version=4 -debugger-tuning=gdb -target-linker-version 305 -ffunction-sections -fdata-sections -coverage-notes-file /Volumes/Projects/Projects/SampleProject/Library/Bee/artifacts/Android/d8kzr/zqff_y-CSharp10.gcno -resource-dir /Applications/Unity/Hub/Editor/2021.3.8f1/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/darwin-x86_64/lib64/clang/9.0.8 -D __ANDROID_API__=22 -D ANDROID -D HAVE_INTTYPES_H -D BASELIB_INLINE_NAMESPACE=il2cpp_baselib -D IL2CPP_MONO_DEBUGGER_DISABLED -D RUNTIME_IL2CPP -D TARGET_ARM64 -D HAVE_BDWGC_GC -D NDEBUG -I . -I /Volumes/Projects/Projects/SampleProject/Library/Bee/artifacts/Android/il2cppOutput/cpp -I /Applications/Unity/Hub/Editor/2021.3.8f1/Unity.app/Contents/il2cpp/libil2cpp/pch -I /Applications/Unity/Hub/Editor/2021.3.8f1/Unity.app/Contents/il2cpp/libil2cpp -I /Applications/Unity/Hub/Editor/2021.3.8f1/Unity.app/Contents/il2cpp/external/baselib/Include -I /Applications/Unity/Hub/Editor/2021.3.8f1/Unity.app/Contents/il2cpp/external/baselib/Platforms/Android/Include -internal-isystem /Applications/Unity/Hub/Editor/2021.3.8f1/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin/../sysroot/usr/include/c++/v1 -internal-isystem /Applications/Unity/Hub/Editor/2021.3.8f1/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin/../sysroot/usr/local/include -internal-isystem /Applications/Unity/Hub/Editor/2021.3.8f1/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/darwin-x86_64/lib64/clang/9.0.8/include -internal-externc-isystem /Applications/Unity/Hub/Editor/2021.3.8f1/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin/../sysroot/usr/include/aarch64-linux-android -internal-externc-isystem /Applications/Unity/Hub/Editor/2021.3.8f1/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin/../sysroot/include -internal-externc-isystem /Applications/Unity/Hub/Editor/2021.3.8f1/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin/../sysroot/usr/include -Os -Wswitch -Wno-trigraphs -Wno-tautological-compare -Wno-invalid-offsetof -Wno-implicitly-unsigned-literal -Wno-integer-overflow -Wno-shift-negative-value -Wno-unknown-attributes -Wno-implicit-function-declaration -Wno-null-conversion -Wno-missing-declarations -Wno-unused-value -Wno-pragma-once-outside-header -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /Volumes/Projects/Projects/SampleProject -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fwrapv -stack-protector 1 -fno-rtti -fno-signed-char -fobjc-runtime=gcc -fcxx-exceptions -fexceptions -fdiagnostics-show-option -fdiagnostics-format msvc -fcolor-diagnostics -vectorize-loops -vectorize-slp -o Library/Bee/artifacts/Android/d8kzr/zqff_y-CSharp10.o -x c++ /Volumes/Projects/Projects/SampleProject/Library/Bee/artifacts/Android/il2cppOutput/cpp/Assembly-CSharp10.cpp 1. <eof> parser at end of file 2. Code generation 3. Running pass 'Function Pass Manager' on module '/Volumes/Projects/Projects/SampleProject/Library/Bee/artifacts/Android/il2cppOutput/cpp/Assembly-CSharp10.cpp'. 4. Running pass 'CodeGen Prepare' on function '@GifEncoder_GetImagePixels_m5E81065BA3C89066FF3574388B659C8B3C47C0D6' 0 clang++ 0x00000001013e3f98 void std::__1::__call_once_proxy<std::__1::tuple<void (&)()> >(void*) + 452872 1 clang++ 0x00000001013e2fd8 void std::__1::__call_once_proxy<std::__1::tuple<void (&)()> >(void*) + 448840 2 clang++ 0x00000001013e45b9 void std::__1::__call_once_proxy<std::__1::tuple<void (&)()> >(void*) + 454441 3 libsystem_platform.dylib 0x00007ff803d40c1d _sigtramp + 29 4 clang++ 0x00000001009de54d llvm::Pass* llvm::callDefaultCtor<llvm::TargetTransformInfoWrapperPass>() + 9949 5 clang++ 0x0000000000000009 llvm::Pass* llvm::callDefaultCtor<llvm::TargetTransformInfoWrapperPass>() + 18446744069404246425 clang++: error: unable to execute command: Segmentation fault: 11 clang++: error: clang frontend command failed due to signal (use -v to see invocation) Android (6454773 based on r365631c2) clang version 9.0.8 (https://android.googlesource.com/toolchain/llvm-project 98c855489587874b2a325e7a516b99d838599c6f) (based on LLVM 9.0.8svn) Target: aarch64-unknown-linux-android22 Thread model: posix InstalledDir: /Applications/Unity/Hub/Editor/2021.3.8f1/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin clang++: note: diagnostic msg: PLEASE submit a bug report to https://github.com/android-ndk/ndk/issues and include the crash backtrace, preprocessed source, and associated run script. clang++: note: diagnostic msg: ******************** PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT: Preprocessed source(s) and associated run script(s) are located at: clang++: note: diagnostic msg: /var/folders/5j/sbt09jjn3lz1ch1x_l5tlv5h0000gn/T/Assembly-CSharp10-667163.cpp clang++: note: diagnostic msg: /var/folders/5j/sbt09jjn3lz1ch1x_l5tlv5h0000gn/T/Assembly-CSharp10-667163.sh clang++: note: diagnostic msg: Crash backtrace is located in clang++: note: diagnostic msg: /Users/SampleUser/Library/Logs/DiagnosticReports/clang++_<YYYY-MM-DD-HHMMSS>_<hostname>.crash clang++: note: diagnostic msg: (choose the .crash file that corresponds to your crash) clang++: note: diagnostic msg: ******************** UnityEditor.BuildPipeline:BuildPlayer (UnityEditor.BuildPlayerOptions) Google.Android.AppBundle.Editor.Internal.BuildTools.AndroidBuilder:Build (UnityEditor.BuildPlayerOptions) (at Assets/GooglePlayPlugins/com.google.android.appbundle/Editor/Scripts/Internal/BuildTools/AndroidBuilder.cs:178) Google.Android.AppBundle.Editor.Internal.BuildAndRunner:EmulateUnityBuildAndRun () (at Assets/GooglePlayPlugins/com.google.android.appbundle/Editor/Scripts/Internal/BuildAndRunner.cs:91) Google.Android.AppBundle.Editor.Internal.BuildAndRunner:BuildAndRunDefault () (at Assets/GooglePlayPlugins/com.google.android.appbundle/Editor/Scripts/Internal/BuildAndRunner.cs:69) Google.Android.AppBundle.Editor.Internal.BuildAndRunner:BuildAndRun () (at Assets/GooglePlayPlugins/com.google.android.appbundle/Editor/Scripts/Internal/BuildAndRunner.cs:53) Google.Android.AppBundle.Editor.Internal.AppBundleEditorMenu:BuildAndRun () (at Assets/GooglePlayPlugins/com.google.android.appbundle/Editor/Scripts/Internal/AppBundleEditorMenu.cs:72) I've tired downloading SDK/NDK via Android studio and pointing unity at those, and still get 5 - 10 of these error types. A: Seems the only way I can get this to work for now is to export a project that can be opened by Android Studio. It then builds and deploys without issue
Q: Python - How to share list declared in Parent process with all of it's subprocess? I have a parent python script which makes a subprocess call to another python script using Popen 10 times with diff arguments. I want this second script to make changes to a list declared in parent python script. Right now I am doing: p = [Popen("python child.py "+str(i),shell=True) for i in range(10)] for i in p: i.wait() While this solves my purpose, now if I have a list declared before the Popen line and I want to access this list in child.py, how do I do it? I considered using pickle library but opening and closing a file for 10 times(as child.py is called 10 times) will just increase my I/O time which is not desirable.
Q: How does Codeigniter's sess_time_to_update work based on the following question/answer CodeIgniter session class not working in Chrome I had the problem where people are unable to login to my website from another country which is far from the US server. After searching online I've stumbled upon a suggestion which describes how the the problem is based on the difference between the server's timezone and the user's timezone. So, by extending the session_expiration I've managed to get around the problem and people are able to log in successfully. My questions is whether the sess_time_to_update creates a new timestamp and it will logout the user because the new timestamp is in the wrong timezone? Do I have to make the new sess_time_to_update 17+ hours so that it covers the broadest range of timezones as explained in the question that I've linked. Is there some other way of storing the session at the user's browser based on their localtime (without asking them to choose timezones in the profiles and other sorts of user unfriendly schemes). I would like to have a 2h default session expiration time + the 800sec. update time. I'm not using the database to store the session and I would rather not use it. A: The sess_time_to_update setting is how often the session details (such as last activity) are updated. The default is every 5 minutes (300 seconds) and a new session ID will be generated. This would reset the expiration date based on the sess_expiration setting. I would suggest keeping the sess_time_to_update at the default (or lower) as that would keep the user session alive longer since the session expiration would keep getting reset. The only setting that may need to remain high would be sess_expiration, that is unless you can determine the users timezone. There are a couple of ways you could try to determine the users timezone. One would be Javascript (Example: Client Side Timezone Offsetting) or you could try using PHP's GEOIP Methods.
Q: Postgres equivalent of Oracle's VARCHAR2(N CHAR)? We are in the process of migrating our existing Oracle database to Postgres. So far I have found that both VARCHAR2 and NUMBER are not compatible, but have equivalents in VARCHAR and NUMERIC respectively. However in our schema I can also see we are defining some datatypes using VARCHAR2(31 CHAR). Changing this to VARCHAR(31 CHAR) is not compatible with Postgres, as it gives a syntax error on the CHAR part. Is there an equivalent way to define this using Postgres 12? A: Postgres doesn't make a distinction between "char length" and "byte length" when declaring the maximum length of a varchar column. The limit is always specified as the number of characters. So the equivalent of Oracle's VARCHAR2(31 CHAR) is VARCHAR(31) in Postgres. There is however, no equivalent for Oracle's VARCHAR2(31 byte).
Q: Microsoft.CSharp.Core.targets(70,5): Error : Out of memory We have Azure DevOps build pipeline for our ASP.NET Core app, where we get from time to time this error in the build step: ... ##[error]C:\hostedtoolcache\windows\dotnet\sdk\3.1.410\Roslyn\Microsoft.CSharp.Core.targets(70,5): Error : Out of memory. C:\hostedtoolcache\windows\dotnet\sdk\3.1.410\Roslyn\Microsoft.CSharp.Core.targets(70,5): error : Out of memory. [D:\a\1\s\Web\App.WebApi\App.WebApi.csproj] This is our pipeline definition. variables: - name: BuildParameters.RestoreBuildProjects value: '**/App.WebApi.csproj' - name: BuildParameters.TestProjects value: '**/*App.Tests.Unit/*.csproj' trigger: branches: include: - refs/heads/development - refs/heads/master paths: include: - Web/App.WebApi - Libraries - Web/App.Web.Framework - App.Tests.Unit - Libraries/App.Core - Libraries/App.Services - Libraries/App.Data exclude: - Libraries/Tfs - Libraries/SomeService batch: True name: $(date:yyyyMMdd)$(rev:.r) resources: repositories: - repository: self type: git ref: refs/heads/development jobs: - job: Phase_1 displayName: Agent job 1 timeoutInMinutes: 0 pool: vmImage: windows-2019 steps: - checkout: self - task: UseDotNet@2 displayName: Use .Net Core sdk 3.1.x inputs: version: 3.1.410 - task: DotNetCoreCLI@2 displayName: Restore inputs: command: restore projects: $(BuildParameters.RestoreBuildProjects) feedRestore: 50ad9938-c030-4dc7-8391-5b3138b77ae5 - task: gitversion/setup@0 displayName: gitversion/setup inputs: versionSpec: 5.x - task: gitversion/execute@0 displayName: gitversion/execute - task: DotNetCoreCLI@2 displayName: Build inputs: projects: $(BuildParameters.RestoreBuildProjects) arguments: --configuration $(BuildConfiguration) -p:Version=$(GitVersion.SemVer) workingDirectory: Web/App.WebApi ... What could be the reason for this error, as this happens sometimes e.g., every 8th or 10th build ?
Q: How do I escape ${} in my Tridion Component Template that is consumed by multiple templates? I am running into a situation where I have a fied with the value ${test}, in my component template that renders this the value comes out ok the problem comes in when another template calls this component and templates using @@RenderComponentPresentation(Component.ID, MyFirstTemplate)@@ at this point the ${test} is evaluated and because there is no such item on the component or in the package it evaluates to nothing. * *I have Component Template One that reads the value of a Component field (which contains: ${test}) * *This template renders fine, I get back "${test}" *Now I have Component Template Two that calls @@RenderComponentPresentation(Component.ID, ComponentTemplateOne.ID)@@ * *This is where the ${test} now gets evaluated instead of retained so it goes from ${test} to "" because it doesn't find a variable or component field name with that name. *Component Template Two then gets called by Component Template Three in the same way @@RenderComponentPresentation(Component2.ID, ComponentTemplateTwo.ID)@@ * *Since the ${test} has already been evaluated and lost in Component Template Two I no longer end up with ${test} I am still left with "". I have tried: * *@@RenderComponentField('myField', 0, False, False)@@ *@@RenderComponentField('myField', 0, True, False)@@ *@@RenderComponentField('myField', 0, False, True)@@ no luck. The following was my work around and it seems to work: * *Placing the "\" in front of both the open and close curly brace $\{test\} *I need to make sure I remove the "\" after the last Template (Page or Component) executes. *I have in place now a C# TBB that takes the "${test}" and does the following to it: * *Converts the ${test} to $\{test\} in the initial template and a C# TBB on the Page Template that then returns it to the initial value of ${test}. Is there a way to prevent this from happening or a way to avoid doing what i am doing to make this work? A: Have you tried this link , you should be able to this with this link @@"$" + "{" + "test" + "}"@@
Q: Why is "Server's certificate is not trusted" is showing on Android studio? When opening Android Studio for first time it shows this prompt: "Server's certificate is not trusted" Why is it showing in the first place? Should I accept the certificate? Any help would be great. Prompt Server's certificate is not trusted Certificate details Issued To CN (Common Name) *.google.com O (Organization) Google Inc L (Locality) Mountain View C (Country) US ST (State or Province) California Issued By CN (Common Name) Kaspersky Anti-Virus Personal Root Certificate O (Organization) AO Kaspersky Lab Validity Period Valid from: 25/7/08 Valid until: 20/7/28 ... Other Info I recently installed kaspersky free on my device. A: Kaspersky is issuing (and initializing) a personal root certificate upon it's first use with Android Studio (Google Network). Once trusted, Kaspersky should not prompt you again. EDIT: This forum thread has some more information on how to get the root certificate configured for Android Studio (and other applications): https://forum.kaspersky.com/index.php?/topic/307871-kis2015-and-android-studio/
Q: Benefits of using $scope.foo versus foo.vaue In a controller, we can sometimes access inputs values by the value of their DOM id instead of setting an ng-model directive and then binding the DOM value to $scope. For example, in <input type="text" ng-model="foo" id=foo> we can either use $scope.foo or foo.value in the controller. What is the advantage of using $scope in this case? A: I think that the main benefits of using ng-model instead of getting the value of input by id is two-way binding. Your variable from ng-model is always up to date and you can use it directly in html or wherever you want. <input type="text" ng-model="foo" id="fooInput" /> <p>ng-model value: <span ng-bind="foo"></span></p> If you choose approach when you get value from input by id you will lose this feature, but you get a little bit better performance. Because whenever you type into into, it will trigger a $digest cycle causing Angular to update all watchers and bindings in the app to see if anything has changed. A little demo on plunker.
Q: OpenGL: Increasing the number of the lines changes the antialiasing? I am writing a paint program in Delphi. The user clicks 2 points on the screen and a line is drawn between them. I want the lines to be anti-aliased. I put this code in create() procedure of the OpenGL class (which is called just 1 time in the start): glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); When I start drawing, the first, second and maybe the third lines are drawn fine. But interestingly enough, when the number of the lines increases (say 7, 8 lines), the anti-aliasing starts to fail! By adding each line on the screen, it just gets worse and the lines edges starts to become like sawtooth!! I also put the same code on the top of my draw() procedure which draws the lines (and runs by each click of the mouse), but nothing changes. Am I doing something wrong here? Anybody has any suggestion? A: Are You sure You're not drawing any line segment more than once? Do You call glClear before doing any drawing? A: Check the value of GL_SMOOTH_LINE_WIDTH_RANGE and compare it against the glLineWidth()s you're trying to use.
Q: Dynamics CRM 2011 - attach file to email before send I have a pretty standard workflow in my Dynamics CRM 2011, which sends email when new entity is created. Now, before email is sent, I'd like to attach some attachments by plugin. Is it possible to capture some before-send event on email activity, so I could create plugin that before email is sent, do some check on created message, attach files and send it? Edit: Files fetched by web service from another system, they are not attachements of other entities in CRM. A: CRM will create the email and then send it, as two separate actions. So you should be able to add code to a post-create plugin on the email entity which adds the attachment. Presumably your workflow will add some flag to the email so your plugin knows which attachment to add to which email. A: There are two messages on Email entity: Send and SendFromTemplate. You should be able to create PreSend or PreSendFromTemplate plugins and attach files.
Q: How to save settings from an windows form app using a savedialog I have a word search creator app. The user inputs a list of words, width and height settings, word placement settings etc. When the user clicks the save button, I would like for these settings to be saved to a file, so that later the user can open the app with the saved settings. I have no idea how to do this though. (except for opening the savefiledialog) A: Open project properties, and select "settings" on left tab. You can add any settings you want to persist there. Capture whatever setting you want from the user and then do something like: var setting = new Settings(); setting.MyCustomSetting = "UserSeting here"; setting.Save(); These settings are saved in the app.config. A: The SaveFileDialog only provides your application with a GUI Save As window that allows the user to choose a save location and filename. The Dialog comes with an event handler (which I believe is called FileOK) where you can access mySaveFileDialog.Filename . No data or file has actually been saved yet. To do that, you could take a variety of routes, but the simplest is using System.IO.StreamWriter: using System.IO; ... StreamWriter sw = new StreamWriter(mySaveFileDialog.Filename); //Pass the chosen filename sw.WriteLine( string goes here ); sw.Close(); You'll have to come up with a string representation of your data, though. For more complex types, use XML serialization. You can define a data structure as a class and then use .NET's built in System.Xml.Serialization namespace to automatically output a representation of the class to an easy to read XML file: public class MyWordGame { public string[] myWords; public int height; ... } ... XmlSerializer xmlOut = new XmlSerializer(MyWordGame.GetType()); xmlOut.Serialize(new FileStream(mySaveFileDialog.Filename), new MyWordGame()); You can then do the reverse (Deserializing) to recover the original class from an XML file There are plenty of tutorials about XML serialization out there that you should look at.
Q: Computability of Brauer groups A friend of mine and I were talking about computable algebra, and this question came up. The answer may already be known, but I couldn't find it with Google: Suppose I have a countable field, $k$. Then the Brauer group of $k$, $Br(k)$, is also countable. This means that I can talk about the computability-theoretic complexity of $Br(k)$. Specifically, we can define the spectrum of $Br(k)$, denoted $Sp(Br(k))$, to be the set of degrees computing copies of $Br(k)$: $$Sp(Br(k))=\{X: \exists G\le_T X(G\cong Br(k))\}.$$ My question is, how does the complexity of $Br(k)$ in this sense relate to the complexity of $k$? Specifically: (1) If $k$ has a computable copy, does $Br(k)$ have a computable copy? A second question, pointing in the opposite direction: (2) Is there a field $k$ with a computable copy, such that $Sp(Br(k))$ has a least element which is nonzero? EDIT: I should point out that this is a strengthening of "has no computable copy": in particular, there are structures with no computable copy, but such that for every noncomputable set $X$, there is a copy $\mathcal{A}$ which does not compute $X$! (This is the "Slaman-Wehner theorem.") A positive answer to (2) would be a strong negative answer to (1): it would mean that not only does $Br(k)$ not always have to be computable, but we can code some specific non-computable set into $Br(k)$. Okay, so why would anyone care? Well, besides just being generally interested in computable algebra, I'm intrigued by the specific obstacles this question faces. Prima facie, the Brauer group $Br(k)$ is quite complicated: its elements are equivalence classes of central simple algebras. This raises a pair of questions, right off the bat: * *How hard is it to tell that a given (finitely presented) algebra over $k$ is central simple? *How hard is it to tell that two central simple algebras are Brauer equivalent? On the face of it, both of these questions are $\Sigma^1_1$: the former quantifies over ideals, and the latter over isomorphisms. This complexity seems to block any easy approach to getting a positive answer to (1). In fact, my suspicion is that both of these questions are $\Sigma^1_1$-complete, when phrased appropriately. EDIT: Actually, I overestimated the complexity of the first question: "centrality" is at worst $\Pi^0_2$ ("is there an element not in the field which commutes with everything?"), and "simplicity" is also at worst $\Pi^0_2$ ("is there a nonzero $a$ such that there is no witness to $(a)$ containin 1?"). So "is a (code for a) central simple algebra" is at worst $\Pi^0_2$. Still pretty bad, but vastly better. I suspect now that Brauer equivalence may also be substantially simpler than $\Sigma^1_1$. . . However, even knowing that each question is as complicated as possible, we would still not have a negative answer to (1); this is because a presentation of $Br(k)$ is just a presentation of $Br(k)$ as an abstract group, and doesn't tell us anything about which elements correspond to what algebras. So conceivably, identifying central simple algebras is $\Sigma^1_1$-complete, but every computable field has a computable Brauer group. Given that, it seems the best way to get a negative answer to (1) would be to get a positive answer to (2), by coding some specific noncomputable set (let's face it, probably $0'$) into the Brauer group of a computable field. This is the part where, for me, things get really interesting: my limited understanding of algebra suggests that this approach would be extremely difficult. So, in addition to some computability theory and some descriptive set theory, this problem seems to really interact with algebra in a serious way. In particular, to the best of my knowledge computability theory hasn't really been "pointed at" cohomology in a serious way; and this problem looks like a good candidate for that to happen. A: At least for a perfect field that is computable and admits a factorization algorithm (i.e., we have an algorithm to factor polynomials over this field), the Brauer group is computable (in the sense that we can compute with its elements — I'm not claiming to know how to compute, e.g., whether it's trivial or not, only whether a given element is trivial or not). This follows from the fact that every element of the Brauer group of $k$ is torsion, and the $m$-torsion part, for $m$ prime to the characteristic of $k$ (say, $p$), coincides with the Galois cohomology group $H^2(k, \mu_m)$ where $\mu_m$ is the group of $m$-th roots, whereas, if $k$ is perfect, there is no $p$-torsion (where $p$ is the characteristic). For a reference and a proof of these statements, see, for example, Gille & Szamuely's excellent book, Central Simple Algebras and Galois Cohomology, specifically around theorem 4.4.7 and its corollaries (page 99). So now we can represent an element of the Brauer group by an integer $m$, a Galois extension $K$ of $k$ (the Galois group is then computable: see., e.g., Fried & Jarden, Field Arithmetic, lemma 19.3.2), and a 2-cocycle of the Galois group with values in the $m$-th roots of unity, the latter being a finitary object. Such an object can always be lifted to a bigger (i.e., multiple) $m$ or a larger $K$, and if we have two of them, we can find a common $m$ and $K$ for them. (Also, we can dispense with the $m$ and take the degree $[K:k]$ for it, see corollary 4.4.8 in Gille & Szamuely's book.) For a given level, we can take the product (it is simply the product in the $m$-th roots of unity) and test for triviality (everything is finite, so we just test over the finitely many 1-cochains to see whether the given element is a coboundary; the key point here is that triviality can be tested at the level at which the object is given, because the relative Brauer group $H^2(\mathrm{Gal}(K/k), K^\times)$ of $k \subseteq K$ injects in the absolute Brauer group $H^2(k, k^{\mathrm{sep}\times})$: depending on the definition used for the Brauer group, this is either a triviality or a consequence of the inflation-restriction exact sequence and Hilbert's theorem 90 (3.3.14 and 4.3.7 in Gille & Szamuely)). Now in the case of a nonperfect field (of characteristic $p$), concerning the $p$-torsion part of the Brauer group, I'm a bit confused as to what happens. From the long exact sequence in cohomology associated to $1 \to k^{\mathrm{sep}\times} \to k^{\mathrm{sep}\times} \to k^{\mathrm{sep}\times}/(k^{\mathrm{sep}\times})^p \to 1$, the $p$-torsion part of the Brauer group coincides with $H^1(k, k^{\mathrm{sep}\times}/(k^{\mathrm{sep}\times})^p)$. Again, we can represent elements of this profinite group cohomology by seeing them at a finite level (given by a separable extension $K$ of $k$), but now the group $k^{\mathrm{sep}\times}/(k^{\mathrm{sep}\times})^p$ (nonzero elements of the separable closure modulo $p$-th powers) is no longer finite. However, because the theory of separably closed fields of given characteristic and given imperfection degree (=Eršov invariant, =cardinality of a $p$-basis) is complete hence decidable (Marker, Messmer & Pillay, Model Theory of Fields, §3 of Messmer's chapter), I suspect that under some reasonable mild assumptions (perhaps "being given a finite p-basis", see prop. 12.4 in this paper by Fabrice Orgogozo and myself) it is possible to decide whether a 1-cocycle is trivial.
Q: Using Pug to render a component variable that contains HTML code Hi I have an Angular2 app, and in one of the components I have an attribute that I want to display. The problem I have is that I'm using Pug as my template engine and the attribute I'm trying to display contains HTML tags, how can I get Pug to interpret this code as its own syntax? So for example I try to display something like this in my template: p {{attribute}} Where attribute is something like this: <h2>Sample Text.</h2> I've tried this p #{attribute} but it doesn't work. A: Turns out it wasn't a Pug problem and had to be resolved with Angular2 by adding [innerHtml] to the element: p([innerHtml]="attribute")
Q: SNOWFLAKE SQL: How to run several select statement in one command I am a newbie in the SQL world, and hoping SMEs in the community can help me. What I am trying to solve for: Several 'select' statement to run on a weekly basis with one call, and the results gets download to on my computer (bonus if it can be downloaded on specific folder) How I am doing it right now: I use SNOWFLAKE (that's the approved software we are using), Run each 'select' statement one at a time, then once each result is displayed, I manually download the csv file on my computer I know there's an efficient way of doing it, so would appreciate the help from this community. Thank you in advance. A: You can run multiple queries at once using SnowSQL Client. Here's how Preparation: * *Setup SnowSLQL connection configuration * *open file: .snowsql/config *add your connection details: [connections.my_sample_connection] accountname = mysnowflakeaccount username = myusername password = mypassword warehousename = mywarehouse *Create your query file. e.g. my_query.sql -- Query 1 select 1 col1, 2 col2; -- Query 2 select 'a' colA, 'b' colB; Execution: snowsql -c my_sample_connection -f my_query.sql -o output_file=/path/query_result.csv -o timing=false -o friendly=false -o output_format=csv Result: /path/query_result.csv - Containing the result of the queries in my_query.sql
Q: Principle of superposition after using seperation of variables To solve a Partial Differential Equation with solution $ u(x,y) $, I separated $u$ into two variables, $u(x,y) = h(x)g(y)$. For background: the resulting differential equations were: $ \frac{h''}{h} = -\frac{g''}{g} = \lambda$ My solution got: For h: $\lambda = 0 \implies h = c_1$ where $c_1$ is any constant. $\lambda < 0 \implies -\lambda = (\frac{n\pi}{L})^2$ with corresponding eigenfunction $h_n = \cos{(n \pi x / L)} $ for $ n = 1, 2, 3, ...$ For g: $\lambda = 0 \implies$ eigenfunction is $ g = y$ $\lambda < 0 \implies$ eigenfunction is $ g_n = \sinh(n \pi y / L)$ How do I now use the principle of superposition to come up with the next step of a solution? I had thought the answer would be: $u(x,y) = \sum_{n = 1}^{\infty} a_n \cos{(n \pi x / L)} \sinh(n \pi y / L) + \sum_{n = 1}^{\infty} b_n \cos{(n \pi x / L)} y $ But my textbook gives the next step as: $u(x,y) = c_0 y + \sum_{n = 1}^{\infty} a_n \cos{(n \pi x / L)} \sinh(n \pi y / L) $ Why is this? A: By looking at $h$ you have found what the eigenvalues are: $$ \lambda_0=0 ,\qquad \lambda_n=-(n\pi/L)^2 \quad (n \ge 1) . $$ To each eigenvalue you have a corresponding function $h_n(x)$. Then for each eigenvalue you solve $$ g_n''(y)=-\lambda_n g_n(y) ,\qquad g_n(0)=0 , $$ to find $g_n(y$). If you combine $h_n$ and $g_n$, you get a separated solution to the PDE for each $n \ge 0$: $$ u_n(x,y)=h_n(x) \, g_n(x) . $$ These separated solutions are then put together in a linear combination $$ u(x,y) = \sum_{n \ge 0} c_n \, u_n(x,y) , $$ where the constants $c_n$ are chosen such that $u(x,t)$ satisfies the last boundary condition $u(x,H)=f(x)$.
Q: Same IP on many systems in different environments I work in an environment where there are multiple locations, and in each locations we have the same IP addressing scheme, that is, we have many machines (one in each location) that share the same IP address (the hostnames are different though). Naturally, there is no communication between these locations, and also no DNS. I connect to each location in turn, by opening VPN tunnels. My workstation is Linux. I am trying to develop a system to allow me to work as safely as possible in this environment. I would like to use hostnames instead of IP addresses directly, as we have an easy-to-remember naming convention. The problems I have encountered so far are: 1) logging in by mistake to a different machine, because a tunnel was open to the wrong location, and 2) ssh having a different host with the same IP but a different hostname in known_hosts, and refusing to connect. So far, I am thinking of creating a different /etc/hosts and ~/.ssh/known_hosts file for each location (e.g. /etc/hosts.location1), and using a location switching script to automatically switch between these files by copying the version customized for my target location over the default file (e.g. cp /etc/hosts.location1 /etc/hosts). Ideally, this script will eventually be integrated with the software that I use to open VPNs to the different locations. My question is: is there a better way to do this? Is there any functionality in ssh or the linux name resolution that I'm missing out on? Many thanks. Edit: this is a production environment, and I am looking for a workstation solution to this problem. A: You mention that you VPN to each site. Could each site have a DNS server (or two) which have their own site domain (site1.mycorp.com, site2.mycorp.com) and use something like Bind views (http://www.zytrax.com/books/dns/ch7/view.html) to provide IP addresses to named hosts to VPN networks? This way, you could give each host in every site a unique FQDN (barney.site1.mycorp.com and rubble.site2.mycorp.com) and these hosts will only resolve properly when you are VPNed to the correct site and that Bind view responds. In each site, barney.site1.mycorp.com and rubble.site2.mycorp.com could potentially have the same IP address. But they wouldn't resolve externally or if you were connected to the wrong VPN. This isn't so a much a "workstation" solution. But if you have the ability to add nodes (VMs or physical hosts) to each site (which don't necessarily need to be part of production), then this could be a solution. If you already have production DNS that you are comfortable modifying, then you might already be able to leverage views and naming that is present. A: Can you do anything at the remote sites, like drop a file in $HOME or edit bashrc? For instance I have at one site's /etc/bashrc: [ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[SITE1 \u@\h \W]\\$ " which helps avoid ambiguity. You could set your prompt to include cat .site_name for instance, if you can install that file. Also look at using .ssh/config for host name definitions. You can have: Host app1.site1 HostName 10.11.12.13 User service etc. and then use ssh app1.site1 and rely on strict host key checking to keep you safe. I'm assuming that sshd was allowed to create its own host keys. If the machines have identical host keys, then you're going to have trouble with that. Lastly, you could write an ssh wrapper script. Consult the routing table (netstat -nr) to find the VPN endpoints and disallow wrong behavior based on endpoint IP. Roughly: safe_ssh site hostname and besides rotating your known_hosts files, if the destination for your remote network is not for the site value you specified, then bail out with an error message. You could probably work something out with ssh connection multiplexing if you wanted the script to bring up and down the VPN as well. A: Is giving each machine a unique IP (as well as it's common, presumably RFC 1918 IP) a solution? We use this approach, we have a number of machines with a RFC 1918 IP alias, but they all have a unique "public" IP.
Q: How to get an infinite scroll with ListView from Firestore with Flutter I'm working with Firestore and ListView in Flutter. Every works fine for some items in the list, but I scroll down farther than the seen limits, I got many messages: "the method was called on null". Seems that the ListView.builder is not handling correctly all the date request from the Firebase or something like it. This is the code: import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:father_home_flutter/screen_audio_selected.dart'; import 'package:father_home_flutter/model/utils.dart'; class AudioScreenList extends StatelessWidget { static const String _collectionRussian = 'speech-ru'; static const String _loadingTextRussian = 'Loading...'; static const String _speechTitle = 'speechTitle'; static const String _speechSubtitle = 'speechSubtitle'; static const String _audioLink = 'audioLink'; static const String _pastorCode = 'pastorCode'; static const String _pastorName = 'pastorName'; static const String _id = "id"; @override Widget build(BuildContext context) { return Scaffold( body: StreamBuilder( stream: Firestore.instance .collection(_collectionRussian) .limit(100) .orderBy(_id, descending: true) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData) return const Center( child: Text( _loadingTextRussian, style: TextStyle(fontSize: 25.0, color: Colors.grey), )); return ListView.builder( itemCount: snapshot.data.documents.length, itemBuilder: (BuildContext context, int i) => _buildRow(context, snapshot.data.documents[i]), ); })); } Widget _buildRow(BuildContext context, DocumentSnapshot document) { return Container( margin: const EdgeInsets.fromLTRB(0.0, 8.0, 0.0, 0.0), height: 90.0, child: ListTile( leading: Padding( padding: EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 0.0), child: Hero( tag: document[_audioLink], child: new ClipOval( child: Container( width: 70.0, height: 70.0, child: Image.asset( Utils.getImagePastor(document[_pastorCode]), fit: BoxFit.cover, ), )))), title: Text(document[_speechTitle]), subtitle: Text(document[_speechSubtitle] + " - " + document[_pastorName]), onTap: () => onPressed(context, document[_speechTitle], document[_pastorCode], document[_audioLink]))); } onPressed(BuildContext context, String speechTitle, String pastorCode, String audioLink) { Navigator.push( context, MaterialPageRoute( builder: (context) => ScreenAudioSelected(speechTitle, pastorCode, audioLink))); } } and this is the problem on the simulator: I was looking around the web for ways how to handle it, but I just found examples where simulate the server request like this example https://flutter-academy.com/flutter-listview-infinite-scrolling/ Anyone had face the same problem or has an idea about how to solve it?. A: Ok, after looking on the net I found a way to resolve this issue thanks to this link I write here the complete code if someone needs: class AudioScreenList extends StatefulWidget { @override _AudioScreenListState createState() => _AudioScreenListState(); } class _AudioScreenListState extends State<AudioScreenList> { bool isPerformingRequest = false; static const String _collectionRussian = 'speech-ru'; static const String _loadingTextRussian = 'Loading...'; static const String _speechTitle = 'speechTitle'; static const String _speechSubtitle = 'speechSubtitle'; static const String _audioLink = 'audioLink'; static const String _pastorCode = 'pastorCode'; static const String _pastorName = 'pastorName'; static const String _id = "id"; @override Widget build(BuildContext context) { return Scaffold( body: StreamBuilder( stream: Firestore.instance .collection(_collectionRussian) .orderBy(_id, descending: true) .snapshots(), builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) { if (!snapshot.hasData) return const Center( child: Text( _loadingTextRussian, style: TextStyle(fontSize: 25.0, color: Colors.grey), )); return ListView(children: getExpenseItems(snapshot)); })); } getExpenseItems(AsyncSnapshot<QuerySnapshot> snapshot) { return snapshot.data.documents .map((doc) => new Container( margin: const EdgeInsets.fromLTRB(0.0, 8.0, 0.0, 0.0), child: ListTile( leading: Padding( padding: EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 0.0), child: Hero( tag: doc[_audioLink], child: new ClipOval( child: Container( width: 70.0, height: 70.0, child: Image.asset( Utils.getImagePastor(doc[_pastorCode]), fit: BoxFit.cover, ), )))), title: new Text(doc[_speechTitle]), subtitle: new Text(doc[_speechSubtitle].toString() + " - " + doc[_pastorName].toString()), onTap: () => onPressed(context, doc[_speechTitle], doc[_pastorCode], doc[_audioLink])))) .toList(); } onPressed(BuildContext context, String speechTitle, String pastorCode, String audioLink) { Navigator.push( context, MaterialPageRoute( builder: (context) => ScreenAudioSelected(speechTitle, pastorCode, audioLink))); } }
Q: OpenGL + Cloth simulation physics isn't working I am attempting to implement a cloth simulation using a spring-particle system but something isn't quite right with my physics. When I run the simulation the cloth draws as expected but over time the force of gravity pulls the cloth downward indefinitely. In other words the forces caused by the springs are not accumulating properly to overcome the downward pull of gravity and I end up with this...: It continues to droop downwards indefinitely. From all of the debugging I have done what I have seen is that the accumulation of forces on a particle caused by all of the springs attached to it is not properly summing when the force of gravity causes increased stretch. I can not figure out what I have overlooked in my physics. My cloth updates every time step using this function void Cloth::updateGeometry(atlas::utils::Time const& t) { for (int i = 0; i < mSprings.size(); ++i) { mSprings[i].calculateForces(); } for (int i = 0; i < mParticles.size(); ++i) { mParticles[i].updateGeometry(t); } } My springs update using the below function where p1 and p2 are pointers to each particle that this spring is attached to. void Spring::calculateForces() { glm::vec3 springVector = normalize((p2->getCurrentPosition() - p1->getCurrentPosition())); GLfloat stretchLength = length(p2->getCurrentPosition(), p1->getCurrentPosition()); GLfloat displacementFromRest = restLength - stretchLength; glm::vec3 springForce = -k * displacementFromRest * normalize(springVector); //Multiply the displacements by the spring constant to get //A vector which represents the force on each spring p1->addToSumOfSpringForces(springForce); p2->addToSumOfSpringForces(-springForce); } Finally my particles update using. void Particle::updateGeometry(atlas::utils::Time const& t) { if (!stationary) { previousPosition = currentPosition; glm::vec3 forceOfGravity = mass * gravity; glm::vec3 totalForce = forceOfGravity + (mass * totalSpringForces) - velocity*Damping; acceleration = totalForce / mass; //Perform Euler Integration currentPosition += t.deltaTime * velocity; velocity += t.deltaTime * acceleration; //============== End Euler==============// //Reset the forces acting on the particle from all of the springs //So that a new accumulated total can be calculated. totalSpringForces = glm::vec3{ 0.0f, 0.0f, 0.0f }; } } The totalSpringForces variable is updated by the call to addToSumOfSpringForces(springForce); in the spring update function. The idea is that each spring is evaluated first according to the current position of each particle then each particle's totalSpringForcevariable is accumulated each iteration using void Particle::addToSumOfSpringForces(glm::vec3 force) { totalSpringForces += force; } Just to add clarification the cloth is constructed using structural, bend and shear springs in accordance with this description. This may be unneccesary but I've included my cloth constructor below. Cloth::Cloth(GLfloat width_, GLfloat height_, GLuint numParticlesWide_, GLuint numParticlesHigh_) : width(width_), height(height_), numParticlesHigh(numParticlesHigh_), numParticlesWide(numParticlesWide_), clothRotationVector{0.0f, 0.0f, 0.0f}, clothPosition{ 0.0f, 5.0f, 0.0f }, clothRotationAngle(0.0f) { USING_ATLAS_MATH_NS; USING_ATLAS_GL_NS; glm::vec3 clothColour{1.0f, 0.5f, 0.2f}; //Create Particles GLuint count = 0; restLength = (width * (1 / (float)numParticlesWide)); for (GLuint y = 0; y < numParticlesHigh; ++y) { for (GLuint x = 0; x < numParticlesWide; ++x) { glm::vec3 pos = {(width * (x / (float)numParticlesWide)), (-height * (y / (float)numParticlesHigh)), 0.0f}; mParticles.push_back(Particle(pos, count, clothColour)); ++count; } } //Create Springs for (GLuint x = 0; x < numParticlesWide; ++x) { for (GLuint y = 0; y < numParticlesHigh; ++y) { //============ Structural springs ==========// //Connect to the particle to the immediate right of the current particle if (x < numParticlesWide - 1) mSprings.push_back(Spring(getParticle(x,y), getParticle(x+1,y))); //Connect to the particle that is immediately below the current particle if (y < numParticlesHigh - 1) mSprings.push_back(Spring(getParticle(x,y), getParticle(x,y+1))); //============ Shear Springs ================// //Connect the shear springs to make the X pattern if (x < numParticlesWide - 1 && y < numParticlesHigh - 1) { mSprings.push_back(Spring(getParticle(x, y), getParticle(x + 1, y + 1))); mSprings.push_back(Spring(getParticle(x+1, y), getParticle(x, y+1))); } //============ Bend Springs ===============// //Connect the current particle to the second particle over to the right if (x < numParticlesWide - 2) mSprings.push_back(Spring(getParticle(x,y), getParticle(x+2,y))); //Connect the current particle to the particle two below if (y < numParticlesHigh - 2) mSprings.push_back(Spring(getParticle(x,y), getParticle(x, y+2))); ////Create the X pattern //if (x < numParticlesWide - 2 && y < numParticlesHigh - 2) { // mSprings.push_back(Spring(getParticle(x, y), getParticle(x+2,y+2))); // mSprings.push_back(Spring(getParticle(x+2,y), getParticle(x,y+2))); //}; } } //Set the top left and right as stationary getParticle(0, 0)->makeStationary(); getParticle(numParticlesWide - 1, 0)->makeStationary(); //Make Indices for Particles for (GLuint row = 0; row < numParticlesWide - 1; ++row) { for (GLuint col = 0; col < numParticlesHigh - 1; ++col) { //Triangle one mParticleIndices.push_back(getParticle(row,col)->getIndex()); mParticleIndices.push_back(getParticle(row,col+1)->getIndex()); mParticleIndices.push_back(getParticle(row+1, col)->getIndex()); //Triangle two mParticleIndices.push_back(getParticle(row, col+1)->getIndex()); mParticleIndices.push_back(getParticle(row+1, col+1)->getIndex()); mParticleIndices.push_back(getParticle(row+1, col)->getIndex()); } } glGenBuffers(1, &clothVertexBufferID); glGenBuffers(1, &clothIndexBufferID); sendDataToGPU(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, clothIndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, mParticleIndices.size() * sizeof(GLushort), &mParticleIndices[0], GL_STATIC_DRAW); defineVAO(); std::string shaderDir = generated::ShaderPaths::getShaderDirectory(); std::vector<ShaderInfo> shaders { { GL_VERTEX_SHADER, shaderDir + "Cloth.vs.glsl" }, { GL_FRAGMENT_SHADER, shaderDir + "Cloth.fs.glsl" } }; mModel = glm::translate(Matrix4(1.0f), clothPosition); mShaders.push_back(ShaderPointer(new Shader)); mShaders[0]->compileShaders(shaders); mShaders[0]->linkShaders(); mUniforms.insert(UniformKey("mvpMat",mShaders[0]->getUniformVariable("mvpMat"))); mShaders[0]->disableShaders(); } EDIT I have verified that the totalSpringForcesvariable is indeed changing. I added a print statement in my Particle update function which you can see in the image below. The selected the totalSpringForces for only particle #55 which in this case is the particle immediately under particle 0 which is stationary and not allowed to move. Also the printout is after about 20-25 iterations. As you can see the totalSpringForcesin the y direction has positive value of 0.7037 (i.e. is counteracting gravity). I let it run for half an hour and it only got to 5. Currently my constants are k = 2.0f mass = 0.1f damping = 0.55f gravity{ 0.0f, -9.81f, 0.0f },
Q: how to get array input values into database using angularjs and PHP I have a form in which on click of button input fields get appended. The form is as below. <body data-ng-app="myApp" data-ng-controller="myController" > <form name="educdetailsform" novalidate> <label>Education Details</label></br> <button ng-click="addfield()">Add Education</button> <div ng-repeat="item in items"> <input type="text" name="qualification[]" data-ng-model="empData.qualification[]" placeholder="Qualification"> <input type="text" name="year[]" data-ng-model="empData.year[]" placeholder="Year of Passing"> <input type="text" name="percentage[]" data-ng-model="empData.percentage[]" placeholder="Percentage"> </div> <input type="submit" name="submit" ng-click="saveUser()" /> </form> </body> The angular JS code for appending input fields is as follows var module=angular.module('myApp',[]); module.controller('myController',function($scope, $http){ $scope.items = [{}]; $scope.addfield = function(){ $scope.items.push({}); } }); This is the code and functionality http://jsfiddle.net/b0jtqzpj/2/ How to get the fields to saveUser() function and then save the data into database table using PHP Like, if the user has entered 3 entries i.e, the first entry must be saved in a row and 2nd entry in next row and 3rd entry in 3rd row. i.e, if 3 entries are entered in html form and submitted, 3 entries must be created in database table. How do I catch data in angularjs saveUser() function and then save in database using PHP A: You can check js fiddle http://jsfiddle.net/ss5yo9xk/4/ for making ajax call and you need to use below code at php side to get post data : $postData = json_decode(file_get_contents('php://input'), true);
Q: Raspberry Pi - How to do other things while preview is running? I am currently writing a script that creates a GUI (writing it with Tkinter) that does a bunch of things. Among them is the ability to start previewing with the camera, and then being able to move this motor forwards and backwards at will. Unfortunately, the preview blocks me from doing anything else with the GUI as it is running, is there any way around it? In my ideal world, you can press the GUI buttons to move the motor forward and backward with the preview running in the background and providing you with active feedback. Here is some of my code: def motorOut(): backwards(int(delayf) / 1000.0, int(stepsf)) setStep(0,0,0,0) def motorIn(): forward(int(delayb) / 1000.0, int(stepsb)) setStep(0,0,0,0) def cameraPreview(): camera.start_preview(fullscreen=False, window = (400, 240, 400, 240)) sleep(20) camera.stop_preview() Thanks for any help! A: It is likely not the preview that is blocking your program, but using sleep(20). Whilst the 'sleep' is occurring, nothing else can process. This causes the block you are noticing. You could fix this by removing that line, and instead binding the camera.stop_preview() to an event (such as a key press). This could look like: root.bind("<space>", lambda e: camera.stop_preview()) Where root is what you define as your access to Tk(). lambda e: specifies an inline function expression, where e is the event object passed.
Q: Drupal: how to set collapsed property for edit-content fields is there any interface to decide which fields should be collapsed and which ones not in content pages ? i.e. Tags is collapsed Menu Settings is expanded, Authoring is expanded.. I would like the opposite. thanks Updated: Taxonomy super-select field (how can I refer to this field ('taxonomy' is not working)) <div class="taxonomy-super-select-checkboxes"><fieldset class=" collapsible collapsed"><legend class="collapse-processed"><a href="#">Tags</a></legend><div class="fieldset-wrapper"><div id="edit-taxonomy-tags-1-wrapper" class="form-item"> <label for="edit-taxonomy-tags-1">Enter New Tags: </label> <input type="text" class="form-text form-autocomplete" value="" size="60" id="edit-taxonomy-tags-1" name="taxonomy[tags][1]" maxlength="1024" autocomplete="OFF"> <div class="description">A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".</div> </div><input type="hidden" disabled="disabled" value="http://localhost/drupal/taxonomy/autocomplete/1" id="edit-taxonomy-tags-1-autocomplete" class="autocomplete autocomplete-processed"><div id="edit-taxonomy-1-20-wrapper" class="form-item"> <label for="edit-taxonomy-1-20" class="option"><input type="checkbox" class="form-checkbox" value="20" id="edit-taxonomy-1-20" name="taxonomy[1][20]"> Tag1</label> </div></div> </fieldset> </div> A: the interface to Drupal's collapsible fieldsets is the Drupal Forms API #collapsed property. if this property is set to TRUE, the fieldset is collapsed, and vice versa. to change the defaults, don't hack core files, but do it (one of) the Drupal way(s) and add this to your template.php: function phptemplate_node_form($form) { $form['taxonomy']['#collapsed'] = false; $form['menu']['#collapsed'] = true; $form['author']['#collapsed'] = true; // etc. for all fieldsets you want to change return drupal_render($form); } after this, you should clean the theme registry.
Q: How 2d array is assign to 1D array? I am using apache commons-math library to calculate regression parameter. As shown in figure 2nd and 3rd line, a 2d array is assigned to single array. When i use same code, I am getting error: "Type mismatch error:cannot convert from double [][] to double []" in 3rd line but not for 2nd line. OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression(); double[] y = new double[]{11.0, 12.0, 13.0, 14.0, 15.0, 16.0}; double[] x = new double[6][]; x[0] = new double[]{0, 0, 0, 0, 0}; x[1] = new double[]{2.0, 0, 0, 0, 0}; x[2] = new double[]{0, 3.0, 0, 0, 0}; x[3] = new double[]{0, 0, 4.0, 0, 0}; x[4] = new double[]{0, 0, 0, 5.0, 0}; x[5] = new double[]{0, 0, 0, 0, 6.0}; regression.newSample(y, x); why this is happening? and how this works? More details on OLS regression are given here A: Case 1 : double[] y = new double[]{11.0, 12.0, 13.0, 14.0, 15.0, 16.0}; You are creating a 1D array with values inserting it right away. Works fine Case 2 : double[] x = new double[6][]; You are declaring a 1D array and trying to assign a 2D array. Which is illegal. Either change your declaration to 2D or initialize with 1D valid declarations will be double[] x = new double[6]; // 1D or double[][] x = new double[6][lenghtYouWant]; //2D After seeing the insertions later on you are wanting a 2D array. To compile the below code successfully you need to change the delcaration to double[][] x = new double[6][];
Q: OutofMemoryError when running Junit Test case I am running Junit test case in Jenkins through build.xml. When I run a particular test case I get the below error. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> <title>Error 500 Java heap space</title> </head> <body><h2>HTTP ERROR 500</h2> <p>Problem accessing /url. Reason: <pre> Java heap space</pre></p><h3>Caused by:</h3><pre>java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:2882) at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:100) at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:390) at java.lang.StringBuilder.append(StringBuilder.java:119) at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Long.parseLong(Long.java:410) at java.lang.Long.valueOf(Long.java:525) at org.codehaus.jettison.mapped.DefaultConverter.convertToJSONPrimitive(DefaultConverter.java:39) at org.codehaus.jettison.mapped.MappedNamespaceConvention.convertToJSONPrimitive(MappedNamespaceConvention.java:282) at org.codehaus.jettison.mapped.MappedXMLStreamWriter$JSONPropertyObject.withProperty(MappedXMLStreamWriter.java:153) at org.codehaus.jettison.mapped.MappedXMLStreamWriter$JSONProperty.withProperty(MappedXMLStreamWriter.java:66) at org.codehaus.jettison.mapped.MappedXMLStreamWriter.writeEndElement(MappedXMLStreamWriter.java:247) at com.sun.xml.bind.v2.runtime.output.XMLStreamWriterOutput.endTag(XMLStreamWriterOutput.java:144) at com.sun.xml.bind.v2.runtime.output.XmlOutputAbstractImpl.endTag(XmlOutputAbstractImpl.java:120) at com.sun.xml.bind.v2.runtime.XMLSerializer.leafElement(XMLSerializer.java:326) at com.sun.xml.bind.v2.model.impl.RuntimeBuiltinLeafInfoImpl$StringImplImpl.writeLeafElement(RuntimeBuiltinLeafInfoImpl.java:1041) at com.sun.xml.bind.v2.model.impl.RuntimeBuiltinLeafInfoImpl$StringImplImpl.writeLeafElement(RuntimeBuiltinLeafInfoImpl.java:1020) at com.sun.xml.bind.v2.runtime.reflect.TransducedAccessor$CompositeTransducedAccessorImpl.writeLeafElement(TransducedAccessor.java:252) at com.sun.xml.bind.v2.runtime.property.SingleElementLeafProperty.serializeBody(SingleElementLeafProperty.java:121) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:340) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:696) at com.sun.xml.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:152) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:340) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:696) at com.sun.xml.bind.v2.runtime.property.ArrayElementNodeProperty.serializeItem(ArrayElementNodeProperty.java:65) at com.sun.xml.bind.v2.runtime.property.ArrayElementProperty.serializeListBody(ArrayElementProperty.java:168) at com.sun.xml.bind.v2.runtime.property.ArrayERProperty.serializeBody(ArrayERProperty.java:155) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:340) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsSoleContent(XMLSerializer.java:593) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:324) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:494) at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:315) Below is the build.xml code I use to run the junit testcase build.xml <target name="runTests"> <junit fork="yes" forkmode="once" printsummary="yes" dir="${basedir}" includeantruntime="yes" failureproperty="failureTest" maxmemory="1024m" jvm=""> <jvmarg value="-XX:MaxPermSize=512M"/> <jvmarg value="-Dlog4j.configuration=log4j.properties"/> But this error is occurring only in specific system, not in all the environments. How can I get rid of this? A: Without looking at the tests, it is really hard to help you but my guess is that whatever you are working with is large especially if it involves building strings. A few suggestions could help you: * *Try to use the StringBuilder class to build the response. I noticed that it makea a huge difference over using the "+" sign when building a large string. *Increase the memory available to eclipse in the eclipse.ini. A good explanation can be found in this link. I would try to inspect and change the code instead of changing the memory settings. As much as you can increase the memory disposed to the JVM, there is a reason why the initial memory settings are small. I think it is because developers should not just write memory run-away programs but should take care to architect programs that run on most environments, including the memory constrained ones. A: Starting from the stacktrace of an OOM is in most of the cases misleading, because once the heap gets almost full, any object allocation might be the one that fails. Increasing the heap might help, but your usecase (testing some validations as you mentioned in a comment) sounds like it shouldn't require gigs of ram. If you want a quick answer, use some tooling. Include the JVM arg: <jvmarg value="-XX:+HeapDumpOnOutOfMemoryError"/>, and once the heap is dumped open it in the Eclipse Memory Analyzer Tool to see what is eating up the memory. It's a very nice tool with which you can spot the problem in minutes (for the simpler cases). One tip: if your test classes use the SpringJUnit4ClassRunner to load a test context, Spring will cache all contexts loaded during the run. If you have a dozen integration tests with different contexts, you have a good chance of running out of that 512m heap. A: Please try increasing your heapspace?
Q: copying link id to an input field The code works fine when links are images. But I have a problem when there are flash movies. Another page opens with undefined in the address bar when it needs to copy the link id to imagesID input box. <script type="text/javascript"> var $input = $("#imagesID"); // <-- your input field $('a.thumb').click(function() { var value = $input.val(); var id = $(this).attr('id'); if (value.match(id)) { value = value.replace(id + ';', ''); } else { value += id + ';'; } $input.val(value); }); </script> <ul class="thumbs"> <li> <a class="thumb" id="62"> <img src="/FLPM/media/images/2A9L1V2X_sm.jpg" alt="Dock" id="62" class="floatLeft" /> </a> <br /> <a href="?Process=&IMAGEID=62" class="thumb"><span class="floatLeft">DELETE</span></a> </li> <li> <a class="thumb" id="61"> <img src="/FLPM/media/images/0E7Q9Z0C_sm.jpg" alt="Desert Landscape" id="61" class="floatLeft" /> </a> <br /> <a href="?Process=&IMAGEID=61" class="thumb"><span class="floatLeft">DELETE</span></a> </li> <li> <a class="thumb" id="60"> <img src="/FLPM/media/images/8R5D7M8O_sm.jpg" alt="Creek" id="60" class="floatLeft" /> </a> <br /> <a href="?Process=&IMAGEID=60" class="thumb"><span class="floatLeft">DELETE</span></a> </li> <li> <a class="thumb" id="59"> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://active.macromedia.com/flash4/cabs/swflash.cab#version=4,0,0,0" id="59" width="150" height="100" style="float:left; border:5px solid #CCCCCC; margin:5px 10px 10px 0;"> <param name="scale" value="exactfit"> <param name="AllowScriptAccess" value="always" /> <embed name="name" src="http://www.refinethetaste.com/FLPM/media/flashes/7P4A6K7M.swf" quality="high" scale="exactfit" width="150" height="100" type="application/x-shockwave-flash" AllowScriptAccess="always" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi? P1_Prod_Version=ShockwaveFlash"> </embed> </object> </a> <br /> <a href="?Process=&IMAGEID=59" class="thumb"><span class="floatLeft">DELETE</span></a> </li> </ul> A: Not all of your a.thumb elements have id attributes, most notably the one associated with the flash object. A: * *You have some links with class "thumb", that don't have an ID or a href, but that will be called from your query code *IDs may not start with an integer *IDs must be unique within the document, which is not the case A: Have you tried preventing the default browser action? $('a.thumb').click(function(event) { event.preventDefault(); // ... snip ... }
Q: How to include padding on a span element that has multiple lines jsfiddle here. I have a span element that is highlighted using background-color: yellow and padding: 1px 10px. However, on smaller devices, this line of text becomes two lines, three lines, etc. This causes the first and second lines to 'lose' the padding on the right side, such as the words "the" and "to", and the second and third lines to 'lose' the padding on the left side, such as the words "highlight" and "better" in the picture below: How can I ensure these words (in the picture above, "the", "highlight", "to", "better") and all other words keep this 10px padding on the left and right side? Someone in response to a similar question suggested using display: block, but this makes the span no longer a span, just a rectangle and that is not how I need it to look. It also makes the highlight span the entire width of the page. A: Use the box-decoration-break CSS. span { background-color:yellow; padding:1px 10px; box-decoration-break: clone; -webkit-box-decoration-break:clone; } This applies the styles to every box fragment in your span. A: You can try faking the background when the span is broken by using box-shadow. Try something like this and see if it works for you: span { background-color: yellow; padding: 1px 0; box-shadow: 10px 0 0 0 yellow, -10px 0 0 0 yellow; } <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam a nisi ipsum. Mauris convallis dapibus diam ac sollicitudin. Vivamus varius nulla magna, ac rutrum nulla accumsan quis. Duis placerat, elit non posuere elementum, tellus massa pellentesque nunc, eu maximus ligula metus non dui. Sed accumsan quam nec sodales sagittis.</span> A: To include as much as possible browsers , you could relay on position:relative and use 2 inline tag inbricated to mimick the desired result. mind that some margins or padding should be considerate to keep inbound the translated element via position. example to show the idea p {/* make the text wrap*/ width:15em; margin:2em; } span { background:yellow; /* increase line height for better reading : optionnal*/ line-height:1.35em; padding: 0.25em 0; } span span { /* move child 1em to left to fake padding */ position:relative; left:1em;/* value of your left alike padding*/ } /* eventually on the last line ? */ span span:after { content:''; padding:0.25em; } <p> <span> <span>This sentence <del> has some padding</del> to make the highlight appear thicker. These are more words to better explain. </span> </span> </p> https://jsfiddle.net/ynh35sL5/3/ This is not the best , extra HTML for styling ... spans are neutral :( A: just wrap it in a container div and put the horizontal padding on that element since that's what you actually want: <div class="span-container><span>my text</span></div> .span-container { padding: 0 10px; } .span-container span { background-color: yellow; padding: 1px 0; } here's a fiddle demonstrating that this achieves exactly what you want without work arounds that don't work in every browser: https://jsfiddle.net/xg1bkgmn/ span is an inline element, it makes sense to use it for your case of highlighting only the text and widening the lines. However, to keep the entire thing padded, it needs a block element container, this is standard practice. Why go with more complicated CSS when the solution is this simple?
Q: Overvoltage protection when going from 24V AC to 3.3V DC I'm trying to wrap my head around transient voltage protection and how to implement it when also trying to rectify a AC source to DC then step it down to 3.3V for a microcontroller. I understand that MOVs are great for high voltage and AC, where as Zener diodes are good for low power DC overvoltage protection. My problem is that I have an 24V AC source which tends to be rather noisy and can spike due to solenoids and motors sharing the same rail. This is unfortunately out of my control. Obviously, surge protection is required, but how to implement it escapes me. I haven't been able to measure how high these surges get but I assume they are higher then the 40V max of the LM2596. My current thinking, as illustrated by the diagram, is to take the 24V AC in then have a MOV to take any major spikes out. Once this is done then rectify the AC current to DC and have a second transient voltage suppressor in the form of a Zener diode. This diode has a reverse voltage of 39V which is lower then the max input of the LM2596 which is 40V. I have read that I might need to add a resistor to this Zener to reduce the load, but what load would be on the diode in a surge event? I know my max load on the 3.3V side of the regulator is 1A, however nominally around 400mA. My real question is then, is my thinking correct or have I miss understood how to protect the circuit? If so, what do I need to look at/change to achieve my goal? A: 24VAC only has a peak voltage of 33.9V (24*1.414) So I the specified MOV looks reasonable. You get two diode drops with the bridge (-1.4) so 33.9 becomes 32.5Vdc. Instead of a zener here, I would pick a TVS diode (Transient Voltage Suppressor). They are fast and able to take large transients and have finer voltage resolution choices when compared to zener diodes. You can easily get one that is designed to stand off 33V all day long and starts conducting around 36V. Also, if you have the space, I would use parallel input caps instead of one large one. Each one has ESR (series resistance) and so the more you parallel them the lower the overall ESR becomes. And that enables the input cap to also slow down/prevent noise as well. Recall from physics that you can not change the voltage on a capacitor instantaneously, instead it must charge up over time. Don't worry about anything downstream of the power supply. With the two/three protection devices in place, then the regulator will do its job and take anything from up to 40V and turn it into 3.3V.
Q: PCR (Dollar-weighted Put Call Ratio) calculation issues I am trying to generate a Put / Call Ratio calculation program for my own purpose. Here is the code: problem is I am stuck in some places. * *I need to generate a summation of all strikes volume * all strikes prices *and final one is generating the ratio i.e. summation (all strikes PUT volume * all strikes PUT prices) / summation(all strikes Call volume * all strikes Call prices). So far I tried a lot and ended up having buggy program. However I am providing the code for now for further so that I can complete the rest of the part get the OutPut properly. (nse does not provide PCR as CBO does provide a solution.) from nsepy import get_history from datetime import date import pandas as pd import requests from io import BytesIO import certifi from scipy import stats from dateutil.relativedelta import relativedelta import numpy as np #import matplotlib.pyplot as plt import datetime import numpy as np import matplotlib.colors as colors import matplotlib.finance as finance import matplotlib.dates as mdates import matplotlib.ticker as mticker import matplotlib.mlab as mlab import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager import talib as ta from talib import MA_Type import statsmodels as sm nf_calls=[] nf_puts=[] #nf_calls[['VolumeCalls']]=np.nan #nf_puts[['VolumeCalls']]=np.nan i=min_avalable_strikes=4850 max_avalable_strike=9400 wPCR=nf_opt_CE=nf_opt_PE=pd.DataFrame() while i in range(min_avalable_strikes,max_avalable_strike): temp_CE = get_history(symbol="NIFTY", start=date(2016,2,1), end=date(2016,4,24), index=True, option_type="CE", strike_price=i, expiry_date=date(2016,4,28)) #print(nf_opt_CE.head()) #if nf_opt_CE['Number of Contracts'].values >0 : '''if nf_opt_CE.empty : nf_opt_CE.append(0) ''' temp_PE = get_history(symbol="NIFTY", start=date(2016,2,1), end=date(2016,4,22), index=True, option_type="PE", strike_price=i, expiry_date=date(2016,4,28)) #nf_opt_PE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True) #nf_opt_CE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True) #temp_CE=temp_CE.drop(temp_CE[temp_CE['Number of Contracts']>0.0].index) #temp_PE=temp_PE.drop(temp_CE[temp_CE['Number of Contracts']>0.0].index) nf_opt_CE=pd.concat([nf_opt_CE,temp_CE]).drop_duplicates() nf_opt_PE=pd.concat([nf_opt_PE,temp_PE]).drop_duplicates() nf_opt_CE.index=pd.to_datetime(nf_opt_CE.index) nf_opt_PE.index=pd.to_datetime(nf_opt_PE.index) i=i+50 #print(i) #print(nf_opt_PE.head()) nf_opt_PE.drop_duplicates(inplace=True) nf_opt_CE.drop_duplicates(inplace=True) #print(nf_opt_PE.head(100)) nf_opt_PE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True) nf_opt_CE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True) nf_opt_PE.drop(['Symbol','Expiry','Open','High' ,'Low','Last','Settle Price','Turnover','Premium Turnover','Open Interest' ,'Change in OI','Underlying'],axis=1,inplace=True) nf_opt_CE.drop(['Symbol','Expiry','Open','High' ,'Low','Last','Settle Price','Turnover','Open Interest','Premium Turnover' ,'Change in OI','Underlying'],axis=1,inplace=True) nf_opt_PE = nf_opt_PE[nf_opt_PE.Volume > 0] nf_opt_CE = nf_opt_CE[nf_opt_CE.Volume > 0] #print(nf_opt_PE.tail()) ##priceCrossVolume### nf_opt_PE['VolCrossPrice']=nf_opt_PE.apply(lambda x: (x['Volume']*x['Close']),axis=1) nf_opt_CE['VolCrossPrice']=nf_opt_CE.apply(lambda x: (x['Volume']*x['Close']),axis=1) #nf_puts= nf_opt_CE['Number of Contracts']*nf_opt_CE['Close'] #print(nf_calls.head()) nf_opt_PE.drop(['Volume','Close'],axis=1,inplace=True) nf_opt_CE.drop(['Volume','Close'],axis=1,inplace=True) #print(nf_opt_PE.index.Date) #nf_opt_PE['Summation']=nf_opt_PE.groupby(nf_opt_PE.columns[[0]])['VolCrossPrice'].sum() wPCR=pd.concat([nf_opt_PE,nf_opt_CE]) #wPCR.drop(['Volume','Close'],axis=1,inplace=True) #wPCR['Summation']=wPCR.groupby(wPCR.columns[[0,1]]).sum() wPCR['Summation']=wPCR[['Option Type'] == wPCR['Option Type']].groupby(level=0).sum() print(nf_opt_PE.head(500)) print(wPCR.tail(500)) Encountered Error: Traceback (most recent call last): File "PCRForNF.py", line 101, in <module> wPCR['Summation']=wPCR[['Option Type'] == wPCR['Option Type']].groupby(level=0).sum() File "/usr/local/lib/python2.7/dist-packages/pandas/core/ops.py", line 761, in wrapper res = na_op(values, other) File "/usr/local/lib/python2.7/dist-packages/pandas/core/ops.py", line 677, in na_op result = lib.vec_compare(x, y.astype(np.object_), op) File "pandas/lib.pyx", line 828, in pandas.lib.vec_compare (pandas/lib.c:14760) ValueError: Arrays were different lengths: 3030 vs 1 I am assuming the error is in: wPCR['Summation']=wPCR[['Option Type'] == wPCR['Option Type']].groupby(level=0).sum() Can anyone suggest a simple way to find the proper weighted PCR from here? A: from nsepy import get_history from datetime import date import pandas as pd import requests from io import BytesIO import certifi from scipy import stats from dateutil.relativedelta import relativedelta import numpy as np #import matplotlib.pyplot as plt import datetime import numpy as np import matplotlib.colors as colors import matplotlib.finance as finance import matplotlib.dates as mdates import matplotlib.ticker as mticker import matplotlib.mlab as mlab import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager import talib as ta from talib import MA_Type import statsmodels as sm nf_calls=[] nf_puts=[] #nf_calls[['VolumeCalls']]=np.nan #nf_puts[['VolumeCalls']]=np.nan i=min_avalable_strikes=4850 max_avalable_strike=9400 nf_opt_CE=nf_opt_PE=pd.DataFrame() while i in range(min_avalable_strikes,max_avalable_strike): temp_CE = get_history(symbol="NIFTY", start=date(2016,2,1), end=date(2016,4,24), index=True, option_type="CE", strike_price=i, expiry_date=date(2016,4,28)) #print(nf_opt_CE.head()) #if nf_opt_CE['Number of Contracts'].values >0 : '''if nf_opt_CE.empty : nf_opt_CE.append(0) ''' temp_PE = get_history(symbol="NIFTY", start=date(2016,2,1), end=date(2016,4,22), index=True, option_type="PE", strike_price=i, expiry_date=date(2016,4,28)) #nf_opt_PE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True) #nf_opt_CE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True) #temp_CE=temp_CE.drop(temp_CE[temp_CE['Number of Contracts']>0.0].index) #temp_PE=temp_PE.drop(temp_CE[temp_CE['Number of Contracts']>0.0].index) nf_opt_CE=pd.concat([nf_opt_CE,temp_CE]).drop_duplicates() nf_opt_PE=pd.concat([nf_opt_PE,temp_PE]).drop_duplicates() nf_opt_CE.index=pd.to_datetime(nf_opt_CE.index) nf_opt_PE.index=pd.to_datetime(nf_opt_PE.index) i=i+50 #print(i) #print(nf_opt_PE.head()) nf_opt_PE.drop_duplicates(inplace=True) nf_opt_CE.drop_duplicates(inplace=True) #print(nf_opt_PE.head(100)) nf_opt_PE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True) nf_opt_CE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True) nf_opt_PE.drop(['Symbol','Expiry','Open','High' ,'Low','Last','Settle Price','Turnover','Open Interest' ,'Change in OI','Underlying'],axis=1,inplace=True) nf_opt_CE.drop(['Symbol','Expiry','Open','High' ,'Low','Last','Settle Price','Turnover','Open Interest','Change in OI','Underlying'],axis=1,inplace=True) nf_opt_PE = nf_opt_PE[nf_opt_PE.Volume > 0] nf_opt_CE = nf_opt_CE[nf_opt_CE.Volume > 0] #print(nf_opt_PE.tail()) ##priceCrossVolume### nf_opt_PE['PESum']=nf_opt_PE.groupby(level=0)['Premium Turnover'].sum() nf_opt_CE['CESum']=nf_opt_CE.groupby(level=0)['Premium Turnover'].sum() #nf_puts= nf_opt_CE['Number of Contracts']*nf_opt_CE['Close'] #print(nf_calls.head()) nf_opt_PE.drop(['Volume','Close'],axis=1,inplace=True) nf_opt_CE.drop(['Volume','Close'],axis=1,inplace=True) #print(nf_opt_PE.index.Date) #nf_opt_PE['Summation']= wPCR= (nf_opt_PE['PESum']/nf_opt_CE['CESum']) #wPCR.rename(columns = {'0':'wPCR'}, inplace = True) wPCR.plot() plt.show() #print(wPCR.head(500)) #print(nf_opt_PE.tail(500))
Q: React Context - not setting state or reading from state correctly I am using the react-beautiful-dnd(https://github.com/atlassian/react-beautiful-dnd) library for moving items around between columns. I am trying to update my columns in state after I drag an item to a different column. In the endDrag function I am logging out the columns variable right before setting state and it is correct at that point. So either I'm not setting state correctly, or I am not reading from state correctly in the column component. My console log in the OrderColumn component is outputting the old state of columns, so that seems to tell me I'm not setting the state correctly. Here is my context file where I set the initial state: import React, { createContext, useState } from 'react'; export const ScheduleContext = createContext(); export const ScheduleProvider = (props) => { const orderData = [ ['First', 'First Order'], ['Second', 'Second Order'], ['Third', 'Third Order'], ['Fourth', 'Fourth Order'], ['Fifth', 'Fifth Order'] ]; const tempOrders = orderData.map(function(val, index) { return { id: index, title: val[0] + ' Order', desc: 'This order is for ' + val[1] + '.' }; }); const orderIDs = tempOrders.map(function(val) { return val.id; }); const columnCount = 5; const cols = []; for (let i = 0; i < columnCount; i++) { cols.push({ title: 'Line ' + i, columnID: 'column-' + i, orderIDs: i === 0 ? orderIDs : [] }); } // eslint-disable-next-line no-unused-vars const [orders, setOrders] = useState(tempOrders); // eslint-disable-next-line no-unused-vars const [columns, setColumns] = useState(cols); const contextValue = { orders, setOrders, columns, setColumns }; return ( <ScheduleContext.Provider value={contextValue}> {props.children} </ScheduleContext.Provider> ); }; Next, this is my SchedulePage which is the top component under App.js. import React, { useContext } from 'react'; import PropTypes from 'prop-types'; import { DragDropContext } from 'react-beautiful-dnd'; import OrderColumn from '../ordercolumn/OrderColumn'; import { ScheduleContext } from '../../schedule-context'; const Schedule = () => { const { columns, setColumns } = useContext(ScheduleContext); const onDragEnd = (result) => { const { destination, source } = result; if (!destination) { return; } if ( destination.droppableId === source.droppableId && destination.index === source.index ) { return; } const column = columns.find( (col) => col.columnID === source.droppableId ); const orderIDs = Array.from(column.orderIDs); orderIDs.splice(source.index, 1); const newColumn = { ...column, orderIDs: orderIDs }; const ind = columns.indexOf(column); columns.splice(ind, 1, newColumn); console.log(columns); setColumns(columns); }; const columnsArray = Object.values(columns); return ( <DragDropContext onDragEnd={onDragEnd}> <div className={'full-width'}> <h1 className={'text-center'}>Schedule</h1> <div className={'lines row no-gutters'}> {columnsArray.map(function(val, index) { return ( <OrderColumn key={index} title={val.title} columnId={val.columnID} orderIDs={val.orderIDs} /> ); })} </div> </div> </DragDropContext> ); }; Schedule.propTypes = { orders: PropTypes.array }; export default Schedule; Finally, the OrderColumn page which is under the SchedulePage: import React, { useContext } from 'react'; import PropTypes from 'prop-types'; import { Droppable } from 'react-beautiful-dnd'; import styled from 'styled-components'; import Order from '../order/Order'; import { Scrollbars } from 'react-custom-scrollbars'; import { ScheduleContext } from '../../schedule-context'; import '../../App.css'; const MyOrder = styled.div``; const OrderColumn = (props) => { const colId = props.columnId; const orders = useContext(ScheduleContext).orders; const orderIDs = useContext(ScheduleContext).columns.find( (col) => col.columnID === colId ).orderIDs; console.log('orderIDs: '); console.log(orderIDs); return ( <Droppable droppableId={colId}> {(provided) => { console.log('orderIDs: '); console.log(orderIDs); return ( <MyOrder className={'col order-column'} ref={provided.innerRef} {...provided.droppableProps} > <Scrollbars // This will activate auto hide autoHide // Hide delay in ms autoHideTimeout={1000} // Duration for hide animation in ms. autoHideDuration={200} > <h3 className={'text-center title'}>{props.title}</h3> <div className={'orders'}> {orderIDs && orderIDs.map((orderID, index) => { const order = orders.find( (o) => o.id === orderID ); return ( <Order key={orderID} order={order} index={index} /> ); })} </div> </Scrollbars> {provided.placeholder} </MyOrder> ); }} </Droppable> ); }; OrderColumn.propTypes = { orders: PropTypes.array, title: PropTypes.string.isRequired, columnId: PropTypes.string.isRequired }; export default OrderColumn; Figured out how to get my whole app online for testing/viewing if that helps anyone: https://codesandbox.io/s/smoosh-shape-g8zsp A: As far as I understood, you change your columns and then save it to the state. Your problem is that you are just mutating your state: columns.splice(ind, 1, newColumn); // <-- mutation of columns array console.log(columns); setColumns(columns); // <-- noop as react compares references of the arrays To prevent this issue, you should just create a copy first and then modify and save it. React then will pick up the change: const adjustedColumns = columns.slice(); // or Array.from(columns) adjustedColumns.splice(ind, 1, newColumn); setColumns(adjustedColumns);
Q: Live Streaming- HLS + RTSP using Video.js (Wowza Server) I am using a Wowza's Gocoder application to live stream video from my iPhone to the Wowza server(version 4.0.4). From the server I was able to fetch the video to my Webpage as well. I used Video.js player to do the same. But all this works only for IOS (HLS stream). Now, I would like to know if I could support streaming from my Android mobile (RTSP) as well using the same player. Is there something I could include to make the single player connect to the RTSP or HLS stream respectively? Thank you for the help ! :) Code: <head> <script type="text/javascript"> document.createElement('video');document.createElement('audio');document.createElement('track'); </script> <link href="//vjs.zencdn.net/4.8/video-js.css" rel="stylesheet"> <script src="//vjs.zencdn.net/4.8/video.js"></script> </head> <body> <video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="auto" width="500" height="300" poster="nfllogo.png" data-setup='{"example_option":true}'> <source src="http://a.b.c.d:1935/live/myStream/playlist.m3u8" type='video/mp4'/> <p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that <a href="http://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a></p> </video> </body> A: if you want to show RTMP streams, afaik you need to fall back to a Flash based player, but that limits your platform ad well. I googled around, but it's not clear to me if Video.js can do that. JW Player can.
Q: Why is this use of "therefore" considered a restrictive adverb? So, I found this explanation of when and when not to set off adverbs with commas. Here is an example in which 'therefore' serves as more of an aside or a pause: All of the test animals, therefore, were re-examined. In this case, 'therefore' is bounded by commas to separate it from the rest of the sentence and to provide a pause for the reader. In this example, if 'therefore' were moved and placed within the verb 'were re-examined', it would be treated as an essential (restrictive) adverb and would not require commas: All of the test animals were therefore re-examined. But, I'm confused as to why 'therefore' suddenly becomes restrictive when inserted into the verb, 'were re-examined'. It's still the same sentence in meaning, right? My guess as to the reason why was that we don't want to use a comma or commas to divide the words that comprise a compound verb. But, then I thought of an example where it would be fine to divide the words of a compound verb! Here it is: If Star Wars were, for example, deemed inappropriate for children, Disney would make relatively less money. So, my question is why does 'therefore' suddenly become restrictive when placed between 'were' and 're-examined"? A: I don't think using commas around therefore has anything to do with the adverb being restrictive or not. Even without the surrounding commas, therefore is not restricting anything. It merely connects between a prior sentence to the current sentence with or without the surrounding commas. With the commas it is presented separately from the main clause, whereas without them it is presented as being integrated into the main clause. A: I agree with JK2 but would add that all adverbs have a "natural" position within a sentence and this position does not require commas: [Nothing was found,] therefore all of the test animals were re-examined. [Nothing was found,] all of the test animals, therefore, were re-examined. [Nothing was found,] all of the test animals were, therefore, re-examined. The extra-position of adverbs adds emphasis to the adverb. In written English this emphasis is displayed by off-setting commas.
Q: How to convert JSON post request to a DataFrame in Python im new to python and pandas but would like to do some real statistics on population in Sweden as a fun project. To retrieve this SCB (statistics database of Sweden) has an API. I have come pretty far with this code below to access some data, but I still don't know how to convert the response to a pandas DataFrame. Below is my code: import json import requests import urllib.request import pandas as pd #API Settings url="http://api.scb.se/OV0104/v1/doris/sv/ssd/" amnesid="BE/" level1="BE0101/" level2="BE0101A/" level3="BefolkningNy/" urlPost= url + amnesid + level1 +level2 +level3 #Post Request url = urlPost payload = { "query": [{"code":"Region", "selection":{"filter":"item", "values":["00"]}}], "response": {"format":"json"} } r = requests.post(url, data=json.dumps(payload)) print(r.text) Here is the console output: {"columns":[{"code":"Region","text":"region","type":"d"}, {"code":"Tid","text":"år","type":"t"}, {"code":"BE0101N1","text":"Folkmängd","comment":"Uppgifterna avser förhållandena den 31 december för valt/valda år enligt den regionala indelning som gäller den 1 januari året efter.\r\n","type":"c"}, {"code":"BE0101N2","text":"Folkökning","comment":"Folkökningen definieras som skillnaden mellan folkmängden vid årets början och årets slut.\r\n","type":"c"}],"comments":[],"data":[{"key":["00","1968"],"values": ["7931193",".."]},{"key":["00","1969"],"values":["8004270","73077"]},{"key": ["00","1970"],"values":["8081142","76872"]},{"key":["00","1971"],"values": ["8115165","34023"]},{"key":["00","1972"],"values":["8129129","13964"]}, {"key":["00","1973"],"values":["8144428","15299"]},{"key": ["00","1974"],"values":["8176691","32263"]},{"key":["00","1975"],"values": ["8208442","31751"]},{"key":["00","1976"],"values":["8236179","27737"]}, {"key":["00","1977"],"values":["8267116","30937"]},{"key": ["00","1978"],"values":["8284437","17321"]},{"key":["00","1979"],"values": ["8303010","18573"]},{"key":["00","1980"],"values":["8317937","14927"]}, {"key":["00","1981"],"values":["8323033","5096"]},{"key": ["00","1982"],"values":["8327484","4451"]},{"key":["00","1983"],"values": ["8330573","3089"]},{"key":["00","1984"],"values":["8342621","12048"]}, {"key":["00","1985"],"values":["8358139","15518"]},{"key": ["00","1986"],"values":["8381515","23376"]},{"key":["00","1987"],"values": ["8414083","32568"]},{"key":["00","1988"],"values":["8458888","44805"]}, {"key":["00","1989"],"values":["8527036","68148"]},{"key": ["00","1990"],"values":["8590630","63594"]},{"key":["00","1991"],"values": ["8644119","53489"]},{"key":["00","1992"],"values":["8692013","47894"]}, {"key":["00","1993"],"values":["8745109","53096"]},{"key": ["00","1994"],"values":["8816381","71272"]},{"key":["00","1995"],"values": ["8837496","21115"]},{"key":["00","1996"],"values":["8844499","7003"]}, {"key":["00","1997"],"values":["8847625","3126"]},{"key": ["00","1998"],"values":["8854322","6697"]},{"key":["00","1999"],"values": ["8861426","7104"]},{"key":["00","2000"],"values":["8882792","21366"]}, {"key":["00","2001"],"values":["8909128","26336"]},{"key": ["00","2002"],"values":["8940788","31660"]},{"key":["00","2003"],"values": ["8975670","34882"]},{"key":["00","2004"],"values":["9011392","35722"]}, {"key":["00","2005"],"values":["9047752","36360"]},{"key": ["00","2006"],"values":["9113257","65505"]},{"key":["00","2007"],"values": ["9182927","69670"]},{"key":["00","2008"],"values":["9256347","73420"]}, {"key":["00","2009"],"values":["9340682","84335"]},{"key": ["00","2010"],"values":["9415570","74888"]},{"key":["00","2011"],"values": ["9482855","67285"]},{"key":["00","2012"],"values":["9555893","73038"]}, {"key":["00","2013"],"values":["9644864","88971"]},{"key": ["00","2014"],"values":["9747355","102491"]},{"key":["00","2015"],"values": ["9851017","103662"]},{"key":["00","2016"],"values":["9995153","144136"]}, {"key":["00","2017"],"values":["10120242","125089"]}]} Thankful if someone can help me out. A: After discussion in the comments, the answer is: df = pd.DataFrame(json.loads(codecs.decode(bytes(r.text, 'utf-8'), 'utf-8-sig'))['data'])
Q: Permision denied when change GPU clock rate in Nvidia Jetson TX1 I have a Nvidia TX1 development kit which I've installed ubuntu 16.04 using JetPack-L4T-3.1-linux-x64.run (in full installation mode) on it. The installation procedure are based on the following link: [ http://docs.nvidia.com/jetpack-l4t/2_1/content/developertools/mobile/jetpack/jetpack_l4t/2.0/jetpack_l4t_install.htm ] I wanted to test its GPU performance for our application but since its clock is set to the minimum value which is 76800000 HZ I can't get enough performance out of it. I've read in this link [ https://stackoverflow.com/questions/41146835/changing-the-gpu-clock-rate-on-a-linux-like-system-nvidia-jetson-tx1 ] how to change the value of GPU when permission denied happens. but none of them works for my linux ! Is there any hope for changing the clock speed of the GPU on this board ? It is worth mentioning that instead of having this path for changing clock rate /sys/kernel/debug/clock/override.gbus/rate I have this path: /sys/kernel/debug/clk/override.gbus/clk_rate So you can see I don't have any clock folder or rate file ! I can see different options for gpu clock rate in this file: /sys/kernel/debug/clk/gbus/clk_possible_rates
Q: switch to another video and repeat continuously The HTML coed is <video autoplay id="myvideo"> <source id="vmp4" src="v1.mp4" type="video/mp4"> <source id="vogg" src="v1.ogg" type="video/ogg"> <p>Your browser does not support this video format.</p> </video> What I want to do is that after page load and at the end of showing video1.mp4, switch to video2.mp4 after 5 seconds and repeat this continuously. ie. video1>5s>video2>5s>video1>... var myvideo1 = ["v1.mp4", "v2.mp4"] var myvideo2 = ["v1.ogg", "v2.ogg"] var vi1=0; var vi2=0; function rotatevid() { document.getElementById("myvideo").addEventListener("ended",switchvideo,false); function switchvideo(e) { vi1++; vi2++; if (vi1==myvideo1.length) { vi1=0; } if (vi2==myvideo2.length) { =0; } document.getElementById("vmp4").src=myvideo1[vi1]; document.getElementById("vogg").src=myvideo2[vi2]; } setTimeout(rotatevid(), 5000); } A: Solved, updating the answer <video id="myvideo" controls autoplay> <source id="vmp4" src="v1.mp4" type="video/mp4"> <source id="vogg" src="v1.ogg" type="video/ogg"> <p>Your browser does not support this video format.</p> </video> <script> var count = 1; var vid = document.getElementById("myvideo"); vid.addEventListener("ended", switchvideo, false); function switchvideo(e) { if (count % 2 === 0) { vid.setAttribute('src', 'v1.mp4'); } else { vid.setAttribute('src', 'v2.mp4'); } count++; vid.load(); try { setTimeout(()=>vid.play(), 2000); } catch (err){ console.log(err) } } </script> This is a working code. Just make sure you have v1.mp4 and v2.mp4 present in the same folder you are keeping this HTML File. A: you can use the bootstrap framework for this. in particular, you can use the carousel component.
Q: JDialog does not fire closing or closed event when button pressed When clicking the "X" button on the window frame of a JDialog * *the closing event is fired, and *the application exits. When clicking the "Ok" button * *the window disappears, *no closing event is fired, and *the application does not exit. Why? And how do I get the two to behave the same; I'd like them both to fire a closing event. I do not want to create a custom button. I want the defaults of the look and feel for the current operating system to dictate the button text and style so that it is consistent with the running OS. I've observed this behavior on macOS, Windows, in Java 11 and Java 13. So I'm guessing it is intentional... but it sure baffles me. I thought any setVisible(false) would trigger a closing event. Here's my SSCCE: import javax.swing.*; import java.awt.event.*; public class JexitOnClose2 { public static void main(String args[]) { SwingUtilities.invokeLater(()-> { final JOptionPane pane = new JOptionPane( new JLabel("hello"), JOptionPane.ERROR_MESSAGE); JDialog dialog = pane.createDialog(null, "title goes here"); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.out.println("window closing"); } @Override public void windowClosed(WindowEvent e) { System.out.println("window closed"); } } ); dialog.setVisible(true); }); } }
Q: Online PIM Needed: EverNote + Cozi =? I am looking for an online solution with free-form note-taking ability like OneNote or EverNote, and also a robust calendaring system (tasks, repeating appts, notifications). Cozi has a great calendar but not much else... EverNote lasks the calendar side of things. Scrybe looks very promising on both fronts but is by invitation only. Oh yeah... it should be free, too :D Am I SOL? A: Have you tried Springpad http://springpadit.com - we make it easy to collect, use and share content and data that you find on the web and we also provide calendaring integrated with gcal and other productivity features for task and project management. A: Google seems to meet all of you requirements with Docs and Calendar, and free. Docs: Not sure how free form you need it to be, but you can insert a drawing (which can be drawn online and not just an uploaded image), or insert a comment. Calendar: has repeat tasks and reminders (popup or email notification. I don't think the calendar and docs really integrate. You can't have a reminder on a doc or link the doc to a reminder, etc. Colaboration and sharing are pluses. And it's free.
Q: Finding homomorphisms and kernels from a given ring R Give the following rings $R$ and ideals $I$ find a ring $S$ and a homomorphism $f:R \rightarrow S$ with kernel $I$ i) $R=\mathbb{Q} [x], I=(x^{2}-2)R$ ii)$R=\mathbb{Z}[i], I=2R$ (Gaussian Integers) With both I'm struggling to find a homomorphism which satisfies the kernel. I would assume for the Gaussian Integers the norm function could be applied? Any help would be great :) A: For the first one, consider the evaluation homomorphism $$\xi:\Bbb Q[x]\to\Bbb Q[\sqrt 2]$$ wth $P\mapsto P(\sqrt 2)$. Then $\xi P=\xi Q$ iff $ (P-Q)(\sqrt 2)=0$ iff $ x^2-2\mid P-Q $ iff $P-Q\in (x^2-2)$. so $\ker \xi =(x^2-2)$. For the second one, consider $\eta:\Bbb Z[i]\mapsto (\Bbb Z/(2))[i]$ where $P$'s coefficients are mapped to their class modulo 2. Then $P\mapsto 0$ iff all its coefficients are divisible by two, iff $P\in (2\Bbb Z)[i]$.
Q: probability of having 2 boys given at least 1 is a boy I am in 12th grade and I can't really understand a question in conditional probability. The question states There is a family with 2 children either boys or girls where both are equally likely. Given that there is at least 1 boy find the probability of having 2 boys. If we take the 2 cases, in the first case if there is 1 boy does it mean that there are 1 boy and 1 girl? Or does it mean that we have 1 boy and the 2nd may or may not be a boy? A: I can understand your confusion. Always write down the total sample space and sample space under condition. This is a question of conditional probability. The total sample space in this case is $\lbrace B, B \rbrace$, $\lbrace B, G \rbrace$, $\lbrace G, B \rbrace$, $\lbrace G, G \rbrace$ each case with equal probability $1/4$. When it says that there is "atleast one boy". Then your conditional sample space shrinks to $\lbrace B, B \rbrace$, $\lbrace B, G \rbrace$, $\lbrace G, B \rbrace$,. Now is asking the probability of having 2 boys, hence your favourable sample space is $\lbrace B, B \rbrace$. Hence the probability is = number of favourable sample space/ number of conditional sample space = 1/3. A: The question means that there is at least one boy, second maybe a boy or a girl. You need to give the probability that both children are boys. Without the information that at least one is a boy we would have four possible events BB, BG, GB, GG. The probability of having two boys (BB) would then be 1/4 as each of the events has the same probability. But now we know that GG is not possible so we have only 3 possibilities so the answer is 1/3. In greater detail: Since the birth of boy or girl has the same probability Births in each order is given by P(BB)=0.5*0.5 P(BG)=0.5*0.5 P(GB)=0.5*0.5 P(GG)=0.5*0.5 Applying Bayes theorem P(BB|one is boy)=$\frac{P(BB)}{P(BB)+P(GB)+P(BG)}=1/3$
Q: Cumulative pnorm in R I'm looking to calculate a cumulative pnorm through as series. set.seed(10) df = data.frame(sample = rnorm(10)) # head(df) # sample # 1 0.01874617 # 2 -0.18425254 # 3 -1.37133055 # 4 -0.59916772 # 5 0.29454513 # 6 0.38979430 I would like the result to be # na # 0.2397501 # last value of pnorm(df$sample[1:2],mean(df$sample[1:2]),sd(df$sample[1:2])) # 0.1262907 # last value of pnorm(df$sample[1:3],mean(df$sample[1:3]),sd(df$sample[1:3])) # 0.4577793 # last value of pnorm(df$sample[1:4],mean(df$sample[1:4]),sd(df$sample[1:4])) # . # . # . if we can do this preferable in data.table, it would be nice. A: You can do: set.seed(10) df = data.frame(sample = rnorm(10)) foo <- function(n, x) { if (n==1) return(NA) xn <- x[1:n] tail(pnorm(xn, mean(xn), sd(xn)), 1) } sapply(seq(nrow(df)), foo, x=df$sample) The way of calculation is similar to Calculating cumulative standard deviation by group using R result: #> sapply(seq(nrow(df)), foo, x=df$sample) # [1] NA 0.23975006 0.12629071 0.45777934 0.84662051 0.83168998 0.11925118 0.50873996 0.06607348 0.63103339You can put the result in your dataframe: df$result <- sapply(seq(nrow(df)), foo, x=df$sample) Here is a compact version of the calculation (from @lmo) c(NA, sapply(2:10, function(i) tail(pnorm(df$sample[1:i], mean(df$sample[1:i]), sd(df$sample[1:i])), 1)))
Q: How do I obtain GDBus interface name with Giomm? I am trying to detect added Bluetooth devices/adapters using Bluez D-Bus API and GDBus. However, I am unable to check the name of the added D-Bus interface. I already tried accessing the interface name using the underlying GDBusInterfaceInfo C object, but calling get_info() on a Gio::DBus::Interface either causes a segmentation fault or returns a null pointer. In addition, calling get_interface("org.bluez.Adapter1") on a Gio::DBUS::Object prints this warning: ** (process:60136): WARNING **: 11:11:58.443: Glib::wrap_auto_interface(): The C++ instance (N3Gio4DBus5ProxyE) does not dynamic_cast to the interface. Here is my code. I compiled it with: g++ dbus.cpp `pkg-config --cflags --libs glibmm-2.4 giomm-2.4` -g and my glibmm version is glibmm 2.66.4-1. #include <glibmm.h> #include <giomm.h> void on_object_added(const Glib::RefPtr<Gio::DBus::Object>& o) { for (auto iface : o->get_interfaces()) { auto info = iface->get_info(); // Causes Segmentation fault. if (!info) { std::cout << "Null InterfaceInfo\n"; } } } int main() { Gio::init(); auto loop = Glib::MainLoop::create(); auto objman = Gio::DBus::ObjectManagerClient::create_for_bus_sync( Gio::DBus::BUS_TYPE_SYSTEM, "org.bluez", "/"); objman->signal_object_added().connect(sigc::ptr_fun(&on_object_added)); for (const auto& o : objman->get_objects()) { std::cout << o->get_object_path() << '\n'; // The next line prints: // ** (process:60136): WARNING **: 11:11:58.443: Glib::wrap_auto_interface(): The C++ instance (N3Gio4DBus5ProxyE) does not dynamic_cast to the interface. auto adapter = o->get_interface("org.bluez.Adapter1"); for (const auto& iface : o->get_interfaces()) { // iface is not a GDBus Proxy instance, // but a PN3Gio4DBus9InterfaceE. std::cout << " " << typeid(iface.operator->()).name() << '\n'; } std::cout << '\n'; } loop->run(); } What am I doing wrong? How can I see the name of an interface when I am not dealing with a GDBusProxy instance? Is it possible to obtain a GDBusProxy instance using GDBusObjectManagerClient? I couldn't find any examples on how to do this. It seems like Giomm GDBus examples and support are in short supply. A: Try: auto proxy = std::dynamic_pointer_cast<Gio::DBus::Proxy>(iface); std::cout << ' ' << proxy->get_interface_name() << '\n'; This works for me using glibmm-2.68. The documentation for Gio::DBus::Interface shows that Gio::DBus::Interface is a superclass of Gio::DBus::Proxy, and indeed it seems that all the Gio::DBus::Interface instances in your provided code are also Gio::DBus::Proxy instances.
Q: Async signalR abort call I am using SignalR javascipt client in my asp.net application. In my application all the abort calls are sequential and blocking further execution of my JavaScript. In signalR code, i observed that there is a flag for making asynchronous abort call. I observed that the default value of async variable inside the ajaxabort method is always false in IE, Chrome, Safari and Firefox. * *Why my abort calls are sequential in chrome and IE. ( not in firefox and safari). Is this expected? *Am i doing something wrong? *What are the side effects if i hard-code the async flag to always true? Update: There is a piece of code in signalR which sets the async property. var asyncAbort = !!connection.withCredentials && firefoxMajorVersion(window.navigator.userAgent) >= 11; Where does the value "connection.withCredentials" is coming from? For me it is always undefined and so my asyncAbort is always false. This makes my long running abort call blocking everything in chrome and IE. Note: I am not using any cross domain calls. Refer Github ticket
Q: Creating Non-stroked Region in C# StreamGeometry Xaml markup I am looking for a way to create non-stroked regions for a StreamGeometry in xaml. In other words, I want to know if it is possible to recreate the following code (taken from msdn) with the StreamGeometry Xaml markup syntax. StreamGeometry geometry = new StreamGeometry(); geometry.FillRule = FillRule.EvenOdd; using (StreamGeometryContext ctx = geometry.Open()) { ctx.BeginFigure(new Point(10, 100), true /* is filled */, true /* is closed */); ctx.LineTo(new Point(100, 100), false/* is not stroked */, false /* is smooth join */); ctx.LineTo(new Point(100, 50), true /* is stroked */, false /* is smooth join */); } I'm looking for a solution which works in WPF since Silverlight doesn't have a StreamGeometry. A: Here is a direct translation using a PathGeometry: <PathGeometry FillRule="EvenOdd"> <PathFigure StartPoint="10,100" IsFilled="true" IsClosed="true"> <LineSegment Point="100,100" IsStroked="false" IsSmoothJoin="false" /> <LineSegment Point="100,50" IsStroked="true" IsSmoothJoin="false" /> </PathFigure> </PathGeometry> This can be simplified by omitting the default values for FillRule, IsFilled, IsStroked and IsSmoothJoin, resulting in this: <PathGeometry> <PathFigure StartPoint="10,100" IsClosed="true"> <LineSegment Point="100,100" IsStroked="false" /> <LineSegment Point="100,50" /> </PathFigure> </PathGeometry> This must be done with a PathGeometry, not with the geometry mini-language (eg "M10,100 L100,100 100,50") because the mini-language provides no way to set IsStroked=false. Since you need a StreamGeometry, I recommend you use GeometryExtensions.DrawGeometry method in this answer to convert the PathGeometry defined in XAML into a StreamGeometry. I would be inclined to do this using a markup extension: <local:ConvertToStreamGeometry> <PathGeometry> <PathFigure StartPoint="10,100" IsClosed="true"> <LineSegment Point="100,100" IsStroked="false" /> <LineSegment Point="100,50" /> </PathFigure> </PathGeometry> </local:ConvertToStreamGeometry> The implementation of the markup extension is trivial: [ContentProperty("Geometry")] public class ConvertToStreamGeometry : MarkupExtension { public Geometry Geometry { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) { var result = new StreamGeometry(); using(var ctx = result.Open()) ctx.DrawGeometry(Geometry); return result; } } Note that this calls the GeometryExtensions.DrawGeometry extension method from the code in my earlier answer.
Q: Highcharts custom symbol I am trying to add custom symbol in angular 5 project. This is my code: import * as Highcharts from "highcharts"; Highcharts.Renderer.prototype.symbols.line, function(x, y, width, height) { return ['M',x ,y + width / 2,'L',x`enter code here`+height,y + width / 2]; } I am getting following error: ERROR in src/app/dashboard/apc-hse-monthly-chart/apc-hse-monthly-chart.component.ts(29,16): error TS2339: Property 'Renderer' does not exist on type 'typeof import("D:/source/QHSE/QHSE_Frontend/node_modules/highcharts/highcharts")'. What is the correct way to do this in angular 5? A: Highcharts.SVGRenderer.prototype.symbols.line = function(x, y, width, height) { return ['M',x ,y + width / 2,'L',x+height,y + width / 2]; }; relace Render with SVGRenderer
Q: How to have an app infrequently search for major updates in the background? This app communicates with a hardware accessory. I would like to have the app woken up once every 24 hours to search for firmware updates for that hardware. If an update is available, a notification will be sent to the notification center and the user can tap it to open the app and download the update. None of the background modes discussed here seem appropriate. The closest is "background fetch" which is meant for an app that "regularly downloads and processes small amounts of content from the network." The problems with this (all can be worked around) are: * *No way to specify how often to wake up to check for updates *An expectation that if content is available, the app will download it immediately (instead, I just want to send the user a notification so they know an update is available) So should I use background fetch and work around its limitations, is there a different background mode or API that would be better suited, or is this something an app shouldn't do? A: You can use background fetch for this, although you can't control if and when this happens (since the user can disable it). Instead of immediately downloading the firmware update, if you want to inform the user you can schedule a local notification to inform them. Push notifications are a more appropriate solution for this problem though. Just send a push notification when a new firmware update is available.
Q: phpMyAdmin - configure to log in remotely I've recently set up XAMPP on Windows 10 for use by high school student in a first year web development course. They each have their own private database in MySQL and I want them to be able to log into phpMyAdmin to access their databases. None of them will be on the server machine. I also want to be able to log in remotely as root. I've done a great deal of googling and played with config.inc.php a lot. So far, I've configed in a way that root is logged in automatically from everywhere; and changed that so that things work well locally but remotely I get 1045 - Access denied for user 'root'@'localhost' (using password: YES) mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES) That's where I am now. Goal: 1. Allow access and force login from any computer in the world. 2. Allow logout 3. Log out automatically on timeout (and when browser closes if possible). A: You'll want the cookie auth_type for this use case. I believe XAMPP uses $cfg['Servers'][$i]['auth_type'] = 'config'; by default, which means you're automatically logged in as whichever user is hardcoded in to config.inc.php. Using 'cookie' allows your students to each enter their login credentials and log out as needed. Further, I believe XAMPP sets up restrictions in Apache to not allow remote connections to phpMyAdmin, so you'll have to edit the Apache configuration file that defines phpMyAdmin access in order to allow access from external connections. I assume you've already got the computer exposed to the internet and configured with DNS so that it's reachable from the internet? You'll need to set your firewall and/or router to allow incoming connections to the server, of course.
Q: How do I add multiple ComponentDialogs? I made a new ComponentDialog by creating a class for it that extends ComponentDialog like so: public class GetPersonInfoDialog : ComponentDialog { protected readonly ILogger Logger; public GetPersonInfoDialog(IConfiguration configuration, ILogger<GetPersonInfoDialog> logger) : base("get-person-info", configuration["ConnectionName"]) { } // code ommitted } } Then I added it in Startup.cs: public void ConfigureServices(IServiceCollection services) { // ... services.AddSingleton<GreetingDialog>(); services.AddTransient<IBot, AuthBot<GreetingDialog>>(); // My new component dialog: services.AddSingleton<GetPersonInfoDialog>(); services.AddTransient<IBot, AuthBot<GetPersonInfoDialog>>(); } } But what I noticed is that only the last Dialog gets used. GreetingDialog now no longer works, saying: DialogContext.BeginDialogAsync(): A dialog with an id of 'greeting' wasn't found. The dialog must be included in the current or parent DialogSet. For example, if subclassing a ComponentDialog you can call AddDialog() within your constructor. I did notice, however, that the GetPersonInfo dialog does indeed begin and the Greeting dialog doesn't anymore. It's like I can only use one or the other. I noticed only the last added "transient" gets used, as if it overrides the previous transients. How do I add multiple component dialogs in my Startup.cs file? Or am I even going about this correctly? I did not find any documentation explaining how to have multiple ComponentDialogs. A: In Startup.cs I will start with your Startup.cs file since that is where the first issue is, then I will suggest an alternative design. What you are effectively doing with the following block of code is: services.AddSingleton<GreetingDialog>(); services.AddTransient<IBot, AuthBot<GreetingDialog>>(); services.AddSingleton<GetPersonInfoDialog>(); services.AddTransient<IBot, AuthBot<GetPersonInfoDialog>>(); * *Registering a single instance of the GreetingDialog for your bot (essentially a static). *Registering the IBot interface to return a new AuthBot of type GreetingDialog everytime an IBot is requested. *Registering a single instance of the GetPersonInfoDialog for your bot (essentially a static). *Registering the IBot interface (again) to return a new AuthBot of type GetPersonInfoDialog everytime an IBot is requested (which will overwrite the registration in step 2). You can read a lot more about Service lifetimes here. So what you actually want is more like the below: public void ConfigureServices(IServiceCollection services) { // Other code // Register dialogs services.AddTransient<GreetingDialog>(); services.AddTransient<GetPersonInfoDialog>(); // Some more code // Configure bot services.AddTransient<IBot, DialogBot<GreetingDialog>>(); } Error message DialogContext.BeginDialogAsync(): A dialog with an id of 'greeting' wasn't found. The dialog must be included in the current or parent DialogSet. For example, if subclassing a ComponentDialog you can call AddDialog() within your constructor. This error message is caused because your GetPersonInfoDialog doesn't know about your GreetingDialog (and it shouldn't). I believe this is a runtime error because I remember running into a similar issue myself. Since you haven't provided the full implementation for your GetPersonInfoDialog class I have to assume that somewhere inside there you are trying to do something like the following: dialogContext.BeginDialogAsync("greeting"); or dialogContext.BeginDialogAsync(nameof(GreetingDialog)); as per the documentation the first parameter is the ID of the dialog to start, this ID is also used to retrieve the dialog from the dialog stack. In order to call one dialog from inside another, you will need to add it to the parent dialog's DialogSet. The accepted way to do this is to add a call inside the constructor for the parent dialog like so: public ParentDialog(....) : base(nameof(ParentDialog) { // Some code // Important part AddDialog(new ChildDialog(nameof(ChildDialog))); } This uses the AddDialog method provided by the Microsoft.Bot.Builder.Dialogs NuGet package and exposed through the ComponentDialog class. Then when you want to display the ChildDialog you would call: dialogContext.BeginDialogAsync(nameof(ChildDialog)); In your case you can replace ParentDialog with GetPersonInfoDialog and ChildDialog with GreetingDialog. Since your GreetingDialog is only likely to be used once (it is not a utility dialog that could be called multiple times but with different arguments - in this case you would want to provide a specific ID rather than using nameof(GreetingDialog)) it is fine to go with the string representation of the class name as the DialogId, you can using "greeting" inside the the AddDialog call but you would also have to update the BeginDialogAsync call to also use "greeting". An alternative design Since I don't believe you want either GreetingDialog or GetPersonInfoDialog to be your actual starting points, I would suggest adding another dialog called MainDialog which inherits from the RouterDialog class (Microsoft.Bot.Builder.Solutions.Dialogs NuGet package). Based on the architecture (Virtual Assistant Template) here you would have your MainDialog spawn off your GreetingDialog and GetPersonInfoDialog. Assuming that your GreetingDialog is only a single stage where it sends a card or some text to the user to welcome them, it could be completely replaced by the OnStartAsync method which sends your card/message. Getting your user to your GetPersonInfoDialog would then be handled by the RouteAsync method example here. The changes you would need to make to your existing project to get this wired up are (assuming that you keep the GreetingDialog): * *Add Transient registrations in Startup.cs for GreetingDialog, GetPersonInfoDialog and MainDialog. *Add a Transient registration for mapping IBot to AuthBot<MainDialog> *Add calls inside the constructor of MainDialog to add the child dialogs GreetingDialog and GetPersonInfoDialog. *In the OnBeginDialog or OnStartAsync of MainDialog start your GreetingDialog. *In the RouteAsync of MainDialog handle any conditions around showing the GetPersonInfoDialog before displaying it. *There may be some additional steps that I have missed. Helpful links: * *Implementing sequential conversation flow. *Reusing dialogs. *Virtual Assistant template outline *Virtual Assistant template architecture. Edit To achieve what you want within the OAuth sample you could do the following: In LogoutDialog.cs change: private async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken)) to protected virtual async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken)) In MainDialog.cs add: protected override async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken)) { if (innerDc.Context.Activity.Type == ActivityTypes.Message) { var text = innerDc.Context.Activity.Text.ToLowerInvariant(); if (text == "check email") { // return innerDc.BeginDialogAsync(/*TODO*/); } else if (text == "check calender") { // return innerDc.BeginDialogAsync(/*TODO*/); } // etc return await base.InterruptAsync(innerDc, cancellationToken); } return null; } along with registering your Calendar, Email, etc dialogs in the constructor for MainDialog using the AddDialog method. I would seriously advise you to look at using the Virtual Assistant Template. As it uses LUIS to determing the user's intent (check email, check calendar etc), then route them accordingly, the relevant code is in this method. Using LUIS to determine intents has the advantage of being able to tie multiple ways of asking the same thing to the same intent, so you're not relying on your users to explicitly type "check calendar", you can have "show me my calendar", "what is my availability for next Monday", "am I free this afternoon", "check if I have any appointments tomorrow" etc. In fact Microsoft has already built Skills for email, and calendar which work with the Virtual Assistant Template, it should be easy enough to port the login code over to this template.
Q: Video game with sentient boomerang-wielding androids I'm looking for a 90s video game (either on the Game Boy Color or the Game Boy Advance) where you played as a robot equipped with a boomerang or a boomerang-like weapon. The weapon could be upgraded so that it could be thrown farther. Another robot followed you as a companion. I don't recall if it had an AI or if it just shot whenever you shot. I believe it was a platformer. One level took place in a forest. Another level took place underground. The robots looked like children, and the companion was larger than the main robot (maybe it was the bigger brother of the smaller robot?). The boomerang weapon they had would glow electric blue if you got a power-up. It might have been able to pass through multiple enemies when it was glowing. The enemies may have been mostly (mutated?) animals. Some of them could fly.
Q: Increased cohesion in simple java program I have a small java program that collects 10 words written by a user and prints them in specified orders. As it stands, the program works, but it is not cohesive. My issue stems from not knowing enough about the concept of cohesion to work on fixing this, as well as being new to Java/OO languages. I believe that the class Entry is way way way too cluttered, and that another class should take on some of this class' functions. Any hint or clue, cryptic or otherwise would be greatly appreciated! The lack of a input reader in Dialogue.java is intentional, as the original code uses proprietary code. These are the three classes: entry, dialogue and printer. Entry.java public class Entry { public static void main(String[] args){ String[] wordArray = new String[10]; Dialogue d = new Dialogue(); wordArray = d.read(wordArray); Printer p = new Printer(); p.printForwards(wordArray); p.printBackwards(wordArray); p.printEveryOther(wordArray); } } Dialogue.java public class Dialogue { public String[] read(String[] s){ String[] temp; temp = new String[s.length]; for(int i=0;i<s.length;i++){ String str = anything that reads input("Enter word number" + " " + (i+1)); temp[i] = str; } return temp; } } Printer.java public class Printer { public void printForwards(String[] s){ System.out.println("Forwards:"); for(int i=0;i<s.length;i++){ System.out.print(s[i] + " "); if(i==s.length-1){ System.out.println(""); } } } public void printBackwards(String[] s){ System.out.println("Backwards:"); for(int i=s.length-1;i>=0;i--){ System.out.print(s[i]+ " "); if(i==0){ System.out.println(""); } } } public void printEveryOther(String[] s){ System.out.println("Every other:"); for(int i = 0; i < s.length; i++){ if(i % 2 == 0){ System.out.print(s[i] + " "); } } } }// /class A: It looks okay overall, the truth is it is a very simple task where as OOP is better suited for more complex programs. That being said, here are a few pointers/examples. You can also do your printing more OOP style. The purpose of this is build reusable, modular code. We do this by abstracting String array manipulations (which previously existed in the Printer class) to it's own class. This is also very similar/also known as loose-coupling. We achieve loose-coupling by splitting the string processing functionality and the printing functionality. Change you Printer class to StringOrderer or something along those lines: public class StringOrderer { private String[] array; public class StringOrderer(String[] array) { this.array = array; } public String[] getArray() { return array; } public String[] everyOther(){ String[] eos = new String[array.length]; for(int i = 0; i < s.length; i++){ if(i % 2 == 0){ eos[eos.length] = s[i]; } return eos; } public String[] backwards() { ... And then in your main class add a method like such: private static void printStringArray(String[] array) { for (int i=0; i<array.length; i++) { System.out.print(array[i]); } } Then call it in your main method: StringOrderer s = new StringOrderer(wordArray); System.out.println('Forward:'); printStringArray(s.getArray()); System.out.println('Every other:'); printStringArray(s.everyOther()); System.out.println('Backwards:'); ... Extra tip - You can also add methods in your main class like so: public class Entry { public static void main(String[] args){ String[] wordArray = readWordArray() Printer p = new Printer(); p.printForwards(wordArray); p.printBackwards(wordArray); p.printEveryOther(wordArray); } private static String[] readWordArray() { Dialogue d = new Dialogue(); return d.read(new String[10]); } } to make it more readable.
Q: In which class should a GetAll method be? Say I have a method GetAllEmails() which retrieves all emails from the database. The question is which class should be I putting the method to? Many sources, even the textbooks, suggest it should be in the class Email, however logically an email should not know how to get all emails, and I think it should be placed in an email manager or helper class in such context. Any opinions? A: Repository design pattern is usually used for this, so in your case it'd be EmailRepository ( or something similar) class getting emails. A: Method GetAllEmails() has to connect to a DB and fetch some data. So I would put it in a class which is related into database. It really depends what sort of application you are writing, like if if you have some other methods which connects to database and fetch some other data, you can have them all in one class. But if you only connect to database for getting emails, then you can have a database subclass in your email class.
Q: IPtables command to block specific port for certain ip I want to block certain services such as ftp, telnet, http for a certain ip address. What command will I execute in order to achieve this. The only command I have tried is sudo iptables -A INPUT -s 10.10.10.10 -j DROP but I want specific ports only not everything. A: Specify the port using --dport: sudo iptables -A INPUT -s 10.10.10.10 -p tcp --dport 80 -j DROP #http sudo iptables -A INPUT -s 10.10.10.10 -p tcp --dport 21 -j DROP #ftp
Q: Hexadecimal data stored in SQL Please see screen grab. I am using a finance application and T-SQL. I would just like to understand why data would be stored on a db table in hexadecimal as opposed to integer, and why it would follow the format of 8-4-4-4-12 characters (total: 32). Thanks in advance. A: It's a UUID (or, in Microsoft parlance, a GUID) - normally used for ensuring UNIQUEness in PRIMARY KEYs across different servers in a distributed system - if your system isn't distributed, there's no reason not to use simple autogenerated INTEGER as PKs.
Q: mysql php table update I have a form that is populated from a MySQL connection. The from names look like this: <td><input type="text" name="Time1[]" value="<?php echo htmlentities($row_newNext['Time1'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td> <td><input type="text" name="Time1Out[]" value="<?php echo htmlentities($row_newNext['Time1Out'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td> I pass the input arrays to another page, but now I need to combine the array somehow in order to insert them using MySQl. I just can't get the structure right. array_combine doesnt work right and neither does merge. Any help please? Array from each looks like this: //first array Array( [0]=>apple [1]=>tree [2]=>rock ) //second array Array( [0]=>foo [1]=>banana [2]=>orange ) I want the arrays to combine into new arrays based on the key. So the new array will be: Array( [0]=>apple [1]=>foo ) Array( [0]=>tree [1]=>banana ) Array( [0]=>rock [1]=>orange ) A: You can serialize $row_newNext['Time1'] and $row_newNext['Time1Out'] before sending it in form and unserialise() it on the page you recieve your post data or implode() it with some sort of delimiter and explode() it later. implode() explode() serialize() unserialize()
Q: PHP preg_replace_callback catch more than one occurance in line I search for custom HTML tags with: $match = preg_replace_callback("/<tag>(.*)<tag>/", function ($key) { $result = getTxt($key[1]); return $result; }, $buffer); It works when input is: Abc <tag>1<tag> efg But why it returns null on: Abc <tag>2<tag> ef <tag>3<tag> h I've tried to group nongreedy ending tag: /$tag(.*)($tag?)/ with same result. A: You need to make the .* non greedy via .*? /<tag>(.*?)<tag>/ Say $tag is <tag>, that means $tag? becomes <tag>? which captures <tag and <tag>
Q: Time dilation without curvature at the center of mass, how is that possible? I have read this Question: What is the general relativity explanation for why objects at the center of the Earth are weightless? And John Rennie's answer where he says: "When $r = 0$ the Christoffel symbol $\Gamma_{tt}^r$ is zero and that means the radial four-acceleration is zero and that means you're weightless." And this Question: Gravitational time dilation at the earth's center And Luboš Motl's answer where he says: "If you spend 1 billion years at the center of the Earth, your twin brother outside the gravitational field will get 1 billion and one years older. If you wish, you may interpret it by saying that it's healthy to live at the center of the Earth. Good luck." So what the two are saying is that at the center of mass: * *there is time dilation *there is no curvature I read and understand what they are writing about the Christoffel symbol $$\Gamma_{tt}^r= \frac{r}{2R^6}\left[2M^2r^2+MR^3\left(3\sqrt{1-\frac{2Mr^2}{R^3}}\sqrt{1-\frac{2M}{R}}-1\right)\right] $$ And the potential at the center, assuming uniformity, is $$ \Phi = -\frac{GM}{R_E} - g(R_E) \frac{R_E}{2} = -\frac 32 \frac{GM}{R_E} = -\frac 32 g(R_E) R_E $$ And that "This gravitational potential determines the slowing of time, too." And somehow I just cannot understand how it is possible to have time dilation without curvature. I thought that time dilation is caused by (in GR, not SR) curvature, which is the effect of gravity, the gravitational potential. I don't understand how there can be gravitational potential without curvature, I thought the only effect gravity has is the curvature of spacetime. * *Can somebody please explain how (with math and with simple way too) how that is possible together? How can there be gravitational potential and time dilation without curvature? *Isn't gravity's only effect the curvature? Is there another effect with what gravity can create potential (so without creating curvature) and so create time dilation? A: Equation (1) in John Rennie's answer is $$ ds^2 = -\left[\frac{3}{2}\sqrt{1-\frac{2M}{R}} - \frac{1}{2}\sqrt{1-\frac{2Mr^2}{R^3}}\right]^2dt^2 + \frac{dr^2}{\left(1-\frac{2Mr^2}{R^3}\right)} + r^2 d\Omega^2 \tag{1} $$ which is, we are told, the Schwarzschild interior metric for a spherical body of uniform density. At the center, where $r=0$, this line element becomes $$ ds^2 = -\left[\frac{3}{2}\sqrt{1-\frac{2M}{R}} - \frac{1}{2}\right]^2dt^2 + \frac{dr^2}{\left(1-\frac{2Mr^2}{R^3}\right)}$$ Assuming one remains at $r=0$, we have that $$d\tau = \left[\frac{3}{2}\sqrt{1-\frac{2M}{R}} - \frac{1}{2}\right]\,dt$$ so, a clock at the center runs slower than a clock 'at infinity' by a factor of $$\frac{d\tau}{dt}=\left[\frac{3}{2}\sqrt{1-\frac{2M}{R}} - \frac{1}{2}\right]$$ So, there is time dilation at the center according to this line element. Note that for $M \rightarrow 0$, the clock at the center runs at the same rate as the clock at infinity. It's not clear to me what you mean by "there is no curvature". Spacetime curvature is manifest in geodesic deviation which is to say that, if there's curvature, two nearby geodesics that are initially parallel will not remain parallel. And that is the case here. A particle that remains at $r=0$ is on a geodesic. A nearby freely falling particle at $r=\epsilon$, initially at rest with respect to the other particle, will fall towards the other particle which means there is curvature. From the comments: What I do not understand is #1 is the particle at rest at the center really on a geodesic, then why is it not moving in space (if it is not moving in space, that means it is still 'moving' in the time dimension at speed c, I understand that) A timelike geodesic $x^\mu(\tau)$ satisfies the geodesic equation $$\frac{d^2x^\mu}{d\tau^2}=-\Gamma^\mu_{\;\alpha\beta}\frac{dx^\alpha}{d\tau}\frac{dx^\beta}{d\tau}$$ Consider the world line of a (massive) particle given by $x'^\mu(\tau)=(t,0,0,0)$. Since $\frac{d^2x'^\mu}{d\tau^2}=0$, then $x'^\mu(\tau)$ is a geodesic if $\Gamma^\mu_{\;tt}=\frac{1}{2}g^{\mu\nu}(g_{\nu t,t}+g_{\nu t,t}-g_{tt,\nu})|_{r=0}=0$ By inspection, the metric depends only on the coordinate $r$ and so we need to evaluate $$\Gamma^r_{\;tt}=-\frac{1}{2}g^{\mu\nu}g_{tt,r}|_{r=0}$$ But, in John Rennie's answer, this evaluates to zero thus a world line given by $(t,0,0,0)$ is a geodesic; a particle that remains at $r=0$ is in free fall. A: Time dilation is not a local property. That is, you can't just take a point in space and say what it's time dilation is. Time dilation is always relative to some other point in space. Suppose we take two points $A$ and $B$, then time dilation means that for the coordinate time $t$ we have: $$ \frac{dt}{d\tau}(\text{at point A}) \ne \frac{dt}{d\tau}(\text{at point B}) $$ and the time dilation isn't determined by what happens at $A$ or what happens at $B$, but by what happens in between $A$ and $B$. In particular it's possible for spacetime to be flat at point $A$ and flat at point $B$, and there can still be time dilation if the spacetime is curved in between points $A$ and $B$. To take a concrete example lets consider a thin spherical shell of mass $M$ and radius $D$. Outside the shell the metric is simply the Schwarzschild metric, so if we go out to $r=\infty$ spacetime is flat. Inside the shell the metric is: $$ ds^2 = -\left(1 - \frac{2GM}{c^2D}\right) c^2dt^2 + \frac{dr^2}{1 - \frac{2GM}{c^2D}} $$ where for simplicity I'll leaving off the angular bit since we dealing only with spherically symmetric systems. At first glance this looks curved, but we can define new time and radial coordinates: $$\begin{align} T &= \sqrt{1 - \frac{2GM}{c^2D}}\,t \\ R &= \frac{r}{\sqrt{1 - \frac{2GM}{c^2D}}} \end{align}$$ and using these coordinates the metric becomes: $$ ds^2 = -c^2dT^2 + dR^2 $$ and this is just the Minkowski metric in polar coordinates. So spacetime is flat inside the spherical shell, which should come as no surprise since it's just Newton's shell theorem. However even though spacetime is flat inside the shell, the flat time coordinate $T$ is not the same as the time coordinate $t$ outside the shell at $r=\infty$. They differ by a factor of $\sqrt{1-2GM/c^2D}$, and that means the time inside the shell is dilated i.e. runs slower, than the time at infinity: $$ \frac{dT}{dt} = \sqrt{1-\frac{2GM}{c^2D}} $$ This gives you an example of two points, both in flat spacetime, that have a relative time dilation. This difference in the time coordinates is due to the spacetime curvature caused by the shell in between the points inside and outside the shell. A: I'd like to add a comment to Alfred's correct answer and all the correct answers you cite. Something to emphasize here, and which I believe is causing problems for your understanding, is that weightlessness and curvature are about different terms in the Taylor series for the metric (and other geometric properties) of spacetime when we expand these objects in geodesic (Riemann normal) co-ordinates. Weightlessness is a first order notion: you can understand it by expanding the Taylor series to first order. Curvature, on the other hand, is a second order or (as it is often called) a tidal notion. At any point in spacetime (curvature present or not), we can always make it look Minkowskian if we restrict ourselves to a small enough neighborhood of that point: that's just part and parcel of the manifold as the geometric object describing spacetime in GTR. And it is in this restricted view that we define weightlessness: there is always has a momentarily comoving inertial frame (a particular choice of basis for the tangent space) wherein an observer is weightless; but in this case when people say things are weightless at the Earth's center, what they are emphasizing is that this comoving frame is stationary relative to the Earth's center, i.e. relative to the stuff that makes the Earth up. The curvature / geodesic deviation is about how the true picture deviates from this localized one as we shift over length / timescales greater than the ones whereover the first order picture, given by the linear tangent space, holds good. So these tidal effects only show up in the second order terms of the relevant Taylor series. As for any Taylor series, I hope that you can understand that the first and second order co-efficients can be set wholly independently.
Q: Why I don't see error exception on the client? I have this action method: public ActionResult SavePoint(PointRequest point) { //some logic throw new System.ArgumentException("Error, no point found"); } and this ajax: function saveFeature(feature, callback, error) { $.ajax({ url: window.homeUrl + "Feature/SavePoint", type: "GET", contentType: "application/json; charset=utf-8", dataType: "json", data: feature, success: callback, error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); } }); } In save feature function I want to alert text of the exception: 'Error, no point found'. But thrownError is empty, any idea why in thrownError I dont see error message? A: Jaromanda X and Brett Caswell answered the "why" in their comments. But you can do it like this: public ActionResult SavePoint(PointRequest point) { try { //some logic } catch (Exception ex) { return BadRequest("Error, no point found"); } } Or, to include the actual error to the user: public ActionResult SavePoint(PointRequest point) { try { //some logic } catch (Exception ex) { return BadRequest($"Error, no point found. Message: {ex.InnerException.Message}"); } }
Q: If statement inside If statement condition I have this code: int a, b; if (a > 0) { a--; DoSomething() } else if (b > 0) { b--; DoSomething(); } I heard it's better to not write the same line (DoSomething();) twice, so is there a way to do this: int a, b; if (a > 0 /* if true a--; */ || b > 0 /* if true b--; */) { DoSomething(); } In other words, is there a better way to do this (without writing DoSomething(); twice): int a, b; if (a > 0) { a--; DoSomething() } else if (b > 0) { b--; DoSomething(); } A: If these are the only or the last statements in the method, you could return in an additional else statement: if (a > 0) { a--; } else if (b > 0) { b--; } else { return; } DoSomething(); If these are the last statements in a loop you can use continue instead of return. In a switch case you can use break. If DoSomething involves something more complex, then using a flag would be appropriate. Otherwise calling DoSomething twice is just fine. bool isDecremented = false; if (a > 0) { a--; isDecremented = true; } else if (b > 0) { b--; isDecremented = true; } if (isDecremented) { // Do something more complex. } A: int a, b; if (a > 0 || b > 0) { if(a > 0) a--; else b--; DoSomething(); } A: How about writing like this? if ((a > 0 && a-- > 0) || (b > 0 && b-- > 0)) DoSomething(); A: You could use a local method to avoid the repetition: void DecrementAndDoSomething(ref int i) { i--; DoSomething(); } if (a > 0) DecrementAndDoSomething(ref a); else if (b > 0) DecrementAndDoSomething(ref b);
Q: How Do i Show Contextual Action Bar from List Adapter? I'm a noob to android development and I am trying to display a CAB from a List_Adapter when a user clicks a button on a listview item. I'm following the ActionbarSherlock sample but am not able to figure why I am getting the error "The method startActionMode(Child_Locations_ListAdapeter.AnActionModeOfEpicProportions) is undefined for the type Child_Locations_ListAdapeter". Any help is greatly appreciated. CODE public class Child_Locations_ListAdapeter extends BaseAdapter implements OnClickListener { private ArrayList<HashMap<String, String>> listData; private LayoutInflater layoutInflater; Context c; int selection; ActionMode mMode; public Child_Locations_ListAdapeter(Context context, ArrayList listData) { this.listData = listData; layoutInflater = LayoutInflater.from(context); c= context; } public void remove(int position) { listData.remove(position); notifyDataSetChanged(); } public void insert(int position, String item, String item2 ) { HashMap<String, String> map = new HashMap<String, String>(); map.put("Location",item ); map.put("Location_Address",item2 ); listData.add(position, map); notifyDataSetChanged(); } @Override public int getCount() { return listData.size(); } @Override public Object getItem(int position) { return listData.get(position); } @Override public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate(R.layout.layout_row_locations, null); holder = new ViewHolder(); //holder.userAvatar = (ImageView) convertView.findViewById(R.id.client_image); holder.locationName = (TextView) convertView.findViewById(R.id.tv_locationname); holder.locationAddress = (TextView) convertView.findViewById(R.id.tv_locationaddress); holder.delete = (ImageButton) convertView.findViewById(R.id.action_delete); holder.delete.setOnClickListener(Child_Locations_ListAdapeter.this); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.delete.setTag(position); //holder.userAvatar.setText(((Comment_Item) listData.get(position)).getUserName()); try{ holder.locationName.setText((listData.get(position)).get("Location")); holder.locationAddress.setText((listData.get(position)).get("Location_Address")); }catch(Exception e){ e.printStackTrace(); //holder.locationName.setText("No Locations For This Child"); //holder.locationAddress.setText(""); } //Geocoder_Class geocoder = new Geocoder_Class(c); //holder.locationAddress.setText(geocoder.getAddress((listData.get(position)).get("Latitude"), (listData.get(position)).get("Longitude"))); return convertView; } static class ViewHolder { ImageView location_picture; TextView locationName; TextView locationAddress; ImageButton delete; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.action_delete: selection = (Integer)v.getTag(); Log.e("Selection", String.valueOf(selection)); mMode = startActionMode(new AnActionModeOfEpicProportions());//<--The method startActionMode(Child_Locations_ListAdapeter.AnActionModeOfEpicProportions) is undefined for the type Child_Locations_ListAdapeter } } public class AnActionModeOfEpicProportions implements ActionMode.Callback { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { //Used to put dark icons on light action bar //boolean isLight = SampleList.THEME == R.style.Theme_Sherlock_Light; menu.add("Save") .setIcon( R.drawable.ic_compose) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); menu.add("Search") .setIcon( R.drawable.ic_search) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); menu.add("Refresh") .setIcon(R.drawable.ic_refresh) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); menu.add("Save") .setIcon(R.drawable.ic_compose) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); menu.add("Search") .setIcon(R.drawable.ic_search) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); menu.add("Refresh") .setIcon( R.drawable.ic_refresh) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { Toast.makeText(c, "Got click: " + item, Toast.LENGTH_SHORT).show(); mode.finish(); return true; } @Override public void onDestroyActionMode(ActionMode mode) { } } } A: The method startActionMode is bound to an Activity, not to a ListAdapter http://developer.android.com/reference/android/app/Activity.html#startActionMode(android.view.ActionMode.Callback) ((Activity) c).startActionMode(new AnActionModeOfEpicProportions());
Q: How to stack cards responsively with Materialize CSS? I'm trying to build a layout in Materialize CSS with many cards that fall into a responsive layout: Four cards in large displays (col l3), two in medium (col m6), and one in small (col s12). Unfortunately, I can't manage for them to stack vertically without gaps, even though their width is the same: https://jsfiddle.net/wdvq57rp/. Large Layout Gaps -> Image .card-panel { margin: 10px; padding: 10px; } .container { margin: 0; max-width: 100%; width: 100%; } <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet"/> <div class="container"> <h1>Stacked-Cards Test</h1> <div class="row card-container"> <!-- Test Cards --> <div class="col l3 m6 s12"> <div class="card-panel grey lighten-4"> <h5>Title</h5> <p>Description</p> <div> <p><a href="#" class="pink-text text-accent2">Link!</a></p> <p><a href="#" class="pink-text text-accent2">Link!</a></p> <p><a href="#" class="pink-text text-accent2">Link!</a></p> <p><a href="#" class="pink-text text-accent2">Link!</a></p> </div> </div> </div> <div class="col l3 m6 s12"> <div class="card-panel grey lighten-4"> <h5>Title</h5> <p>Description</p> <div> <p><a href="#" class="pink-text text-accent2">Link!</a></p> </div> </div> </div> <div class="col l3 m6 s12"> <div class="card-panel grey lighten-4"> <h5>Title</h5> <p>Description</p> <div> <p><a href="#" class="pink-text text-accent2">Link!</a></p> <p><a href="#" class="pink-text text-accent2">Link!</a></p> </div> </div> </div> <div class="col l3 m6 s12"> <div class="card-panel grey lighten-4"> <h5>Title</h5> <p>Description</p> <div> <p><a href="#" class="pink-text text-accent2">Link!</a></p> </div> </div> </div> <div class="col l3 m6 s12"> <div class="card-panel grey lighten-4"> <h5>Title</h5> <p>Description</p> <div> <p><a href="#" class="pink-text text-accent2">Link!</a></p> <p><a href="#" class="pink-text text-accent2">Link!</a></p> <p><a href="#" class="pink-text text-accent2">Link!</a></p> </div> </div> </div> <div class="col l3 m6 s12"> <div class="card-panel grey lighten-4"> <h5>Title</h5> <p>Description</p> <div> <p><a href="#" class="pink-text text-accent2">Link!</a></p> </div> </div> </div> </div> <!-- Row Container with Cards END--> </div> <!-- Main Container END--> <!-- JS Imports --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/js/materialize.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <script src="./js/magic.js"></script> A: Basically in 12 grid system you can't use l3 6 times which means 3*6=18, so you can use one more row inside the container to use the rest of the grid. See this fiddle. https://jsfiddle.net/wdvq57rp/2/ A: Finally found out what I wanted to achieve is possible with column-width & column-gap: https://jsfiddle.net/wdvq57rp/4/ div.card-container { -moz-column-width: 23rem; -webkit-column-width: 23rem; -moz-column-gap: 1rem; -webkit-column-gap: 1rem; } .card-panel { display: inline-block; width: 100%; } <!DOCTYPE html> <html> <head> <title>Stacked-Cards Test</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="utf-8"> <!-- CSS Imports --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.min.css"> <link rel="stylesheet" href="./css/style.css"> <!-- Fonts Imports --> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <h1>Stacked-Cards Test</h1> <!-- Card Container --> <div class="row card-container"> <div class="card-panel"> <h5 id="title">Title</h5> <p id="description">Description</p> <div> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> </div> </div> <div class="card-panel"> <h5 id="title">Title</h5> <p id="description">Description</p> <div> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> </div> </div> <div class="card-panel"> <h5 id="title">Title</h5> <p id="description">Description</p> <div> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> </div> </div> <div class="card-panel"> <h5 id="title">Title</h5> <p id="description">Description</p> <div> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> </div> </div> <div class="card-panel"> <h5 id="title">Title</h5> <p id="description">Description</p> <div> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> </div> </div> <div class="card-panel"> <h5 id="title">Title</h5> <p id="description">Description</p> <div> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> </div> </div> <div class="card-panel"> <h5 id="title">Title</h5> <p id="description">Description</p> <div> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> </div> </div> <div class="card-panel"> <h5 id="title">Title</h5> <p id="description">Description</p> <div> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> </div> </div> <div class="card-panel"> <h5 id="title">Title</h5> <p id="description">Description</p> <div> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> <a href="#" target="main" class="pink-text text-accent-2">Link!</a><br> </div> </div> </div> <!-- Card Container END --> <!-- JS Imports --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/js/materialize.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> </body> </html>
Q: State of composite Higgs models I'm studying the analogies between U(1) Higgs model and superconductivity BCS and GL theories. The question arises when Cooper pairs seem to be the responsible of the effective mass of the photon (I mean: no superconductivity, no cooper pairs, no photon's effective mass). Cooper pairs are a composite particle, so by analogy, Higgs boson might be. I found some ''old'' models (before Higgs boson discovery) but I'm an undergraduate student and I don't understand many things, but I think some of those models are now discarded. So nowadays, which is the state of composite Higgs models? I said 'nowadays'. As I said, I'm undergraduate, I'm starting in this field, I don't understand much the articles. I don't want details, I want to know what hypothesis are still plausible and some information about them. A: This is a nice model of recent times. Look also here. To be more divulgative, consider the second. In the second link the most recent attempt to envision the compositeness of the Higgs (and all other particles), sees the Higgs as composed out of rishons, first introduced by Harari in 1981. For example, the $W^{+/-}$ are composed out of three $T$ rishons and three $V$ rishons ($W^-$'s or their anti's for the $W^+$). An electron is envisioned as three $T$'s, a neutrino as three $V$'s, and the up- and down quark in between. All generations are considered excitations. The Higgs exists too but is not the cause of mass. It simply follows from the theory. There is a force more basic than the weak. The weak is considered an "emergent" force and there is no matter-anti-matter problem. Of course there are problems with this model (due to the energy having to be comprised in a very small volume, because of which potential energy and kinetic energy are comparable) and in the linked article an attempt is made to solve these.
Q: What can I do to avoid impedance discontinuity when high-speed signal bifurcates on PCB? As mentioned before, I want to supply two PCBs with same-frequency clock(as high as 10GHz).But now there is only one pair of differential clock, while both of the PCBs need one. So I am thinking of using an extra PCB, whose task is to distribute one clock into two. However, this involves a bifurcation for the high-frequency clock, inevitably causing impedance discontinuity.Is there any better way to deal with this?
Q: Relation between open and closed sets in Metric space let $(\mathbb{N},d)$, where $d : \mathbb{N} \times \ \mathbb{N} \to \mathbb{R}$, $d(m,n)=| \frac{1}{n}-\frac{1}{m}| $. Is every open set closed at the same time? Find $Bd(\{n \in \mathbb{N} : n \ge 3\})$. Any ideas? A: Each point is isolated, hence for all $n$, the set $\{n\}$ is open and closed. Hence any set is open, and so any set is also closed. Hence the closure of $A= \{n | n \ge 3\}$ is $A$ and the closure of $A^c$ is $A^c$. Hence the boundary is empty.
Q: Why should $z = \alpha x+ (1 - \alpha)y$ also be a solution of the given equation In order for $A−1$ to exist, $Ax = b$ must have exactly one solution for every value of $b$. However, it is also possible for the system of equations to have no solutions or infinitely many solutions for some values of $b$. It is not possible to have more than one but less than infinitely many solutions for a particular $b$; if both $x$ and $y$ are solutions then $z = αx + (1 − α)y$ is also a solution for any real $α$. I'm relatively new to Linear Algebra so I haven't been able to understand as to why $z = αx + (1 − α)y$ must also be a solution if there exists multiple solutions. A: \begin{align*}Az&=A(\alpha x+(1-\alpha)y)\\[0.2cm]&=A(\alpha x)+A\left((1-\alpha)y\right)\\[0.2cm]&=\alpha \cdot Ax+(1-\alpha)\cdot Ay=\alpha\cdot b+(1-\alpha)\cdot b=b\end{align*}
Q: JAWS not reading table header from contents in IE I have the below markup. <!DOCTYPE html> <html> <body> <h2>HTML Table</h2> <table> <tr> <th tabIndex="0">Company</th> <th tabIndex="0">Contact</th> <th tabIndex="0">Country</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Maria Anders</td> <td>Germany</td> </tr> <tr> <td>Centro comercial Moctezuma</td> <td>Francisco Chang</td> <td>Mexico</td> </tr> </table> </body> </html> I am using IE11 and JAWS18. When navigating with tabs, JAWS is not reading the table headers. When I tried with the same markup in chrome and JAWS, it is reading all the table headers. I also tried specified aria-label for table headers, but no use. <th tabIndex="0" aria-label="Company">Company</th> <th tabIndex="0" aria-lable="Contact">Contact</th> <th tabIndex="0" aria-label="Country">Country</th> Can someone please tell why JAWS18 could not read table headers in IE? It could not read either from the table headers contents or from aria-label in IE. Also, is there any alternative for this? A: Add a scope attribute to the header cells, e.g. <th scope="col">Company</th> This tells the screenreader what the relationship is between the header cells and other cells. You don't need the tabindex or ARIA for this, just use the arrow keys to navigate instead of tabbing.
Q: How to have the same routine executed sometimes by the CPU and sometimes by the GPU with OpenACC? I'm dealing with a routine which I want the first time to be executed by the CPU and every other time by the GPU. This routine contains the loop: for (k = kb; k <= ke; k++){ for (j = jb; j <= je; j++){ for (i = ib; i <= ie; i++){ ... }}} I tried with adding #pragma acc loop collapse(3) to the loop and #pragma acc routine(routine) vector just before the calls where I want the GPU to execute the routine. -Minfo=accel doesn't report any message and with Nsight-System I see that the routine is always executed by the CPU so in this way it doesn't work. Why the compiler is reading neither of the two #pragma? A: You need to enable OpenACC processing: -acc (with NVHPC tools) or -fopenacc (with GCC), for example, and then you need to use an OpenACC compute construct (parallel, kernels) to actually launch parallel GPU execution (plus host/device memory management, as necessary). For example, you could call your routine from that compute construct, and the routine would annotate the loop nest with OpenACC loop directives, as you've mentioned, to actually make use of the GPU parallelism. Then, to answer your actual question: the OpenACC compute constructs then support an if clause to specify whether the region will execute on the current device ("GPU") vs. the local thread will execute the region ("CPU"). A: To follow on to Thomas' answer, here's an example of using the "if" clause: % cat test.c #include <stdlib.h> #include <stdio.h> void compute(int * Arr, int size, int use_gpu) { #pragma acc parallel loop copyout(Arr[:size]) if(use_gpu) for (int i=0; i < size; ++i) { Arr[i] = i; } } int main() { int *Arr; int size; int use_gpu; size=1024; Arr = (int*) malloc(sizeof(int)*size); // Run on the host use_gpu=0; compute(Arr,size,use_gpu); // Run on the GPU use_gpu=1; compute(Arr,size,use_gpu); free(Arr); } % nvc -acc -Minfo=accel test.c compute: 4, Generating copyout(Arr[:size]) [if not already present] Generating NVIDIA GPU code 7, #pragma acc loop gang, vector(128) /* blockIdx.x threadIdx.x */ % setenv NV_ACC_TIME 1 % a.out Accelerator Kernel Timing data test.c compute NVIDIA devicenum=0 time(us): 48 4: compute region reached 1 time 4: kernel launched 1 time grid: [8] block: [128] device time(us): total=5 max=5 min=5 avg=5 elapsed time(us): total=331 max=331 min=331 avg=331 4: data region reached 2 times 9: data copyout transfers: 1 device time(us): total=43 max=43 min=43 avg=43 I'm using nvc and set the compiler's runtime profiler (NV_ACC_TIME=1) to show that the kernel is launched only once.
Q: How to get sprite following mouse position when camera is rotated 30 degree on X axys on UNITY3D? I'm trying to get a sprite following my mouse position with my camera rotated at 30 on x axys, this works fine if camera have a rotation of 0,0,0 but not on 30,0,0, how I have to calculate this? I have tryed substracting to x position with no success, here is my code: this is attached on the object I want to follow the mouse private void FixedUpdate() { Vector3 pos = cam.ScreenToWorldPoint(Input.mousePosition); transform.position = new Vector3(pos.x, pos.y, transform.position.z); } EDIT: also my camera is ortographic not perspective A: ScreenToWorldPoint isn't really appropriate here because you don't already know the proper distance to put the sprite away from the camera. Instead, consider using a raycast (algebraically, using Plane) to figure where to put the sprite. Create an XY plane at the sprite's position: Plane spritePlane = new Plane(Vector3.forward, transform.position); Create a ray from the cursor's position using Camera.ScreenPointToRay: Ray cursorRay = cam.ScreenPointToRay(Input.mousePosition); Find where that ray intersects the plane and put the sprite there: float rayDist; spritePlane.Raycast(cursorRay, out rayDist); transform.position = cursorRay.GetPoint(rayDist); Altogether: private void FixedUpdate() { Plane spritePlane = new Plane(Vector3.forward, transform.position); Ray cursorRay = cam.ScreenPointToRay(Input.mousePosition); float rayDist; spritePlane.Raycast(cursorRay, out rayDist); transform.position = cursorRay.GetPoint(rayDist); }
Q: What is correct Maven scope of findbugs annotations? I want to use a library that has the following dependency: <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>annotations</artifactId> <version>2.0.3</version> </dependency> I read that FindBugs is for static analysis of Java code, so I though it isn't necessary to include in application. Is it safe to exclude the jar with <scope>provided</scope> or with an <exclusion>...</exclusion>? One reason to exclude it is that there is a company policy against (L)GPL licence. A: Yes, you can safely exclude this library. It contains only annotations which do not need to be present at runtime. Take care to have them available for the FindBugs analysis, though. Note that you should also list jsr305.jar, like this: <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>annotations</artifactId> <version>3.0.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> <version>3.0.2</version> <scope>provided</scope> </dependency> Both JARs are required to make these annotations work. Check the most recent findbugs version in Maven Central. FindBugs is provided under the LGPL, so there should not be any problems for your company. Also, you are merely using FindBugs; you are not developing something derived from FindBugs. A: In theory, it should be entirely safe (as defined in the OP's clarifying comment) to exclude the Findbugs transitive dependency. If used correctly, Findbugs should only be used when building the library, not using it. It's likely that someone forgot to add <scope>test</scope> to the Findbugs dependency. So - go ahead and try the exclusion. Run the application. Do you get classpath errors, application functionality related to the library that doesn't work, or see messages in the logs that seem to be due to not having Findbugs available? If the answer is yes I personally would rethink using this particular library in my application, and would try to find an alternative. Also, congratulations on doing the classpath check up front! As a general practice, it is a great idea to do what you have done every time you include a library in your application: add the library, then check what other transitive dependencies it brings, and do any necessary classpath clean-up at the start. When I do this I find it makes my debugging sessions much shorter.
Q: How to bind SecurityManagerService to security domain I'd like to know how to associate (to bind), in jboss AS, a custom SecurityManagerService to a specific security domain. Basically I need to have two different SecurityManagerService configurations for two different security domains defined in the login-config.xml as application-policy section. In other words, is there any way to specify the SecurityDomainService in this xml section? <application-policy name="myDomain"> -- </application-policy> A: Well, it appears I cannot have two different instances of JaasSecurityManagerService running on jboss AS , having a different configuration, i.e. different value of DefaultCacheTimeout. After a couple of attempts I got this exception: Caused by: javax.naming.NameAlreadyBoundException: SecurityProxyFactory I had a look at the JaasSecurityManagerService, this is the block of code which causes the exception: SecurityProxyFactory proxyFactory = (SecurityProxyFactory) securityProxyFactoryClass.newInstance(); ctx.bind("java:/SecurityProxyFactory", proxyFactory); log.debug("SecurityProxyFactory="+proxyFactory); No words, they put the jndi value SecurityProxyFactory hard-coded with no possibility to change it! I have no other choice than extend the JaasSecurityManagerService
Q: Need to write an python function to resolve expression of varying parameters I aksed this question sometime back but possible could not explain. Trying again to explain it better. Firstly, i have recently started coding python so please let me know if any other details required. I have 2 excel tabs one containing the expressions in format * *( ( 36 AND 17 ) AND 57 ) OR ( 270 ) *( 71 ) OR ( 41 AND 70 ) *( ( 35 AND 2 ) AND 64 ) OR ( 63 ) *( ( 37 ) AND 65 ) *( ( 0 ) AND 65 ) OR ( ( 36 AND 17 ) AND 67 ) OR ( 66 ) *( 68 ) *( 69 ) *( 292 ) OR ( 42 AND 74 ) OR ( 41 AND 75 ) *( 72 ) the other tab contains the values of these numbers which are used to construct above listed expressions.Now i am trying to write a functionality where i can pass an expression from the above list and get is resolved. Presently i was able to have a workaround by joining the 2 excel tabs based on a common id -- xls = pd.ExcelFile('C:\\Users\\i0853\\Downloads\\r4.xlsx') df3 = pd.read_excel(xls, 'Operands')-- operands contains the individual number with values for e.g. 71 => (age < 15), 41 => gender='male', 70 => codes in(1,2,3) so that the expression ( 71 ) OR ( 41 AND 70 ) will become (age<15) OR (gender='male' AND codes in(1,2,3) df4 = pd.read_excel(xls, 'Expression Operands')-- this contains the expression as listed above. Now , i am only able to merge the two dataframes ` df2['value_set']=df2['value_set_id'] df_valueset=pd.merge(df2, df3, on='value_set', how='right') .. i am able to store the resolved values in a panda list --- oplistf=pd.concat([oplist1a,oplist2]) enter image description here.. i have attached the screenshot of how the oplistf looks like. it contains the resolve values of the numbers. ` to create the complete expression i am using basic print statements print (f"enrflg in {tuple(oplistf['S348'])} AND bfsdcd in {tuple(oplistf['S349'])}") print (f"enrflg in {tuple(oplistf['S348'])} AND bfsdcd in {tuple(oplistf['S350'])}") print (f"enrflg in {tuple(oplistf['S342'])} AND icd10 in {tuple(oplistf['S343'])}") print (f" ra_factor {tuple(oplistf['S4'])} AND {tuple(oplistf['S2'])}") My requirements is to write a generic function so that i can get any expression resolved . Presently i have to separately write individual print statements to resolve a single expression A: You can do something like this, if you need help with generateMapping method just add in comment will be happy to help :) DATA_FROM_CSV_1 = [ ... "( 292 ) OR ( 42 AND 74 ) OR ( 41 AND 75 )", ... ] # expressions in an array loaded DATA_FROM_CSV_2 = { ... 292: "ABC", 42: "DEF", ... } # mapping of corrseponding number loaded def generateMapping(exp): # assume you have a single exp and write code to convert and return ... return FINAL_STRING # ( converted expression ) for expression in DATA_FROM_CSV_1: print(generateMapping(expression)) A: i was trying to work on this using an alternate approach-- i transposed the dataframe columns so that the numbers in the column become the column themselves and their resolved value are now their values so each column as ha single value.. exv= oplistf.to_frame().transpose() all_columns = list(exv) # Creates list of all column headers exv[all_columns] = exv[all_columns].astype(str) so that i am able to write the expression by calling the numbers directly as column which will ultimately resolve to its value . For example ,one of the expression given in the column is : '( ( 36 AND 17 ) AND 187 ) OR ( 188 )' . Now to resolve it i am using exp1=(exv['36'] + 'AND' + exv['17'] + 'AND' + exv['187'] + 'OR' + exv['188'])``` so that exp1 resolves to ```0 ['15 >= age']AND['999 <= age']AND['g301']OR['g309', 'g300', 'g308'] but still i have a tedious task of adding + , 'AND' and 'OR' manually to concatenate the individual subexpression and construct the complete expression. Can any expert here guide me on how to get a solution to this so that this concatenation of 'AND' and 'OR' can be taken care of in a better way ..
Q: Feature with WebApplication scope - deploy only to one webapplication After deploying my new Sharepoint solution, containing a feature with WebApplication scope, I noticed that feature was added to ALL webapplications in the farm. The solution was deployed to a one particluar webapplication, so I wonder if such behavior is correct. Any way to make feature appear only in WebApplication, solution was deployed to? A: How did you deploy from powershell or from central admin? If you deployed from central admin you should have been given a list of web apps to deploy too, but if you did powershell and left off the WebApplication flag (http://technet.microsoft.com/en-us/library/ff607534.aspx), it would have deployed to all of the web apps. A: This is unfortunately by design. The solution is deployed to a single web application, e.g. but the features are visible on all web applications, i.e.: Feature /= solution. That means that some elements from the solution (not features) will appear only in the designated web application. One workaround is to hide the feature so that users cannot activate it. Check out also these posts: Is it possible to deploy a solution to a web application so that its features are only visible within this web application? Creating a solution that deploys to selected WebApplications but copies the assembly to GAC A: if the solution deployed to ABC webApp so it won't deployed to another WebApp, if it happened better remove from all WebApp and deploy to ABC webApp by PowerShell command. - Praveen
Q: recording EEG data using python ,brain flow and saving it into csv file. I an unable time stamp and channel name title in CSV file EEG device is OpenBCI and board is Cyton and daisy.My sample code is here: from datetime import datetime import argparse import numpy as np import pandas as pd import csv import mne from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds from brainflow.data_filter import DataFilter import time def main(): BoardShim.enable_dev_board_logger() # use synthetic board for demo params = BrainFlowInputParams() board = BoardShim(BoardIds.SYNTHETIC_BOARD.value, params) board.prepare_session() board.start_stream() now = datetime.now() current_time = now.strftime("%H:%M:%S") BoardShim.log_message(LogLevels.LEVEL_INFO.value, 'start sleeping in the main thread') time.sleep(10) data = board.get_board_data() board.stop_stream() board.release_session() eeg_channels = BoardShim.get_eeg_channels(BoardIds.SYNTHETIC_BOARD.value) # demo for downsampling, it just aggregates data for count, channel in enumerate(eeg_channels): print('Original data for channel %d:' % channel) print(data[channel]) print("Current Time =", current_time) # demo how to convert it to pandas DF and plot data # eeg_channels = BoardShim.get_eeg_channels(BoardIds.SYNTHETIC_BOARD.value) # df = pd.DataFrame(np.transpose(data)) # print('Data From the Board') # print(df.head(10)) # demo for data serialization using brainflow API, we recommend to use it instead pandas.to_csv() DataFilter.write_file(data, 'test.csv', 'w') # use 'a' for append mode # writing the data in csv file restored_data = DataFilter.read_file('test.csv') restored_df = pd.DataFrame(np.transpose(restored_data)) print('Data From the File') print(restored_df.head(5)) if __name__ == "__main__": main()
Q: setting style properties from jquery I am trying to make a script that adds a left and right border to a button in a line of 3 buttons when that button is clicked, and keep it with no border otherwise. The code I have so far is: $("#popular").click(function(){ clearBorders(); //make borders here (this works) }); $("#suggestions").click(function(){ clearBorders(); //make borders here (this works) }); $("recent").click(function(){ clearBorders(); //make borders here (this works) }); function clearBorders(){ $('popular').css("border", "solid"); $('suggestions').css("border", "none"); $('recent').css("border", "none"); } }); I am able to create the borders fine, but for some reason the clearborders method is not working. I know the function is being called because if I put an alert at the beginning of it, it shows up. Why won't this function work? A: Your selectors are missing the leading id (#) or class (.) designator symbol in your clearBorders() function A: I did a test of this and you need to do a $("document").ready(function(){}); wrapper. I had already adjusted to use classes so you might or might not work with ids. At least the test case below didn't work for me until I handled the document.ready. <script type="text/javascript"> $("document").ready(function(){ $(".popular").click(function(){ clearBorders(); } ); $(".suggestions").click(function(){ clearBorders(); // make borders here (this works) }); $(".recent").click(function(){ clearBorders(); //make borders here (this works) }); } ); function clearBorders(){ $('.popular').css("border", "1px solid red"); $('.suggestions').css("border", "1px solid red"); $('.recent').css("border", "1px solid red"); }; </script> rich
Q: gitignore in PHPStorm I create a .gitignore file and add two folders. But when I click "commit directory" in PHPStorm my folders are always in my commit changes. magento/media/ magento/var/ What is going wrong? In Terminal it works great A: Most likely, certain files inside those directories were already added to version control before the directories were added to .gitignore; note that the files listed as ignored in the command line and the ones being modified in the UI are not the same. You can remove them from source control (but not your working dir) with git rm --cached. Note that this will remove the file in other people's working directories when they do a git pull.