INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Cropping a UIImage makes it rotate 90º anti-clockwise upon saving I am making an app that has a fullscreen camera with `AVFoundation`. I was saving the UIImage directly without compressing it. And it gave me the desired output, i.e., it was saving images with the orientation they were taken. But when I tried to crop it to a rect (CGRect), it saved the image like before. Here's what I did: @objc func saveTapped() { myIndicator.isHidden = false guard let imageToSave = imageToShow else { return } let crop = CGRect(x: 0, y: 0, width: 1440.0, height: 2560.0) let croppedCGImage = imageToSave.cgImage?.cropping(to: crop) let croppedUIImage = UIImage(cgImage: croppedCGImage!) UIImageWriteToSavedPhotosAlbum(croppedUIImage, nil, nil, nil) myIndicator.stopAnimating() } I don't know how to save them in my desired orientation. Please help!
Change below line from let croppedUIImage = UIImage(cgImage: croppedCGImage) to let croppedUIImage = UIImage(cgImage: croppedCGImage, scale: imageToSave.scale, orientation: imageToSave.imageOrientation)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, uiimage, swift4, cgimage" }
Import-StartLayout does nothing for current user Using the command as follows: Import-StartLayout -LayoutPath "C:\Users\User\Desktop\Blank_Layout.xml" -MountPath "C:\" Unfortunately does not change the current Start Menu layout. It creates a new file under `C:\Users\Default\AppData\Local\Microsoft\Windows\Shell\LayoutModification.xml`, and it is blank. I'm hoping that is because I intended the layout to be blank, I also had to grant permissions to that folder to run the command in the first place. The information I used came from Technet, I do know that this can be pushed via GPO and added to an image, but that is not the intended goal for now.
This batch script worked for me, I'm in the process of converting it to a powershell script. Got it working but with a few errors. But the batch version worked 100% with no issues. It can be found here: GitHub
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "powershell, windows 10, startmenu" }
ggplot2 line between title and subtitle Is there a way to include a line, like a separator, between the title and the subtitle with ggPlot? I know how to color the background of the title (see this Post)
One possible solution is to manually trace a segment using `geom_segment` while setting `clip = "off"` on `coord_cartesian`: df <- data.frame(x = 1:10, y = 2:11) ggplot(df, aes(x = x, y = y))+ geom_point()+ labs(title = "Main Title", subtitle = "Subtitle")+ coord_cartesian(clip ="off")+ geom_segment(x =0.5, xend = 2.5, y = 12.1, yend = 12.1) ![enter image description here]( You will have to adapt the position based on data you are going to plot but it is one possible solution
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "r, ggplot2" }
How do I undo the last git commit while preserving changes? I've made a git commit that I haven't pushed yet, but I would like to remove the commit, but keep the changes to my file. How do I do that?
like this git reset --soft HEAD~1 git reset .
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "git, github" }
XML parsing format using php I am trying to parse Xml file using PHP but whenever i runs the code mit gives me error: invalid argument supplied for foreach() XML <?xml version="1.0" standalone="yes"?> <Rows> <Row Code="10004" Name="EDEN 46cm TROUGH Terracotta" /> </Rows> PHP code: $xml = simplexml_load_string(file_get_contents('XML/STKCatigories.xml')); $i = 0; foreach($xml->Rows->Row as $key=>$product) { echo '<li>'.anchor ('/shop/listings/'.$product->Code,$product->Name).'</li>'; } I couldn't understand where i am wrong.Kindly help me
It should be $xml = simplexml_load_string(file_get_contents('XML/STKCatigories.xml')); $prifix = '/shop/listings/' ; foreach ( $xml as $row ) { $attr = $row->attributes(); printf('<li>%s</li>', anchor($prifix . $attr->Code, $attr->Name)); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, xml, parsing" }
Solidity contract method not working on web3 I have a method on my contract: function reservePlace(address _address, uint _place) public{ require(places[_place] == 0, "Place is already reserved"); userIds[_address] = lastUserId; places[_place] = lastUserId; lastUserId += 1; } and it works perfectly on `truffle`, I can execute it and works well but when I use `web3` and I pass: contract.methods .reservePlace("0x95f086ee384d54a056d87dC8A64E354cC55E2690", 1) .call(); it doesn't do anything, also it doesn't show any error. Other methods work fine when I use them with `web3` so `web3` setup is correct. How can I solve it?
This is because you are calling data from the blockchain instead of sending it. In order for it to work, you should call: contract.methods.reservePlace("0x95f086ee384d54a056d87dC8A64E354cC55E2690", 1).send({from:'your authorized address'});
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "solidity, web3js" }
Sequence of sequences on an arbitrary metric space Let $(X,d)$ be a metric space and let $(x^{(n)})_{n=1}^{\infty}$ be a sequence in $X^{\mathbb{N}}$, that is, a sequence of sequences. Define a metric on $X^{\mathbb{N}}$ by \begin{equation} d'(x^{(n)}, x) := \sum_{k=1}^{\infty} \frac{1}{2^k} \frac{d(x_k^{(n)}, x_k)}{1 + d(x_k^{(n)}, x_k)} \end{equation} Show that if $x_{k}^{(n)} \to x_k$ for each $k$, i.e., for all $k$ and for all $\epsilon > 0$ there exists $N_k \in \mathbb{N}$ such that if $n \geq N_k$ then $d(x_k^{(n)}, x_k) < \epsilon$, then $x^{(n)} \to x$ where $x := (x_k)_{k=1}^{\infty} \in X^{\mathbb{N}}$. I thought maybe I should try to get a uniform $N$ that works for all $k$ but I realised shortly after that a maximum or supremum need not exist and now I am stuck.
Hints: $1).\ $ Choose $N$ so large that $\sum^{\infty}_{k=N} \frac{1}{2^k}<\frac{\epsilon}{2}$ and then $2).\ $ Note that For each $1\le k\le N-1$ there is an $n_k$ such that $d(x_k^{(n)}, x_k)<\frac{\epsilon}{2}$ as soon as $n>n_k.$ Now $3).\ $ Consider the sum $ \sum_{k=1}^{N-1} \frac{1}{2^k} \frac{d(x_k^{(n)}, x_k)}{1 + d(x_k^{(n)}, x_k)}.$
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "sequences and series, convergence divergence" }
References inside a customization opened in Visual Studio I am working inside Visual Studio 2017, I have 2 DAC's and 1 graph file all in App_Runtimecode, is there a build or other setting that I that I have to set so that the Graph can "find" the DAC's for the autocomplete? !Open Files Thanks
Files in App_RuntimeCode are compiled dynamically on demand by IIS. IntelliSense works on statically compiled code and therefore can't parse dynamic code. To have complete IntelliSense support requires creating an Extension Library instead of a Runtime customization project.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "acumatica" }
Should these Bitcoin Core build warnings be addressed or are they entirely harmless? When I build Bitcoin Core on MacOS I get a number of "overriding a member function" Boost warnings: e.g. /usr/local/include/boost/signals2/connection.hpp:212:34: warning: 'release_slot' overrides a member function but is not marked 'override' [-Wsuggest-override] Should these be addressed in future or are they entirely harmless and safe to ignore?
Yes, this particular warning can be ignored. The given file name is of a system dependency and so there is nothing that can be done about it except to wait for the boost project to fix the error and publish a fix that you can apply to your system. You can suppress these warnings by configuring with `--enable-suppress-external-warnings`.
stackexchange-bitcoin
{ "answer_score": 3, "question_score": 1, "tags": "bitcoin core development, compiling" }
Why do we have something like "-3.5ex \@plus‎ -‎1ex \@minus‎ -‎.2ex" instead of a fixed value? > **Possible Duplicate:** > What is glue stretching? In the book class, we have the following. ‎\newcommand\section{\@startsection {section}{1}{\z@}%‎ ‎{-3.5ex \@plus‎ -‎1ex \@minus‎ -‎.2ex}%‎ ‎{2.3ex \@plus.2ex}%‎ ‎{\normalfont\Large\bfseries}}‎ I want to know why we have something like `-3.5ex \@plus‎ -‎1ex \@minus‎ -‎.2ex` instead of a fixed value like `-3.5ex`? What are the `\@plus` and the `\@minus` for?
by default, the first line and the last line of every page should be on the same height. This is easy if you have only normal text lines with the same font size and without math, images, section headings and so on. But it is not easy if you have such of these objects. Then you need some parts which you can vertically stretch (plus) or shrink (minus). Those length is called a skip. Over (`\@plus‎ -‎1ex \@minus‎ -‎.2ex`) and under (`\@plus.2ex`) a section title is a good place to stretch/shrink. Also between paragraphs and so on. And the same problem in horizontal direction for a line. You can only stretch (plus) between words. All that is not needed if you use the commands `\raggedbottom` and/or `\raggedright`. But that always gives a lousy typesetting ...
stackexchange-tex
{ "answer_score": 9, "question_score": 11, "tags": "spacing, macros" }
Difference between float and unrestricted shares I am looking at a company's statistics on the OTC market and I'm confused about the difference between Float and Unrestricted shares. I thought that both are calculated using the formula `outstanding shares - restricted shares`. What is the difference? < ![DTII security details](
From my understanding: 1. Unrestricted shares = outstanding shares - restricted shares. 2. Float = unrestricted shares - shares "held directly or indirectly by an officer, director, any person who is the beneficial owner of more than 10 percent of the total shares outstanding (a “control person”), or any affiliates thereof, or any immediate family members of officers, directors and control persons". Source: <
stackexchange-money
{ "answer_score": 1, "question_score": 1, "tags": "stocks, shares" }
¿Enviar datos desde una aplicacion móvil a un servidor HTTPS garantiza cierta seguridad? Estoy creando una aplicacion móvil que tiene un sistema de login, utilizo javascript (AJAX) para enviar datos (realizar consultas) a un servidor web con PHP y que este me retorne respuestas. Leí un post acerca de como encriptar los datos pero que al fin y al cabo no servía de nada por que de todas maneras los datos se podían interceptar y que era mejor tener HTTPS. Por esto mi servidor web cuenta con HTTPS. ¿Esto garantiza cierta seguridad en el traspaso de datos entre este servidor y mi app?
Si claro, HTTPS garantiza cifrado entre el cliente (Tu aplicación) y el servidor, entonces si existe algiuen quien intercepte el mensaje no podra entenderlo...Es importante que el Servidor esté configurado con certificados firmados... Justamente eso es lo que hace HTTPS es el protocolo HTTP con seguridad SSL...Es el estandar adoptado por bancos, comercios electrónicos y otras entidades a nivel mundial para enviar mensajes....Es importante acotar, que usar solo HTTPS no garantiza que tu sistema sea seguro, esto es solo uno de los puntos que debes atacar en materia de seguridad, que en este caso evita ataques de hombres en el medio. Pero pueden haber otros tipos de ataques a parte de la capa de transporte.
stackexchange-es_stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "ajax, http, seguridad, app" }
Are JPA's Query objects returned by an EntityManager reusable? Let's say I'm in a loop creating JPA queries: for(A elem : collection) { emanager.createQuery("update A a set a.x=:y where a.id=:id") .setParameter("id",elem.id) .setParameter(":y", 123) .executeUpdate(); } Can I reuse the returned `Query` instance? Query query = emanager.createQuery("update A a set a.x=:y where a.id=:id"); for(A elem : collection) { query .setParameter("id",elem.id) .setParameter(":y", 123) .executeUpdate(); } Does it apply for all instances of `Query`? `NamedQuery`, `NativeQuery`, etc Of course, I'm talking about reusing an instance within the same `EntityManager`, ie, within the same transaction
It is reusable for Query. As far as I've tried working.
stackexchange-stackoverflow
{ "answer_score": -2, "question_score": 7, "tags": "java, jpa" }
Is a Delphi global procedure threadsafe If two or more threads call a standard Delphi/Pascal procedure (not a method of an object), **is this threadsafe ?** There is no instance data, just local variables in the procedure. My guess is that the local storage being used by one thread could be corrupted by the other thread.
Local storage is maintained on the stack, which is unique to each thread. If no global data is being manipulated by the routine, it is safe.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 5, "tags": "multithreading, delphi" }
How toxic is brake fluid? Is brake fluid especially toxic or is it about the same as dirty oil (not very toxic in trace amounts or just occasional human exposure). I'm trying to figure out how much effort I should put in cleaning up a DOT 3 brake fluid spill that happened a year ago. Thank you for any help!
Most brake fluids are not terribly dangerous. Throw sand on it to absorb anything left, use a grease-cutting cleaner to get rid of the stain. You may wish to try brake cleaner and paper towels.
stackexchange-mechanics
{ "answer_score": 1, "question_score": 6, "tags": "cleaning, brake fluid, toxins" }
Rails - wrong number of arguments (2 for 0..1) error I am having trouble with some code inside an application I am working on. With the following code: @herbivores=Deer.find(:all,:conditions =>['state like?', '%' + params[:number]+'%']) @[email protected](:all,:conditions =>['city like?', '%bad%']) I receive the error: wrong number of arguments (2 for 0..1) Can anybody explain what is happening?
Use the query API to keep the correct scope, and also do this more cleanly since `where` is chainable: @herbivores=Deer.where('state like ?', '%' + params[:number]+'%') @[email protected]('city like ?', '%bad%') You can also chain these directly without an intermediate variable: @herbi = Deer.where('state like ?', "%#{params[:number]}%").where('city like ?', "%bad%") Or you can merge it into one method call: @herbi = Deer.where('state like ? AND city like ?', "%#{params[:number]}%", "%bad%")
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ruby on rails, ruby, oop" }
failed to access perfctr msr - When running Fedora on a VM I'm trying to run a Virtual Machine with Fedora, and I choose to "Start fedora" from a list where I can start it or troubleshoot problems. The I get the following output: [ 0.00000] tsc: Fast TSC calibration failed [ 0.73...] Failed to access perfctr msr (MSR c00100044 is 0) I have tried 3 versions of Fedora (Desktop, MATE, LXDE). All give me the second line, MATE and LXDE give also the first line. Then the VM just hangs. What is the reason? What can I do? * The host runs Ubuntu and has an AMD processor with Virtualization enabled in the BIOS. * Running another version (the first from here) on a VM works fine. Running some lite version of Ubuntu also worked in the past. * I use the following command `qemu-system-x86_64 -hda fedora.img -boot d -cdrom fedora.iso -m 512`
Regarding: `Failed to access perfctr msr` This is a notification that the CPU does not support performance counters. These are only used to help the OS detect hanging (NMI Watchdog) and for PMU based performance analysis. This can be ignored. Regarding: `Fast TSC Calibration Failed` This can also be ignored or try the following: Add "clocksource=tsc" to grub sudo mousepad /etc/default/grub GRUB_CMDLINE_LINUX="clocksource=tsc" update "grub.cfg" sudo grub-mkconfig -o /boot/grub/grub.cfg reboot
stackexchange-superuser
{ "answer_score": 1, "question_score": 3, "tags": "ubuntu, virtual machine, fedora, qemu" }
atk V4.2.1 Working example sha256/salt new to atk and going well until I started to implement UserAuth using sha256/salt. I can register and it creates and stores an encrypted password but I cannot login. It works with no encryption. Has anyone implemented sha256/salt password encryption successfully? The examples on the site seem outdated in this regard and some documentation relating to this no longer exists. I cannot find any relevant examples so I am finding it a little difficult. Thanks in advance.
I'm using the following code in 4.2.1 now and it works fine... $auth=$this->add('Auth_Basic'); $auth->usePasswordEncryption('sha256/salt'); $auth->setModel('User','user','pwd'); $auth->check(); You'll have to create a Model ( _User_ here) that holds the username/pwd and such...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "atk4" }
Is connect() necessary if I want only to receive data in C/TCP? if I want ONLY to receive data from a client, and not send data out, is it necessary have a connect() in the code of my server? Or is it sufficient to have the following? socket(); bind(); listen(); accept();
This describes the basic principle of server-client interaction. As you can see, the client must `connect` to the server before any interaction. > Once you've built a socket descriptor with the socket() call, you can connect that socket to a remote server using the well-named connect() system call. Also the sequence you mentioned is in the `server`. If you want to only receive data from server, just do the `read` in client and `write` in server. But `connect` is neccessary. !Server-Client
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c, tcp, connect" }
Why does not the weight decrease in an ascending and accelerating lift? My textbook says that weight of a person in a lift that is accelerating in upward direction increases. But,why is it so? The acceleration of lift and the acceleration due to gravity are in opposite direction. Hence,weight of the person should be $m(a-g)$(where $m$ is the mass of the person,$a$ is the acceleration of lift and $g$ is the acceleration due to gravity. Then,where is my serious conceptual flaw? I have checked Why do we weigh less when falling? I donot find satisfactory explanation of my query there.
You asked if there's a serious flaw in the assumptions that you're making. The flaw is that Newton's law hold, in its simplest form, in an inertial frame only. So, if you have a lift which is going up with an acceleration $-a$, then you've to introduce a fictitious acceleration $a$ on the body. I have assumed the downward direction to be positive. So, the net acceleration downward is $a+g$. Always think about the acceleration on the body, rather than on the frame. Once you agree with this, you have the weight being equal to $m(a+g)$, and hence it has increased by $ma$
stackexchange-physics
{ "answer_score": 1, "question_score": -1, "tags": "newtonian mechanics, weight" }
A better way to convert Integer (may be null) to int in Java? An `Integer` can be `null`. I convert an `Integer` to an `int` by: Integer integer = null; int i; try { i = integer.intValue(); } catch (NullPointerException e) { i = -1; } Is there a better way?
Avoiding an exception is always better. int i = integer != null ? integer.intValue() : -1;
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 16, "tags": "java, integer, int, converters" }
Matlab, Find cell elements I have two cell arrays of string A and B. All cells of B are also in A. I want to find the index of cell of B in A. Thanks. Example: A= 'aaaa' 'bbbb' 'cccc' 'dddd' 'ffff' B= 'ffff' 'aaaa' ans= 5 1 or ans= 1 5
use either `intersect` or `ismember` [~, idxInA] = intersect(A,B) or LocInA = find(ismember(A,B))
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "string, matlab, find, cell" }
updating a record in Access table I'm using following query to update a record in an Access table, but I'm getting a syntax error? How can I do this? string str = string.Format("UPDATE [MIX] SET[Stock quantity],[Retail price],[Original price])Values(?,?,?,?) WHERE [Brand name]=@brandname"); OleDbCommand comd = new OleDbCommand(str, conn); comd.Parameters.AddWithValue("@brandname", comboBox3.Text); comd.Parameters.AddWithValue("Stock quantity", comboBox1.Text); comd.Parameters.AddWithValue("Retail price", comboBox4.Text); comd.Parameters.AddWithValue("Original price", comboBox5.Text); comd.ExecuteNonQuery();
What you need is something more like this: string str = "UPDATE [MIX] SET " + "[Stock quantity] = ?, " + "[Retail price] = ?, " + "[Original price] = ? " + "WHERE [Brand name] = ?"; OleDbCommand comd = new OleDbCommand(str, conn); comd.Parameters.AddWithValue("?", comboBox1.Text); // [Stock quantity] comd.Parameters.AddWithValue("?", comboBox4.Text); // [Retail price] comd.Parameters.AddWithValue("?", comboBox5.Text); // [Original price] comd.Parameters.AddWithValue("?", comboBox3.Text); // [Brand name] comd.ExecuteNonQuery(); Note that the parameters are defined in the exact same order that they appear in the CommandText.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, ms access, oledb" }
Excel VBA Mismatch Good evening. As the title implies: I require help with an Excel macro, that determines if there's anything in 2 cells, then in a third one the result of their subtract. I tried fiddling with the data and cell type. No results. Using: [h]:mm;@ and the data in the cells are "Time" in 24H Format. Dim e As Integer Dim r As Integer Dim w As Integer Dim i As Integer Dim q As Integer Dim one As String Dim two As String Dim k as long q = 3 w = 5 e = 3 r = 3 i = 4 For k = 1 To 7 one = Cells(e, r).Value two = Cells(e, i).Value If Cells(e, r).Value > 0 And Cells(e, i).Value > 0 Then Cells(q, w) = Cells(e, i).Value - Cells(e, r).Value 'pas.Cells(q, w) = two - one 'Range(q, w) = Cells(e, i).Value - Cells(e, r).Value else cells(q,w) = 0 end if next k
Why not use a formula? Cells are formatted using 24hr time "HHmm" however A1 & B1 data is as per below. A1 = `1:30:00 PM` displayed as `1330` B1 = `2:55:00 PM` displayed as `1455` Formula for C1 `=IF(OR(A1="",B1=""),0,B1-A1)` result displayed as `0125`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "excel, vba" }
How to find a window and push the button procedurally in WinAPI? I need to get the disk formatting dialog window handle and then press the button from my program. In other words, I have to open the disk formatting dialog manually: !enter image description here And then I launch my program. The program is needed to find the dialog window (maybe using something such as FindWindow() function, then find the "Start" button and send a message as it just pressed. How can I do this? I feel stuck.
No, you don't. For programmatic tasks, you use the programmatic APIs. Why would your program use the UI and simulate user input? Eg. use the Format method of Win32_Volume class.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "c++, windows, winapi" }
Visual Studio 2008 using the wrong framework version Using Visual Studio 2008, and I'm trying to use some of the .net Framework 3.5 utilities - specifically Extension Methods. However when I try and get to things in the System.Runtime.CompilerServices namespace, the required .Extension namespace is unavailable. If I go to "add reference" and look for System.Core - the required library for this functionality - it's in the list but is greyed out and unavailable, as are all the other 3.5 libraries. I have the 3.5 framework installed on my machine. Indeed many of the libraries are being loaded through web.config. Anyone know what's going on here and how I can fix it?
You need to set the project to the correct target framework version (in the project properties). Note that compiler features (such as declaring and using extension functions) is not dependent on the selected framework version, since those are independent of the CLR version (framework versions 2.0-3.5 uses the same runtime).
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "visual studio 2008, .net 3.5" }
Estilo de botón en vb Tengo un botón que llama una función que da números al azar cada que le dan click. Lo que quiero es que no se "note" cuando el usuario da click en el botón, es decir, que no parezca que se unde ni cambie de color al presionarlo, saben como hacer eso?
Esta solución es un poco cutre, pero hace exactamente lo que quieres, sin complicar demasiado. Yo he hecho un ejemplo muy sencillo. He creado una macro que dice "Hola mundo", y la he asignado a un botón: ![introducir la descripción de la imagen aquí]( Fíjate que el botón está hundido cuando hice clic. El truco consiste en hacer un pantallazo del botón, y meterlo como imagen. Recórtala justo por el borde. Algo así: ![introducir la descripción de la imagen aquí]( Pégala en tu archivo y asígnale una macro. Funcionará igual que un botón, pero no se hundirá al hacer click. Te quedará algo así: ![introducir la descripción de la imagen aquí](
stackexchange-es_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vba, vb" }
How to show withdraw payment amount in MetaMask? I'm using OpenZeppelin's PullPayment to handle payouts from my eth smart contracts. While withdrawing the coins with MetaMask, MetaMask shows 0 ETH when withdrawing for instance 2 ETH: ![MetaMask Notification when withdrawing payments]( Is it possible for the payout amount to appear in MetaMask?
It is not possible, due to the design of MetaMask. There are a couple of ERCs to show human-readable transaction data fields, but as far as I know none of them have been adopted yet.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ethereum, smartcontracts, metamask, openzeppelin" }
Wither a given FFTW lib was compiled in a single or double precision? Is there a way for to check - wither FFTW was compiled in a single or double precision?
If the name of the library is suffixed with an f, it is single precision. Otherwise it is double. E.g., libfftw3.a is double-precision libfftw3f.a is single-precision
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "fftw" }
OrbitControls - Can I enable/disable zooming dynamically? I'm running Three.js r69 with the bundled OrbitControls.js. I have a simple scene with a couple of objects that are selectable. I'd like to be able to disable zooming while an object is selected and re-enable it once I've cleared the selection. I'm working on a temporary solution, but it involves editing the OrbitControls.js code. This could make it really annoying to upgrade to a new version of Three.js, especially if OrbitControls is ever changed. Is there currently a way to enable/disable certain features (like zooming, panning, or orbiting) on the fly, independently of each other?
Is simple: controls = new THREE.OrbitControls( camera ); // to disable zoom controls.enableZoom = false; // to disable rotation controls.enableRotate = false; // to disable pan controls.enablePan = false;
stackexchange-stackoverflow
{ "answer_score": 39, "question_score": 15, "tags": "three.js" }
How to set the user_dump_dest parameter in oracle for SQL trace How to set the user_dump_dest parameter in oracle for SQL trace for the current session? alter session set user_dump_dest="C:\TKprof\Trace"; Is giving me ther error: > ORA-02096: specified initialization parameter is not modifiable with this
Try this: alter system set user_dump_dest = 'C:\TKprof\Trace' scope=both The `DBA` or `ALTER SYSTEM` privilege is required.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "oracle, database administration" }
Slight confusion with linked lists in C I'm reading about linked lists and their implementation in C on Wikipedia. I haven't picked up on them as quick as other C concepts. In the `list_add()` function, I am wondering why it says... n->next = *p; /* the previous element (*p) now becomes the "next" element */ I don't really understand the comment. Why would the previous element become the next? Shouldn't the new node become the next on the old node? Remember, I've just started looking at linked lists, so walk me through it slowly. Thanks. ### Update Sorry if it wasn't obvious, but all the code I am looking at is on the Wikipedia article.
In a simplest linked list implementation, new nodes are added to the front of the list, because it's easier. You only need a single pointer to the first node of the list and you don't have to search through the list to find the end. A more complex implementation might keep a front and end pointer in order to add to either end of the list.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "c, linked list" }
bash script array array=('org.battery.plist' 'org.disk.plist' 'org.memory.plist'); echo "1) org.battery.plist" echo "2) org.disk.plist" echo "3) org.memory.plist" echo "Enter selection(s) to load, separated by commas: " read var sudo launchctl load -w ${array[$var]} Am I on the right track? I'm a little stuck. Can someone help? If user inputs 1, 2, I expect the script to perform this below - sudo launchctl load -w org.disk.plist sudo launchctl load -w org.memory.plist
Try this, IFS="," for i in $var do sudo launchctl load -w ${array[$i - 1]} done You will also need to check whether the input is out of array bounds and throw and error.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "bash" }
Changing the origin/pivot point of the parent in Unity I create a game object, add some children to it, and would like the pivot point of the parent to be somewhere inside the area occupied by the children, not far away in the scene. Like in the example below, I have three blocks of platforms situated near each over. I add them into a parent, then try to move that parent and notice that the origin point of the parent is actually not somewhere between its children, but outside them on the upper right: ![Image showing transform gizmo on pivot well outside the child area]( Does someone know a way to change the origin point in such case?
The solution is straightforward. First remove all the children from under the parent and put them somewhere else in the hierarchy temporarily. Then move your parent's position to where you want it to be with respect to the children. After that, move all children back inside the parent with the help of Hierarchy view. Since the editor won`t move your objects in the Scene view if you make some changes in the Hierarchy view, the children will stay in the same net coordinates. So, after doing that you will get the origin point of the parent in any place that's convenient for you.
stackexchange-gamedev
{ "answer_score": 3, "question_score": 2, "tags": "unity, 2d, pivot" }
WCF 4 Rest Getting IP of Request? Hey, how do you get the IP address of the person making a request in something like the following: [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public partial class UsersService { [WebInvoke(UriTemplate = "", Method = "PUT")] public User AddNewUser(User newUser) { // code goes here including GETTING AN IP?? } Thanks!
Inside AddNewUser use following snippet: OperationContext context = OperationContext.Current; MessageProperties messageProperties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; RemoteEndpointMessageProperty instance offers Address and Port properties.
stackexchange-stackoverflow
{ "answer_score": 39, "question_score": 21, "tags": "c#, wcf, rest, tcp" }
How «cool confidence» could be understood? Context: > We'll help you answer those questions and others with **cool confidence**. I can guess that 'confidence' is like 'certainty', isn't it? But it's unclear is 'cool' about calm or cold mind?
In this context they are meaning that you will be able to deal with these questions unflustered, and with aplomb. Cool has multiple meanings. The one that fits best is > Free from excitement, anxiety, or excessive emotion. <
stackexchange-english
{ "answer_score": 2, "question_score": 1, "tags": "meaning, expressions" }
Drupal: make a text field collapsible Fieldsets in Drupal are collapsible. Is there a simple way to re-cycle this kind of functionality to a text field in a content type? A text field is typically rendered as <div class="field field-type-text field-field-my-field"> <div class="field-label"> My field Label: </div> <div class="field-items"> .... </div> </div> Like with a field set, how would one make the `field-label` clickable to collapse and expand the `field-items`? My current avenue of attack is to add the `collapsed` css class with jQuery when the page is rendered, but am wondering if this kind of thing is already available somehow in the Drupal framework.
This was easier than I thought: $(document).ready(function() { $(".field-field-mytextfield .field-items").css('display','none'); $(".field-field-mytextfield .field-label").click ( function () { $(this).parent().children( ".field-items").slideToggle('slow'); } ); });
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "jquery, drupal" }
Grouping data by MONTH on DATETIME column in SQL Server I have a table `Employee` which has the columns Id, Date of joining and Name Date of joining is a `DATETIME` column. I want to know how many users have joined in the month of October?
If you're just looking for October **regardless of the year** , then the easy way would be to just `COUNT` the records from that month: SELECT COUNT(*) AS NumberOfJoiners FROM Employee WHERE MONTH(DateOfJoining) = 10; or SELECT COUNT(*) AS NumberOfJoiners FROM Employee WHERE DATEPART(MONTH, DateOfJoining) = 10; If you want to group by year, then you'll need a group by clause, otherwise October 2013, 2014, 2015 etc would just get grouped into one row: SELECT DATEPART(YEAR, DateOfJoining) AS YearOf Joining, COUNT(*) AS NumberOfJoiners FROM Employee WHERE DATEPART(MONTH, DateOfJoining) = 10 GROUP BY DATEPART(YEAR, DateOfJoining);
stackexchange-dba
{ "answer_score": 7, "question_score": 7, "tags": "sql server, group by, datetime" }
AWS access keys and federation If an application runs in a corporate Data center (i.e. outside of AWS environment) and uses corporate credentials from its on premise Microsoft Active Directory as the sign in mechanism, would that application be able to federate into AWS programatically (i.e. use AWS federation, programatically) and access AWS resources via a role? I am trying to find out if this can be considered as an approach to avoid using access keys (access key ID and secret access key) within an application running outside of AWS environment.
You are probably looking for AWS Identity Pools, where you can integrate with custom identity providers and then exchange them for AWS credentials. Have a look at <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "amazon web services, amazon iam, federated identity" }
Find probability of B Computer A produced a bit. This bit was then sent to computer B, then from B sent to computer C, and finally from C to computer D. Every time one computer sends a bit to another, there's a 56% chance that an error will occur and the bit will change (from 0 to 1, or from 1 to 0). If the bit arrived "successfully" (meaning the value of the bit at A is the same as at D, an even number (including no changes at all) of changes occurred) to D, what's the probability that the bit was not changed when sent from A to B?
Let $0$ denote no change from one computer to the next, and let $1$ denote a change. Then the four different ways a bit can arrive successfully is $000$ with a probability of $ 0.44^3 $ and $110$, $101$ and $011$, each with a probability of $ 0.44\cdot 0.56^2 $. Given that the bit arrived successfully, the probability for a change from computer A to computer B is $$ \frac{0.44^3+0.44\cdot 0.56^2}{0.44^3+3\cdot0.44\cdot 0.56^2}. $$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability" }
Eclipse 'Compare' menu options are all disabled I recently upgraded my Subversion repository to version 1.6 and I'm connecting to it with Eclipse. However, when I check out a project branch and try to compare it with a different revision, (or any other circumstances for that matter) all of the options for comparison are disabled except for comparing with the base revision of the current working copy. Has anybody else encountered this, or possibly even found a solution ?
See bug 275287, fixed in the weekly builds (reported as such back in July). Since the latest release is the 0.7.8.I20090506-1500, from 04 September 2009, it may be also fixed in this official release as well. So to be sure, you could complete your question with the exact version of eclipse / and subversive plugin version you are using.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "eclipse, svn, comparison" }
Excel Multiple Selection Count I want to know how to count some cells in excel based on its contents. For example, I have something like this: aa ad sa fafv xcv aaw gadf aae I want to count all if it begins or contains "aa". How can this be acheived?
If list is in range A1:A8 use =COUNTIF(A1:A8,"*aa*") ' for contains =COUNTIF(A1:A8,"aa*") ' for begins with
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "excel, excel formula, excel 2007, excel 2003" }
I would like to know the best way to implement the following I have a collection of User data, and I want to get the first_name all those users. We can simply use user_list.map(&:first_name) similarly for middle and last name, I need to do the same user_list.map(&:middle_name) user_list.map(&:last_name) as we can see here I have to loop over the same data 3 times to get collection of first, middle and last name. Can anyone suggest me a way I can do that in a single loop. so the output will be like. {first_name: ["tom", "harry", "ronald"], middle_name: ["marvello", "james", "bilius"], last_name: ["riddle", "potter", "weasley"] } PS, its not an active record call to use pluck. Its a collection of record on which i need to run this, not a Active record call.
An obvious solution is an `each` loop: names = {first_name: [], middle_name: [], last_name: []} user_list.each do |user| names[:first_name] << user.first_name names[:middle_name] << user.middle_name names[:last_name] << user.last_name end Or using `each_with_object`: user_list.each_with_object(first_name: [], middle_name: [], last_name: []) do |user, names| names[:first_name] << user.first_name names[:middle_name] << user.middle_name names[:last_name] << user.last_name end
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby on rails, ruby, arrays, hash, enumerable" }
Adding button to right side of Hub header Unlike default "Back" button, I want to have "Add" button to the **right side** of the `Hub` header. Also that button should remain at its place like how header do. (so that it can be accessible from any `HubSection`) Expected result: !enter image description here Currently getting: !enter image description here
The solution is very simple. Instead of placing the button inside `<Hub.HeaderTemplate>` tag, place it in the `Grid` that contains the `Hub` itself. for example, <Grid> <Hub> .... </Hub> <Button> .... </Button> </Grid>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "xaml, windows store apps, win universal app" }
How can you add a dogear to a div or table cell using css? How can you add a dogear to a div or table cell to produce something like... dogeared div block
Found something similar in post How do you make this dogeared shape with css only. It put the dog ear in the bottom right. This does a more traditional dogear in the upper left. Use the following: CSS: .status-caution { text-align: center; background-color: #ffff99; } .status-good { text-align: center; background-color: #ccffcc; } .status-dogear { background: linear-gradient(135deg, #333 0%, #333 10%, transparent 10%, transparent 100%); } HTML: <table> <td class="status-caution status-dogear"> 5 </td> <td class="status-good"> 0 </td> <!-- for comparison without dogear --> </table>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Any real use for table-per-concrete-class with implicit polymorphism? If mapping inheritance using table per concrete class, while mapping concrete classes simply just as any other class (without union-subclass), NHibernate allows same PKs across subclasses. For example if you have BillingDetails and subclasses CreditCard and BankAccount, requesting all BillingDetails will get you all records from both tables, which can in turn have duplicate primary keys, which can be problematic due to not valid business identity of those objects. This of course is not the case with guids and such, but what about cases of plain identity or sequence id generators? Simply, the question is, is there any real use of this scenarion of duplicate id keys when requesting polymorphic query like that? Could these duplicate ids make problems for NHibernate when handling entities internally?
Implicit polymorphism is necessary when mapping legacy models where the tables do not share a common key. There are no problems with getting a list of BillingDetails with CreditCard and BankAccount instances sharing the same Id, because NH knows they are unrelated (and they are treated as related only for the purposes of querying, by running one query for each mapped subclass) You should not use it for greenfield development.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "nhibernate, orm, nhibernate mapping" }
The uniform convergence of $\int_0^\infty \mathrm{e}^{-ax^2}x^{2n}\mathrm{d}x \quad w.r.t \ a$ > For fixed $n\in \mathbb{N}$, study the uniform convergence of $$\int_0^\infty \mathrm{e}^{-ax^2}x^{2n}\mathrm{d}x \quad w.r.t \ a\in(0,\infty)$$. Actually I want to compute the integral by differentiating $$ \int_0^\infty \mathrm{e}^{-ax^2}\mathrm{d}x=\dfrac{1}{2}\sqrt{\dfrac{\pi}{a}}, $$ but we need to prove $$\int_0^\infty \mathrm{e}^{-ax^2}x^{2n+2}\mathrm{d}x $$ converges uniformly w.r.t $a>0$. Then the procedure is legal. The Weierstrass, Dirichlet and Abel criterion all seem do not work. Appreciate any help!
The convergence of the improper integral is uniform for $a$ in any interval $[A,\infty)$ where $A > 0$. This follows from the Weierstrass M-test since $|e^{-ax^2}x^{2n}| \leqslant e^{-Ax^2}x^{2n}$ for all $a \geqslant A$ and for any fixed $n$ the improper integral $\int_0^\infty e^{-Ax^2}x^{2n} \, dx$ converges. However, for any $c > 0$ and $a_c = 1/c^2 \in (0,\infty)$, $$\sup_{a \in (0,\infty)}\left|\int_c^{\infty} e^{-ax^2}x^{2n} \, dx\right| \geqslant \sup_{a \in (0,\infty)}\int_c^{2c} e^{-ax^2}x^{2n} \, dx\geqslant \sup_{a \in (0,\infty)}c \cdot e^{-a (2c)^2} c^{2n}\geqslant e^{-4a_c c^2} c^{2n+1}\\\ = e^{-4}c^{2n+1} \underset{c \to \infty}\longrightarrow \infty$$ Thus, the improper integral fails to converge uniformly (with respect to $a$) on $(0,\infty)$.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "real analysis, analysis, improper integrals, uniform convergence" }
The current path,didn't match any of these I have this in urls.py urlpatterns = [ path("product/<str:title>/<slug:pname>/<uuid:puid>",views.viewProduct), ] But when I try to click on the url. I got this error. The current path, product/amazon/home-secure-snake-shield-natural-snake-r/B0882NKXW7, didn't match any of these. Here I just want the puid but to match the pattern of URL I added str:title and str:pname I don't want the title and pname. But my URL patern is like this- product/store_name/product_name_slug/product_id
I replace the URL path urlpatterns = [ path("product/<str:title>/<slug:pname>/<str:puid>",views.viewProduct), ]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "django, django views, django templates, django urls, django url reverse" }
Having two versions of Python installed and installing a new module I have two installations of Python on my machine: * 1 : Python 2.7 32 bits (c:\python27) (installed first) * 2 : Python 2.7 64 bits (c:\python27-64) (installed more recently, **not** setup as system's default Python) When I install a new package with its standard Windows installer (e.g. `wxPython3.0-win64-3.0.0.0-py27.exe` for `wxPython`), there is no question like : _"For which installation of Python do you want to install this module?"_ Then this module is not recognized by my second Python install. **How to deal with module package installation when two versions of Python are installed ?**
An installer for `win64` and `py27` will automatically try to find the 64-bit Python 2.7 installation and install it for that. It won’t try to install it for an incompatible Python installation. For package installations via pip etc., you just need to call the correct one to install it for that version. So `C:\python27\Scripts\pip.exe` or `C:\python27-64\Scripts\pip.exe` in your case.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "python, python 2.7, python 3.x" }
CSS in ie only works with dev tools Been enjoying all the excellent answers on here for a while and now it's time for myself to hopefully get an answer for my question. I'm working on a web site with some pretty tight design. Works great in FF but when it comes to IE I have problems with the content not showing. The content that gives me problems is placed in width and height specific divs. Some of the content renderes properly but not all. I tried to use the IE dev tools and found that if I disable and/or enable any css rule the content will be rendered properly in IE. I can't figure out if the problem is in my css or an issue with my ie/bootcamp install. Should say that I run IE on a bootcamp partition on mac. Don't know if that has any impact on the issue. IE version is 8 Anyone experienced similar issues?
Ok, seems like it was a bug in IE/Dev Tools that somehow had to do with relative positioning. My CSS didn't work even though it seemed to when i enabled/disable any css rule through the dev tools. The fix was pure css and had nothing to do with IE, Dev Tools or my bootcamp installation. However, it does seem like I stumbled upon another bug in IE/Dev tools, that is, the fact that enabling or disabling a random css rule can change the rendering of of the entire page. I don't have time to investigate this at all so hopefully the right people are already aware of this and working on fixing it. Thanks for the help everyone.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "css, internet explorer" }
how to make validation rule for a field if another field is not empty in laravel I have two input field one is **startDate** input field and another is **endDate** input field.I want to make validation rule such that if **startDate** field is not empty than **endDate** should not be empty and vice versa.So How to make validation rule for that.Below is the validation I have put on it 'startDate' => [ 'nullable', 'date_format:d-m-Y' ], 'endDate' => [ 'nullable', 'date_format:d-m-Y', 'after_or_equal:startDate' ]
**First Method is** request()->validate([ 'startDate' => [ 'nullable', 'date_format:d-m-Y' ], 'endDate' => [ 'required_with:startDate', 'date_format:d-m-Y', 'after_or_equal:startDate' ] ]); **Second Method** request()->validate([ 'startDate' => [ 'nullable', 'date_format:d-m-Y' ], 'endDate' => [ 'nullable', 'date_format:d-m-Y', 'after_or_equal:startDate' ] ]); if(!empty(trim(request("startDate")))){ request()->validate([ 'startDate' => [ 'required', 'date_format:d-m-Y' ], 'endDate' => [ 'required', 'date_format:d-m-Y', 'after_or_equal:startDate' ] ]); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, laravel, laravel 5" }
String to numeric conversion using regex in scala Hi have an array of numbers as string: `val original_array = Array("-0,1234567",......)` which is a string and I want to convert to a numeric Array. val new_array = Array("1234567", ........) How can I aheive this in scala? Using original_array.toDouble is giving error
The simple answer is ... val arrNums = Array("123", "432", "99").map(_.toDouble) ... but this a little dangerous because it will throw if any of the strings are not proper numbers. This is safer... val arrNums = Array("123", "432", "99").collect{ case n if n matches """\d+""" => n.toDouble } ... but you'll want to use a regex pattern that covers all cases. This example won't recognize floating point numbers ("1.1") or negatives ("-4"). Something like `"""-?\d*\.?\d+"""` might fit your requirements.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "regex, scala" }
working with console writeline c# I need to output the value of `d` using the same `Console.WriteLine`. But i am only getting _Result_ not the value of `d` in output. In what way i can achieve this? namespace ConsoleApplication2 { class Program { static void Main(string[] args) { int a; int b; Console.WriteLine("Please Enter the first Digit"); a = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Please Enter the Second Digit"); b = Convert.ToInt32(Console.ReadLine()); int d = a + b; Console.WriteLine("Result",(d)); } } }
Use: Console.WriteLine("Result {0}", d); You are using this overload. UPDATE If you look at the link above, you can read how it works. In short, first you specify the formatting, where {0} references the first value of the param object-array, {1} references the second value of the param object-array, etc. After the format, you give the objects to use. So in your case, you need a single value, which means two arguments, a format, and a value. Hence "Result {0}" with d, which will become (when for example d=10) "Result 10". Note: also removed the unnecessary parenthesis.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 3, "tags": "c#" }
Get the number of GPUs used in Tensorflow Distributed in a multi node approach I am currently trying to compare Horovod and Tensorflow Distributed API. When using using Horovod, I am able to access the total number of GPUs currently used as follows: import horovod.tensorflow as hvd size = hvd.size() A similar concept is available when using PyTorch Distributed API: size = int(os.environ["WORLD_SIZE"]) * * * I would like to perform the same operation and obtain the number of GPUs currently in use for multi GPUs/nodes with TF Distributed official API. I can't use `CUDA_VISIBLE_DEVICES` environment variable as it would only work on a single node.
A few findings which answer my question: * Equivalent of `hvd.size()`: (the session must be started and initialized first unlike hvd ! Else you will just get "1") ==> `tf.distribute.get_strategy().num_replicas_in_sync` * Equivalent of `hvd.rank()`: (the session must be started and initialized first unlike hvd ! Else you will just get "0") def get_rank(): replica_id = tf.distribute.get_replica_context().replica_id_in_sync_group if isinstance(replica_id, tf.Tensor): return tf.get_static_value(replica_id) != 0) else: return 0 * Is TF Distributed running ? : `tf.distribute.has_strategy() => True/False` (same remark as above, else you just get False)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, tensorflow, nvidia, distributed" }
Regular expression that matches a number How can I improve this regular expression? (((\s|^)(\d+)*(\s|$))|((\s|^)(\d{1,3})(\.\d{3})*(\s|$))) I want to recognise only the numbers from a string. The numbers must be without anything, or if it has dot must be grouped in groups of three but must be taken as a whole number. the number can begin with whitespace or to be at the begining of the line and can end with whitespace or end of the line. Currently if the string beggins with whitespace it will find only the whitespace.
You may use (?<![\d.])\b(?:\d{1,3}(?:\.\d{3})*|\d+)\b(?!\.\d) See the regex demo **Details** : * `(?<![\d.])` \- there should be no digit or dot immediately before the current position * `\b` \- a leading word boundary, there must be start of string or a non-word char before the current position * `(?:\d{1,3}(?:\.\d{3})*|\d+)` \- 1 of the 2 alternatives: * `\d{1,3}(?:\.\d{3})*` \- 1 to 3 digits followed with zero or more sequences of `.` and 3 digits * `|` \- or * `\d+` \- one or more digits * `\b` \- a trailing word boundary * `(?!\.\d)` \- there must be no dot and a digit immediately after the current position.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "regex" }
Are there d3.js best practises for custom selections? I am new to d3.js. I understand that I can select a whole group of nodes with `selectAll`, e.g. `node = svg.selectAll(".node")` and call methods on all of them. However, if I don't want the methods to be applied to all nodes, but e.g. to all except one node, how would I best do that? Do `selectAll` on another subset defined by e.g. another class? Or more generally put: Given d3.js specific selection approach, what is the idiom for selecting different subsets of nodes? Define a class for every subset and select based on that class? I wonder if in such a scenario a `for` loop over all nodes with `if`s selecting subsets would be a good solution?
You can chain `selectAll()` like that : d3.selectAll("tr").selectAll("td"); (see < Or you can use `filter()` to remove some elements (see < Or you can exclude one element like that d3.selectAll('.node:not(#idToExclude)').remove() (see this example <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "d3.js" }
How select rows with multiple conditions and calculate a new column in the original dataframe I need to use the following code: raw_data.loc[(raw_data['PERMNO']==10006)&(raw_data['month']>=50)&(raw_data['month']<=100)]['resi']=raw_data['RET']-raw_data['ewretd'] that is based on the conditions to calculate column 'resi'. But I keep getting warnings like D:\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: < """Entry point for launching an IPython kernel. How to correct this?
Try adding `df.copy`: raw_data = raw_data.copy() raw_data.loc[(raw_data['PERMNO']==10006)&(raw_data['month']>=50)&(raw_data['month']<=100), 'resi'] = raw_data['RET'] - raw_data['ewretd']
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, pandas, dataframe" }
Why does ReplaceAll match pattern while MatchQ fails Why does the following pattern with `MatchQ` fail MatchQ[1+Sin[1] I, a_Complex /; Im[a] > 0] (* False *) Whereas, the same pattern with `ReplaceAll` works? 1 + Sin[1] I /. {a_Complex /; Im[a] > 0 -> 3} (* 1+3Sin[1] *) 1 - Sin[1] I /. {a_Complex /; Im[a] > 0 -> 3} (* 1-iSin[1] *) If I look at the `FullForm` of my expression it is `Plus[1,Times[Complex[0,1],Sin[1]]]`. Shouldn't `a_Complex` match `Complex[0,1]` and `Im[a] == 1 > 0` evaluate to `True`? At least that's what seems to be happening with `ReplaceAll` but I can't quite figure out why `MatchQ` fails.
`MatchQ` matches the whole expression. It doesn't match inner rules. In[1]:= MatchQ[12345, _Integer] Out[1]= True In[2]:= MatchQ[{12345}, _Integer] Out[2]= False `ReplaceAll` works recursively over a whole function, replacing all instances of that pattern it finds. That's the meaning of `All` in the function name. A careful reading of the usage messages for `MatchQ` and `ReplaceAll` would have explained this.
stackexchange-mathematica
{ "answer_score": 2, "question_score": 1, "tags": "pattern matching, replacement" }
python script from crontab vs console : print and logging ordered differently From this python script: import logging print('normal print') logging.error('logger test error') If I run this script from command line I get: $ python3 ./test.py normal print ERROR:root:logger test error Now if I set up a cron job with the same script as follow: 25 10 * * * python3 ~/test.py I get the following email: ... Content-Type: text/plain; charset=UTF-8 ... Date: Fri, 8 Oct 2021 10:25:01 +0200 (CEST) ERROR:root:logger test error normal print We see that the output is reversed. What's happening here ?
I found an eligible answer at < Basically, I suppose that cron redirects the command output somewhere to generate the email and that buffering is happening - which is not the case for console output. Here, print()'s output is buffered (eg. not flushed). However, `logging` _does_ flush the stream after each call.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, logging, cron" }
Define default return value/function of a class? Can I create a class with a default return value? Lets say if I create an object of this class I get always a specific value, without calling the properties or something else. Example: int i = new MyIntClass(/*something*/); //will return an int Actually I would like to use a default function for returning something. Maybe like this: class MyCalculator() { public double a { get; set; } public double b { get; set; } MyCalculator(double a, double b) { this.a = a; this.b = b; } public double DoMath() { return a*b; } } /* somewhere else */ double result = new MyCalculator(5.5, 8.7); `result` should be the result of `DoMath()`. Is that possible? I know its maybe not the best example, but something like this would be nice. Any ideas?
You can do an implicit cast. Example (add to class): public static implicit operator double(MyCalculator c) { return c.DoMath(); }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c#, .net" }
parameter name used more than once in postgresql My project used MS SQL, and postgresql so I can't change my parameter to another name, something like below CREATE OR REPLACE FUNCTION myfunction( ReservationNo integer) RETURNS TABLE("reservationno" integer) AS $BODY$ begin RETURN QUERY select rr.ReservationNo FROM Mytable rr WHERE rr.ReservationNo = myfunction.ReservationNo; end $BODY$ LANGUAGE plpgsql VOLATILE COST 100 ROWS 1000; ALTER FUNCTION myfunction(integer) OWNER TO postgres; But it give me an error > parameter name "reservationno" used more than once How can I fix it?
You can change it to a SQL function, which doesn't have this problem: CREATE OR REPLACE FUNCTION myfunction( ReservationNo integer) RETURNS TABLE("reservationno" integer) AS $BODY$ select rr.ReservationNo FROM Mytable rr WHERE rr.ReservationNo = myfunction.ReservationNo; $BODY$ LANGUAGE sql stable ;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "postgresql" }
Converting a number to datetime sql I have the number 20080331. I need to cast/convert this into a datetime so I can do a date comparison within the database. How will i go about converting this number. Using CONVERT(DATETIME, Value) does not seem to work.
SELECT CONVERT(DATETIME, CAST(20110331 AS VARCHAR(8)), 112)
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "sql, sql server" }
How to pass a array's total elements as an function's postion parameter? I had a array in c: int array[] = {1, 2, 3, 4}; and I had a function's protype like this: int add_all(int a, int b, int c, int d); But how can I pass the array's all elements as the function's parameter at one time? I know in python, this can be done like this: array=[1,2,3,4] add_all(*array) Could someone tell me how to achieve the same effect in C?
Use this: int add_all(array, 4); When you call a function, and you try to pass it an array, this array will be converted to a pointer to the first element of the array. Function prototype int add_all(int[] , int size); or int add_all(int* , int size);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c" }
XPDL XSD to MySQL DDL I want to convert this schema < to MySQL DDL statements. Unfortunately, i don't have much time to do this. What would be the quickest and easiest way to accomplish this task?
No perfect solution for this. XMLSpy comes close but there is no fully automated way to convert XSD to DDL.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql, xml, xsd, ddl" }
Make a delete function I tried to implement a function that automatically does this: del data['method_code'] del data['aqi'] del data['local_site_name'] del data['cbsa_name'] I have this function: def del_data_func(data,columns): data[columns] = data[columns].apply(lambda x: del(x)) return data del_list = data.columns[['method_code','aqi','local_site_name','cbsa_name']] del_data_func (data, del_list) How can i implement it in the right manner and avoid any errors like this one : data[columns] = data[columns].apply(lambda x: del(x)) SyntaxError: invalid syntax
I don't know if `lambda` is requirement, otherwise one way is to `loop`: If `df` is: col1 col2 col3 col4 col5 0 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 4 5 5 5 5 5 Then, function can be written as: def del_data_func(data,columns): for column_name in columns: del data[column_name] Now, calling the function: del_list = ['col2', 'col4'] del_data_func (data, del_list) print(data) Output: after `col2` and `col4` are removed: col1 col3 col5 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python 3.x, pandas" }
GeoAlchemy get closest point to another point I have loaded into my db the `cities1000.txt` available here. I am attempting to create a query using `GeoAlchemy` to return the nearest city when I pass in Lat and Long. I currently have the query setup using `ST_ClosestPoint`, but it returns the same city no matter what lat/lon values I pass in. Here is the query I have written so far: q = db.session.query(cities1000, func.ST_ClosestPoint(cities1000.c.geom, func.Geometry(func.ST_GeographyFromText( 'POINT({} {})'.format(lon, lat))))).first() Is `ST_ClosestPoint` what i'm looking for? Performance is a concern.
I was unable to get this query working with `ST_ClosestPoint`, but the following seems to work with `ST_Distance`: q = db.session.query(cities1000.c.name, cities1000.c.stateRegion, cities1000.c.country).\ order_by( func.ST_Distance(cities1000.c.geom, func.Geometry(func.ST_GeographyFromText( 'POINT({} {})'.format(lon, lat))))).limit(1).first()
stackexchange-gis
{ "answer_score": 5, "question_score": 4, "tags": "python, postgis, geoalchemy" }
Firebase DB how does the offline cache works on android? I am wondering if I cache all the data from firebase and after turn off the wifi it will work as well as was before. But if I turn off the wifi and restart the phone and enter the program without wifi, will it work?
Yes, you can still query the data, as it's been persisted on the device's storage. This should be pretty easy for you to try for yourself.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, firebase" }
Parametric Equations Problem Im back! Um, i have a simple question im trying to get ready for test after 5 days.. I slacked of sadly :( on math, so i have to pick up my skills.. On my test review i have this question: The parametric equations of a vector are $x_t=3+5t$ and $y_t=-1+3t$. Find the vector equation and the Cartesian equation. I dont understand above, because i couldnt remember what my teacher told me about this one.. Can somone help me out! Much appreciated for reading thankyou!
Presumably, the vector equation _is_ the vector $r=\left[3+5t,-1+3t\right]$ or the equation $r=\left[5,3\right]t+\left[3,-1\right]$, and the Cartesian equation would just be $y=\frac{3}{5}(x-3)-1$ or $y=\frac{3}{5}x-\frac{14}{5}$. Just solve for the parameter $t$ in the first equation, and then substitute it into the second. $t=\frac{1}{5}(x_t-3)$, and so $y_t = -1 + 3(\frac{1}{5}(x_t-3))$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "parametric" }
Python as back-end and Polymer as the front-end I want to create a desktop application written in python and using polymer as the front-end. To access the user interface, we use web browser such as chrome, mozilla, and safari. I did a lot of research in how to do this. The only reference I have is home Assistant, but I'm still don't quite understand about the architecture and the approach. Anyone have another solution or approach in how to do this?
python ships with a basic http server, however according to the docs it's not made for production use. But it's probably good enough for your use case (single user). On top of this you can implement a basic REST-Api and serve your frontend (.js/.html) as static content. Or use a framework like django <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, polymer, desktop application" }
Why can't use the Int value from hashUnique? I want to store the value returned from hashUnique into a list, but I can't do that: import Data.Unique import Data.List as L cnter = do u <- newUnique return (hashUnique u) main = cnter:[] It will give out the error message : `No instance for (Show (IO Int)), arising from a use of 'print' at <interative>`
`cnter` is an IO action that returns an Int. That is, `cnter` has type `IO Int`. You are trying to use it as an `Int`. What you really want is to execute the action, obtaining the `Int`, and then use that result: import Data.Unique import Data.List as L cnter = do u <- newUnique return (hashUnique u) main = cnter >>= \c -> print [c] Or with do notation: main = do c <- cnter print [c] But I'm not sure why you want to construct a list just to print it, I'd just `print c`, personally: main = cnter >>= print
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "haskell, monads" }
Closed Windows Retaining Their Values/Choices I have an application that has a few different forms. From the main form I can open a number of other forms, I use the following command to display the chosen window: frmConversions.ShowModal; Once the user has completed what they need to do in that window and they close that window I close the window using the following: frmConversions.Close; However if the user then goes back to frmConversions, the settings that they had previously chosen will still be selected/entered. Am I handling multiple windows correctly and if so how do I stop the retention of data?
It depends on how you create the form. If you auto-create the form, then it will exist for the lifetime of the program and so will retain any values stored in the form's variables. If, however, you create modal forms whenever needed and free them afterwards (as is the custom), then values will _not_ be stored. This is done thus with TFrmConversions.Create(nil) do try ShowModal; finally Free; end;
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 4, "tags": "windows, delphi, user interface" }
Python CSV Add Numbers to Empty Cells Python 3.8. I've a CSV file with 12,000 rows and 4 columns. One column has over 4000 blank cells in various places. Starting at the top, I need to place a sequential number in each blank cell starting at 1. **Existing** : First,Sec,Third,Fourth R,E,C,D S,F,C,D blank,S,C,D V,G,C,D blank,Q,C,D blank,F,C,D E,W,C,D **Proposed** : First,Sec,Third,Fourth R,E,C,D S,F,C,D 1,S,C,D V,G,C,D 2,L,C,D 3,F,C,D E,W,C,D I'm a bit of novice but this where I got to. Thank you in advance. import csv with open('Original.csv', newline='') as DataIn2: fileReader2 = csv.reader(DataIn2) Start_Number = 0 Number_Fill = Start_Number + 1 if (fileReader2['Data ID'].isnull().Number_Fill else next(row) ??? with open('New.csv', 'w', newline='') as DataOut2: fileWriter2 = csv.writer(DataOut2)
Its easier to use pandas and process the df then you can save the processed df: import pandas as pd df = pd.read_csv('Original.csv') Start_Number = 1 for i,row in df.iterrows(): if pd.isnull(row['Data ID']): df.loc[i,'Data ID'] = Start_Number; Start_Number +=1 df.to_csv('New.csv')
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, pandas, csv" }
When does Urbanization occur in Age of Steam I am second in turn order, I select Urbanization. Do I place the city at the start of my build track phase or before the first person who builds track?
You place the new city as your first action during your Build Track phase. On page 2 of the rules > **Urbanization action:** > > Implemented during the Build Track phase. This action allows this player to place one of the New City tiles on a Town **before** they build their track. This is from the Warfrog edition (2002). It seems the rules haven't changed much at all despite the plethora of editions.
stackexchange-boardgames
{ "answer_score": 3, "question_score": 3, "tags": "age of steam" }
Showing two metrics are equivalent. Let $(X,d)$ be a metric space. Define $$d_1(x,y)=\frac{d(x,y)}{1+d(x,y)}$$ (do you know the name of this metric?) Show that the metrics $d$ and $d_1$ are equivalent. **Edited** : Captain Lama pointed out that I was looking for strong equivalence which is not there. So how do I show they are equivalent?
Consider a point $p\in X$, and let $U^1$ be any $d_1$-neighborhood of $p$. Then there is an $\epsilon>0$ with $U_\epsilon ^1(p)\subset U^1$. Since $d_1(x,y)<d(x,y)$ it follows that $$U_\epsilon(p)=\\{x\>|\>d(x,p)<\epsilon\\}\subset\\{x\>|\>d_1(x,p)<\epsilon\\}=U_\epsilon ^1(p)\subset U^1\ .$$ This shows that $U^1$ is a neighborhood of $p$ with respect to $d$ as well. Conversely: Consider a point $p\in X$, and let $U$ be any $d$-neighborhood of $p$. Then there is a positive $\epsilon<1$ with $U_\epsilon(p)\subset U$. Since $$d(x,y)={d_1(x,y)\over 1-d_1(x,y)}\leq 2d_1(x,y)$$ when $d_1(x,y)<{1\over2}$ it follows that $$U^1_{\epsilon/2}(p)=\\{x\>|\>d_1(x,p)<\epsilon/2\\}\subset \\{x\>|\>d(x,p)<\epsilon\\}=U_\epsilon (p)\subset U\ .$$ This shows that $U$ is a neighborhood of $p$ with respect to $d_1$ as well. Altogether we have proven that $(X,d)$ and $(X,d_1)$ possess the same open sets.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "real analysis, metric spaces" }
Logistic model solution in r I have fit a logistic model and I want to know the value of x when y=0.5. library("faraway") data = read.table("SBay.txt", header=T) female = subset(data,sex==2) amat = c(0,1) mod1 = glm(amat[maturity]~age,family=binomial,data=female) summary(mod1) (len_50 = (log(1)-mod1$coef[1]) /mod1$coef[2]) (plot(female$age,amat[female$maturity],pch=1,col=2)) s = seq(0, 20, 0.1) lines(s,ilogit(mod1$coef[1]+mod1$coef[2]*s),col=2,lty=2,lwd=2) I google the answer and get: F1 = ilogit(mod1$coef[1]+mod1$coef[2]) F2 = 0.5 solve(F1,F2) I got the answer equal to 9.931613, however, it doesn't match the graph I've plot. SO I think there might be something wrong with my code. Here are my graph, it seem the answer is between 2 and 3. <
What you need is the `predict` function followed by an `ifelse` expression: # Logistic Regression Classifier mod1 = glm( amat[maturity]~age,family=binomial,data=female) # Probabilities prob_pred = predict( mod1, type = "response", newdata = female) # probability outcomes # Outcomes (True/False) y_pred = ifelse( prob_pred > 0.5, 1, 0) # NOTE: the 0.5, it filters outcomes > 0.5 probability
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r" }
Slicing byte arrays in Java I'm trying to slice a byte array to prune the first part of the array. I'm using ByteBuffer but it does not behave like I would expect. byte[] myArray = new byte[10]; ByteBuffer buf = ByteBuffer.wrap(myArray); buf.position(5); ByteBuffer slicedBuf = buf.slice(); byte[] newArray = slicedBuf.array(); I would expect the size of newArray to be 5, containing only the last portion of my ByteBuffer. Instead, the full byte array is returned. I understand that this is because the "backing buffer" is the same all along. How can I slice to have only the desired part of the array? EDIT: Added context The bytes are received from network. The buffer is formed like this : `[ SHA1 hash ] [ data... lots of it ]` I already have a function that takes a byte array as a parameter and calculate the SHA1 hash. What I want is to slice the full buffer to pass only the data without the expected hash.
You can use the `Arrays.copyOfRange` method. For example: // slice from index 5 to index 9 byte[] slice = Arrays.copyOfRange(myArray, 5, 10);
stackexchange-stackoverflow
{ "answer_score": 128, "question_score": 54, "tags": "java" }
Highlight the minimize the browser window I have create a custom call messenger which is working perfectly fine without any issue. I need a suggestion for when i minimize the messenger browser window and that time if any call comes in i want to show some kind of indication in terms of pop out that window or highlight. I have tried `window.focus` which work if the window is not focus but when it's minimized it's not working. Is there any other way which way i can show any indication to particular window.
You need to take a look at javascript Notifications for that Additionaly you could change the `document.title` or the favicon to indicate that this tab has some notifications like YouTube does it for example with the counter of notifications in the title
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, html" }
Scraping Names with Rvest I am trying to scrape the names from the following webpage: < This is the code I have used library(rvest) rod_phillips<-html(' Rod_phillips %>% + html_node("#employees .small") %>% + html_text() But, when I type in this code, I just get [1] NA. Any advice?
Try this: rod_phillips <- jsonlite::fromJSON(" postions <- rod_phillips$positions Short explanation: I opened chrome, click `F12` key, and than network. Than I paste your url to url tab. After you click enter, you can track what's happening in the network. You are mostly interested in `XHR` part. There you can see the site is sending GET requests to the server with with `aplication/json` response. This is a laic explanation (I don't know much about networks).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "r, web scraping, rstudio, rvest" }
Not understanding 'Possible leak of an object' error 346 - NSFileManager *fileManager = [[NSFileManager alloc] init]; 347 - [fileManager removeItemAtPath:[mediaSource.newMediaToDelete objectAtIndex:i] error:nil]; 348 - [fileManager release]; The error points towards line 348 and says: > 'Potential leak of an object allocated on line 347' I don't understand this, obviously line 347 isn't an allocation, and the allocation on line 346 is already released.
Avoid using the 'new' or 'create' in your own method names (unless they return objects that are not autoreleased I guess). It confuses the static analyser. I've had this issue and found it went away when I changed my method name. Update: I see Bavarious has already noted this in the comments.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "iphone, objective c, xcode, memory leaks" }
Shadow only plane isn't working. Keeps sending me the ground as being pitch black, and I have compared it to a working file I have tried copying the settings from (< To no evail. Here is my .blend (<
![enter image description here]( Any questions on this solution I came up with, just ask. Sorry for the late reply. Hope this helps the rest of you! You can use an HDRI with this BTW!
stackexchange-blender
{ "answer_score": 0, "question_score": 1, "tags": "cycles render engine, compositing nodes" }
What is the docker run -r flag I am looking at this repo: < To run with Docker we'd use docker run --rm --name=gitleaks zricethezav/gitleaks -v -r I am having trouble figuring out what the `-r` flag is doing...it doesn't look like it's making it read-only, does anyone know? <
The `-v -r ...` apply to the container process **not** to the `docker` command. The way to read this is in 2 parts: 1. Run a command `gitleaks` using `docker run --rm --name=gitleaks zricethezav/gitleaks` 2. Provide `gitleaks` flags and params with `-v -r You can (often) determine what flags|parameters a container instance wants by running the process without any flags|parameters or giving it `--help`, i.e. docker run -it --name=gitleaks zricethezav/gitleaks --help Usage: gitleaks [OPTIONS] Application Options: -r, --repo= Repo url to audit ... Example: ... -v, --verbose Show verbose output from gitleaks audit ...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "docker, docker run, gitleaks" }
Write an .htaccess rewrite rule excluding one file I'm working with a framework and need to make a call to a specific file within a directory, however the directory is set up for url of all requests to index.php for the framework's sake. I have a file called `check-session.php` and need any requests to `localhost/admin/check-session.php` to execute the actual check-session.php file instead of route to `index.php`. How do I do that with .htaccess file within the same folder as `check-session.php`? I have little to no experience with rewrite rules / conditions.
Find the RewriteRule that rewrites to index.php and put these directly before it: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteCond %{REQUEST_URI} !\.php$ That should stop it mapping to index.php if it's a real file you request. If that doesn't work, post the actual rewrites in .htaccess
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, regex, apache, .htaccess" }
What is the purpose of declaring typealias for generic type parameter Consider following code: public struct Foo<E: Hashable>: Equatable, Collection { public typealias Element = E private var array: [Element] ... } This kind of coding practice can be found in many places, including official Apple code-bases like < What is the purpose of declaring typealias `Element` instead of using `Element` directly as generic type parameter name like: public struct Foo<Element: Hashable> { private var array: [Element] ... } Is it just some sort of coding preference, or there are some other reasons, like achieving some functionality that could not be made without such simple typealias declarations?
Declaring a public typealias makes it possible to access the generic type parameter outside of the closed generic type. For example if you declare a typealias `WidgetFoo = Foo<Widget>` and keep using `WidgetFoo` in other places it will be possible to access its `T` via `WidgetFoo.Element`(which refers to `Widget`) whereas you cannot access the generic type parameter `E` itself. This enables robust and refactoring friendly code - imagine you want to replace `Widget` with `BetterWidget` you only have to change one place (the type alias declaration) and no other because `WidgetFoo.Element` will then refer to `BetterWidget`. * * * Example code (provided by @Airspeed Velocity) struct S<T> { typealias U = T } typealias TA = S<Int> let x: TA.T // 'T' is not a member type of 'TA' (aka 'S<Int>') let y: TA.U
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 9, "tags": "swift, generics" }
What is the designated initializer for SKLabel node in Swift I was wondering what the designated initalizer for SKLabelNode is in the Swift programming language with SpriteKit?
init(fontNamed:) is the designated initializer. Convenience initializers have the convenience keyword.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "swift, sprite kit" }
docker container not able to reach some of host's ports I have a stack with docker-compose running on a VM. Here is a sample output of my `netstat -tulpn` on the VM Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 0.0.0.0:9839 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:8484 0.0.0.0:* LISTEN The docker is able to communicate with port `9839` (using `172.17.0.1`) but not with port `8484`. Why is that?
That's because the program listening on port 8484 is bound to 127.0.0.1 meaning that it'll only accept connections from localhost. The one listening on 9839 has bound to 0.0.0.0 meaning it'll accept connections from anywhere. To make the one listening on 8484 accept connections from anywhere, you need to change what it's binding to. If it's something you've written yourself, you can change it in code. If it's not, there's probably a configuration setting your can set.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "docker, networking, netstat" }
http response to GET request - working in FF not Chromium For fun I'm trying to write a very simple server in C. When I `send` this response to Firefox it prints out the body "hello, world" but with Chromium it gives me a `Error 100 (net::ERR_CONNECTION_CLOSED): Unknown error.` This, I believe, is the relevant code: char *response = "HTTP/1.0 200 OK\r\nVary: Accept-Encoding, Accept-Language\r\nConnection: Close\r\nContent-Type: text/plain\r\nContent-Length:20\r\n\r\nhello, world"; if(send(new_fd, response, strlen(response), 0) == strlen(response)) { printf("sent\n"); }; close(new_fd); What am I missing? Thanks!
Content-Length seems to be 12, not 20. < > When a Content-Length is given in a message where a message-body is allowed, its field value MUST exactly match the number of OCTETs in the message-body. HTTP/1.1 user agents MUST notify the user when an invalid length is received and detected Doesn't that mean FF violates specs? (Well, you are using HTTP/1.0, so maybe not.)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c, http, network programming" }
How to read encrypted assertions? I'm writing a SAML2 service provider/relying party. My IdP is returning Assertions in an encrypted form (EncryptedAssertion element). Is this Assertion decryption scenario supported by `ITfoxtec.Identity.Saml2`? I'm getting this exception: ITfoxtec.Identity.Saml2.Saml2RequestException: There is not exactly one Assertion element. at ITfoxtec.Identity.Saml2.Saml2AuthnResponse.GetAssertionElementReference() at ITfoxtec.Identity.Saml2.Saml2AuthnResponse.GetAssertionElement() at ITfoxtec.Identity.Saml2.Saml2AuthnResponse.Read(String xml, Boolean validateXmlSignature) at ITfoxtec.Identity.Saml2.Saml2PostBinding.Read(HttpRequest request, Saml2Request saml2RequestResponse, String messageName, Boolean validateXmlSignature) at ITfoxtec.Identity.Saml2.Saml2Binding`1.ReadSamlResponse(HttpRequest request, Saml2Response saml2Response) Thank you!
Finally got it! I just needed to set `Saml2Configuration.DecryptionCertificate`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": ".net core, saml, itfoxtec identity saml2" }
Multiple instances of IEntityChangeTracker error get when try to insert data into database in c# Multiple instances of IEntityChangeTracker error get when try to insert data into database in c#. I try to search solution to debuge this code but i can't get anythink from it.now help me to resolve this. public void insertdatarootmasterDetails(TblRootMasterDetail objstud1) { DBLaxmiTatkalEntities2 objentity1 = new DBLaxmiTatkalEntities2(); objentity1.TblRootMasterDetails.AddObject(objstud1); objentity1.SaveChanges(); }
You can use the AddObject function for adding newly created items. It seems like objstud1 is previously selected from the EF context. In this case you should use the Attach function instead. objentity1.TblRootMasterDetails.Attach(objstud1); objentity1.Entry(objstud1).State = System.Data.Entity.EntityState.Modified; objentity1.SaveChanges();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": ".net, entity framework, asp.net mvc 4" }
Apply a Regex with a conditional lookaround Suppose those sentences: > My name is James Bond > > My name is the famous James Bond I want to capture `James Bond`. If I apply `((?<=is)(.*)`, it takes `James Bond` for the first and `the famous James Bond` for the second. If I apply `((?<=famous)(.*)`, it takes James Bond for the second sentence. Doing that does not work, logically: ((?<=famous)|(?<=is))(.*) Is it possible to end up with one regex returning `James Bond` in both cases? As the Regex engine parser works, I'm pretty sure that a programmatic way is more relevant for this use case, but I'm not so sure. **EDIT-----------** The Regex should handle any case where there is a "is" or/and "famous", not only those both sentences, taken as examples.
You may get the last occurrence of `is` or `famous`: .*(?:famous|is)\s*(.*) The result is in Group 1. See the regex demo. **Details** * `.*` \- any 0 or more chars other than line break chars as many as possible * `(?:famous|is)` \- a `famous` or `is` substring (use word boundaries if they must be whole word) * `\s*` \- 0+ whitespaces * `(.*)` \- Group 1: any 0 or more chars other than line break chars as many as possible.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "regex, regex lookarounds" }
Arithmetic Sequence with conditions The question is: Let $\\{a_n\\}$ be an arithmetic sequence with the following conditions: $S_{16} = 376$ and $a_{16} = 46$, where $S_n$ is the sum of terms $a_1$ through $a_n$. Find $a_1$.
Using the two relevant formula for APs you have: $$376=S_n=16\cdot a_1+\frac{16\cdot15}{2}d=16\cdot a_1+120d$$ $$46=a_n=a_1+15d$$ The first can be simplified to: $$\frac{47}{2}=a_1+\frac{7}{2}d$$ The second one minus this gives: $$\frac{45}{2}=\frac{15}{2}d$$ $$d=3$$ Subbing $d$ back in gives: $$a=1$$
stackexchange-math
{ "answer_score": 1, "question_score": -4, "tags": "algebra precalculus, arithmetic" }
NSString Append EXC_BAD_ACCESS Url Connection I am new to Objective-C however I am slowly making progress. All I would like to do is append a new string to a current string. I need to do this for my `NSURLConnection` so that I can put all the data into one string. I currently have something like this, however it does work and I don't fully understand why and what I need to do to fix it. NSString *temp = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; html = [htmlTemp stringByAppendingString:temp]; htmlTemp = html; Thanks For any help I am sure its something to do with the memory however I don't fully understand that either.
`StringByAppendingString` is a convenience method that does not start with "new" or contains "alloc" or "copy", the returned string will be `autoreleased` most likely in the next run cycle, which is why when you try to read it again from html, it has already been released. To fix this you can send a `copy` message like this: htmlTemp = [html copy]; I would recommend making htmlTemp a property like this: @property (nonatomic, copy) NSString *htmlTemp; This way when you assign a new value to it, using the setter, the old value will get released, before pointing to the new value that way you can do: self.htmlTemp = [htmlTemp stringByAppendingString:temp];
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "objective c, ios, string, append, nsurlconnection" }
R: Best way to convert a mts to a non-time series dataframe with time indexes I'm currently using the following method to convert a mts dataset to a data frame with time indexes as columns. Is there a more elegant way to do this? z <- ts(matrix(rnorm(300), 100, 3), start=c(1961, 1), frequency=12) YM<-cbind(Year=as.numeric(floor(time(z))),Month=as.numeric(cycle(z))) z<-cbind(as.data.frame(YM),as.data.frame(z)) str(z)
Try this: data.frame(Year = c(floor(time(z) + .01)), Month = c(cycle(z)), z) or as.data.frame(cbind(Year = floor(time(z) + .01), Month = cycle(z), z))
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "datetime, r, data structures, time series" }
How to create a boost thread with data? I'm running into some issues with boost::bind and creating threads. Essentially, I would like to call a "scan" function on a "Scanner" object, using bind. Something like this: Scanner scanner; int id_to_scan = 1; boost::thread thr1(boost::bind(&scanner::scan)); However, I'm getting tripped up on syntax. How do I pass the data into scan? As part of the constructor?
Keep in mind that the first argument to any member function is the object. So if you wanted to call: scanner* s; s->scan() with bind you would use: boost::bind(&scanner::scan, s); If you wanted to call: s->scan(42); use this: boost::bind(&scanner::scan, s, 42); Since I often want bind to be called on the object creating the bind object, I often do this: boost::bind(&scanner::scan, this); Good luck.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 4, "tags": "c++, multithreading, boost" }
How to set an expiration date in java I am trying to write some code to correctly set an expiration date given a certain date. For instance this is what i have. Date lastSignupDate = m.getLastSignupDate(); long expirationDate = 0; long milliseconds_in_half_year = 15778463000L; expirationDate = lastSignupDate.getTime() + milliseconds_in_half_year; Date newDate = new Date(expirationDate); However, say if i the sign up date is on 5/7/2011 the expiration date output i get is on 11/6/2011 which is not exactly half of a year from the given date. Is there an easier way to do this?
I would use the Calendar class - the add method will do this kind of thing perfectly. < Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH, 6); java.util.Date expirationDate = cal.getTime(); System.err.println(expirationDate);
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "java, date" }
particular solution guess to $2e^x + e^{-x}$ Why is the guess to the particular solution of $y''-2y'+y = 2e^x + e^{-x}$ equal to $Ax^2*e^x+Be^{-x}$ and not $Ae^x+Be^{-x}$?
This is because $1$ is a double root of the characteristic equation $\lambda^2-2\lambda +1=0$. So $e^{ x}$ and $xe^{x}$ are both solutions of the homogeneous equation, and we have to go to $x^\color{red}{2} e^x$ (next power of $x$) when looking for a particular solution.
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "ordinary differential equations" }
iOS custom keyboard on iPad I'm building an iPad app witch will use a numeric keyboard. The numeric keyboard for the iPad is really huge, all i need is something smaller, something like the decimal keyboard for the iphone. If i use the default one, half the screen gets covered with keys i dont need. I know i can move the textfields out of the way but it is such a waste of screen space. So i tried building a custom UIView with no button for start and setting the textfield.inputview to my custom UIView. The only thing i got is that my custom view is displayed like/in place of/the stock keyboard and the only thing i can change is the height of the custom view. How could i build a sort of custom keyboard that apple will accept and works with the textfields. Thank you.
I found what i was looking for. The answer is UIPopover. I managed to build a custom keypad inside a uipopover. Here's a good tutorial for the uipopover: < And here's some more info on what you have to do to make it work: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "ios, uiview, keyboard, uitextfield" }
Delay image loading with jQuery I have a page with several galleries including accordions and sliders. The problem is that the page takes forever to load. Is there a way of wrapping an image in a bit of code or applying a class to it to force it to load only after everything else is loaded?
Sure you can. Replace your img src attributes with a "#", and add a custom attribute, something like this: <img src="#" data-delayedsrc="/img/myimage.png" /> Then, add a javascript line when your page loads that does something like this: $('img').each(function(){ $(this).attr('src', $(this).data('delayedsrc')); });
stackexchange-stackoverflow
{ "answer_score": 59, "question_score": 29, "tags": "javascript, jquery, html, css" }
Applications frequently losing mouse focus I am programming in Windows 7 and the applications I am using are increasingly losing mouse focus; the system, at times, is unusable as a result. A restart does not solve the problem, Microsoft Security Essentials has not identified any threats, and MalwareBytes is coming up empty. The only "odd" thing is that the ApplicatioLog is full events like these: `Skipping: Eap method DLL path validation failed. Error: typeId=23, authorId=8086, vendorId=0, vendorType=0` I am currently downloading any updates I can think of, and have tried disabling Bluetooth as per this post. What might be causing the focus problem? What techniques can I use to diagnose the problem?
The problem was caused by Lenovo's Access Connections software. When the wireless connection is dropped, it steals focus. (I cannot determine in my environment whether it is a bug in Access Connections dropping the connection or if the wireless network is to blame, but it is definitely a response to a dropped connection; if I had to guess, I am inclined to believe it is the wireless environment and not the program itself causing the connection to be dropped.)
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "windows 7, mouse, window focus" }
Is the order of parameter estimates preserved from multiple simple regressions to one multivariable regression? Assume I have $y$, $x_1$ and $x_2$. I regress * $y\sim\alpha_0 + \alpha_1 x_1$, * $y\sim\beta_0 + \beta_1 x_2$ and * $y\sim\gamma_0 + \gamma_1 x_1 + \gamma_2 x_2$ using Ordinary Least Squares. Does $\alpha_1 \geq \beta_1$ imply $\gamma_1 \geq \gamma_2$? If not, are there "simple" conditions under which it would?
**No.** I don't know under what conditions your conjecture would hold, but I found a counterexample to its most general form by brute force. If $x_1 = (0, 2, 1)$, $x_2 = (2, 1, 2)$, and $y = (0, 1, 2)$, then the model coefficients are: * $α_0 = \frac{1}{2}$, $α_1 = \frac{1}{2}$ * $β_0 = 1$, $β_1 = 0$ * $γ_0 = -6$, $γ_1 = 2$, $γ_2 = 3$
stackexchange-stats
{ "answer_score": 1, "question_score": 2, "tags": "regression, least squares" }
How do i split a text 2 by 2? The variable is: Hello The result I want: split[0] = he; split[1] = ll; split[2] = o + ( space ); I tried this code: string[] split = new string[text.Length / 2 + (text.Length % 2 == 0 ? 0 : 1)]; for (int i = 0; i < split.Length; i++) { split[i] = text.Substring(i, i + 2 > text.Length ? 1 : 2); } The output is "He el lo" (it doubles the second character).
I think this code will help: string text = "1234567"; int loop = text.Length / 2 + (text.Length % 2 == 0 ? 0 : 1); List<string> split = new List<string>(); int readTotal = 0; int textLen = text.Length; for (int i = 0; i < loop; i++) { if (textLen- readTotal >= 2) split.Add(text.Substring(i * 2, 2)); else split.Add(text.Substring(i * 2, 1)); readTotal += 2; }
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": -2, "tags": "c#, arrays, string, split" }