qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
664,740
I am trying to understand the proof of the following: Suppose $U,W$ are vector subspace of $V$, then $\dim (U+W)+\dim (U \cap W)= \dim (U) +\dim (W).$ The proof goes like this: Let $S: V \rightarrow V/W$ be the natural surjection. Then we have $\dim (V) = \dim (W) +\dim (V/W)$ by rank-nullity. Now let $T: U \rightarrow (U+W)/W$. Then we have $\dim \ker (T)= \dim (U \cap W)$ and $\dim Im (T)= \dim (U+W) - \dim (W)$ and the result follows. Basically I don't understand what is going on after "Now let $T$..." I don't understand how is $T$ actually define, and why the rank and nullity of $T$ equals that (which I think will be clear once I know how $T$ is defined), could someone please help, thanks!
2014/02/05
[ "https://math.stackexchange.com/questions/664740", "https://math.stackexchange.com", "https://math.stackexchange.com/users/126452/" ]
$T$ is defined as the composition $U\to U+W\to (U+W)/W$, where the first map is just the inclusion, and the second map is the canonical projection.
111,834
I'm using [ICMP time stamping](https://stackoverflow.com/questions/20172028/awk-hping-print-difference-between-icmp-originate-receive/20186781#20186781) on my mid-2013 MacBook Air, and I need my clock to have an accuracy of no worse than 1ms. I see that `ntpd` is running, with the default settings, and `/etc/ntp.conf` contains just one line, `server time.apple.com`, without even any comments. However, if I run `ntpdate -d time.apple.com` (or `ntpdate -d ntp1.yycix.ca`, which produces the same offset reading for any given time as time.apple.com farm does), always as a non-root user, I'm often getting the reading that my clock is offset by as much as 6ms, or, most often around 4ms (sometimes 0ms, but very rarely). Why is this happening? I'm not even rebooting my MacBook, it runs 24/7, plugged in, why is its `ntpd` not keeping the time correctly? Syslog has the following: ``` % syslog | fgrep ntp | fgrep -v sudo | tail Nov 19 12:59:30 mba.cnst ntpd[86861] <Notice>: proto: precision = 1.000 usec ``` Last I checked, `1.000 usec` is no worse than 1 us, which is 0.001ms, or 0.000001s; why does it claim that precision is 0.001ms, when in reality the clock is offset by as much as 6ms?
2013/11/26
[ "https://apple.stackexchange.com/questions/111834", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/37893/" ]
**The `server` keyword of [ntp.conf(5)](http://mdoc.su/f/ntp.conf.5) would appear to configure only a single server, even if the provided hostname resolves to more than one IP address.** It would appear that the specific server that was being selected is a PoS. ``` mba: {4899} ntpdc -s ; ntpdc -sn remote local st poll reach delay offset disp ======================================================================= *time.apple.com 129.xx.xxx.xxx 2 4096 377 0.07106 0.000248 0.24763 remote local st poll reach delay offset disp ======================================================================= *17.151.16.22 129.xx.xxx.xxx 2 4096 377 0.07106 0.000248 0.24763 mba: {4900} ntpdate -d 17.151.16.22 |& tail -1 ; \ ? ntpdate -d time.apple.com |& tail -1 ; \ ? ntpdate -d ntp1.yycix.ca |& tail -1 26 Nov 01:49:13 ntpdate[97738]: adjust time server 17.151.16.22 offset -0.000318 sec 26 Nov 01:49:16 ntpdate[97740]: adjust time server 17.171.4.15 offset -0.006493 sec 26 Nov 01:49:16 ntpdate[97742]: adjust time server 192.75.191.6 offset -0.006443 sec mba: {4901} ``` Going to **Date & Time Preferences**, and providing a comma-separated list of valid NTP servers seems to fix the issue. Providing a comma-separated list in GUI results in several `server` entries in /etc/ntp.conf, although you have to make sure that the hostnames themselves are different (otherwise, the repeated hostnames don't result in any extra actual servers being selected, as per `ntpq -p`). ``` mba: {5104} cat /etc/ntp.conf server ntp1.yycix.ca server time.nist.gov server tick.usask.ca server tock.usask.ca server clock.nyc.he.net mba: {5105} ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== +ntp1.yycix.ca .GPS. 1 u 138 512 377 56.517 -0.662 0.319 -2610:20:6f15:15 .ACTS. 1 u 117 512 377 27.975 -1.774 0.989 +tick.usask.ca .GPS. 1 u 456 512 377 31.388 -0.636 0.135 *tock.usask.ca .GPS. 1 u 124 512 377 31.486 -0.864 0.413 -clock.nyc.he.ne .CDMA. 1 u 139 512 377 26.860 -2.161 0.194 mba: {5106} ``` A list of servers is available at <http://support.ntp.org/servers>; you have to try to select the servers that are close to you, especially not just geographically, but network-wise.
36,678,381
As my iPhone application gets increasingly more complicated, I find it more and more annoying to trace certain data structures that get passed throughout my project to various files. Just recently I noticed that I was setting my array to nil in some part of the code when I should have been removing all objects. This caused me to add objects to a nil array. Is there any way to take a look at a certain memory location and just have a debugger catch any modifications to the data structure? I know there's an option in Xcode to catch the point of an error occurring whilst debugging, so I'm wondering if there is another option, or way, or suggested method to catch the modifications to a specific structure (NSArray, NSDictionary, etc...)
2016/04/17
[ "https://Stackoverflow.com/questions/36678381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2977578/" ]
Instead of using the `partialPlot` function, consider using the `plotmo` function in the [plotmo](https://cran.r-project.org/web/packages/plotmo/index.html) package. This will draw plots for all variables and variable pairs on a single page. For example: ``` library(randomForest) data(trees) mod <- randomForest(Volume~., data=trees) library(plotmo) plotmo(mod, pmethod="partdep") # plot partial dependencies ``` which gives ![plot](https://i.stack.imgur.com/R4yjZ.png) You can specify exactly which variable and variable pairs get plotted using plotmo's all1, all2, degree1 and degree2 arguments. Additional examples are in the [vignette for the plotmo package](http://www.milbo.org/doc/plotmo-notes.pdf).
94,875
[![enter image description here](https://i.stack.imgur.com/gjwZd.png)](https://i.stack.imgur.com/gjwZd.png) I have a plane and a loop cut that is highlighted as shown in the image above. I wanted to know how do I scale the plane to the exact dimensions of the loop cut?
2017/11/21
[ "https://blender.stackexchange.com/questions/94875", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/48629/" ]
You may do it using a ***snapping tool***. First select the edge loop in *Edit Mode* (`Alt`+`RMB`) and snap the cursor to it (`Shift`+`S`-->*Cursor to Selected*). Then select the plane in *Object Mode* and press `Shift`+`S`-->*Selection to Cursor [Offset]*). [![enter image description here](https://i.stack.imgur.com/MVsiA.gif)](https://i.stack.imgur.com/MVsiA.gif) Next press the *magnet icon* to enable the *snapping tool* and change its type to *Vertex*. Scale the plane until it snaps to the loopcut's border. [![enter image description here](https://i.stack.imgur.com/9iGFO.gif)](https://i.stack.imgur.com/9iGFO.gif) To see the loopcut in *Object Mode* check the *Wire* and *Draw All Edges* checkboxes in *Display* panel of the *Object* header. [![enter image description here](https://i.stack.imgur.com/nuQSM.png)](https://i.stack.imgur.com/nuQSM.png) For irregular planes you can scale along the chosen axes (e.g. `S`,`Y`). [![enter image description here](https://i.stack.imgur.com/lgwKF.gif)](https://i.stack.imgur.com/lgwKF.gif) You may also snap the plane to the corner of the edge loop in *Object Mode*. Then change the *pivot point* type to *3D Cursor*, snap the cursor to the corner of the plane in *Edit Mode* with `Shift`+`S`-->*Cursor to Selected* and then scale it until it fits the edgeloop. [![enter image description here](https://i.stack.imgur.com/K66IM.gif)](https://i.stack.imgur.com/K66IM.gif)
452,125
I'm asking this question out of my curiosity. Is there anyway around to configure apache2 with the php that had been install through yum? Or vice versa? Because based on my self experiences and goggling,we can only install both packages from repo (yum install httpd php) or install both form source on their respective site. Hope someone can clarify this matter.I really appreciate that.Thanks.
2012/11/26
[ "https://serverfault.com/questions/452125", "https://serverfault.com", "https://serverfault.com/users/119720/" ]
The technology you are looking for is called RAID (Redundant Array of Independent/Inexpensive Disks). You can create a disk array on a number of levels. * Hardware controller (LSI Logic etc) or integrated storage (Drobo etc) * Software on the driver level like Dynamic Disks (windows), mdraid (Linux/MacOS) * Software on the volume or filesystem level like ZFS, Logical volume managers (LVM) Any of these might be suitable for a web server, exact configuration depending on requirements. I'll add that 4 TB drives have just started appearing, which could significantly lower the cost of a 20-30 TB array.
34,101,634
I have found SDK of Signalr for Android: <https://github.com/SignalR/java-client>. My code is working fine when web app is hosted on IIS but when I deploy on Azure, it's not able to connect; it waits forever While my javascript client code is working fine. I follow following to deploy my web app: <http://www.asp.net/signalr/overview/deployment/using-signalr-with-azure-web-sites> Following log I received ``` AutomaticTransport - Response received<br/> AutomaticTransport - Read response data to the end<br/> AutomaticTransport - Trigger onSuccess with negotiation data: {"Url":"/signalr","ConnectionToken":"4GGnSKxMOsuP6jkG1det5Z3Ch073H6ixe3Ium6k69k/RAM/x2KJkHP03XkNnPx56EatX8qxDmSOASS7HGKm5UJtsTqCP71YVJ05vLYrAT4pLYzecAwxziEUotCyVUpOc","ConnectionId":"28e1bb42-f03d-42b9-a874-171be7531eef","KeepAliveTimeout":20.0,"DisconnectTimeout":30.0,"ConnectionTimeout":110.0,"TryWebSockets":true,"ProtocolVersion":"1.3","TransportConnectTimeout":5.0,"LongPollDelay":0.0}<br/> HubConnection - Negotiation completed<br/> HubConnection - ConnectionId: 28e1bb42-f03d-42b9-a874-171be7531eef<br/> HubConnection - ConnectionToken: 4GGnSKxMOsuP6jkG1det5Z3Ch073H6ixe3Ium6k69k/RAM/x2KJkHP03XkNnPx56EatX8qxDmSOASS7HGKm5UJtsTqCP71YVJ05vLYrAT4pLYzecAwxziEUotCyVUpOc<br/> HubConnection - Keep alive timeout: 20.0<br/> HubConnection - Entered startLock in startTransport<br/> HubConnection - Starting the transport<br/> HubConnection - Starting transport for InitialConnection<br/> HubConnection - Getting connection data: [{"name":"myhub"}]<br/> HubConnection - Getting connection data: [{"name":"myhub"}]<br/> ```
2015/12/05
[ "https://Stackoverflow.com/questions/34101634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2153858/" ]
Based on @BNK's comments & my understanding, I post the answer for people have the same issue. I reviewed the code `Connection.java` (<https://github.com/SignalR/java-client/blob/master/signalr-client-sdk/src/main/java/microsoft/aspnet/signalr/client/Connection.java>) that has two functions called `start`. The code of function `start` with no argument below use the `AutomaticTransport` as the default `ClientTransport`. ``` public SignalRFuture<Void> start() { return start(new AutomaticTransport(mLogger)); } ``` And I continued to review the code `AutomaticTransport.java` (<https://github.com/SignalR/java-client/blob/master/signalr-client-sdk/src/main/java/microsoft/aspnet/signalr/client/transport/AutomaticTransport.java>). It try to select the one of the three `ClientTransport` in the function `initialize` that contains `WebSocketTransport`, `ServerSentEventsTransport` & `LongPollingTransport`, please see below. ``` private void initialize(Logger logger) { mTransports = new ArrayList<ClientTransport>(); mTransports.add(new WebsocketTransport(logger)); mTransports.add(new ServerSentEventsTransport(logger)); mTransports.add(new LongPollingTransport(logger)); } ``` The reason of the issue might be the server using SignalR on Azure that not implement for supporting the three transport of `AutomaticaTransport`. So using the function `public SignalRFuture<Void> start(final ClientTransport transport)` of Class `Connection` to select a transport suppored by the server-side manually to solve the issue.
60,919,566
My unit tests in Visual studio almost never run saying 'Test not run'. This happens regardless of the project. All day Yesterday they ran and passed with the only issue being a test in a test class I deleted still passed for some reason. I didn't do anything different yesterday, I just open Visual Studio as normal. I closed my laptop lid last night and attempted to run them again this morning and now they will not run again. Has anyone had this issue before? I have Visual Studio 2019.
2020/03/29
[ "https://Stackoverflow.com/questions/60919566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13002976/" ]
I believe the problem was that my desktop folder that contained my project was in my One Drive. I moved it to my C drive and now the tests run again.
50,502,664
**MyContext.js** ``` import React from "react"; const MyContext = React.createContext('test'); export default MyContext; ``` I created my context in a separated `js` file where I can access my parent as well as my child component **Parent.js** ``` import MyContext from "./MyContext.js"; import Child from "./Child.js"; class Parent extends Component { constructor(props) { super(props); this.state = { Message: "Welcome React", ReturnMessage:"" }; } render() { return ( <MyContext.Provider value={{state: this.state}}> <Child /> </MyContext.Provider> ) } } ``` So I created the parent component with a Provider context and calling child component in the provider tab **Child.js** ``` import MyContext from "./MyContext.js"; class Child extends Component { constructor(props) { super(props); this.state = { ReturnMessage:"" }; } ClearData(context){ this.setState({ ReturnMessage:e.target.value }); context.state.ReturnMessage = ReturnMessage } render() { return ( <MyContext.Consumer> {(context) => <p>{context.state.Message}</p>} <input onChange={this.ClearData(context)} /> </MyContext.Consumer> ) } } ``` So in child by using the `Consumer`, I can display the data in child rendering part. I'm facing an issue when I want to update the state from the consumer. How to update provider state or manipulate state of provider?
2018/05/24
[ "https://Stackoverflow.com/questions/50502664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9786905/" ]
You could use the useContext hook to achieve this. It's quite easy to use it in the child elements of the Provider. As an example... authContext.js ``` import { createContext } from "react"; const authContext = createContext({ authenticated: false, setAuthenticated: (auth) => {} }); export default authContext; ``` Login.js (component consuming the Context) ``` import React, { useContext } from "react"; import authContext from "./authContext"; export default () => { const { setAuthenticated } = useContext(authContext); const handleLogin = () => setAuthenticated(true); const handleLogout = () => setAuthenticated(false); return ( <React.Fragment> <button onClick={handleLogin}>login</button> <button onClick={handleLogout}>logout</button> </React.Fragment> ); }; ``` Finally the index.js ``` import ReactDOM from "react-dom"; import React, { useState } from "react"; import authContext from "./authContext"; import Login from "./Login"; const App = () => { const [authenticated, setAuthenticated] = useState(false); return ( <authContext.Provider value={{ authenticated, setAuthenticated }}> <div> user is {`${authenticated ? "" : "not"} authenticated`} </div> <Login /> </authContext.Provider> ); }; ReactDOM.render(<App />, document.getElementById("container")); ``` As you can see, it becomes quite easy to consume the data stored in the context using the useContext hook. Of course, as with every React hook, it only works with functional components. If you want to see the code working. <https://codesandbox.io/s/react-playground-forked-wbqsh?file=/index.js>
53,236,494
I installed MySQL workbench 8.0 in windows 7. After the installation I just clicked server status its through the error like `Could not acquire management access for administration. Run-time Error: Unable to execute command chcp. Please make sure that the C:Windows\System32 directory is in your path environment variable`. How can I solve this error?
2018/11/10
[ "https://Stackoverflow.com/questions/53236494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9887634/" ]
I solved the same problem on enable the parameter "Beta : Use UTF-8 for worldwide language support" in Control Panel > Region > Administrative > Change system locale... It's disturbing because it's have nothing about the PATH environment variable. But it's work. Notice that I working on french environment and MySQL Workbench 8.0.24 version.
42,416,602
I am learning Elm and I find a lot of things that are attractive about it, such as its elegance and simplicity. However, one aspect that I find puzzling is its use of "++" to concatenate strings. For example: ``` > "hello" ++ " world" "hello world" ``` Addition works the way you would expect it. ``` > 2 + 3 + 9 14 ``` The majority of high level languages such as C#/Java/JavaScript/Python use a single plus "+" in concatenating strings in the analogous way multiple numbers would be summed. It seems so much more intuitive, as there is a certain consistency in concatenating strings like summing numbers. Does anyone know the logic behind the design decision to use a ++ instead of + in this context?
2017/02/23
[ "https://Stackoverflow.com/questions/42416602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5617152/" ]
Elm allows you to define polymorphic functions. Parametric polymorphism is when a function can be applied to elements of any types: ``` f : (a, b) -> (b, a) f (x, y) = (y, x) ``` Ad-hoc polymorphism is when a function can be applied to elements of some types: ``` g : appendable -> appendable -> appendable -> appendable g x y z = x ++ y ++ z h : number -> number -> number h x y = (x + 2) * y ``` The type variables `number` and `appendable` are special because they represent a subset of all Elm types. `List` and `String` are `appendable` types while `Float` and `Int` are number types. It could theoretically be possible to instead define a `hasPlus` type variable which would include `List`, `String`, `Float` and `Int`, but then when defining a polymorphic function you would need to be aware that it is possible that `x + y` is different than `y + x` and that would be quite a burden if you are actually thinking about numbers...
668,502
I had an idea to test the internet speed of my local library. Some downloads finish quickly and some don't. Plus, I feel better knowing how to do networking administration from the command line. I found a few programs that can be used via command line to test internet speed. The programs I found, `speedtest-cli` and `wget`. I tried `speedtest-cli` first on ubuntu 15.10. It worked and I got a better idea of the internet speed of my local library. It was pretty slow. I wanted to use the same program on ubuntu 14.04. However, the program issued an error that the `speedtest_cli` module was not available. ``` /usr/local/bin$ speedtest-cli Traceback (most recent call last): File "/usr/local/bin/speedtest-cli", line 7, in <module> from speedtest_cli import main ImportError: No module named speedtest_cli ``` Is this module supplied with the `speedtest-cli`, if not, how do I install it?
2015/09/02
[ "https://askubuntu.com/questions/668502", "https://askubuntu.com", "https://askubuntu.com/users/37848/" ]
From a command prompt install pip, the python specific package manager, then use pip to install speedtest\_cli and all dependent modules. ``` sudo apt-get install python-pip sudo pip install speedtest-cli ``` To run use the command `speedtest-cli`
60,808,326
A table named `Fruit` has columns `ID`, `Fruit name` and `Cost` and `New Cost`: ``` |ID | Fruit Name | Cost | New Cost +---+------------+------+--------- | 1 | Apple | 10 | 9 | 2 | Banana | 20 | 22 | 3 | Orange | 33 | 33 ``` I wish to query this table under one condition. If New Cost is more than Cost then Final Cost should be 0.9\*Cost else Final Cost should be New Cost. Output should look like: ``` | ID | Fruit Name | Final Cost +----+------------+----------- | 1 | Apple | 9 | 2 | Banana | 18 | 3 | Orange | 29.7 ``` Unfortunately, I am not able to apply If condition in SQL query. Is there any way to achieve this??
2020/03/23
[ "https://Stackoverflow.com/questions/60808326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13098753/" ]
i didn't know that string are immutable but i found a workaround for [this](https://stackoverflow.com/a/60808387/8069500) passing trough a list: ``` string = 'aa String aa' string = list(string) for index in range(len(string)): if string[index] == 'a': string[index] = 'c' string = "".join(string) ``` maybe other method are faster but if you need to specifically loop though the string this would work fine.
3,718,849
[![Was](https://i.stack.imgur.com/jsr4X.png)](https://i.stack.imgur.com/jsr4X.png) Is my calculation for the area enclosed by $y=x^2,y=0,x=-1,x=2$ correct? To calculate the volume of the shape formed by rotating the area enclosed by function $y=x^2$ and $y = 0, x = 0, x=2$ around the axis $x=2$, we can use this integral $$\pi\int\_{0}^{4} ydy$$. To calculate the volume of the shape formed by rotating the area enclosed by function $y=x^2$ and $y=0, x=0, x = -1$ around the axis $x=2$, we can use this integral $$\pi\int\_{0}^{1} 9-(2+\sqrt{y})^2dy$$.
2020/06/14
[ "https://math.stackexchange.com/questions/3718849", "https://math.stackexchange.com", "https://math.stackexchange.com/users/790922/" ]
Notice, there is mistake only in first part. Your second part is correct. For the first part, the volume of solid generated by revolving region bounded by $y=x^2$, $y=0$, $x=0$ & $x=2$ around the line $x=2$ is given as $$\int\_{0}^{4}\pi (2-x)^2dy=\pi\int\_{0}^{4}(2-\sqrt y)^2dy$$ For the second part, the volume of bounded region revolved around the line $x=2$ is given as $$\int\_{0}^{1}\pi (3^2-(2+\sqrt y)^2)dy=\pi\int\_{0}^{1}(9-(2+\sqrt y)^2)dy$$
29,900,551
I'm working on this site: <http://animevid-episode.webflow.io/> I'd like to give users the possibility to download the video I put in the player. Do you know how to add a "download video" button to this player or any other generic HTML5 video player? Actually, I can only find on Google about tools to download video and how to prevent downloading. I guess it's possible with JavaScript, but really can't find how. Any suggestions or tips are welcome.
2015/04/27
[ "https://Stackoverflow.com/questions/29900551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3973127/" ]
Maybe: ``` <video id="Video1" > <source src="something.ogv" type="video/ogg" /> HTML5 Video is required for this example. <a href="something.ogv">Download the video</a> file. </video> ```
61,169,546
i have manually downloaded and added the bootstrap library into my code and trying to click my bootstrap navbar-toggler button it is not working, but when i try to add the CDN Bootstrap Librabry it is working fine please somebody help me ho do i solve this issue for manual downloaded bootstrap library ``` <!doctype html> <html lang="en"> <head> <meta charset="utf-8" > <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1"> <title>Bootstrap Navbar</title> <link rel="stylesheet" href="font_awesome/css/font-awesome.min.css" /> <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css"/> <script src="node_modules/jquery/dist/jquery.min.js"></script> <script src="node_modules/@popperjs/core/dist/umd/popper.min.js"></script> <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script> </head> <body> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <a href="" class="navbar-brand"><img src="img/logo/logo.png" width="150px" height="auto" style="border: 1px solid lightgrey; border-radius: 3px"></img></a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#collapsibleNavbar"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navber-collapse" id="collapsibleNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#">Menu 1</a> </li> </ul> </div> </nav> <script></script> </body> </html> ```
2020/04/12
[ "https://Stackoverflow.com/questions/61169546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13127097/" ]
Try to add the jquery, proper & bootstrap js file at the end of the "body" ``` <!doctype html> <html lang="en"> <head> <meta charset="utf-8" > <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1"> <title>Bootstrap Navbar</title> <link rel="stylesheet" href="font_awesome/css/font-awesome.min.css" /> <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css"/> </head> <body> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <a href="" class="navbar-brand"><img src="img/logo/logo.png" width="150px" height="auto" style="border: 1px solid lightgrey; border-radius: 3px"></img></a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#collapsibleNavbar"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navber-collapse" id="collapsibleNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#">Menu 1</a> </li> </ul> </div> </nav> <script src="node_modules/jquery/dist/jquery.min.js"></script> <script src="node_modules/@popperjs/core/dist/umd/popper.min.js"></script> <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script> <script></script> </body> </html> ```
1,166,923
I'm creating application that will create certificates for users. I want to mark somehow those certificates so that later I can search them in windows user certificate store by following categories: * application GUID (or name - I want to know that this cert is for my application) * certificate role (administrative certificate or user certificate) * user email I know that for the last one I should use "E = [email protected]" or OID number "1.2.840.113549.1.9.1 = [email protected]" But I don't know which OIDs to choose for application GUID and certificate role. Or maybe I should use "Key Usage" field? I don't know if it's important, but certificates will be used to authenticate to my application and to decrypt data in database. Are there any standard ways to do it ?
2009/07/22
[ "https://Stackoverflow.com/questions/1166923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22569/" ]
You should get the src attribute to get the value ``` $("#imgThumbnail").attr('src'); ```
1,270,194
> > Let $\sigma \in \mathfrak{S}\_n$, denote $\alpha\_n(\sigma)$ the number of cycles in the decomposition of product of disjoint cycles. > > > Let $$P\_n=\sum\_{\sigma \in \mathfrak{S}\_n} X^{c\_n(\sigma)}.$$ > > > The question is to factorize $P\_n$ as irreducible factors in $\mathbb{Q}[X]$. > > > I am stuck on this problem. The problem is a little dry without any intermediate steps. Can someone provide some steps to solve this exercise? Thanks.
2015/05/06
[ "https://math.stackexchange.com/questions/1270194", "https://math.stackexchange.com", "https://math.stackexchange.com/users/179344/" ]
Notice that $$P\_{n+1}(X)=(X+n)P\_n(X).$$ The term $XP\_n(X)$ comes from the elements $\sigma\in\mathfrak S\_{n+1}$ such that $\sigma(n+1)=n+1$; such a permutation corresponds to a permutation in $\mathfrak S\_n$, but has one more cycle (of length one). The term $nP\_n(X)$ comes from those elements of $\mathfrak S\_{n+1}$ that do move $n+1$: if $\tau\in\mathfrak S\_{n}$ and $k\in\{1,2,\dots,n\}$ then we can define $\sigma\in\mathfrak S\_{n+1}$ via "splicing $n+1$ after $k$": $\sigma(k)=n+1$, $\sigma(n+1)=\tau(k)$, $\sigma(m)=\tau(m)$ for $m\neq k,n+1$. The number of cycles of $\sigma$ and $\tau$ is the same. As $P\_1(X)=X$, we get $$P\_n(X)=X(X+1)(X+2)\dots(X+n-1).$$
68,320,500
I know perfectly well that this question has already been asked but none of the answers helped me. The "webController" it mentions in the stacktrace is no present, it existed before. I hope you can help me.. \*\*org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'webController' method com.example.demo.controllers.WebController#showForm(PersonForm) to {GET [/register]}: There is already 'registerController' bean method \*\* com.example.demo.controllers.RegisterController#showForm(PersonForm) mapped. POM: 4.0.0 org.springframework.boot spring-boot-starter-parent 2.4.5 com.example demo 0.0.1-SNAPSHOT demo Demo project for Spring Boot <java.version>1.8</java.version> org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-validation org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web org.thymeleaf.extras thymeleaf-extras-springsecurity5 ``` <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> ``` Class: @Controller public class LoginController implements WebMvcConfigurer { ``` @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/a").setViewName("results"); registry.addViewController("/login").setViewName("login"); registry.addViewController("/access-denied").setViewName("accessDenied"); } @GetMapping public String goToHome(Principal principal){ if(principal.getName().equalsIgnoreCase("admin")) return "Homepage"; else return "start"; } ``` } @Controller public class RegisterController implements WebMvcConfigurer { ``` @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/results").setViewName("results"); } @Autowired RegisterRepository registerRepository; @GetMapping(value = "/register") public String showForm(PersonForm personForm) { return "formValidation"; } @PostMapping(value = "/register") public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult, @RequestParam(value = "nome") String nome, @RequestParam(value = "cognome") String cognome, @RequestParam(value = "dataNascita") String dataNascita, @RequestParam(value = "password") String password) { if (bindingResult.hasErrors()) { return "formValidation"; } else if (registerRepository.findByCognome(cognome) == null) { Utente utente = new Utente(0, nome, cognome, LocalDate.parse(dataNascita), false, password); registerRepository.save(utente); UserDetails user = User.withDefaultPasswordEncoder() .username(utente.getCognome()) .password(utente.getPassword()) .roles("USER") .build(); WebSecurityConfig.inMemoryUserDetailsManager.createUser(user); return "results"; } else return "errorRegisterPerson"; } @PostMapping(value = "/results") public String returnResults(){ return "results"; } ``` } @Controller public class ShowUserController { ``` @Autowired RegisterRepository registerRepository; @Autowired UserRepository userRepository; @GetMapping(value = "/Users") public String showUsersDB(Model model){ List<Utente> lista = registerRepository.findAll(); model.addAttribute("lista", lista); return "Users"; } @GetMapping(value = "/searchUser") public String searchUserForName(@RequestParam(value = "name")String nome, Model model){ List<Utente> lista = Collections.singletonList(userRepository.findByCognome(nome)); model.addAttribute("lista", lista); return "Users"; } @PostMapping(value = "/addUser") public String addUser(@RequestParam String name, @RequestParam String surname, @RequestParam String date, @RequestParam String password, Model model){ LocalDate data = LocalDate.parse(date); Utente utente = new Utente(0,name,surname,data,false,password); registerRepository.save(utente); UserDetails user = User.withDefaultPasswordEncoder() .username(utente.getCognome()) .password(utente.getPassword()) .roles("USER") .build(); WebSecurityConfig.inMemoryUserDetailsManager.createUser(user); List<Utente> lista = registerRepository.findAll(); model.addAttribute("lista", lista); return "Users"; } @GetMapping(value = "/prova/{password}") public String show(@PathVariable("password")String password, Model model){ model.addAttribute("oldPassword",password); return "UserProfile"; } @PostMapping(value = "/changeUserPsw/{oldPsw}") public String changePsw(@PathVariable("oldPsw")String oldPsw,@RequestParam(value = "password")String password, Model model){ userRepository.setUserPassword(password,oldPsw); List<Utente> lista = registerRepository.findAll(); model.addAttribute("lista", lista); return "Users"; } ``` } @Controller public class UserController { ``` @Autowired RegisterRepository registerRepository; @GetMapping("/ciaooo") public String showUserDB(Model model){ model.addAttribute("lista",registerRepository.findAll()); return "Users"; } ``` } @Controller public class VehiclesController { ``` @Autowired VehiclesRepository vehiclesRepository; @GetMapping(value = "/Vehicles") public String showVehiclesDB(Model model){ List<Mezzo> lista = vehiclesRepository.findAll(); model.addAttribute("lista", lista); return "Vehicles"; ``` } ``` @GetMapping(value = "/searchVehicles") public String searchVehiclesForName(@RequestParam(value = "name")String nome, Model model){ List<Mezzo> lista = Collections.singletonList(vehiclesRepository.findByModello(nome)); model.addAttribute("lista", lista); return "Users"; } @GetMapping(value = "/prova/{targa}") public String showTarga(@PathVariable("targa")String targa, Model model){ model.addAttribute("oldTarga",targa); return "VehicleProfile"; } @PostMapping(value = "/changeVehicleTarga/{vecchiaTarga}") public String changeTarga(@PathVariable("vecchiaTarga")String oldTarga,@RequestParam(value = "targa")String targa, Model model){ vehiclesRepository.setVehicleTarga(targa,oldTarga); List<Mezzo> lista = vehiclesRepository.findAll(); model.addAttribute("lista", lista); return "Vehicles"; } @PostMapping(value = "/addVehicle") public String addVehicle(@RequestParam(value = "modello")String modello, @RequestParam(value = "casaCostr")String casaCostr, @RequestParam(value = "tiplogia")String tipologia, @RequestParam(value = "targa")String targa, @RequestParam(value = "annoImm")int annoImm, Model model){ Mezzo mezzo = new Mezzo(0,targa,modello,casaCostr,tipologia,annoImm); vehiclesRepository.save(mezzo); List<Mezzo> lista = vehiclesRepository.findAll(); model.addAttribute("lista", lista); return "Vehicles"; } ``` }
2021/07/09
[ "https://Stackoverflow.com/questions/68320500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16415966/" ]
lineDashPattern={[number]} add this in polyline or react MapViewDirections ``` <MapViewDirections lineDashPattern={[0]} origin={origin} destination={destination} apikey={GOOGLE_MAPS_APIKEY} /> ```
27,691,225
I'm trying to understand how negative lookaheads work on simple examples. For instance, consider the following regex: ```regex a(?!b)c ``` I thought the negative lookahead matches a position. So, in that case the regex matches any string that contains strictly 3 characters and is not `abc`. But it's not true, as can be seen in **[this demo](https://regex101.com/r/eM4tF1/4)**. Why?
2014/12/29
[ "https://Stackoverflow.com/questions/27691225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2786156/" ]
Lookaheads do not consume any characters. It just checks if the lookahead can be matched or not: ``` a(?!b)c ``` So here after matching `a` it just *checks* if it is followed not by `b` but does not consume that `not` character (which is `c`) and is followed by `c`. How `a(?!b)c` matches `ac` -------------------------- ``` ac | a ac | (?!b) #checks but does not consume. Pointer remains at c ac | c ``` --- Positive lookahead ------------------ The positive lookahead is similar in that it ***tries to match the pattern in the lookahead***. If it can be matched, then the regex engine proceeds with matching the rest of the pattern. If it cannot, the match is discarded. E.g. `abc(?=123)\d+` matching `abc123` ``` abc123 | a abc123 | b abc123 c abc123 #Tries to match 123; since is successful, the pointer remains at c | (?=123) abc123 # Match is success. Further matching of patterns (if any) would proceed from this position | abc123 | \d abc123 | \d abc123 #Reaches the end of input. The pattern is matched completely. Returns a successfull match by the regex engine | \d ```
57,252,810
I want to make a horizontal number picker as shown in the image below: ![Image Horizontal Picker](https://i.stack.imgur.com/JHUDq.png) I tried using horizontal listview and pageview widgets but couldn't do it. I've even tried using some GitHub addons such as NumberPicker and Carousel but they don't show the number's on the side. Thank you!
2019/07/29
[ "https://Stackoverflow.com/questions/57252810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11239404/" ]
Please look into [this] : <https://github.com/andrezanna/NumberPicker> This has all type of number picker.
50,159,447
I would like to take the first row of a dataframe (which will change weekly) and also a row containing a reference date (which is a constant) in order to perform a mathematical operation on them. I can use `dplyr::slice()` to get the first row but any ideas on how to also return the additional row in the same call? ``` library(dplyr) df <- data_frame(x = c(10, 45, 65, 10), dt = as.POSIXct("2018-01-01", tz = "GMT")) slice(df, 1) ``` Ideally, I will get two rows back as a dataframe. The first row and the row specified by date.
2018/05/03
[ "https://Stackoverflow.com/questions/50159447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5630261/" ]
I'd use `dplyr::filter` because it lets you provide multiple conditions using an OR statment. We can then filter based on the desired criteria or based on a specific row number (generated by the `dplyr::row_number()` function): ``` df %>% filter(x == 65 | row_number() == 1) # A tibble: 2 x 2 x dt <dbl> <dttm> 1 10 2018-01-01 00:00:00 2 65 2018-01-01 00:00:00 ```
48,719,333
How do you initialize the value of x using array new: ``` int (*x)[5] = ? ``` `new int[5]` doesn't work because it has a type of `int*` Do you have to use a C-style cast as follows? ``` int (*x)[5] = (int( *)[5])(new int[5]); ```
2018/02/10
[ "https://Stackoverflow.com/questions/48719333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8538582/" ]
A fixed sized array in C++ would be [`std::array`](http://en.cppreference.com/w/cpp/container/array). And, guessing from the pointer to array `int (*x)[5]` this might be either ``` std::array<int, 5> x; ``` or ``` std::array<int, 5> *x = new std::array<int, 5>; ``` Although the former is preferred, unless there's a real need to put the array on the heap. --- If you want a variable number of fixed sized arrays, combine this with a [`std::vector`](http://en.cppreference.com/w/cpp/container/vector) ``` std::vector<std::array<int, 5> > x; ```
16,698,626
I have a task to take millions of floats and store them in the database in batches of 5,000, as binary. This is forcing me to learn interesting things about serialization performance. One of the things that surprises me is the size of the serialized data, which is a factor of ten above what I expected. This test shows me that a four-byte float is serialized to 55 bytes and an eight-byte double to 59 bytes. What is happening here? I expected it to simply split the float value into its four bytes. What are the other 51 bytes? ``` private void SerializeFloat() { Random rnd = new Random(); IFormatter iFormatter = new BinaryFormatter(); using (MemoryStream memoryStream = new MemoryStream(10000000)) { memoryStream.Capacity = 0; iFormatter.Serialize(memoryStream, (Single)rnd.NextDouble()); iFormatter.Serialize(memoryStream, rnd.NextDouble()); } } ```
2013/05/22
[ "https://Stackoverflow.com/questions/16698626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7989/" ]
Serialization is more than simply blitting bits and bytes to a stream. Serialization is structured output. This structure accounts for your actual differences. The Framework encodes additional information which lets it know the type and number of objects in the serialized data, among many other possibilities. It is an implementation detail best left alone. If you need unstructured output, [you could use `BinaryWriter` instead](http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx).
124,302
The [Broom of Flying](https://www.dndbeyond.com/magic-items/broom-of-flying) does not require attunement, and can be controlled via [command words](https://www.dndbeyond.com/compendium/rules/basic-rules/magic-items#CommandWord): > > This wooden broom, which weighs 3 pounds, functions like a mundane broom until you stand astride it and speak its command word. It then hovers beneath you and can be ridden in the air. It has a flying speed of 50 feet. It can carry up to 400 pounds, but its flying speed becomes 30 feet while carrying over 200 pounds. The broom stops hovering when you land. > > > **You can send the broom to travel alone to a destination within 1 mile of you if you speak the command word, name the location, and are familiar with that place. The broom comes back to you when you speak another command word, provided that the broom is still within 1 mile of you.** > > > The bolded passage lays out a use case for the broom's command words that do not require attunement nor physical contact with the broom. So: can anyone (including an enemy) who knows the command words for the broom summon it to them or send it to another location (as long as it's not being ridden)?
2018/06/12
[ "https://rpg.stackexchange.com/questions/124302", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/42959/" ]
The intent is probably that only whoever activated it can use it. > > functions like a mundane broom until ***you* stand astride it and speak its command word**. > > > Activation requires physical contact. From my reading, this intent is given by the use of *you*, in every sentence. Usually it would be unclear who exactly is "you", but the earlier sentence defines it (as the person who stood astride and spoke the command word). > > **You** can send the broom to travel alone to a destination within 1 mile of you if **you** speak the command word, name the location, and are familiar with that place. The broom comes back to **you** when **you** speak another command word, provided that the broom is still within 1 mile of you. > > > The wording, if it was intended that any creature could use it, would probably be "A creature that says the command word", for example. As an additional conjecture, it would be silly that anyone hearing the command word could mess up the item easily like that.
28,306,344
I have a script that monitors a specific process and I have a working script that outputs it as such; ``` 0 0 0 ``` I am using this script to try to cut everything after the first "0" using this script ``` Get-Content –path c:\batchjobs\location\test.txt | Trim(Char[8,60]) > c:\batchjobs\location\test1.txt ``` the powershell ise keeps erroring out, here's the output, from that: ``` PS C:\batchjobs\location> C:\batchjobs\location\TestTrim.ps1 The term 'Trim' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\batchjobs\location\TestTrim.ps1:2 char:58 + Get-Content –path c:\batchjobs\location\test.txt | Trim <<<< (Char[8,60]) > c:\batchjobs\location\test1.txt + CategoryInfo : ObjectNotFound: (Trim:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ``` any help would be greatly appreciated
2015/02/03
[ "https://Stackoverflow.com/questions/28306344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Methods such as `Trim` and `SubString` require an object to operate on, you are not telling the script which object you mean. In the context you will want to indicate `$_` for the result object. Also, Get-Content will return all the lines of the file, iterate over them using `For-Each` a.k.a `%`. ``` Get-Content -path c:\batchjobs\location\test.txt | % { $_.Substring(0,7).Trim(); } > c:\batchjobs\location\test1.txt ```
14,138
We are having serious issues in the startup (boot) time of our application. After carefull investigation we have discovered that the most time is consumed by first-time-visit compilation of the cshtml files. This compilation can take up to 50 seconds per cshtml file. We use Helix architecture with a lot of components. The combination of all those compilations takes ages and it can take up between 20 and 30 minutes for the site to boot. Once all cshtml have been hit once, the site speed and performance is ok. Example: this cshtml takes 43 seconds to compile! ``` @using Sitecore.Mvc @inherits System.Web.Mvc.WebViewPage @inherits Glass.Mapper.Sc.Web.Mvc.GlassView<Feature.PageLayout.Models.PageSectionViewModel> @{ var sectionClasses = Model.Presentation.BackgroundColor != null ? Model.Presentation.BackgroundColor.CssClass : ""; } <section class="section-box @sectionClasses"> <div class="container"> @Html.Sitecore().DynamicPlaceholder("pagelayout-pagesection") </div> </section> ``` We have tried to precompile our cshtml files. This was a major difference and we had the site cold started in under 3 minutes. Unfortunatly, we can only precompile our own code, and we don't have precompiled cshtml and aspx from Sitecore, causing the platform not to work giving the error that those pages are not precompiled. (e.g. login page, experience editor, ...) So precompilation is out of the option. On IaaS platforms, we do not experience this compilation time of cshtml taking up so much time. My question: Did anyone experience the same kind of issues? Are there any settings in Azure PaaS that we are missing?
2018/09/26
[ "https://sitecore.stackexchange.com/questions/14138", "https://sitecore.stackexchange.com", "https://sitecore.stackexchange.com/users/3675/" ]
By default Sitecore doesn't use the Roslyn compiler nuget package `Microsoft.CodeDom.Providers.DotNetCompilerPlatform`, and instead will use the version of Roslyn installed on the system. I've seen a very noticeably improved compilation performance improvement when using the latest version of that package. Installation: 1. Install the latest version of the `Microsoft.CodeDom.Providers.DotNetCompilerPlatform` nuget package to all projects in the solution. 2. Make sure your web.config is using the correct CodeDom configuration for the version you have installed. For example: Web.config ``` <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" /> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" /> </compilers> </system.codedom> ```
50,065,192
I am totally new to this and search did not help. This works: ``` import rhinoscriptsyntax as rs obj = rs.GetObject("Select a curve", rs.filter.curve) if rs.IsCurve(obj): i=0 while i < 100: rs.OffsetCurve( obj, [0,0,0], -i ) i += 0.2 rs.OffsetCurve( obj, [0,0,0], -i ) i += 0.7 ``` This does not: ``` import rhinoscriptsyntax as rs a = raw_input("Please enter first number: ") b = raw_input("Please enter second number: ") obj = rs.GetObject("Select a curve", rs.filter.curve) if rs.IsCurve(obj): i=0 while i < 100: rs.OffsetCurve( obj, [0,0,0], -i ) i += a rs.OffsetCurve( obj, [0,0,0], -i ) i += b ``` With integers it's `i += int(a)`, but `a` and `b` must be decimals. I have no clue. Help :) Danke
2018/04/27
[ "https://Stackoverflow.com/questions/50065192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9711016/" ]
You can pass a lambda function to the `key` argument: ``` result = sorted(rsp, key=lambda x: x.get('user', {}).get('uid', -1) ) ``` In this case I am using `get` to ensure the sort does not fail if one of the elements does not have a `user` key, and any sub-dictionaries that do not have a `uid` key will be place first.
11,585,682
is there a way, when making a table to make the width of a cell in a new table row less that the with of the one above in here's a simple example with this code both cells will be 100px even though the bottom one one is specified as 50px. I can think of a few over comlicated ways of doing it but is there a simple solution? Thanks ``` <table> <tr> <td width=100 height='20' bgcolor='pink'></td> </td> </tr> <tr> <td width='50' height='20'bgcolor=blue> </td> </tr> </table> ```
2012/07/20
[ "https://Stackoverflow.com/questions/11585682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
No all cell at a given sequence are always of the same widths for all rows in the table. You can have merged cells though. For eg two cells in bottom row can correspond to one cell in top if you use `<td colspan=2>` in the bottom row.
36,827,487
I am attempting to write a context-free grammar for L = the set of strings in which the number of 1’s is one more than the number of 0’s. Thus, 1011010, 0001111 etc. are in L, but strings like 001101, 000011 etc. are not in L. So far, I have a context-free grammar for L = the set of strings in which the number of 1’s is more than 0’s: S → TS|1T|1S T → TT|0T1|1T0|ε How can I change this so that the number of 1's is ONLY 1 more than the number of 0's?
2016/04/24
[ "https://Stackoverflow.com/questions/36827487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5420266/" ]
Based on templatetypedef's answer, you can find such grammar at <https://math.stackexchange.com/questions/2207708/context-free-grammar-for-language-a-b-where-the-number-of-as-the-number> So basically the final grammar would be: ``` S -> T1T T -> 1T0T | 0T1T | ε ```
2,715,800
I am confused betweeen tangent plane to the level set(is it the same as level surface?) and to the tangent plane on the surface? I know the formula $z=f(x,y): z-z\_0 = f\_{x}(x\_0)(x-x\_0) +f\_y(y\_0)(y-y\_0)$ but cannot understand for which case it corresponds. Also I found some example where it was just without $z$ and $z\_0$ : $f\_{x}(x\_0)(x-x\_0) +f\_y(y\_0)(y-y\_0)=0$ What whould be the difference between two tangent planes? It would be very nice if someone could explain it on the numerical example.
2018/03/31
[ "https://math.stackexchange.com/questions/2715800", "https://math.stackexchange.com", "https://math.stackexchange.com/users/458659/" ]
This one $$z-z\_0 = f\_{x}(x\_0)(x-x\_0) +f\_y(y\_0)(y-y\_0)$$ is the general expression for the tangent plane to $z=f(x,y)$ at the point $(x\_0,y\_0,z\_0)$ while $$f\_{x}(x\_0)(x-x\_0) +f\_y(y\_0)(y-y\_0)=0$$ is the intersection of the tangent plane with $x-y$ plane $(z=0)$ when $z\_0=0$. For example $z=f(x,y)=x^2+y^2 \implies f\_x=2x \quad f\_y=2y$ then at $(1,1,2)$ the tangent plane is $$z-2=2(x-1)+2(y-1)$$
55,471,946
I have an HTML table inside which i have a column `AcceptedQty` which is input field Total i have 5 columns `Code`,`Item Name`,`unitcode`,`Quantity` and `AcceptedQty` two of them `Quantity` and `AcceptedQty` have same values but `AcceptedQty` is input field so user can input any number inside that and i have made that type="number" to enter only numbers **What i am trying to do** * when user input any number inside the input field it should not allow him to enter greater number to the corresponding quantity * suppose for `code` 1326 `Quantity` is 3 so while editing `AcceptedQty` i want to restrict user not to enter any number greater then 3 * here i have a HTML table and so many rows that's why finding it dificult to do **Snippet** ```js var tableDataDraft = [{ "Code": "1326", "Item Name": "PINEAPPLE KG", "unitcode": "NOS", "Quantity": "3.0000", "AcceptedQty": "3.0000" }, { "Code": "1494", "Item Name": "2D CAKE CHARGES PER KG", "unitcode": "NOS", "Quantity": "3.0000", "AcceptedQty": "3.0000" } ] function addTableDraft(tableDataDraft) { var col = Object.keys(tableDataDraft[0]); var countNum = col.filter(i => !isNaN(i)).length; var num = col.splice(0, countNum); col = col.concat(num); var table = document.createElement("table"); var tr = table.insertRow(-1); for (var i = 0; i < col.length; i++) { var th = document.createElement("th"); th.innerHTML = col[i]; tr.appendChild(th); tr.classList.add("text-center"); tr.classList.add("head") } for (var i = 0; i < tableDataDraft.length; i++) { tr = table.insertRow(-1); for (var j = 0; j < col.length; j++) { let tabCell = tr.insertCell(-1); var hiddenField = document.createElement("input"); //creating input field hidden hiddenField.style.display = "none"; var tabledata = tableDataDraft[i][col[j]]; if (tableDataDraft[i]['Code'] === tableDataDraft[i][col[j]]) { //now setting html attributes tabCell.innerHTML = tabledata; hiddenField.setAttribute('name', 'Item_Code'); hiddenField.setAttribute('value', tabledata); tabCell.appendChild(hiddenField); } if (tableDataDraft[i]['Item Name'] === tableDataDraft[i][col[j]]) { tabCell.innerHTML = tabledata; hiddenField.setAttribute('name', 'Item_Name'); hiddenField.setAttribute('value', tabledata); tabCell.appendChild(hiddenField); } if (tableDataDraft[i]['unitcode'] === tableDataDraft[i][col[j]]) { tabCell.innerHTML = tabledata; hiddenField.setAttribute('name', 'Unit_code'); hiddenField.setAttribute('value', tabledata); tabCell.appendChild(hiddenField); } if (col[j] === 'Quantity') { tabCell.innerHTML = tabledata; hiddenField.setAttribute('name', 'Quantity'); tabCell.appendChild(hiddenField); } if (col[j] === 'AcceptedQty') { var quantityField = document.createElement("input"); quantityField.style.border = "none"; quantityField.style["text-align"] = "right"; quantityField.setAttribute("name", "AcceptedQty"); quantityField.setAttribute("autocomplete", "on"); quantityField.setAttribute("value", tabledata); quantityField.setAttribute("type", "number"); quantityField.setAttribute("required", "required"); quantityField.classList.add("dataReset"); quantityField.toLocaleString('en-IN'); tabCell.appendChild(quantityField); } if (j > 1) tabCell.classList.add("text-right"); } } var divContainer = document.getElementById("table"); divContainer.innerHTML = ""; divContainer.appendChild(table); table.classList.add("table"); table.classList.add("table-striped"); table.classList.add("table-bordered"); table.classList.add("table-hover"); } addTableDraft(tableDataDraft) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"> <div class="table-responsive" id="commonDvScroll"> <table id=table></table> </div> ```
2019/04/02
[ "https://Stackoverflow.com/questions/55471946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
> > and i have made that type="tel" to enter only numbers > > > Use `type="number"` (`"tel"` is a *telephone number*) and the `min` and `max` attributes (and reflected properties) of the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) (and `step` if you don't want fractional values). Probably also include an `input` handler to handle browsers without HTML5 field features. See the `***` commented lines: ```js var tableDataDraft = [{ "Code": "1326", "Item Name": "PINEAPPLE KG", "unitcode": "NOS", "Quantity": "3.0000", "AcceptedQty": "3.0000" }, { "Code": "1494", "Item Name": "2D CAKE CHARGES PER KG", "unitcode": "NOS", "Quantity": "3.0000", "AcceptedQty": "3.0000" } ] function addTableDraft(tableDataDraft) { var col = Object.keys(tableDataDraft[0]); var countNum = col.filter(i => !isNaN(i)).length; var num = col.splice(0, countNum); col = col.concat(num); var table = document.createElement("table"); var tr = table.insertRow(-1); for (var i = 0; i < col.length; i++) { var th = document.createElement("th"); th.innerHTML = col[i]; tr.appendChild(th); tr.classList.add("text-center"); tr.classList.add("head") } for (var i = 0; i < tableDataDraft.length; i++) { tr = table.insertRow(-1); for (var j = 0; j < col.length; j++) { let tabCell = tr.insertCell(-1); var hiddenField = document.createElement("input"); //creating input field hidden hiddenField.style.display = "none"; var tablerow = tableDataDraft[i]; // *** var tabledata = tablerow[col[j]]; // *** if (tableDataDraft[i]['Code'] === tableDataDraft[i][col[j]]) { //now setting html attributes tabCell.innerHTML = tabledata; hiddenField.setAttribute('name', 'Item_Code'); hiddenField.setAttribute('value', tabledata); tabCell.appendChild(hiddenField); } if (tableDataDraft[i]['Item Name'] === tableDataDraft[i][col[j]]) { tabCell.innerHTML = tabledata; hiddenField.setAttribute('name', 'Item_Name'); hiddenField.setAttribute('value', tabledata); tabCell.appendChild(hiddenField); } if (tableDataDraft[i]['unitcode'] === tableDataDraft[i][col[j]]) { tabCell.innerHTML = tabledata; hiddenField.setAttribute('name', 'Unit_code'); hiddenField.setAttribute('value', tabledata); tabCell.appendChild(hiddenField); } if (col[j] === 'Quantity') { tabCell.innerHTML = tabledata; hiddenField.setAttribute('name', 'Quantity'); tabCell.appendChild(hiddenField); } if (col[j] === 'AcceptedQty') { var quantityField = document.createElement("input"); quantityField.style.border = "none"; quantityField.style["text-align"] = "right"; quantityField.setAttribute("name", "AcceptedQty"); quantityField.setAttribute("autocomplete", "on"); quantityField.setAttribute("value", tabledata); quantityField.setAttribute("type", "number"); quantityField.min = 0; // *** quantityField.max = tablerow.Quantity; // *** quantityField.setAttribute("required", "required"); quantityField.classList.add("dataReset"); quantityField.toLocaleString('en-IN'); tabCell.appendChild(quantityField); } if (j > 1) tabCell.classList.add("text-right"); } } var divContainer = document.getElementById("table"); divContainer.innerHTML = ""; divContainer.appendChild(table); table.classList.add("table"); table.classList.add("table-striped"); table.classList.add("table-bordered"); table.classList.add("table-hover"); } addTableDraft(tableDataDraft) ``` ```css input:invalid { color: #d00; border: 1px solid #d00 !important; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"> <div class="table-responsive" id="commonDvScroll"> <table id=table></table> </div> ``` Note that the user will still be able to *enter* a higher number, but the form won't validate. See [this tutorial](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation) on MDN.
35,785,747
I'm building an iOS app using React Native and trying to get it testable on phones. If I plug my phone into the computer and "build" directly to the phone, the app is built correctly and opens/operates correctly, no problem. But if I try to archive it and send it to phones using iTunes Connect's TestFlight or Fabric with Crashlytics, the app crashes immediately upon opening. It briefly shows the launch screen, but no more. Moreover, there are no crash reports -- in TestFlight, in Crashlytics, or in XCode, once I plug the phone back in. So I'm operating in the dark here, without any information on what's breaking. Haven't been able to find a similar issue online, so I figured I'd just ask. Any ideas what could be going wrong? Please let me know if there's any code or other data you might need to see. Some of it's confidential, but I'll try to post an approximate version.
2016/03/04
[ "https://Stackoverflow.com/questions/35785747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1408935/" ]
As Chris Geirman suggested, the problem was a JavaScript error. I'm not sure people with similar problems will find this thread, but in case they do, here is the weird error that was occurring. I had created a simple ORM system, with a BaseModel and a bunch of models that inherited from it. The BaseModel constructor looked like this: ``` constructor(props = {}, relations = {}) { Object.keys(props).forEach((k) => { // Save props to object this[k] = props[k]; }); this.relations = relations; this.className = this.constructor.name; } ``` That last line was the problem. On my local simulator and if I build the app to my phone by plugging it in, this works fine. As in, if a Message model inherits from BaseModel, calling `var msg = new Message(data, relations); msg.className` returns `Message`. But something about bundling/archiving/sending the app through TestFlight or Fabric.io minifies and *uglifies* the JavaScript, such that the class names are changed. So instead, if I do this -- `var msg = new Message(data, relations); msg.className` -- I'll get back a random variable name, something like 't'. This was a problem in my app, because my home page contained a switch statement that worked off of the className: ``` iconContent() { return { Message: { icon: <Image style={styles.feedItemIconImage} source={ require('../assets/img/icon_message.png') } />, color: c.grass }, ... }[this.props.className] // from the model item } ``` But `'Message'` wasn't, as expected, the value of `this.props.className` -- `'t'` was. And so, if I were to try to tunnel into, say, the `color` value, I'd hit an error, because I was trying to access the `color` property of `null`. Why that didn't report, I don't know (I followed Chris's suggestions and installed Sentry, but it still seemed not to report that error). But that's what was going on. Minification/uglification occurred **only** when I installed the app on a phone via TestFlight/Fabric, and that's why the app only crashed in those conditions. Hope this saves anyone running into a similar bug from tearing out their hair.
8,174,728
How do I run the while loop until the end of line or null character reached. Here is my code ``` #include<iostream> using namespace std; main() { char input[20]; cout<<"Enter a line: "; cin>>input; while(input!='\0') { cout<<"This is a text"; } system("pause"); } ```
2011/11/17
[ "https://Stackoverflow.com/questions/8174728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1032593/" ]
If you want to read until either a newline or a NUL, read one character at a time *inside* the loop. ``` #include<iostream> int main() { char input; std::cout << "Enter a line: " << std::flush; while(std::cin >> input && input != '\n' && input != 0) { std::cout << "This is a test\n"; } } ``` Notes: * main requires a return type * Never, ever, say "using namespace std;" * Don't forget to flush if you want `cout` to appear immediately. * Notice the compound test in the `while` condition: + First, did the read succeed? + Next, is it not `'\n'` (one of your conditions). + Next, is it not NUL (the other of your conditions). * The body of the loop will be executed once per input character -- is that what you wanted? But, consider if you have correctly specified your requirement. It is an unusual requirement -- why would there be a NUL in a text file, and why would you want to process each character individually? In idiomatic C++, you can read the input file in a line at a time using `std::getline`: ``` std::string myString; while(std::getline(std::cin, myString)) { // process myString } ``` If you just want to read in a single line: ``` std::string myString; if(std::getline(std::cin, myString)) { // process myString } ``` Finally, if you want to read a line, and ignore its contents: ``` std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); ```
63,301,741
I am trying to use Pyinstaller to package my project into an executable. Currently, I am doing it on my Ubuntu based PC for proof of concept, after which I plan to switch to Windows to build an .exe which can be run on windows. The issue is that after I build the executable and run it, it cannot find one of the local packages which were imported in the startup file. This is my project structure: ``` . ├── hook-streamlit.py ├── __init__.py ├── models │   ├── __init__.py │   ├── loader.py │   ├── nn.py │   └── runner.py ├── notebooks ├── README.md ├── requirements.txt ├── stapp │   ├── __init__.py │   ├── main.py │   └── session_state.py ├── startup.py ├── startup.spec ├── test_data │   ├── test_x.csv │   ├── test_y.csv │   ├── train_x.csv │   └── train_y.csv ├── tkapp.py ├── unipredictor-icon.ico ├── UniPredictor.spec └── utils.py ``` `startup.py` is the startup script and these are the contents: ``` import os import subprocess import shlex from models import nn, loader, runner from stapp import main subprocess.call(shlex.split(f"streamlit run {os.path.join('stapp', 'main.py')} --global.developmentMode=false")) ``` Even though I don't need the `models` and `stapp` packages in the startup script, I import them, just to ensure that pyinstaller resolves the dependencies since I use subprocess to run the app. But even with this, I still get `ModuleNotFoundError: No module named 'models'` after building and running the executable. This error comes from `stapp.main` where `models` is imported. I have tried adding both `models` and `stapp` to `hiddenimports` without success. I would think that since the project root is added to PYTHONPATH, it shouldn't have any issue with local packages. And even if for some reason it did, the import and hiddenimports should deal with that. Here is my current spec file: ``` # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['startup.py'], pathex=['/home/kenneth/PycharmProjects/universal_predictor'], binaries=[], datas=[], hiddenimports=['models', 'stapp'], hookspath=['.'], runtime_hooks=[], excludes=['torch.distributions'], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='startup', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=False , icon='unipredictor-icon.ico') ``` I will appreciate any help on how to make pyinstaller include the project's local packages. Thanks!
2020/08/07
[ "https://Stackoverflow.com/questions/63301741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3442256/" ]
I resolved the issue by loading the needed packages and modules as data. ``` # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['startup.py'], pathex=['/home/kenneth/PycharmProjects/universal_predictor'], binaries=[], datas=[('.streamlit', '.streamlit'), ('.data', '.data'), ('models', 'models'), ('stapp', 'stapp'), ('utils.py', '.')], hiddenimports=[], hookspath=['.'], runtime_hooks=[], excludes=['torch.distributions'], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='startup', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=False , icon='unipredictor-icon.ico') ```
72,173,717
I am trying to make a crystal report in which there is a requirement to convert number into words of each individual digit. For Example: Convert 1234 into One Two Three Four or Convert 56789 into Five Six Seven Eight Nine If anybody can help?
2022/05/09
[ "https://Stackoverflow.com/questions/72173717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19077663/" ]
After discussion with a lot of good guys from here, i found the problem. I did not need to convert image data from the database to base64 format, i can directly serve the image as it's original binary format but have to indicate this header: ``` res.setHeader('Content-type:', 'image/jpg'); ``` and if i need to use that image in my html i just do this: ``` <img src="/path to api /" /> ```
799,463
Got any ideas (what substitution should I use) to evaluate $$\int \frac{\sin^2(x)}{1+\sin^2(x)}dx~?$$
2014/05/17
[ "https://math.stackexchange.com/questions/799463", "https://math.stackexchange.com", "https://math.stackexchange.com/users/136299/" ]
Write: $$\frac {\sin^2 x} {1 + \sin^2 x} = \frac {1 +\sin^2 x - 1} {1 + \sin^2 x} = 1 - \frac 1 {1 + \sin^2 x} = 1 - \frac {\sec^2 x} {\sec^2 x + \tan^2 x} = 1 - \frac {\sec^2 x} {1 + 2\tan^2 x} $$ Now substitute $u = \tan x$ and the rest is easy.
57,080,685
I am simply using the default YouTube embed code (generated by YouTube) to display videos on my website. With the layout that uses a fairly narrow width (320px wide) for the YouTube player, the video thumbnail is a very low quality that is visibly pixelated. However, with the layout that uses a fairly wide width (1100px wide) for the YouTube player, the video thumbnail is the high resolution version and looks great. Here are two links that compare the different thumbnails: * Narrow, low quality thumbnail: <http://slackrbike0.wpengine.com/> * Wide, high quality thumbnail: <http://slackrbike0.wpengine.com/?cat=1> Has anyone run into this issue where the thumbnail quality is crap on smaller embedded videos? And has anyone come up with a fix? Or do I have to wait for YouTube to fix it on their end? Here is the embed code I am using, again the default generated by YouTube: ``` <iframe width="560" height="315" src="https://www.youtube.com/embed/NoIKoTs1s9Y" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> ```
2019/07/17
[ "https://Stackoverflow.com/questions/57080685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3242758/" ]
Basically YT send multiple dimension of thumbnail, if ur container is smaller that 321px then the smallest thumbnail will get loaded that is `"width": 120,"height": 90`. this is root-cause of this issue. Element with `width <= 320px` having issue of bury thumbnail. I have found a workaround by setting iframe width with `min-width:321px` that will force to load higher dimension thumbnail ``` iframe { min-width:321px; } ``` I hope this will helpfull for you.
7,151,090
``` @property(nonatomic, retain) NSString *password; -(id)init { ... password=[NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; OR password=[[NSProcessInfo processInfo] globallyUniqueString]; } ``` My problem is that during course of execution at some random point the password object gets automatically released. Effect is same when i use either of the assignments. As soon as i put in a retain, the problem no longer exists. I'm sure there is no release of password object anywhere in the flow - as i mentioned it is in a singleton class. I also checked that the class instance is same even when the password object is released. Any hints please!
2011/08/22
[ "https://Stackoverflow.com/questions/7151090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/906355/" ]
You assign the iVar, not the property... So as you don't use the setter method, your object is not retained. Use the property instead: ``` self.password = ... ```
2,278,304
Alright, see if I can pick your brains from you all. I'm currently working on a project where all the information comes from different clients, the only thing in common is that the received data is done with excel. The excel spread sheet that they present is just a bunch of references and codes, and the problem than I'm facing is that I need the references and codes to be entered in certain format in order for the website to work. The perfect situation will be to go to each client and teach how I would need the data, but I can't do that because of the large number of clients, and more importantly I will be interrupting their work flow. Each client has its own codes and reference model and they are not willing to change their process The good news is that there is a standard pattern for the codes, but I'm talking close to 200 thousand codes with a bunch of combination. They way that we are currently solving the problem is that we have a person who checks each excel sheet received, runs a few macros, and manually fixes those codes in which the macro was not able to fix. The person that is doing this, is already burn out and frustrated and I would like to automatize this process with php. Suggestions?
2010/02/17
[ "https://Stackoverflow.com/questions/2278304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69033/" ]
There's a nice class called PHPExcel that allows you to write and read from a variety of document types: <http://www.codeplex.com/PHPExcel> You need to enable the php\_zip extension for Excel 2007 documents
18,277,422
I am trying something out... Say I have this: ``` <div id="helloworld" call="chart" width="350" height="200" value="[[4, 8, 1, 88, 21],[45, 2, 67, 11, 9],[33, 4, 63, 4, 1]]" label="['test1', 'test2', 'test3', 'test4', 'test5']"/> ``` I am using jQuery to fetch my all the element attribute into an object array, that part worked, and I am getting something like this: ``` Object { id="helloworld", call="chart" ... } ``` The second part I need to do is to convert the "String representation of the array" into an actual array, it works for my *value* using JASON.parse() for the value... however trying to do the same thing with the *label* didn't work, it doesn't like the single quote (') I have in there... Tried escaped it with \" still no dice. Does anyone know an elegant way to convert it back into an array?
2013/08/16
[ "https://Stackoverflow.com/questions/18277422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009046/" ]
As you're using jQuery, and custom attributes, the first thing to fix is the attributes: Instead of: ``` <div id="helloworld" call="chart" width="350" height="200" value="[[4, 8, 1, 88, 21],[45, 2, 67, 11, 9],[33, 4, 63, 4, 1]]" label="['test1', 'test2', 'test3', 'test4', 'test5']" /> ``` You should use: ``` <div id="helloworld" data-call="chart" width="350" height="200" data-value="[[4, 8, 1, 88, 21],[45, 2, 67, 11, 9],[33, 4, 63, 4, 1]]" data-label='["test1", "test2", "test3", "test4", "test5"]'></div> ``` Be sure to also use valid JSON encoding for your data. When you do that, you can access the values of the attributes with [jQuery's `.data()` method](http://api.jquery.com/data) ``` $('#helloworld').data('label'); //returns the actual array ``` [In some cases you may want to use `.attr()` to access the string representation of the attribute.](https://stackoverflow.com/a/7262427/497418) --- If you absolutely must leave the data as it was, and you can guarantee that the "strings" won't contain special characters, you could call `$.parseJSON($('#helloworld').attr('data-label').replace("'", '"'));`, but it *will* fail if the string contains quotes or other special characters that are not correctly encoded/escaped.
67,877,245
I'm showing pdfs in an `embed` by using `<embed id="pdfPrev" src="foo.pdf">` An example of how this is rendered in Chrom is shown below [![enter image description here](https://i.stack.imgur.com/BUCcI.png)](https://i.stack.imgur.com/BUCcI.png) It's in a "container" and shows a preview and has buttons download, zoom, rotate, print, etc.. However, an end user is seeing something different [![enter image description here](https://i.stack.imgur.com/ANjXt.png)](https://i.stack.imgur.com/ANjXt.png) The first thing I thought was that they had some custom Chrome extension for rendering PDFs. This was not the case. Also, we have the same exact versions of Chrome. Opening up in a private window didn't resolve it either. Edit: Here's the css I'm using for the actual embed. ``` #pdfPrev{ border: 1px solid #ddd; /* Gray border */ border-radius: 4px; /* Rounded border */ padding: 5px; /* Some padding */ width: 1000px; height: 500px; margin: 5% auto; /* Will not center vertically and won't work in IE6/7. */ left: 0; right: 0; } /* Add a hover effect (blue shadow) */ #pdfPrev:hover { box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5); } ``` Any ideas? Thanks!
2021/06/07
[ "https://Stackoverflow.com/questions/67877245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2402616/" ]
you didn't give much info about your situation But can you force the height and width ! something like this : ``` <embed src="foo.pdf" width="400px" height="1000px" /> ```
54,769,289
I tried to replace validation from my previous project on Asp.net MVC 4 to Asp.net Core. And have some problems. The flow in Asp.net Core project like that: Middleware => ControllerCTOR => FluValidator => Filter => Action Also when some of Rules in FluValidator failed it's just return response with errors through Middleware stack to client. But I need to have access to ModelState in Filter or in Action. Why this don`t work correct? Or, if it's actually right flow, how to make it go deeper to Action? Startup ``` public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add(typeof(ValidateModelAttribute)); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>()); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "CorpLight API V1"); }); app.UseMiddleware<RequestResponseLoggingMiddleware>(); app.UseMiddleware<ErrorHandlingMiddleware>(); app.UseMiddleware<AuthenticateMiddleware>(); app.UseMvc(); } ``` Middleware ``` private readonly RequestDelegate _next; public ErrorHandlingMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } ``` Validator ``` public class CardInformationRequestValidator : AbstractValidator<RequestModel<CardInformationRequest>> { public CardInformationRequestValidator() { RuleFor(x => x.Request.RU) .NotNull() .NotEmpty(); RuleFor(x => x.Request.Currency) .NotNull() .NotEmpty(); RuleFor(x => x.Request.AccountNumber) .NotNull() .NotEmpty(); } } ``` Controller ``` [Route("api/[controller]")] [ApiController] public class CardController : ControllerBase { private readonly ICardRepo _cardRepo; private readonly IMapper _mapper; public CardController(ICardRepo cardRepo, IMapper mapper) { _cardRepo = cardRepo; _mapper = mapper; } [HttpPost] public async Task<MessageWithElements<CardInformation, CardInfo>> CardInformations(RequestModel<CardInformationRequest> request) { if (!ModelState.IsValid) throw new InvalidParametersException($"can't be empty"); //logic } } ``` Filter ``` public class ValidateModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid) { //logic } } } ``` Typical Valid Json: ``` { "request": { "ru": "string", "accountNumber": "string", "currency": 1 } } ``` Typical Invalid Json: ``` { "request": { "ru": "string", "accountNumber": "string", "currency": 0 } } ``` When currency NOT zero it's valid, and reach filter. But when it's zero, NotEmpty become failded and flow go back. Typical response with Valid request: ``` { "elements": [ { <object fields> } ], "messageText": "string", "messageNumber": 1 } ``` Typical response with Invalid request (400 Bad Request): ``` { "Request.Currency": [ "'Request. Currency' must not be empty." ] } ```
2019/02/19
[ "https://Stackoverflow.com/questions/54769289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9009524/" ]
The second argument passed to the `map` function is the index, which you could use to read the correct `key`. ``` const IconosSeccion = () => ( <div className="containerIconosSeccion"> <div className="parentIconos" /> {equipos.map(equipo => ( <div> {equipo.images.map((image, index) => ( <div className="backgroundIconoIndependiente"> <img alt="#" className="iconoIndependiente" src={image} /> <span className="textoIconoIndependiente">{equipo.key[index]}</span> </div> ))} </div> ))} </div> ); ```
27,642,948
i want to write a code which converts for example this text: "aaaaaaabbbb" into :"a7b4". It should read from one file and write to another. Here is the wrong part of the code and i cannot make it work. Ty for help.. ``` fread(&fx,sizeof(fx),1, fin); // read first character while(!feof(fin)) { fread(&z, sizeof(z),1, fin); //read next characters if(z!=fx) { fputs(fx, fout); fputs(poc, fout); poc=1; // if its different count=1 fx=z; // and z is new character to compare to } else poc++; } fputs(fx, fout); fputs(poc, fout); ```
2014/12/24
[ "https://Stackoverflow.com/questions/27642948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4392714/" ]
This is my code (not an optimal solution) to solve the problem with comments....Hope it helps for your own code and program !! ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { /* file is a pointer to the file input where to read the line */ /* fileto is a pointer to the file output where we will put */ /* the compressed string */ FILE* file, *fileto; file=fopen("path_to_input_file","r"); fileto=fopen("path_to_output_file","w"); /* check if the file is successfully opened */ if (file!=NULL) { /* the str will contain the non compressed str ing */ char str[100]; /* read the non compressed string from the file and put it */ /* inside the variable str via the function fscanf */ fscanf(file,"%[^\n]s",str); /* the variable i will serve for moving character by character */ /* the variable nb is for counting the repeated char */ int i=0,nb=1; for (i=1;i<strlen(str);i++) { /* initialization */ nb=1; fprintf(fileto,"%c",str[i-1]); /* loop to check the repeated charac ters */ while (i<strlen(str) && str[i]==str[i-1]) { i++; nb++; } fprintf(fileto,"%d",nb); } /* handle the exception for the last character */ if(strlen(str)>=2 && str[strlen(str)-1]!=str[strlen(str)-2]) fprintf(fileto,"%c%d",str[strlen(str)-1],1); /* handle the string when it is composed only by one char */ if(strlen(str)==1) fprintf(fileto,"%s%d\n",str,nb); fclose(fileto); fclose(file); } return 0; } ```
65,955,074
I store a text in my database as `$dataStorage = "This is my short string.\n\nThank you."` When i fetch the string from database and display in input box or text area, It appears just as it is stored in the database (i.e with the new break line" as below ``` This is a short string. Thank you. ``` Now, i am trying to display the text in div. The text appears but the new lines do not show. So it appears like ``` This is a short string.Thank you ``` How can i fix this using jquery **HTML** ``` <div class="chat-content rounded" id="msg"> </div> ``` **JS** //result is the string from the database ``` $('#msg').val(result); ```
2021/01/29
[ "https://Stackoverflow.com/questions/65955074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14812075/" ]
You can replace the newlines by br: ``` result.replace(/\n/g,"<br />"); ```
125,192
When I receive a 100€ salary net on my bank account after all taxes, my company had to actually cash out X€, split into their charges and my gross salary. After my charges and taxes are removed, I see the 100€ above. The value of X depends on the country, let's assume that for France that would be 400€. This is the case for **salaries**. Why wouldn't a company rather give me a **donation** of Y€? They would need to pay taxes on that (not charges), and then I could (and should) pay charges (social security, retirement, etc. - similar to the charges which are deducted from my salary). I would not pay taxes on donation. **Is this solely because for a final 100€ in my account, Y is greater than X?** I would be interested in a European perspective (and to fix things - ideally French, other countries are fine too if they are not that different from France) --- **EDIT**: For the sake of clarity, I am not interested in any fraudulent setup. I wanted to understand whether the solution is legal, and if so why it is not used. Answers of the type * it is not allowed by law because whenyou work for someone the only way you can be paid is though a salary (so a legal contraint) * it is not interesting financially (for either the company, the employee or both) are perfectly fine.
2020/05/08
[ "https://money.stackexchange.com/questions/125192", "https://money.stackexchange.com", "https://money.stackexchange.com/users/29745/" ]
I think you mean a "gift". Clearly pay for work is not a gift. It's a payment for consideration (consideration means your work). Gifts don't have consideration. Passing it off as such is fraud. It's also the case that the rules for companies gifting their employees are different than the ones for individuals gifting individuals. But you're not describing gifts anyway, so it doesn't matter.
21,677,633
I have a html table. I need 2 rules to work: 1. On mouse over table row should change background color. 2. Cells in 1 column should be with different color depending on cell content, for example - if value in the cell="Green" , background should be green. For the first rule I did rule in css: ``` tr:hover { background: brown; } ``` For the second - I've attached jQuery 2.0.3 and added js function which create class "color" for td: ``` $(document).ready(function(){ $('td.color').each(function(){ var x = $(this).text().trim(); if ( x === "Green" ) $(this).css({background: 'green'}); else if (x === "Yellow") $(this).css({background: 'yellow'}) ; else if (x === "Red") $(this).css({background: 'red'}) ; }); }); ``` The html of table is: ``` <table> <tr class='tr'> <td class='td'>Name1</td> <td class='td'>Green</td> <td class='color'>Green</td> </tr> <tr class='tr'> <td class='td'>Name2</td> <td class='td'>Yellow</td> <td class='color'>Yellow</td> </tr> <tr class='tr'> <td class='td'>Name3</td> <td class='td'>Red</td> <td class='color'>Red</td> </tr> </table> ``` (class color assigned only to last column) The sample with result you can see here: **<http://jsfiddle.net/bM5aW/7/>** So, backgrounds in last column are coloured depending on text value, and table rows change background color on mouse over event. **But** the last column doesn't change color on mouse over, as I understand because "**td**" rule from js script overrides "**tr**" rule from css. How to force "tr" rule to work if "td" rule was also declared?
2014/02/10
[ "https://Stackoverflow.com/questions/21677633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3221158/" ]
Add a !important to the rule ``` tr:hover, tr:hover td { background: brown !important; } ``` Demo: [Fiddle](http://jsfiddle.net/arunpjohny/B8mMY/) The problem is you are applying an inline style to the last td element, which has precedence over the `tr` element's style. --- Another option is to use class selectors to apply the color ``` $(document).ready(function () { $('td.color').addClass(function(){ return $.trim($(this).text()).toLowerCase() }) }); ``` then ``` tr:hover, tr:hover td { background: brown; } td.green { background: green; } td.yellow { background: yellow; } td.red { background: red; } ``` Demo: [Fiddle](http://jsfiddle.net/arunpjohny/dNREP/)
12,122,263
When I print out all files in the windows 7 system32 directory using ruby, some files are missing. I use this simple directory iteration: ```rb Dir.foreach("C:\\Windows\\System32") do |fname| puts fname end ``` I am specifically looking for python27.dll, which is not printed, though it exists. File.exists? seems to have the same problem as the dir iteration. it returns false for an existing file: ```rb File.exists? "C:\\Windows\\System32\\python27.dll" #returns false ``` Checking for another existing file of the folder works: ```rb File.exists? "C:\\Windows\\System32\\quartz.dll" #returns true ``` But it does not work if I duplicate an existing file or create a new one in system32 ```rb File.exists? "C:\\Windows\\System32\\quartz2.dll" #returns false ``` Also, copying python27.dll to another directory and checking for existence works: ```rb File.exists? "C:\\Otherfolder\\python27.dll" #returns true ``` The problem has nothing to do with letter-case or the path delimiter. I checked that. Also, I don't see differences in the user-rights for files that work and that don't ... I really have no idea, why this happens ... can anyone reproduce this??? thanks **[edit]** Took a while, but I found the answer. It was a 32/64-bit issue. for ruby as a 32bit application, "C:\Windows\System32" is actually "C:\Windows\SysWOW64". As the 64bit WinExplorer showed, python27.dll was in System32 (which only 64bit processes see - well, confusing), wheras it should have been in SysWOW64 for ruby to see. Installing the 32bit version of Python fixed the problem for me (as I couldn't change the ruby script, because it was part of rubypython).
2012/08/25
[ "https://Stackoverflow.com/questions/12122263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110464/" ]
Are you sure the files are available in `C:\\Windows\\System32\\`? I don't know this problem from the `System32`-folder, but I had some problems like yours with the `Program Files`-folder. If you try to save data in some system folders and you are no Admin, Win7 don't store it at that location, but in a user specific Virtual Store. When you look at your system folder, files from the virtual store are also shown there. But the path is another one. You may check your virtual store anywhere in `c:\users\<username>\Appdata\local\Virtual Store\` (at least the Program-folder is there).
71,395,493
For example I have an field that needs to have an user selected, so I have another React component where I select there the value, so I have a state there, how can I send that data to the current Component I have.
2022/03/08
[ "https://Stackoverflow.com/questions/71395493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107260/" ]
This is because the .reverse() method does not return any value, it simply reverses the list it was called from. (list\_3 has been reversed) Try this to print off the list: ``` list_3.reverse() print(list_3) ```
255,795
I'm trying to track down the title of a short story I read at least twenty years ago, probably nearer 30 and may not have been new at the time. Almost certainly in an anthology. The starting premise is a human crew stranded in space and with some sort of time constraint - it may have been specific to them (limited food or air), or an external issue (limited time to complete a mission). They find what appears to be an abandoned ship which acts as a zoo - a number of different alien species are on board, each in their own enclosure - but no crew. The determine that one of the species on board is actually the crew, acting like unintelligent animals to throw the humans off the track. The humans have some sort of mind probe that can test for intelligence - but only one species at a time, and it will take too long to run through them all. Someone - quite possibly not the 'obvious' character - works out that the crew are actually symbiotes. There is a small, intelligent species (possibly looking like a helmet) paired with a larger species (possibly humanoid, bear-like, or ape-like) that actually pilot the ship. Once the actual crew is identified, they appear to reach an amicable arrangement fairly easily. A couple of other elements: When the control room is found, they activate a control for a 'jet boost'. The switch was on a light contact, which they used to rule out a high-g species. Exploring the ship, they found living quarters with bunks and some small shelves, which turned out to be bunks for the two symbiotic aliens. There was an attempt to use the atmosphere as a discriminator, but the ship had a device that would reproduce an atmosphere it was exposed to; once the humans had gone, they would 'open the door of their cell a crack', release some of the atmosphere, and wait until it was made dominant by this device.
2021/11/06
[ "https://scifi.stackexchange.com/questions/255795", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/118276/" ]
I think this is the Van Rijn story "[Hiding Place](https://www.isfdb.org/cgi-bin/title.cgi?55496)" (1961) by Poul Anderson, originally published in *Analog* and collected in [*Trader to the Stars*](https://www.isfdb.org/cgi-bin/title.cgi?38030). The story starts with the ship Van Rijn is on having suffered damage in an escape from some hostile ships, with only a limited amount of time before critical systems shut down. They search along their course for a ship, hoping to find some help, and discover the zoo-ship. The time constraint is that they need to repair their ship and be underway before the hostiles they are fleeing from can get in front of them and put up pickets to intercept them. The ship they find tries to fire at them, tries to flee, and Van Rijn's ship pursues, locks on and the crew burn their way in. That's when they discover the zoo: > > Torrance chose to answer the last question first. "It seems to be an interstellar animal collector's transport vessel. The main hold is full of cages-environmentally controlled compartments, I should say-with the damnedest assortment of creatures I've ever seen outside Luna City Zoo." > > > As you say, there's no time to test them all: > > "Horse maneuvers!" Van Rijn's fist struck the table. The bottle and glasses jumped. "How long it takes to catch and check each one? Hours, nie? And in between times, takes many more hours to adjust the apparatus and > chase out all the hiccups it develops under a new set of, conditions. Also, Yamamura will collapse if he can't sleep soon, and who else we got can do this? All the whiles, the forstunken Adderkops get closer. We have not got time for that method! If the gorilloids don't fan out, then only logic will help us. We must deduce from the facts we have, who the Eksers are." > > > The aliens do indeed take the form of helmets and are symbiotic: > > Jukh grunted something. The gorilloid was too busy to talk, squatting where a pilot seat should have been, his big hands slapping control plates as he edged the ship into a hyperbolic path. BarkIakh, **the helmet beast** on his shoulders, who had no vocal cords of his own, waved a tentacle before he dipped it into the protective shaftlet to turn a delicate adjustment key. The other tentacle remained buried on its side of the gorilloid's massive neck, drawing nourishment from the bloodstream, receiving sensory impulses, and emitting the motor-nerve commands of a skilled space pilot. > > > At first the arrangement had looked vampirish to Torrance. But though the ancestors of the helmet beasts might once have been parasites on the ancestors of the gorilloids, they were so no longer. **They were symbionts.** They supplied the effective eyes and intellect, while the big animals supplied strength and hands. Neither species was good for much without the other; in combination, they were something rather special. > > >
20,970,886
First off the URL is being posted from a different page: ``` http://www.xxredxiiixx.com/games/ ``` click a link to take to example ``` http://www.xxredxiiixx.com/games/PS4/Knack#42 ``` This is showing the LAST trophy (#42) for Knack I have this code already (jQuery) ``` var hash = location.hash.replace("#",""); $(hash).removeClass("row").removeClass("row1").addClass("row2"); ``` The var gets the #42 correctly but I cant seem to alter the class to highlight the selected trophy. The IDs are just simply numbered accordingly ``` <tr class="row<?php echo ($j++ % 2 == 0 ? '' : '1'); ?>" id="<?php echo $xmb; ?>"> <tr class="row" id="42"> ``` Any help would be great. ``` .row2 td{ background-color: #FFF; } .row1 td{ background-color: #242424; border-top: 1px solid #121212; } .row td{ background-color: #2a2a2a; border-top: 1px solid #121212; } var hash = location.hash.replace("#",""); $(hash).removeClass("row").removeClass("row1").addClass("row2"); <tr class="row" id="42"> ```
2014/01/07
[ "https://Stackoverflow.com/questions/20970886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756010/" ]
You do not have to give dot `.` in `addClass` and `removeClass` functions. ``` $(hash).removeClass("row row1").addClass("row2"); ```
266,297
What is the searching algorithm used in switch statement in C language? If the cases are not in order still it searches proper case which means it is not a binary search algorithm, can anybody explain?
2014/12/12
[ "https://softwareengineering.stackexchange.com/questions/266297", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/110742/" ]
Several options: 1. the naive method would be an if else cascade (slow) 2. the compiler can sort the cases behind the scene and then do a binary search (good for disjoint cases) 3. a jump table; only good for sequential cases but very fast. For string-based switches there is the option of the [prefix Trie](http://en.wikipedia.org/wiki/Trie), a sorted table that can be binary searched or the strings are hashed and used for the cases of a switch against the hash of the input string with a double check in each case.
18,029,531
I have an array to 10 numbers supprse A[10] = {1,2,3,4,5,6,7,8,9,10} and I have to compute the multiplication of numbers in a particular range but not getting correct answer, I am using segment tree and dont know how to use query operation Here is my code : ``` #include<stdio.h> #define m 1000000000 #define MAX 100010 typedef unsigned long long ull; ull a[MAX]; ull tree[4*MAX]; void build_tree(int n,int b,int e){ if(b>e)return ; else if(b==e){ tree[n] = a[b]; return ; } build_tree(n*2,b,(b+e)/2); build_tree(n*2+1,(b+e)/2+1,e); tree[n] =( tree[n*2]%m * tree[n*2 + 1]%m )%m; } ull query(int index, int ss, int se, int qs, int qe) { ull p1, p2,p; if (qs > se || qe < ss) return -1; if (ss >= qs && se <= qe) return tree[index]; p1 = query(2 * index, ss, (ss + se) / 2, qs, qe); p2 = query(2 * index + 1, (ss + se) / 2 + 1, se,qs, qe); printf("\np1 = %d p2 = %d",p1,p2); p=(tree[p1]%m*tree[p2]%m)%m; return p; } int main(){ int n,i,query_start,query_end,segment_start,segment_end,index; ull value; scanf("%d",&n); for(i=0;i<n;i++) scanf("%lld",&a[i]); build_tree(1,0,n-1); query_start=1; query_end=2; segment_start=0; segment_end = n-1; index=1; printf("Tree Formed :-\n"); for(i=0;i<n*4;i++) printf("%d ",tree[i]); printf("\n\n"); value=query(index,segment_start,segment_end,query_start,query_end); printf("\nvalue = %lld\n",value); return 0; } ```
2013/08/03
[ "https://Stackoverflow.com/questions/18029531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/661801/" ]
This is slightly off topic, but posting this mainly as a response to sasha sami. This still works as an alternate idea to solve the OP's problem. If there are no queries, we don't really need to use a segment tree. The idea is to keep another array containing the cumulative products of the values in the input array. So, if the input array is ``` [1,2,3,4,5,6,7,8,9,10] ``` The corresponding product array will be: ``` [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800] ``` Now, we know the product of all elements [0, i] for any index i. To get the product between indices i and j, we can just get the product for [0, j] and [0, i] and use that to get our answer. The product for [i, j] is actually [0, j] / [0, i - 1]. To avoid specially handling the case where i = 0 we can also rewrite it as [0, j] / [0, i] \* element at i. Code (in Python): ``` #! /usr/bin/python def build_products_array(array):   ret = [0 for i in xrange(len(array))]   ret[0] = array[0]   last_value = 1 if array[0] else array[0]   for i in xrange(1, len(array)):     if array[i]:       ret[i] = last_value * array[i]       last_value = ret[i]     else:       ret[i] = last_value   return ret def build_zero_array(array):   ret = [0 for i in xrange(len(array))]   ret[0] = 0 if array[i] else 1   for i in xrange(1, len(array)):     ret[i] = ret[i - 1] + (0 if array[i] else 1)   return ret def check_zeros(zero_array, array, i, j):   return zero_array[j] - zero_array[i] + (0 if array[i] else 1) def query(products, zero_array, array, start, end):   if check_zeros(zero_array, array, start, end):     return 0   else:     return products[end] / products[start] * array[start] def main():   array = [1, 2, 3, 4, 5, 0, 7, 8, 9, 10]   products = build_products_array(array)   zeros = build_zero_array(array)   for i in xrange(len(array)):     for j in xrange(i, len(array)):       print "Querying [%d, %d]: %d\n" % (i, j, query(products, zeros, array, i, j)) if __name__ == '__main__':   main() ``` The thing to watch out for is overflows because the cumulative products can get quite big, even if the answers to the queries are guaranteed to be small enough. The above code it in Python, so there's not fear of overflows there, but in C++ you might want to use bignums. Its also handy if you need to find the products modulo some number - in which case overflow is not an issue. This approach will also work for finding the sum of a range of numbers, or any operation for which an inverse operation also exists (e.g. for sum the inverse is subtraction, for products the inverse is division). It wouldn't work for operations like max or min. This takes O(n) to build the initial product array, and each query is O(1). So this is actually faster than segment tree (which queries in O(log n) ). EDIT: Updated the code to handle zeros in the input. We keep another array keeping the total count of 0s at each index. For each query we check that array to see if there are any zeros in that range (as before, knowing the count for [0, i] and [0, j], we can figure out the count for [i, j])). If there are, the answer to that query must be 0. Otherwise we return the product.
521,851
I want two pictures next to another big one and every picture has a different size (like the example below). [![enter image description here](https://i.stack.imgur.com/ooE9p.png)](https://i.stack.imgur.com/ooE9p.png) I want that all pictures keep their aspect ratio and the pictures to the right should have the same height. Also all 3 pictures should be as wide as the `\textwidth`. I've tried `subfigure` and `\resizebox`, but I could not set the right heights dependent on the height of the left picture. Manually trying to fit all the sizes is way too tedious, is there an easy way to do that? Edit: Here are more informations for my problem. My current code looks like this. I've just adjustet the sizes of the pictures until they fit (trial end error). A very tedious process. The pictures have individual caption with (a), (b) and (c) and the whole picture has another caption. It would be nice to manage the size of the right pictures so that they are not bigger than the left one and that alle 3 pictures don't exceed the linewitdh. ``` \begin{figure}[H] \centering \begin{subfigure}[p]{.45\textwidth} \includegraphics[height=\textheight]{MMC.eps} \caption{MMC Schaltbild, \cite{Eremia.2016}} \label{fig:ch2_MMC \end{subfigure} \qquad \begin{subfigure}[p]{.45\textwidth} \centering \includegraphics[height=0.39\textheight]{Halfbridge.eps} \caption{Halfbridge, \cite{Shah.17.07.201621.07.2016}} \label{fig:ch2_Halfbridge} \vspace{2ex} \includegraphics[height=0.39\textheight]{Fullbridge.eps} \caption{Fullbridge, \cite{Shah.17.07.201621.07.2016}} \label{fig:ch2_Fullfbridge} \end{subfigure} \caption{MMC and Submodule}\end{figure} ```
2019/12/26
[ "https://tex.stackexchange.com/questions/521851", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/203892/" ]
You want to use `symbolic x coordinates` *and* `ybar` instead of `ybar interval`. ``` \documentclass{article} \usepackage[margin=0.5in]{geometry} \usepackage[utf8]{inputenc} \usepackage{textcomp} \usepackage{pgfplots} \pgfplotsset{width=10cm,compat=1.9}%<- 1.16 would be better \begin{document} Bar chart: \begin{tikzpicture} \begin{axis}[symbolic x coords={Testing1,Testing2,Testing3,Testing4,Testing5, Testing6,Testing7,Testing8,Testing9}, x tick label style={anchor=north west,rotate=-30}, ylabel=Number, enlargelimits=0.05, legend style={at={(0.5,-0.2)}, anchor=north,legend columns=-1}, ybar ] \addplot coordinates {(Testing1,9) (Testing2,4) (Testing3,4) (Testing4,1) (Testing5,1) (Testing6,8) (Testing7,1) (Testing8,1) (Testing9,1)}; \addplot coordinates {(Testing1,3) (Testing2,5) (Testing3,5) (Testing4,4) (Testing5,5) (Testing6,7) (Testing7,0) (Testing8,0) (Testing9,0)}; \legend{Series 1, Series2} \end{axis} \end{tikzpicture} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/gh29L.png)](https://i.stack.imgur.com/gh29L.png) Here is a more automatic version. ``` \documentclass{article} \usepackage[margin=0.5in]{geometry} \usepackage[utf8]{inputenc} \usepackage{textcomp} \usepackage{pgfplots} \pgfplotsset{width=10cm,compat=1.16} \begin{document} \begin{tikzpicture} \pgfplotsforeachungrouped \X in {1,...,9} {\ifnum\X=1 \edef\mylst{Testing1} \else \edef\mylst{\mylst,Testing\X} \fi} \begin{axis}[symbolic x coords/.expanded=\mylst, ylabel=Number, enlargelimits=0.05, x tick label style={anchor=north west,rotate=-30}, legend style={at={(0.5,-0.2)}, anchor=north,legend columns=-1}, ybar, ] \addplot coordinates {(Testing1,9) (Testing2,4) (Testing3,4) (Testing4,1) (Testing5,1) (Testing6,8) (Testing7,1) (Testing8,1) (Testing9,1)}; \addplot coordinates {(Testing1,3) (Testing2,5) (Testing3,5) (Testing4,4) (Testing5,5) (Testing6,7) (Testing7,0) (Testing8,0) (Testing9,0)}; \legend{Series 1, Series2} \end{axis} \end{tikzpicture} \end{document} ```
56,781,799
I'm trying to count all the people in an excel file that scored less than 75 on exam 1 but scored over 900 on either exam 2 OR 3. I tried using `countifs` but if both exam 2 and exam 3 are over 900, it counts them twice. Any suggestions? Please help! I've tried `sumproduct` as well but I can't figure out how to include an `OR` condition that's based on 2 separate columns ``` =COUNTIFS($C:$C, "<75",$E:$E,">900",$F:$F,">900") ``` I would expect to keep a count of all the students that meet this criteria.
2019/06/26
[ "https://Stackoverflow.com/questions/56781799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2943021/" ]
As an array formula (entered with Ctrl+Shift+Enter) ``` =SUM( (C3:C5<75)* (1*(E3:E5>900)+1*(F3:F5>900)>0) ) ```
11,386,946
What's the difference between sizeof and alignof? ``` #include <iostream> #define SIZEOF_ALIGNOF(T) std::cout<< sizeof(T) << '/' << alignof(T) << std::endl int main(int, char**) { SIZEOF_ALIGNOF(unsigned char); SIZEOF_ALIGNOF(char); SIZEOF_ALIGNOF(unsigned short int); SIZEOF_ALIGNOF(short int); SIZEOF_ALIGNOF(unsigned int); SIZEOF_ALIGNOF(int); SIZEOF_ALIGNOF(float); SIZEOF_ALIGNOF(unsigned long int); SIZEOF_ALIGNOF(long int); SIZEOF_ALIGNOF(unsigned long long int); SIZEOF_ALIGNOF(long long int); SIZEOF_ALIGNOF(double); } ``` will output 1/1 1/1 2/2 2/2 4/4 4/4 4/4 4/4 4/4 8/8 8/8 8/8 I think I don't get what the alignment is...?
2012/07/08
[ "https://Stackoverflow.com/questions/11386946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1494506/" ]
Well, "memory" is basically a huge array of bytes. However, most larger things like integers need more than 1 byte to store them -- a 32 bit value, for example, would use 4 consecutive bytes of memory. Now, the memory modules in your computer aren't usually "bytes"; they are also organized with a few bytes "in parallel", like blocks of 4 bytes. For a CPU, it's much easier = more efficient = better performance to not "cross" such block-borders when reading something like an integer: ``` memory byte 0 1 2 3 4 5 6 7 8 9 10 11 integer goooood baaaaaaaaad ``` This is what the "alignment" says: an alignment of 4 means that data of this type should (or must, depends on the CPU) be stored starting at an address that is a multiple of 4. You observation that sizeof==alignof is incorrect; try structures. Structures will also be aligned (because their individual members need to end up on the correct addresses), but their size will be much larger.
26,777,579
I have a class and some methods in that class which I want to reference using a dictionary inside the class. If I define the dictionary before the class method I get a "not defined error". However, if I put the dictionary after the method definition python does not complain. Why is that? And what can I do to fix it? Code example: This does not work ``` class foo: fooFunDic = { 'fooFun1': fooFun1, 'fooFun2': fooFun2 } def fooFun1(self): return 0 def fooFun2(self): return 0 ``` Ugly but works ``` class foo: def fooFun1(self): return 0 def fooFun2(self): return 0 fooFunDic = { 'fooFun1': fooFun1, 'fooFun2': fooFun2 } ```
2014/11/06
[ "https://Stackoverflow.com/questions/26777579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
The names are yet do be defined when you define the dictionary. The class body is executed like a function and the local namespace forms the attributes. The same order of name definition applies therefor. Note that even in your second example, what you store in the dictionary are *functions*, not methods. Calling those functions would require you to explicitly pass in `self` parameters if you want them to work like methods. You could define the dictionary in the `__init__` method instead to get bound methods in a dictionary stored on the instance: ``` class foo: def __init__(self): self.fooFunDic = { 'fooFun1': self.fooFun1, 'fooFun2': self.fooFun2 } def fooFun1(self): return 0 def fooFun2(self): return 0 ``` If you don't care about bound methods vs. bare function objects, you can define the dictionary first, then 'register' each function with that dictionary: ``` class foo: fooFunDic = {} def fooFun1(self): return 0 fooFunDic['fooFun1'] = fooFun1 def fooFun2(self): return 0 fooFunDic['fooFun2'] = fooFun2 ```
30,642,876
I have this short example: **CODE CSS:** ``` body{ background:url(DECUPATE/TEST/images/ppp.jpg); bacground-size:contain; backgoun-repeat:none; } ``` I put a picture to understand what they want to do. <http://i61.tinypic.com/10xeeeb.jpg> if you put `background size: cover` appears to the end but there is the incomplet image. How can I solve this problem? Thanks in advance!
2015/06/04
[ "https://Stackoverflow.com/questions/30642876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4952498/" ]
You have to use html instead of body ,see the code below : ``` html { background: url(images/bg.jpg) no-repeat center center fixed; -webkit-background-size: 100% 100% cover; -moz-background-size: 100% 100% cover; -o-background-size: 100% 100% cover; background-size: 100% 100% cover; /* set the padding and margin to "0" */ margin: 0; padding: 0; /* set the position rules */ top: 0; left: 0; } ```
474,198
In QM books (at least those I have read) the definition of the [Hilbert space](https://en.wikipedia.org/wiki/Hilbert_space) used is somewhat blurred (the "space of square integrable functions" is not enough to define it precisely : which kind of square integrable function ? measurables ? continuous ? something else ?..) . Ok, separable Hilbert spaces are all isometric, but in practice the choice of one representation of that isomorphic class seems important in the context of QM isn't it? So, precisely, which function space is used to represent the states of a quantum system?
2019/04/21
[ "https://physics.stackexchange.com/questions/474198", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/228890/" ]
The Hilbert space of 1D quantum mechanics is constructed as the completion of the Schwartz space $\mathcal{S}(\mathbb{R})$ of smooth functions that decay faster than the inverse of any polynomial. The completion of this space is $\overline{S}(\mathbb{R})=L\_2(\mathbb{R})$, the set of all Lebesgue-integrable functions with finite norm. That is, the space of measurable functions $f$ such that $$\langle f, f\rangle=\int|f(x)|^2\mathrm{d}\mu(x)<\infty.$$ This is easily generalized to higher dimensions. Furthermore if the system in question is also equipped with a finite-dimensional degree of freedom (spin, for instance) with (finite-dimensional) Hilbert space $\mathbb{C}^n$, then the full Hilbert space becomes $$L\_2(\mathbb{R})\otimes\mathbb{C}^n.$$ I hope this helps!
140,996
I want to negate the symbol whose code is `\models` (this would be specific to Formal Logic). How can I do that? I tried a number of combination, but didn't find how this could be done. I tried `\neqmodels`, `\nemodels`, `\notmodels`, `\nmodels` but all of them are wrong. Is there a general way to negate symbols?
2013/10/27
[ "https://tex.stackexchange.com/questions/140996", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/39030/" ]
There are a number of ways to achieve the negation of a symbol: 1. Follow the guidelines in [How to look up a symbol or identify a math symbol or character?](https://tex.stackexchange.com/q/14/5764) to see whether such a symbol already exists. This is usually the best course of action, since the symbol would have been constructed to match certain specification (say, placement and height/depth of negation symbol). If such a symbol is only available in a different font, then consider including only that symbol by following the instructions in [Importing a Single Symbol From a Different Font](https://tex.stackexchange.com/q/14386/5764). ![enter image description here](https://i.stack.imgur.com/BnLBJ.png) ``` \documentclass{article} \usepackage{amssymb}% http://ctan.org/pkg/amssymb \begin{document} \[ a \neq b \nparallel c \nvDash d \nprec e \] \end{document} ``` 2. For a symbol `\mysymbol`, try `\not\mysymbol`. `\not` is a zero-width math relation that is set "on the right" of where it's called. As such, it visually overlaps the typical math relation/symbol. Not always perfect, but works in general. ![enter image description here](https://i.stack.imgur.com/f7ddv.png) ``` \documentclass{article} \begin{document} \[ a \not= b \not\geq c \not\sim d \not\approx e \not\in f \] \end{document} ``` 3. [`centernot`](http://ctan.org/pkg/centernot) works well when symbols are somewhat wider than usual, yet you still want the regular `\not`-like visual. ![enter image description here](https://i.stack.imgur.com/FTTHZ.png) ``` \documentclass{article} \usepackage{centernot}% http://ctan.org/pkg/centernot \begin{document} \[ a \not= b \centernot= c \not\parallel d \centernot\parallel e \not\longrightarrow f \centernot\longrightarrow g \] \end{document} ``` 4. The [`cancel` package](http://ctan.org/pkg/cancel) draws a diagonal line across a symbol to "cancel" it. ![enter image description here](https://i.stack.imgur.com/TaqlH.png) ``` \documentclass{article} \usepackage{centernot,cancel}% http://ctan.org/pkg/{centernot,cancel} \begin{document} \[ a \not= b \centernot= c \mathrel{\cancel{=}} d \not\longrightarrow e \centernot\longrightarrow f \mathrel{\cancel{\longrightarrow}} g \] \end{document} ``` 5. Other methods include using graphics packages like [`tikz`](http://ctan.org/pkg/pgf) or [`pstricks`](http://tug.org/PSTricks/main.cgi/) to draw rules in specific locations across a symbol/construction.
4,233
I have a pack of rectangular pictures (some landscape, some portrait) but I need them to be square. I know how to use imagemagick for resizing and converting. ![example1](https://i.stack.imgur.com/FopYy.jpg) ![example2](https://i.stack.imgur.com/rbOQC.jpg) ![example3](https://i.stack.imgur.com/jzKeT.jpg) Some of the pictures are wider, some of them higher; but I really don't know how can I make my pictures square in bulk? Any help/ideas for my issue?
2011/10/19
[ "https://graphicdesign.stackexchange.com/questions/4233", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/2693/" ]
In general you have three basic possibilities: 1) Increase your picture's dimensions (on the shortest side) to make it square (As Lauren suggested) 2) Crop them to be square (As DA01 suggested) 3) Stretch your images to fit a square All three of them have their pros and cons of course. The first one makes it square, but it adds useless "information". The second technique takes away some of your picture, and you may lose some "information". The third one keeps everything but it makes it look distorted and strange. There are of course more complicated options such as [extracting your object](http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=extract%20an%20object%20photoshop) and then standardizing a background or faking the background by [extending it](http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=extract%20an%20object%20photoshop#sclient=psy-ab&hl=en&source=hp&q=extend%20background%20photoshop&pbx=1&oq=extend%20background%20photoshop&aq=f&aqi=g2g-v2&aql=1&gs_sm=e&gs_upl=22925l26485l0l26636l27l17l0l5l5l1l483l5912l2-1.11.4l19l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=b571422ac7922aeb&biw=1920&bih=989). If you are the photographer, then I would suggest setting up a system when you take the pictures of your objects and leave plenty of room around your object so that you can crop it square later. However, if there as the pictures you are using, then it shouldn't be a hassle to use either of the above techniques.... here's an example of the first three, respectively. Extra background: ![enter image description here](https://i.stack.imgur.com/fWYHp.png) Cropped: ![enter image description here](https://i.stack.imgur.com/44eJT.png) Stretched: ![enter image description here](https://i.stack.imgur.com/z9io9.png) In addition to that (again, given that these are the actual pictures) it's important to remember what you're using these images for. If you're selling furniture, it's best that you don't stretch the image in any way, as it may make the furniture seems smaller/larger or more out of proportion than it really is. The second technique works great if you can simply crop out the background, and if that's not an option then adding a background to expand the image may be your best bet.
77,439
I've successfully installed Ubuntu 11.10 alongside Windows 7. During installation I've manually changed the Windows partition size ( there were 24Gb used, I've changed virtual partition size from 100Gb to 40Gb) and killed the 150Mb partition where Windows stores system recovery data. I've installed Ubuntu on second virtual partition. So now when the GRUB starts it cannot see the Windows installer. I think it's all OK with windows loader, just GRUB does not know about it. So I need to specify it manually. Where and how?
2011/11/09
[ "https://askubuntu.com/questions/77439", "https://askubuntu.com", "https://askubuntu.com/users/21261/" ]
Run this from Ubuntu: ``` sudo update-grub ``` And reboot. Windows should be in the Grub menu now.
5,427,876
The onCreate() method is called but the new Activity never appears. No errors are logged. Follow up - There was no problem with calling startActivty() from a Fragment (we had a bug in the second Activity that caused it to exit immediately). startActivity() from a Fragment works exactly like startActivty() from outside a Fragment.
2011/03/25
[ "https://Stackoverflow.com/questions/5427876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/275479/" ]
A fragment should not be calling `startActivity()`, IMHO. A fragment should be telling its activity to display something, and the activity should be deciding how to do that. In some devices, that might be launching another activity. In some devices, that might be by adding a fragment. That decision should be made at the activity level, as it is the activities that are deciding what fragments go in what activities, based upon screen size. [Here is a sample application](https://github.com/commonsguy/cw-android/tree/master/Fragments/EU4You_6) where a click on an item in a `ListFragment` causes either a separate `DetailsFragment` to be updated (for `large`/`xlarge` screens) or pops a new activity (for normal screens).
33,322,201
Can you remove the top margin and padding from the first element in a div? So if the first element is a paragraph or a header there's no top margin. The first element could be anything. The idea is not having to write all the permutations of elements, but I will do if I need to. Thanks
2015/10/24
[ "https://Stackoverflow.com/questions/33322201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1382451/" ]
Yes. You want to use the :first-child selector ``` .parent :first-child { margin-top:0; } ```
255,949
While the way the Earth is saved by microorganisms seems naïve perhaps today, I suspect that the idea of microorganisms affecting aliens was very new since it was not even completely accepted that disease was caused in humans by bacteria (or had only recently been accepted) at this time. Did any previous story feature microorganisms or was Wells the first, as he often was, to come up with this idea?
2021/11/12
[ "https://scifi.stackexchange.com/questions/255949", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/105042/" ]
A few years previously (**1892**) was [*The Germ Growers: An Australian Story of Adventure and Mystery*](https://www.isfdb.org/cgi-bin/title.cgi?1948064), by Robert Potter. A hostile alien race mutates naturally-occurring Earth bacteria in order to conduct bio-warfare against humanity: > > But this Davelli has lately taken up a line of action against God and man which some of the more powerful of his kind took up ages ago with far wider success; he has established here, and in the inaccessible parts of the Himalayas, and in one or two other places, artificial seed-beds of pestilence. His emissaries gather, from all quarters, germs of natural and healthful growth, and submit them to a special cultivation under which they become obnoxious and hurtful to human nature. And then they sow them here and there in the most likely places, and thus produce disease, death, and disaster among men. > > > The story is public domain, and available at [Project Gutenberg](https://www.gutenberg.org/ebooks/60312).
41,764,335
I have extremely little knowledge of PHP and was trying to make a contact form for the website I'm helping to develop. The PHP form sends the email but for whatever reason doesn't replace the variables with the input fields from the contact page. The website is [SWFDA](http://swfda.org/contact.html). Here is the PHP form I created: ``` <?php if(!isset($_POST['submit'])) { $name = $_POST['name']; $visitor_email = $_POST['email']; $message = $_POST['message']; $email_from = '[email protected]'; $email_to = '[email protected]'; $email_subject = 'Contact Form Submission (Under testing)'; $email_body = 'You have received a form submission from $name . Email: $visitor_email . Here is the message: $message'.; mail($email_to,$email_subject,$email_body); header('Location: contact-sent.html'); } ?> ``` This is the HTML for the form. ``` <form method="post" action="contactForm.php"> <div class="row uniform"> <div class="6u 12u$(large) 6u(medium) 12u$(xsmall)"> <label for="name">Name</label> <input type="text" name="name" id="name" required/> </div> <div class="6u$ 12u$(large) 6u$(medium) 12u$(xsmall)"> <label for="email">Email</label> <input type="email" name="email" id="email" required/> </div> <div class="12u$"> <label for="message">Message</label> <textarea name="message" id="message" rows="5" required></textarea> </div> <div class="12u$"> <ul class="actions"> <li><input type="submit" value="Send Message" class="special" /></li> <li><input type="reset" value="Reset" /></li> </ul> </div> </div> </form> ``` The received email looks like: You have received a form submission from $name. Email: $visitor\_email. Here is the message: $message.
2017/01/20
[ "https://Stackoverflow.com/questions/41764335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7446356/" ]
Finally I solved this mystery. If you have installed Spyder from the Anaconda, go to the Anaconda launcher. There go to environments, you will see two of them: root and tensorflow. The latter one is created due to the instructions by tensorflow.org. Just run all those instructions on the root, don't activate tensorflow environment, it will work. Everything will be available in spyder.
51,385,823
How can I repeat only the values of the `recommendaciones` object with `*ngFor`?. For example, I am now repeating the values in this way: ``` <div ngFor="let producto of productos"> <div> {{ producto.titulo }} </div> <div>Recomendaciones: <span *ngFor="let producto of productos.recomendaciones"> {{ producto.recomendaciones }}</span> </div> </div> </div> ``` But how do I get to repeat each value of `recommendaciones` in an individual `span`? service.ts ``` getProductos() { this.productos = [ { id: 'lomoFino', titulo: 'Lomo fino', descripcion: 'Es la pieza más fina de la res, de textura tierna.', recomendaciones: ['Guisos', 'Freir', 'Plancha'], ubicacion: 'Lomo', }, { id: 'colitaCuadril', titulo: 'Colita de cuadril', descripcion: 'Es un corte triangular y ligeramente marmoleado.', recomendaciones: ['Guisos', 'Freir', 'Horno'], ubicacion: 'Trasera', }, { id: 'asadoCuadrado', titulo: 'Asado cuadrado', descripcion: 'Corte fibroso, de sabor agradable.', recomendaciones: ['Guisos', 'Freir', 'Plancha'], ubicacion: 'Entrepierna', } ] return this.productos } ```
2018/07/17
[ "https://Stackoverflow.com/questions/51385823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8312532/" ]
I recently publish a project that solves the exactly same problems. I manage the file upload in a separate class that also covers Drag / Drop. Basically, you must return target.result on the "load" event. ``` const fileReader = new FileReader(); fileReader.addEventListener("load", this.fileReader_load.bind(this, file.name), false); fileReader.readAsDataURL(file); fileReader_load(fileName, event) { event.target.removeEventListener("load", this.fileReader_load); this.onFileLoaded(fileName, event.target.result); } ``` See the full image loader here: <https://github.com/PopovMP/image-holder/blob/master/public/js/file-dropper.js> The image preview is easy. Make an image element and set its `src` to the imageData. Here is the full source code: <https://github.com/PopovMP/image-holder>
11,424,382
ok so I have the sql and the output for if someone has an image, how would I re-write this to set a default image if the user hasn't uploaded a profile picture? ``` $search = mysql_query("SELECT users.username, users.id, tbl_image.photo, tbl_image.userid FROM users LEFT OUTER JOIN tbl_image ON users.id=tbl_image.userid WHERE users.username LIKE '%$search_term%' and users.business <> 'business'"); <img src="/image/'.$results_row['photo'].'" width="50px" height="40px"> ```
2012/07/11
[ "https://Stackoverflow.com/questions/11424382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1496850/" ]
If the image is NULL or "", you use your default: ``` $image = $results_row['photo']; if (empty($image)) $image = "default.png"; <img src="/image/'.$image.'" width="50px" height="40px"> ```
45,395,669
I get this message when trying to display a notification on Android O. > > Use of stream types is deprecated for operations other than volume > control > > > The notification is straight from the example docs, and displays fine on Android 25.
2017/07/30
[ "https://Stackoverflow.com/questions/45395669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/560600/" ]
Starting with Android O, you are required to configure a [NotificationChannel](https://developer.android.com/preview/features/notification-channels.html), and reference that channel when you attempt to display a notification. ``` private static final int NOTIFICATION_ID = 1; private static final String NOTIFICATION_CHANNEL_ID = "my_notification_channel"; ... NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT); // Configure the notification channel. notificationChannel.setDescription("Channel description"); notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.RED); notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000}); notificationChannel.enableVibration(true); notificationManager.createNotificationChannel(notificationChannel); } NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setVibrate(new long[]{0, 100, 100, 100, 100, 100}) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Content Title") .setContentText("Content Text"); notificationManager.notify(NOTIFICATION_ID, builder.build()); ``` A couple of important notes: 1. Settings such as vibration pattern specified in the `NotificationChannel` override those specified in the actual `Notification`. I know, its counter-intuitive. You should either move settings that will change into the Notification, or use a different NotificationChannel for each configuration. 2. You cannot modify most of the `NotificationChannel` settings after you've passed it to `createNotificationChannel()`. You can't even call `deleteNotificationChannel()` and then try to re-add it. Using the ID of a deleted `NotificationChannel` will resurrect it, and it will be just as immutable as when it was first created. It will continue to use the old settings until the app is uninstalled. So you had better be sure about your channel settings, and reinstall the app if you are playing around with those settings in order for them to take effect.
2,146,875
Let **d** be a positive integer.The question is to prove that there exists a right angled triangle with rational sides and area equal to $d$ if and only if there exists an Arithmetic Progression $x^2,y^2,z^2$ of squares of rational numbers whose common difference is $d$ I tried using Heron's formula to get a relation between squares of sides and area but i failed and couldnot proceed.Is this an instance of an already known result I am unaware of?Any ideas?Thanks.
2017/02/16
[ "https://math.stackexchange.com/questions/2146875", "https://math.stackexchange.com", "https://math.stackexchange.com/users/356886/" ]
Let $a,b$ the legs and $c $ the hypothenuse of the right angled triangle with rational sides and area equal to a given integer $d =\dfrac {ab}{2}$. Then $\dfrac {(a-b)^2}{4}$, $\dfrac {c^2}{4} $, and $\dfrac {(a+b)^2}{4}$ form an arithmetic progression of squares of rational numbers with common difference $\dfrac {ab}{2} $.
231,777
After doing some research and with the help of people on this site, I finally came to an understanding of what interpretation actually is. Essentially, what interpretation means is (correct me if I'm wrong): 1. Scan a piece of code. 2. Come up with a piece of code in another language, with the same meaning. 3. **Execute** that new piece of code. So for example, and interpreter written in Java that interprets code in C, and sees this line of code:`printf("hello world");` Will come up with this line of code: `System.out.println("hello world");` And will **execute** it (as opposed to a compiler, which will **store** it). **If all of this is true, then here is my question:** I think, that **every execution an interpreter carries out, actually creates a chain of interpretations down to the lowest level.** I'd like to know if this is true. Here is what I mean: When an interpreter **executes** a line of code (which is the new line it came up with, after scanning a line), **it actually tells the underlying platform to interpret it.** For example, as we know, an interpreter written in Java that interprets C code, sees `printf("hello")` and **executes** in reaction the new line of code `System.out.println("hello")`. But what does "**executes** `System.out.println("hello")`" actually mean? **It means to tell the underlying platform (in this case the JVM) to interpret this line.** And so, another interpretation begins: The (in this example) interpreter in the JVM receives the line `System.out.println()`, comes up with a new line of code with the same meaning in another language, and **executes** it. And when it **executes** the new line of code, again: It actually tells it's underlying platform to interpret it (in this example, the OS). And then another interpretation begins in the OS, which comes up with a new line of code with the same meaning in a different language, and tells an even lower level to interpret it. This continues down to the lowest level of the CPU. My question is: Is this true? **Is every execution an interpreter carries out, actually a call to the underlying platform to interpret?** (Thus creating a chain of interpretations down to the lowest level?) When people say that an interpreter **executes** code, do they actually mean that it tells it's underlying platform to interpret that code? (And so on?) *(Note: I might be not accurate about the function of the JVM specifically, I missed some steps there. But my question is more general, Java is just an example).*
2014/03/09
[ "https://softwareengineering.stackexchange.com/questions/231777", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/122638/" ]
Yes, but more than that. *All* of the interpreter's code is interpreted by a lower level, including the "scan a piece of code" step. However, there are less levels than you think - more than three levels is rare. Jython is one example of an interpreter running on an interpreter. It runs Python code, and is itself written in Java, which is interpreted by a JVM, which is machine code (that was compiled from C or C++) which is interpreted by the CPU. JVMs commonly are written in C or C++, and run directly on the CPU, not the OS. Native programs run directly on the CPU, alongside the operating system, rather than being interpreted by the operating system. The difference between the OS and a native program is that the OS has more access to the hardware, so that if the native program wants to access the hardware (e.g. to display stuff on the screen) it still needs to ask the OS. Also, the "coming up with a line of code in a new language" is [Just-In-Time Compilation](http://en.wikipedia.org/wiki/Just-in-time_compilation), not strictly interpretation. Many programs traditionally thought of as interpreters (including nearly all JVMs) do use some form of JIT compilation. A JIT compiler looks something like this: ``` void execute(instruction instructions_to_execute[]) { lower_level_function f; if(is_translation_in_cache(instructions_to_execute)) f = get_translation_from_cache(instructions_to_execute); else { f = translate_to_lower_level_instructions(instructions_to_execute); put_translation_in_cache(instructions_to_execute, f); } f(); } ``` while an interpreter looks like this: ``` void execute(instruction instructions_to_execute[]) { for(instruction i in instructions_to_execute) { switch(i.type) { case PRINT_STRING: print(i.string_to_print); break; case ADD: variables[i.result_variable] = variables[i.left_variable] + variables[i.right_variable]; break; case CALL: execute(functions[i.function_to_call].instructions); break; // etc } } } ``` JIT compiling is usually faster for frequently run sections of code, because they can be converted into the lowest level code, and then executed directly. Interpreting is faster for sections of code that are infrequently executed, because the compiler (the `translate_to_lower_level_instructions` function) is slow.
45,140,509
I am with a bit of a stuggle here. I managed to create the dynamic URL using the following code: *Home Page Controller* ``` $satellites = DB::table('satellites')->get(); return view('pages/home', ['satellites' => $satellites]); ``` *Blade File* ``` @foreach($satellites as $satellite) <a href="{{$satellite->norad_cat_id}}"><li>{{$satellite->satname}}</li></a> @endforeach ``` *web.php* ``` Route::get('{norad_cat_id}', 'Satellite@show'); ``` *Controller* ``` public function show($norad_cat_id) { return view('pages/satellite'); } ``` The URL generated is: mysite.com/12345 (where 12345 is the norad\_cat\_id). This code manages to create the dynamic URLs using the norad\_cat\_id from the database - which is what I want. The problem is that I can replace the URL with anything and it still creates a page (ie. replace the 12345 with something not from the database and a page is still created). What I want is only for a URL to be generated only with the norad\_cat\_id and if there is no matching norad\_cat\_id in the database, display a 404 page.
2017/07/17
[ "https://Stackoverflow.com/questions/45140509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770645/" ]
In the show method add a fetch from database if there is no record just abort ``` public function show($norad_cat_id) { $satellite = DB::table('satellites')->where('norad_cat_id', $norad_cat_id)->first(); if( ! satellite){ return abort(404); } return view('pages/satellite'); } ``` PS: abort will automatically redirect to your resources/views/errors/404.blade.php
34,870
When I create reports, they list either Contacts, Contributions, Activities or similar. Is it possible to list Custom Field entries? For example, I have a TAB with custom fields. I'd like to get a list of entries that have PARAMETER X with corresponding DATA value from multiple contacts, while not listing Y. Alternatively, I'd like to get ALL of these **Custom Field entries** from multiple contacts (including contact name), not just the names of contacts that contain these Custom Fields entries. Is that possible? If not via reports, maybe somehow else? [![enter image description here](https://i.stack.imgur.com/mwZcC.png)](https://i.stack.imgur.com/mwZcC.png)
2020/02/27
[ "https://civicrm.stackexchange.com/questions/34870", "https://civicrm.stackexchange.com", "https://civicrm.stackexchange.com/users/3597/" ]
It turns out, I can do it easily with CiviCRM Constituent Summary report. (**Class used: CRM\_Report\_Form\_Contact\_Summary**) I just need to enable to show all necessary custom fields and it returns exactly the table needed.
101,397
**The main question:** Is it advisable to refuse a job offer in a place you've worked as intern, if you fear it could be uninteresting, poor in terms of career growth, and generally not the best thing you could try? **Background:** I'm a (almost graduated) master degree student in Computer Science, currently ending my unpaid internship with company A. So far, while I do enjoy some aspects of the culture of A, I'm not satisfied with the internship; most days I've nothing much to do or I'm forced to wait for input from my overworked colleagues. The project I'm on seemed interesting at first, but now - after months of little feedback and a rather disinterested attitude by, well, anyone - I'm disheartned and I don't care anymore. Of course, I could have been a better employee, but that's a tale for another day. **The point is,** now that the internship is ending, everyone seems convinced that I'll receive a job offer soon. This is somewhat dreadful to me, since I'm not enjoying my stay, I'm struggling to care about the project and I don't imagine what my future in the company could be. Moreover, I'm not really conviced I'd like to work with the current technologies I'm using now in company A. I'll add more meat to the fire and say that, given the actual hiring policy of company A, it's unlikely that I will work there for more than one or two years. As an almost new-grad, I'm well aware there are many things I don't know; I'm afraid of stagnating in a place that won't add anything relevant to my skill set (at least, nothing that I didn't learn through my internship already).
2017/10/24
[ "https://workplace.stackexchange.com/questions/101397", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/72130/" ]
> > Is it advisable to refuse a job offer in a place you've worked as intern, if you fear it could be uninteresting, poor in terms of career growth, and generally not the best thing you could try? > > > *If* you get a job offer after your internship it is up to you to decide if you take it or not. In now way ever you *have to* take a job offer only because it was given to you. It seems that you are not enjoying the company, so it could be wise to refuse such offer if they ever give it to you, and look for other jobs in places that are a better fit for your interests. Before you refuse it, make sure that the offer they give you is of no interest to you. It could be that they offer you a somewhat different role, with new responsibilities and tasks. *If* you think you may like that then consider taking it, if it is the same role as your internship then I suggest you seek for other job.
19,992,597
I am using Bootstrap 3 to build my personal website and have been searching for a way to do the following: I would like to assign unique gutter widths to specific rows in my layout. The rest of the website will make use of the underlying gutter width. Is it possible? Any help would be much appreciated. Thanks in Advance / Trev
2013/11/15
[ "https://Stackoverflow.com/questions/19992597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2994629/" ]
Yes. Add a unique CSS class, say `my-personalized-row` to the row you want to edit. Then in your CSS, add a section for this as following: ``` .my-personalized-row { margin-bottom: 5px !important; //If you want 5px of gutter width. } ``` Now, whatever you put between the two braces will apply only to this row and the rest of the site will use the underlying gutter width. **UPDATE:** I have added the style rule you would want to use to reduce the gutter width for a specific row to 5px. The `!important` is to ensure that specificity rules will not interfere with your declaration. Note that it is not mandatory to use `!important` since Bootstrap declares styles with a single class as well.
50,855,737
The command ``` git cat-file -p 3b18e512dba79e4c8300dd08aeb37f8e728b8dad ``` prints on screen the content of the file referred by the hash above, a `hello.txt` with just `hello world` inside. The command ``` git rev-parse 3b18e512d ``` instead, is an astute shortcut to get the whole hash just by referring to the first hexes. Now, how can I pass the output of `git rev-parse` to `git cat-file -p` above? I tried with ``` git cat-file -p | git rev-parse 3b18e512d ``` but without success, even if this is usually the way I proceed with when piping outputs through different commands.
2018/06/14
[ "https://Stackoverflow.com/questions/50855737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274567/" ]
If you're running a recent version of Airflow and you set your schedule's interval to be @monthly then I think the `{{ data_interval_start }}` and `{{ data_interval_end }}` is what you're looking for. You can see all the macros [here](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html)
48,328,000
I have thousands of files on google drive which i have deleted sent to trash. My problem is they are still showing up after emptying the trash. Emptying the trash simply does not work. The only way i can delete items and reduce quota is by searching for items using the is:trashed search operator permanently deleting them that way except this takes forever and i have no idea how to automate this using drives api. I have successfully ran [this](https://stackoverflow.com/questions/32749289/how-to-automatically-delete-file-from-google-drive-trash-folder) from another question but it doesn't help my cause. I am essentially after a script that lists files tagged as trashed owned by me and then permanently deletes them. Any help greatly appreciated
2018/01/18
[ "https://Stackoverflow.com/questions/48328000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236524/" ]
"I have thousands of files on google drive which i have deleted sent to trash. My problem is they are still showing up after emptying the trash." Just picking up on that second sentence, it's worth bearing in that when using the Google API (eg with rclone) or even with Google's own web interface, there is always a delay between issuing any "Empty the Bin" instruction, to Google Drive actually actioning it. And the more files that are in the Bin, and the smaller they are, the longer it will take for the Bin to be fully cleared. Thousands of very small files can take quite a while. And you have no control over when Google Drive will actually start the deletion or how fast it will work its way through the Bin. Anyone who's familiar with Garbage Collection will understand precisely what I mean - "Ye know not at what hour the master cometh", as my minister Dad would have [annoyingly] put it :D You can demonstrate this behavior for yourself by "removing" lots of files to the Bin, have the Bin displayed in a web browser and then issue (for example), "rclone cleanup mydrive:" which is the rclone command to empty the Google Drive Bin (where mydrive: has been configured to point to your Google Drive). Firstly, you can observe that although the instruction has been issued, it can take a while before the Bin's list of files begins changing and at times, it can chug quite slowly through the list. The other thing is that if you instruct the web interface to empty the bin it will immediately replace the list of files and folders with a graphic saying the Bin is empty. In fact, it's not, as you will see if you click on the "My Drive" folder and then immediately click back on the Bin again - the entire list will be redisplayed as before, minus anything that Google Drive has deleted in the interim. In the background, however, Google Drive will be revving up to delete your files. The other, other thing is also that any further files and folders that are removed to the Bin after the initial "Empty the Bin" instruction has been issued, will need a subsequent command for them to be deleted permanently - they will not be covered by the first command. Again, you can demonstrate this to yourself by removing items to the Bin while the first "Empty the Bin" is in progress - you will ultimately be left with a Bin containing the second lot of removals. I just thought it was worth pointing this out (you may disagree :D ), as I too have tried to empty my Bin in the past and thought that Google Drive wasn't doing anything. Edit: apologies for the edit. I meant to say that once you've issued the "rclone cleanup mydrive: " command, if you then use "rclone about mydrive:", one of the stats it reports is the total space used by the files in the Bin. By periodically issuing "rclone about..." you can see the amount of space used by Bin decreasing each time. This is often the better way of checking how your "Delete Forever" command is progressing since Google Drive already considers those files gone, albeit in theory rather than practice.
1,521,958
For a Data Structures project, I must find the shortest path between two words (like `"cat"` and `"dog"`), changing only one letter at a time. We are given a Scrabble word list to use in finding our path. For example: ``` cat -> bat -> bet -> bot -> bog -> dog ``` I've solved the problem using a breadth first search, but am seeking something better (I represented the dictionary with a trie). Please give me some ideas for a more efficient method (in terms of speed and memory). Something ridiculous and/or challenging is preferred. I asked one of my friends (he's a junior) and he said that there is *no* efficient solution to this problem. He said I would learn why when I took the algorithms course. Any comments on that? We must move from word to word. We cannot go `cat -> dat -> dag -> dog`. We also have to print out the traversal.
2009/10/05
[ "https://Stackoverflow.com/questions/1521958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127139/" ]
**NEW ANSWER** Given the recent update, you could try A\* with the Hamming distance as a heuristic. It's an admissible heuristic since it's not going to overestimate the distance **OLD ANSWER** You can modify the dynamic-program used to compute the [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) to obtain the sequence of operations. EDIT: If there are a constant number of strings, the problem is solvable in polynomial time. Else, it's NP-hard (it's all there in wikipedia) .. assuming your friend is talking about the problem being NP-hard. EDIT: If your strings are of equal length, you can use [Hamming distance](http://en.wikipedia.org/wiki/Hamming_distance).
24,878,847
I am trying to learn indexing in Mongodb. I created a database and a collection as follows: ``` use mydb db.createCollection("myFirstCollection") one={name:"Helios"} two={name:"Kepler"} db.myFirstCollection.insert(one) db.myFirstCollection.insert(two) ``` I was able to list out my results as follows: ``` db.myFirstCollection.find() { "_id" : ObjectId("53cde256f8807057b6bd827b"), "name" : "Helios" } { "_id" : ObjectId("53cde25bf8807057b6bd827c"), "name" : "kepler" } ``` I want to add unique index on the field `name`. But when I tried, got the following error ``` db.myFirstCollection.ensureIndex({name:1},{unique:true}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "ok" : 0, "errmsg" : "E11000 duplicate key error index: mydb.myFirstCollection.$name_1 dup key: { : null }", "code" : 11000 } ``` I am unable to figure out the mistake what I am making. Please help.
2014/07/22
[ "https://Stackoverflow.com/questions/24878847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1254255/" ]
This should work. ``` void triangle(int m, int n) { // Prevent stack overflow if ( m > n ) { return; } // Draw m symbols. drawline('*', m); // If m and n are not equal, recurse. if ( m != n ) { triangle(m+1,n); drawline('*', m); } } ```
10,604,544
I'm having trouble with a regular expression. I'm trying to use preg\_match on a query string. I want it to exclude any sequence of *drop* or *truncate* regardless of the case (?i) that is between *'* or *`* and has any number of characters between the sequence and the two signs, but I want to catch any of those two words that is NOT between the two signs. If you haven't guessed it yet, I want to detect whether or not an input is trying to DROP | TRUNCATE anything, but there is no easy way of doing that without excluding those words from non malicious input. e.g. I want this not to trigger: ``` SELECT * FROM `drop` SELECT * FROM 'drop_truncate' -- drop drop ``` but this to trigger: ``` DROP TABLE `users` ``` EDIT: So my question was about regular expressions and I received answers on database security, no doubt there was something about the question that made you think that, sorry for misleading! No, I don't care about database security here for that I already handled, all I wanted here was to check for any INTENT of using either drop or truncate and log it somewhere. *sigh*
2012/05/15
[ "https://Stackoverflow.com/questions/10604544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/777525/" ]
You're handling the security of your database entirely in the wrong manner. This statement here *but there is no easy way of doing that* is false. You are just looking to 'secure' this input in an extreamly narrow mindset of tunnel vision. **Do NOT allow users to mangle your query by inputting user defined SQL!!** Please research [prepared statements](https://stackoverflow.com/questions/1457131/php-pdo-prepared-statements) at the utter least. [PHP.net](http://www.php.net/manual/en/intro.pdo.php) has a great starter on explaining its PDO library. Though I highly \*\*highly\* advise against `"use preg_match to prevent malicious query intent"`, see [AD7six](https://stackoverflow.com/questions/10604544/how-do-you-use-regex-to-scan-a-query-from-commands-like-drop-truncate-etc/10604729#10604729)'s answer if you really think that is your best course of action. (HINT: Its not).
35,319
Not sure if this is question for this part of SE. Anyway, how would you sound proof a door that is made just with wood frame and a sheet of glass 5 milimeters thick? I got to some ideas like Egg crates but that is too tall to fit properly in the space available. I could cut it but it would look ugly. Another idea I got is bottle caps, but that way I have to buy lot of bottles to cover the whole area. Here are some images I made of my door. The glass is covered with wood-lookalike duck-tape. ![glass door 1](https://i.stack.imgur.com/phVLm.jpg) ![glass door 2](https://i.stack.imgur.com/96DlQ.jpg) As you can see from the second image the frame has space which is 2-2.5 centimeters deep.The Egg crate is about 6 centimeters tall. Any ideas are welcome. I got inspiration by NASA soundless room: ![NASA soundless room](https://i.stack.imgur.com/JdrmA.jpg)
2015/06/04
[ "https://sound.stackexchange.com/questions/35319", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/7607/" ]
The only way to soundproof anything is **mass**. You need weight. Nothing else will work for bass frequencies. No amount of egg boxes will have any effect. Assuming you actually still need access to the door & that rebuilding the entire thing triple-glazed is right out of the question, then the only thing I can think of might be lots of heavy blankets, floor to ceiling. It's either that or a half ton of concrete ;-)
10,211,050
I have a code as bellow where I try to insert a data into a table and return the ID (given by auto increment) of the new element. ``` int newEquipmentID = new int(); query = database.ParameterizedQueryString("INSERT INTO Equipment (EquipmentTypeID) VALUES ({0})", "equipmenttypeID"); newEquipmentID = (int)database.Connection.ExecuteScalar(query, DefaultTimeout, equipment.EquipmentTypeID); ``` But it fails and returns null, as if the new item wasn't added yet. But actually I can see the new item making a simple consult at the DB. My question is "when" the data is actually added into the DB and how can I get the ID of the new added item. Thanks!
2012/04/18
[ "https://Stackoverflow.com/questions/10211050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1237911/" ]
You don't need two queries to create the new record and retrieve the new identity value: ``` using (var con = new SqlConnection(ConnectionString)) { int newID; var cmd = "INSERT INTO foo (column_name)VALUES (@Value);SELECT CAST(scope_identity() AS int)"; using (var insertCommand = new SqlCommand(cmd, con)) { insertCommand.Parameters.AddWithValue("@Value", "bar"); con.Open(); newID = (int)insertCommand.ExecuteScalar(); } } ``` Side-Note: I wouldn't use such a Database-Class since [it's prone to errors](https://stackoverflow.com/questions/9705637/executereader-requires-an-open-and-available-connection-the-connections-curren/9707060#9707060).
23,191,493
When we press the button home twice, it will shows all app that running in background on screen. Is there a way to get all these screenshot within app (with objective-c codes) ?
2014/04/21
[ "https://Stackoverflow.com/questions/23191493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1142944/" ]
The short answer is **NO**. ***Why?*** Apple always maintain its own security. Apple never allow to access anything that could cause problem to any other app. Also apple don't allow to access its private API's.
19,521,497
I want to convert this google map url "http//maps.google.com/maps?f=q&q=14.674518%2C120.549043&z=16" to just value of latitude and longitude. Here's my code: ``` $string='http://maps.google.com/maps?f=q&q=14.674518%2C120.549043&z=16'; $regex=' , http://maps\.google\.com/maps\?q=\K[^&]+,'; preg_match($regex,$string,$m); echo $m[0].'<br />'; ``` Thanks!
2013/10/22
[ "https://Stackoverflow.com/questions/19521497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2906094/" ]
There are nice URL-functions(`parse_url()` and `parse_str()`) available in PHP: ``` <?php $query = array(); //parse the url to get the QUERY_STRING $urlParts = parse_url('http://maps.google.com/maps?f=q&q=14.674518%2C120.549043&z=16'); //parse the QUERY_STRING to get the variables parse_str($urlParts['query'], $query); echo $query['q']; //returns 14.674518,120.549043 ?> ```
10,069,373
I am trying to animate some text by alternating the color of every other char. My code is working as far as styling it one way, but `setTimeout` is not calling it again to alternate the text color. The problem seems to be my use of a global variable as a counter, which may be a simple problem that I am overlooking. Any ideas? Here is my javascript code: ``` var num = 0; function animateText(){ var str = ""; var title = document.getElementById("title").innerHTML; for(var i = 0; i < title.length; i++){ if(num % 2 == 0){ if(i % 2 == 0){ str += '<span style = "color: silver;">' + title.charAt(i) + '</span>'; } else { str += title.charAt(i) + ""; } } else { if(i % 2 != 0) { str += '<span style = "color: silver;">' + title.charAt(i) + '</span>'; } else { str += title.charAt(i) = ""; } } } document.getElementById("title").innerHTML = str; num++; if(num == 10) num = 0; setTimeout("animateText()", 500); } ```
2012/04/09
[ "https://Stackoverflow.com/questions/10069373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1298685/" ]
Aside from the typo that Jonathan points out, your logic seems flawed. The first time through the function, you get the initial string and build some HTML with various `<span>` tags in it. The next time through the function, you get the innerHTML from the DOM element and start processing it again as if it was just your string, but this time it's the previous HTML with all the tags in it - it's not the string you started with. You will need to save the original string somewhere unmodified so you can start with just the text string each time through the function rather than build on the previous formatted HTML each time.
22,072,826
I have a registeration form with the if statement: ``` $query = "SELECT `username` FROM `users` WHERE `username`='$username'"; $query_run = mysql_query($query); if (mysql_num_rows($query_run)==1) { echo "Username already exist."; } ``` The thing i want to do is checking also the "email" and "nickname" if they exist in database. How can i do that?
2014/02/27
[ "https://Stackoverflow.com/questions/22072826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263836/" ]
Try this, ``` SELECT `username`, `email`, `nickname` FROM `users` WHERE (`username` = '$username' OR `email` = '$username' OR `nickname` = '$username' ) ```
3,335
This question started out on the Pro Webmasters SE. See: <https://webmasters.stackexchange.com/q/8578/1847> I am a web developer. My designer gave me a mock-up of a web form. In it, there are several long winded yes or no questions. Some of which include background information. Here is an example of how it was mocked up: > > Some long winded yes or no question?   ◉ Yes   ○ No > > > As a web developer my intuition tells me that the *right* way to do a "yes or no" question is with a checkbox and turn the "question" into a statement: > > The positive answer to the long winded question ☒ > > > I'm not asking you to tell me how to mark either way up in HTML. I'm interested in if there are "industry" best practices on how *yes* or *no* questions should be displayed. Please share any original research, or references to best practices on this matter if you know of any. I have thus far been unable to locate any papers or resources through the usual channels. *(read "Google")* **UPDATE**: I'd like to clarify that this is *not* an opt-in/out. This is an answer to a question which is completely unrelated to any marketing effort.
2011/02/03
[ "https://ux.stackexchange.com/questions/3335", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/3493/" ]
I'd go for the radio buttons. The checkbox is too easily ignored, so a lot of people might answer "no" when they really meant "what, I have to read through all this?" But instead of just offering "Yes" and "No", use longer labels, e.g. ( ) Yes, I want to become a member of the eat-all-you-can-club right now. ( ) No, I don't want to become a member.
7,365,754
i have two separate questions; however, since they are very similar i will ask them in one posting. what is the reason i cannot reference the textboxes from here? i created another file in my project and put ``` namespace EnterData.DataEntry { public partial class WebForm1 : System.Web.UI.Page { ``` to make it go into the same namespace and partial class as the webform. but i cannot access the textbox! ``` public partial class WebForm1 : System.Web.UI.Page { public class LOMDLL.Main_Lom_Form PopulateMainForm() { //populate class LOMDLL.Main_Lom_Form TheForm = new LOMDLL.Main_Lom_Form(); try { TheForm.lom_number = lom_numberTextBox.Text.ToInt(); TheForm.identified_by = identified_byTextBox.Text; TheForm.occurrence_date = occurrence_dateTextBox.Text.ToDateTime(); //TheForm.pre_contact = pre_contactTextBox.Text; //need to create this texdtbox //TheForm.pre_practice_code = pre_practice_codeTextBox.Text; //create this TheForm.report_by = report_byTextBox.Text; TheForm.report_date = report_dateTextBox.Text.ToDateTime(); TheForm.section_c_comments = section_c_commentsTextBox.Text; TheForm.section_c_issue_error_identified_by = section_c_issue_error_identified_byTextBox.Text; TheForm.section_d_investigation = section_d_investigationTextBox.Text; TheForm.section_e_corrective_action = section_e_corrective_actionTextBox.Text; TheForm.section_f_comments = section_f_commentsTextBox.Text; } catch (Exception e) { } ``` i get this error: Erro`r 20 Cannot access a non-static member of outer type 'EnterData.DataEntry.WebForm1' via nested type 'EnterData.DataEntry.WebForm1.LOMDLL' C:\Documents and Settings\agordon\My Documents\Visual Studio 2008\Projects\lomdb\EnterData\DataEntry\DAL.cs 68 38 EnterData` on all textboxes what is the reason that i cannot access the textboxes from here?
2011/09/09
[ "https://Stackoverflow.com/questions/7365754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117700/" ]
Create a db table to hold the facebook likes (URL, Likes, Timestamp). Upon page load, if Timestamp > now + a certain amount of time, refresh the Likes in the table. The data could be slightly out of date, but if you had a refresh time of 5-10 minutes, I would think it would be pretty close most of the time.
18,255,458
I am making an app that uses sound effects. I would like to know how i can detect when a sound has finished playing and trigger an event . i tried this : ``` player = new MediaPlayer(); if (player != null) { player.reset(); player.release(); } player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { sonar.setBackgroundResource(R.drawable.sonar_off); stopPlay(); } }); if(state==1){ player = MediaPlayer.create(this, R.raw.sonar_slow); }else if(state==2){ player = MediaPlayer.create(this, R.raw.sonar_medium); }else if(state==3){ player = MediaPlayer.create(this, R.raw.sonar_fast); } try{ player.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } player.start(); ```
2013/08/15
[ "https://Stackoverflow.com/questions/18255458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2363425/" ]
You can set an OnCompleteListener() to the player object. The code for it is: ``` mPlayer.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { "your code comes here" } }); ``` Here the mPlayer is the object of the MediaPlayer which is currently running.
6,672,121
I'm using rails 3 and this is how I've set up my link\_to in my view ``` <%= link_to ('add', :url => {:controller => 'favourite_companies', :action =>'create', :company_id=>@company.id, :company_name=>@company.company_name, :remote => true}) %> ``` When I click it, the page refreshes and nothing happens. I've added <%= csrf\_meta\_tag %> and all javascript files. In the controller, the function looks like this: ``` def create @favorite_list = FavouriteCompany.new(:user_id=>curr_user.id,:company_id=>params[:company_id]) @favorite_list.save render :partial => "create" ``` end Any idea what might be wrong? Thanks.
2011/07/12
[ "https://Stackoverflow.com/questions/6672121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509014/" ]
Have you looked at the HTML that is being output via your browsers dev tools (ie firebug, etc)? I believe you have the `:remote => true` in the wrong hash. Try: ``` <%= link_to ('add', {:url => {:controller => 'favourite_companies', :action =>'create', :company_id=>@company.id, :company_name=>@company.company_name}}, :remote => true) %> ``` Is there a reason you aren't using Rails Routes and generating the link via the standard Rails process like: ``` <%= link_to 'add', favourite_companies_path(@company), :remote => true %> ```
148,964
I have an ASP .NET 2.0 website connected to a SQL Server 2005 database. The site is pretty simple and stores information about staff, including salary. What is the best way to encrypt the salary value so no-one (including myself) can ever see what it is, except for the authorised staff using the web-app? I don't want to encrypt / decrypt on the SQL Server because I could just run SQL Profiler to view the information, so I assume the encrypt/decrypt happens in the BLL on the web server? Also, do I need SSL to stop someone sniffing HTTP responses between the browser and the web server? Many thanks! Anthony
2008/09/29
[ "https://Stackoverflow.com/questions/148964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23465/" ]
SSL is probably your best bet to keep someone from sniffing, but be aware that it is still possible. As for the other bit, SQL Server 2005 supports table-level encryption out of the box. [Here's an article on it](http://blogs.technet.com/keithcombs/archive/2005/11/24/sql-server-2005-data-encryption.aspx). You could create a SALARY table that is linked to an employee and keep that table encrypted.
54,667,841
i have a model that includes a key "service\_id" and the values stored in database are like "10001", i want to add a method to admin page that instead of displaying the id it displays a custom value like "Car Wash".
2019/02/13
[ "https://Stackoverflow.com/questions/54667841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11055657/" ]
I think you need to create a [custom field](https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display) to be added in your `list_display` ``` from django.contrib import admin @admin.register(MyModelClass) class MyModelClassAdmin(admin.ModelAdmin): list_display = ('my_field') def my_field(self, obj): return obj.description().title() my_field.short_description = "My field" ``` You can change the value returned by the `my_field` method as you prefer (take into consideration that you can use the `obj` instance).
21,993,462
Can anyone please help me with a Do while Not loop. I'm very new to programming: I need to check and print a list, and limit it to 5 names. ``` Do While Not rsP.EOF And iCount > 5 sLT = sLT & rsP![Name] & vbNewLine iCount = iCount + 1 rsP.MoveNext Loop If rsP.RecordCount > 5 Then sLT = sLT & "..." End If ``` right now it will not print the list, if I take out iCount > 5, it shows, but I need to limit it to only 5 names maximum to show? What should I change the iCount to? Thanks
2014/02/24
[ "https://Stackoverflow.com/questions/21993462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347312/" ]
Assuming `iCount` is zero outside the loop: `iCount > 5` is initially false so the loop does not run. Simply change to: ``` Do While Not rsP.EOF And iCount < 5 ```
28,997,133
I am trying to use a piped CustomLog to filter my logs: **httpd.conf**: ``` CustomLog "|/bin/sed -r s/pass/REDACTED/g >> /workplace/tmp/access.log" common ``` However, when I make a request to Apache, I get an error saying ``` /bin/sed: can't read >>: No such file or directory ``` What am I doing wrong here? (It seems [others have been able to use piped CustomLog like this](https://stackoverflow.com/questions/9467405/is-it-possible-to-exclude-specified-get-parameters-in-apache-access-logs))
2015/03/11
[ "https://Stackoverflow.com/questions/28997133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2288585/" ]
I just solved this and thought I should put an update here even though this thread is old. First, the poster above who suggested that the input file was missing is not correct. There is no input file. Apache is sending the logging messages to sed through a pipe, not through a file. The trick here is to tell apache to launch a shell for the sed command. Without launching a shell, the ">>" has no special meaning and is treated like a filename. To tell apache to launch a shell for the sed, you append a "$" after the pipe symbol like this: ``` CustomLog "|$/bin/sed s/'creditCardPAN=[^ ]*'/'creditCardPAN=REDACTED'/ >>logs/ssl_access_log" PaymentLogFormat ```
14,669,614
I have been on this for hours, attempting different methods looking at just about every question. Perhaps I have it completely wrong, but I feel that I have my math of it correct, but no matter what numbers I input, I get the same output. My code is off somewhere and I have to turn it in by midnight. It is the all so fun: Find if a point is within a triangle code. (for beginners) ``` import java.util.Scanner; public class PointsTriangle { // checks if point entered is within the triangle //given points of triangle are (0,0) (0,100) (200,0) public static void main (String [] args) { //obtain point (x,y) from user System.out.print("Enter a point's x- and y-coordinates: "); Scanner input = new Scanner(System.in); double x = input.nextDouble(); double y = input.nextDouble(); //find area of triangle with given points double ABC = ((0*(100-0 )+0*(0 -0)+200*(0-100))/2.0); double PAB = ((x*(0 -100)+0*(100-y)+0 *(y- 0))/2.0); double PBC = ((x*(100-0 )+0*(0 -y)+200*(y-100))/2.0); double PAC = ((x*(0 -100)+0*(100-y)+200*(y- 0))/2.0); boolean isInTriangle = PAB + PBC + PAC == ABC; if (isInTriangle) System.out.println("The point is in the triangle"); else System.out.println("The point is not in the triangle"); }//end main }//end PointsTriangle ```
2013/02/03
[ "https://Stackoverflow.com/questions/14669614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2019997/" ]
If you draw a picture, you can see the point has to satisfy simple inequalities (below / above / to the right of certain lines). Whether "on the edge" is in or out I will leave up to you: ``` Y > 0 (above the X axis) X > 0 (to the right of the Y axis) X + 2* Y < 200 (below the hypotenuse) ``` Write an if statement around these three and you're done: ``` if( (y > 0) && (x > 0) && (x + 2*y < 200) ) System.out.println("The point is in the triangle"); else System.out.println("The point is not in the triangle"); ```
40,039,533
Prologue -------- I want to create a `pre-receive hook` from my `pre-push hook`. Now, looking around the 'net and the SO, I have found many questions pertaining to specific problems, and/or focusing on a description of the hook, instead of actually showing it (I'm looking at you, git-scm). The point --------- So anyway, as far as I have gathered, `pre-receive hook` is called with **no parameters**. How do I get data then? There is very much data that I would see myself wanting to get a hold of in such hook, for example: * *pushername (pardon the pun)* * *commit message* * *timestamp* * *changed files* * *target branch* but I honestly have no idea how to get the data - and I know that people do it, because I have seen such scripts in action. Assumptions ----------- I would like to assume that it's `bash`-doable, because the less configuration the better, amirite? Actual question --------------- ### Coding a pre-receive hook, how to gather data about the push that triggered it?
2016/10/14
[ "https://Stackoverflow.com/questions/40039533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2192137/" ]
What you are really asking for is `first-of-class` which, as yet, does not exist. You can target, however, the first element with a class that immediately follows one that does NOT have that class with the `:not()` seelctor and the immediate sibling selector. As follows: ```css a { margin-right: 50px; } .float-right { float: right; } *:not(.float-right) + .float-right { margin-right: 0; } ``` ```html <a href="">LOGO</a> <a href="" class="float-right">Login | Register</a> ``` This is not ideal as it's not really extendable to a large degree but it does offer a solution to your specific request.
49,148,308
I have a query which returns a huge set of data (json). This takes far to long to present the grid to the user. So what I want to do is fire the initial query with a filter (say the records of the current year) and let the grid be build. The grid is presented to the user and he can start working. Meanwhile I fire a second query (in the background) to get all the other records (everything except the current year). Now I want to add those records to the already existing grid. Without the user noticing. Is this possible? I think JSgrid and JQgrid behave the same but I use JSGrid Thanks, Mike
2018/03/07
[ "https://Stackoverflow.com/questions/49148308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8771201/" ]
Client Libraries use Application Default Credentials to authenticate Google APIs. So when you don't explicitly use a specific Service Account via `GOOGLE_APPLICATION_CREDENTIALS` the library will use the Default Credentials. You can find more details on this [documentation](https://cloud.google.com/docs/authentication/production#howtheywork). Based on your sample, I'd assume the Application Default Credentials were used for fetching those files. Lastly, you could always run `echo $GOOGLE_APPLICATION_CREDENTIALS` (Or applicable to your OS) to confirm if you've pointed a service account's path to the variable.
9,064,263
I have rather stupidly published a game on the android market with a package name of mick.game.tangletwister, whereas I should have called it com.rai.tangletwister (where rai is the name of my company)... it all seems to work fine - but could it cause some trouble in the future - should I change it? And if I do change it, will it cause problems for existing users that grab the updated version?
2012/01/30
[ "https://Stackoverflow.com/questions/9064263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169774/" ]
It will be fine if you keep the existing package name. Nothing wrong with that. The TLD.company.appname format is just a convention. As long as you don't enter some special characters in your packagename (which you did not), it will work anyway. But if you try to change it you will run into trouble. See [Things That Cannot Change](http://android-developers.blogspot.com/2011/06/things-that-cannot-change.html).
30,136,539
when Run my app it gives java.lang.NoClassDefFoundError: com.parse.Parse i tried several times changed min sdk level but still gives the error. please if anyone ever solved it,please help me
2015/05/09
[ "https://Stackoverflow.com/questions/30136539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3578677/" ]
Regarding the file part, you can save the data in browser localStorage instead of writing it into a file to save something: ``` localStorage.setItem("param1",param1Value); ``` to get it (after loading the page again, on load): ``` var param1Value = localStorage.getItem("param1"); ``` regard the add task, I've added [fiddle example](http://jsfiddle.net/8fcya6t6/) but it uses jQuery (which is very recommended for your tasks..) hope that's help ``` <div><button id="addTaskButton" class="btn">Add Task</button></div> $("#addTaskButton").click(function (event) { var nextNumber = $(".well").length + 1; $($("hr")[0]).before("<div class='well' style='width:400px;'><input type='button' value='Task " + nextNumber + "' onClick='add()' class='btn btn-danger'> <span class='label label-default'>+50</span></div>"); }); ``` Press 'Add Task' button will add you a new task button..
17,841,646
I want to take a backup of a table in my database for every 2hrs is it possible? I have a backup table in my database which holds the values from a different table I wanted to know whether I can schedule this backup for every two hours I dont need a full database back up i need just a table
2013/07/24
[ "https://Stackoverflow.com/questions/17841646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2540455/" ]
You can move the table into its own filegroup and backup just that filegroup. [This article](http://msdn.microsoft.com/en-us/library/ms179401%28v=sql.105%29.aspx) describes how to back up a single file or filegroup.
5,501,115
I'm looking for a light weight timer to measure timing of few sections of a C code. This timer implementation shouldn't add to the overall program execution time.
2011/03/31
[ "https://Stackoverflow.com/questions/5501115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/685872/" ]
Look at [`clock_gettime`](http://www.kernel.org/doc/man-pages/online/pages/man2/clock_gettime.2.html) for POSIX-compliant platforms; you can do it yourself really easily by comparing one timestamp with one generated a little later. Remember to use the `CLOCK_PROCESS_CPUTIME_ID` or `CLOCK_THREAD_CPUTIME_ID` parameters to specify that you want CPU time taken just by *that process* (and its children) or thread, and not the wider, absolute, "wall" time. An [alternative](https://stackoverflow.com/questions/733530/visual-c-how-to-get-the-cpu-time) on Windows might be [`GetProcessTimes`](http://msdn.microsoft.com/en-us/library/ms683223%28VS.85%29.aspx).