qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
44,179,585
I have installed LAMP in CentOS 7 When I placed my files in the default directory (var/www/html in my case) I receive the following when I access my page: > > Erreur : PB de connexion au serveur mysql de la langue : fr > Erreur : PB de connexion � la base de donn�es de la langue : fr > Erreur SQL : SELECT \* FROM parametres > Access denied for user 'apache'@'localhost' (using password: NO) > > > The following is my config file: ``` $action = "action"; @error_reporting (E_ALL); @setlocale(LC_TIME, 'french'); $host = "localhost"; $user = ""; $password = "" ; //---> La langue utilisée (fr, en, ar) global $lang ; $lang = isset($_REQUEST["lang"])? $_REQUEST["lang"] : ""; switch($lang) { case "ar" : $lang = "ar" ; break; case "en" : $lang = "en" ; break; case "fr" : $lang = "fr" ; break; default : $lang = "fr" ; //---> La langue par défaut } //Fin switch global $lang_param; $lang_param = array ( //---> principal = TRUE "fr" => array( "host" => "localhost" , "db" => "database_fr" , "user" => "user1" , "password" => "" , "chemin" => "fr" , "description" => "Langue française" , "short" => "Fran&ccedil;ais" , ), //---> principal = FALSE "en" => array( "host" => "localhost" , "db" => "database_en" , "user" => "user1" , "password" => "" , "chemin" => "en" , "description" => "Langue anglaise" , "short" => "Anglais" , ) , "ar" => array( "host" => "localhost" , "db" => "database_ar" , "user" => "user1" , "password" => "" , "chemin" => "ar" , "description" => "Langue arabe" , "short" => "Arabe" , ) ); //Fin $lang_param //---> Se connecter $r = @mysql_pconnect($lang_param[$lang]["host"], $lang_param[$lang] ["user"], $lang_param[$lang]["password"]); if ($r==0) { echo "Erreur : PB de connexion au serveur mysql de la langue : $lang<br>"; } //Fsi $r = @mysql_select_db($lang_param[$lang]["db"]); if ($r==0) { echo "Erreur : PB de connexion à la base de données de la langue : $lang<br>"; } //Fsi ``` How can I gain access for apache@localhost?
2017/05/25
[ "https://Stackoverflow.com/questions/44179585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8064758/" ]
It seems using a simple `import 'angular-ui-router'` works.
2,540,530
I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information? Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated.
2010/03/29
[ "https://Stackoverflow.com/questions/2540530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186184/" ]
The approach of getting the country code of the user's locale will work ... but only if the user's iTunes store is the same as their locale. This won't always be the case. If you create an in-app purchase item, you can use Apple's StoreKit APIs to find out the user's actual iTunes country even if it's different from their device locale. Here's some code that worked for me: ``` - (void) requestProductData { SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers: [NSSet setWithObject: PRODUCT_ID]]; request.delegate = self; [request start]; } - (void) productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { NSArray *myProducts = response.products; for (SKProduct* product in myProducts) { NSLocale* storeLocale = product.priceLocale; storeCountry = (NSString*)CFLocaleGetValue((CFLocaleRef)storeLocale, kCFLocaleCountryCode); NSLog(@"Store Country = %@", storeCountry); } [request release]; // If product request didn't work, fallback to user's device locale if (storeCountry == nil) { CFLocaleRef userLocaleRef = CFLocaleCopyCurrent(); storeCountry = (NSString*)CFLocaleGetValue(userLocaleRef, kCFLocaleCountryCode); } // Now we're ready to start creating URLs for the itunes store [super start]; } ```
36,312,509
I wanted to first say this is a really nice plugin (<https://github.com/katzer/cordova-plugin-local-notifications>) but having some difficulties getting it working. I am using an Android and Phonegap CLI. I have tried both CLI 5.0 and now Phonegap 3.5.0, this is my config.xml: `<preference name="phonegap-version" value="3.5.0" />` In my config.xml I have tried all these combinations: ``` <plugin name="de.appplant.cordova.plugin.local-notification" spec="0.8.1" source="pgb" /> <gap:plugin name="de.appplant.cordova.plugin.local-notification" /> <plugin name="de.appplant.cordova.plugin.local-notification" source="pgb" /> ``` However the notifications do not appear - nothing happens on the phone - nothing, nada, zilch. I have also downloaded the KitchenSink App (<https://github.com/katzer/cordova-plugin-local-notifications/tree/example>) and installed on Phonegap build and my phone and nothing again happens.. This is my code on index.html so when the phone fires it should register a local notification asap: ``` cordova.plugins.notification.local.registerPermission(function (granted) { // console.log('Permission has been granted: ' + granted); }); cordova.plugins.notification.local.schedule({ id: 1, title: 'Reminder', text: 'Dont forget to pray today.', every: 'minute', icon: 'res://icon', smallIcon: 'res://ic_popup_sync' }); ``` I also tried ``` cordova.plugins.notification.local.schedule({ id: 2, text: "Good morning!", firstAt: tomorrow_at_8_am, every: "day" // "minute", "hour", "week", "month", "year" }); ``` Even the KitchenSink app is not working - nothing happens on the phone?? My Android version is: 5.1.1 **How can I get local notifications to appear in Phonegap?**
2016/03/30
[ "https://Stackoverflow.com/questions/36312509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/596952/" ]
I too have spent many hours trying to get this plugin working & I have, but i do find it to be one of the most temperamental. Within your js - ``` var testNotifications = function () { document.addEventListener("deviceready", function () { console.warn("testNotifications Started"); // Checks for permission cordova.plugin.notification.local.hasPermission(function (granted) { console.warn("Testing permission"); if( granted == false ) { console.warn("No permission"); // If app doesnt have permission request it cordova.plugin.notification.local.registerPermission(function (granted) { console.warn("Ask for permission"); if( granted == true ) { console.warn("Permission accepted"); // If app is given permission try again testNotifications(); } else { alert("We need permission to show you notifications"); } }); } else { var pathArray = window.location.pathname.split( "/www/" ), secondLevelLocation = window.location.protocol +"//"+ pathArray[0], now = new Date(); console.warn("sending notification"); var isAndroid = false; if ( device.platform === "Android" ) { isAndroid = true; } cordova.plugin.notification.local.schedule({ id: 9, title: "Test notification 9", text: "This is a test notification", sound: isAndroid ? "file://sounds/notification.mp3" : "file://sounds/notification.caf", at: new Date( new Date().getTime() + 10 ) // data: { secret:key } }); } }); }, false); }; ``` Now on your html tag - ``` <button onclick="testNotifications()">Test notification</button> ``` That should trigger a notification or warn you that it needs permissions Also top tip is to make sure your notifications are in a folder in the root of the project. android should be mp3 and ios caf
6,319
Ever since upgrading to Google Maps 5.1.0 on my Droid X, I have often had Google Maps bog down and freeze to the point of completely crashing the phone. Anyone else seeing this crash? Anyone find a solution?
2011/02/23
[ "https://android.stackexchange.com/questions/6319", "https://android.stackexchange.com", "https://android.stackexchange.com/users/3078/" ]
You can usually uninstall updates from the app's page in the market. However, previous updates to Google Maps had similar problems for users that never turned their phones off. Try just restarting your phone.
11,385,214
By default Gson uses fields as a basis for it's serialization. Is there a way to get it to use accessors instead?
2012/07/08
[ "https://Stackoverflow.com/questions/11385214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1089998/" ]
The developers of Gson [say](https://groups.google.com/forum/#!topic/google-gson/4G6Lv9PghUY) that they never felt swayed by the requests to add this feature and they were worried about murkying up the api to add support for this. One way of adding this functionality is by using a TypeAdapter (I apologize for the gnarly code but this demonstrates the principle): ``` import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.google.common.base.CaseFormat; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; public class AccessorBasedTypeAdaptor<T> extends TypeAdapter<T> { private Gson gson; public AccessorBasedTypeAdaptor(Gson gson) { this.gson = gson; } @SuppressWarnings("unchecked") @Override public void write(JsonWriter out, T value) throws IOException { out.beginObject(); for (Method method : value.getClass().getMethods()) { boolean nonBooleanAccessor = method.getName().startsWith("get"); boolean booleanAccessor = method.getName().startsWith("is"); if ((nonBooleanAccessor || booleanAccessor) && !method.getName().equals("getClass") && method.getParameterTypes().length == 0) { try { String name = method.getName().substring(nonBooleanAccessor ? 3 : 2); name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, name); Object returnValue = method.invoke(value); if(returnValue != null) { TypeToken<?> token = TypeToken.get(returnValue.getClass()); TypeAdapter adapter = gson.getAdapter(token); out.name(name); adapter.write(out, returnValue); } } catch (Exception e) { throw new ConfigurationException("problem writing json: ", e); } } } out.endObject(); } @Override public T read(JsonReader in) throws IOException { throw new UnsupportedOperationException("Only supports writes."); } } ``` You can register this as a normal type adapter for a given type or through a TypeAdapterfactory - possibly checking for the presence of a runtime annotation: ``` public class TypeFactory implements TypeAdapterFactory { @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { Class<? super T> t = type.getRawType(); if(t.isAnnotationPresent(UseAccessor.class)) { return (TypeAdapter<T>) new AccessorBasedTypeAdaptor(gson); } return null; } ``` This can be specified as normal when creating your gson instance: ``` new GsonBuilder().registerTypeAdapterFactory(new TypeFactory()).create(); ```
21,006,390
I need to consume the services of a number of third party systems on my applications homepage. The data pertaining to these downstream systems are updated at different intervals and ideally my system will surface the latest data. It's not a scalable solution for my system to generate requests to each of these downstream systems each time a user hits my homepage. What strategy can i use to ensure the data i surface is current without effecting the reliability of these downstream systems? Is a consumer/producer strategy most suitable for this requirement?
2014/01/08
[ "https://Stackoverflow.com/questions/21006390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24481/" ]
Have the method accept an expression, just as the method you're passing it to does: ``` public class Foo { public void UpdateEmployeeOrders(IEnumerable<Employee> employees, Expression<Func<Employee, object>> selector) { foreach (var employee in employees) { UpdateSpecificEmployeeOrder(employee.id, selector); } } } ``` Also, since the only thing we ever do with `employees` is iterate over it, we can type the parameter as `IEnumerable` instead of `ICollection`. It provides all of the guarantees that this methods needs, while allowing a broader range of possible input types.
60,362
I'm coming from an understanding of the continuous-time Fourier Transform, and the effects of doing a DFT and the inverse DFT are mysterious to me. I have created a noiseless signal as: ``` import numpy as np def f(x): return x*(x-0.8)*(x+1) X = np.linspace(-1,1,50) y = f(X) ``` Now, if I were to perform a *continuous* Fourier transform on the function $f$ given above, restricted to $[-1,1]$, I would expect the sum of the first few Fourier basis components to give a reasonable approximation to the function $f$ (this is an observation specific to our $f$, since it is approximately sine-wavey over $[-1,1]$). The discrete Fourier transform is an approximation to the continuous one, so assuming that my points `y` are sampled noiselessly from $f$ (which they are by design), then the DFT coefficients should approximate the CFT coefficients (I think). So, I obtain a DFT like so ([formulae employed](https://docs.scipy.org/doc/numpy/reference/routines.fft.html#implementation-details)): ``` def DFT(y): # the various frequencies terms = np.tile(np.arange(y.shape[0]), (y.shape[0],1)) # the various frequencies cross the equi-spaced "X" values terms = np.einsum('i,ij->ij',np.arange(y.shape[0]),terms) # the "inside" of the sum in the DFT formula terms = y * np.exp(-1j*2*np.pi*terms/y.shape[0]) # sum up over all points in y return np.sum(terms, axis=1) def iDFT_componentwise(fy, X): # this function returns the various basis function components of y, sampled at X # so the result is a len(X) x len(fy) matrix with each: # row corresponding to a point in X and each # column corresponding to a particular frequency. terms = np.tile(np.arange(len(fy)), (X.shape[0],1)) terms = fy * np.exp(1j*2*np.pi*np.einsum('i,ij->ij',np.arange(X.shape[0])*fy.shape[0]/X.shape[0],terms)/fy.shape[0]) return terms/fy.shape[0] def iDFT(fy,X): # summing the Fourier components over all frequencies gives back the original function return np.sum(iDFT_componentwise(fy,X), axis=1) ``` I am interested in inspecting the various basis functions that comprise my signal, so I oversample the domain to get a better-resolved picture: ``` oversampled_X = np.linspace(-1,1,100) ``` and proceed to check out my components: ``` fy = DFT(y) y_f_components = iDFT_componentwise(fy, oversampled_X) ``` The positive-frequency components look as expected. ``` import matplotlib.pyplot as plt plt.plot(oversampled_X, y_f_components[:,1],c='r') plt.plot(X,y) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/KUvMW.png)](https://i.stack.imgur.com/KUvMW.png) However, the *negative* frequency components look all weird: ``` plt.plot(oversampled_X, y_f_components[:,49],c='r') plt.plot(X,y) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/Wfmfy.png)](https://i.stack.imgur.com/Wfmfy.png) This last image looks like it has problems with [aliasing](https://en.wikipedia.org/wiki/Aliasing). This, in turn, causes problems when I try to reconstitute the function from the Fourier components (see image below) ``` plt.plot(oversampled_X, iDFT(fy,oversampled_X),c='r') plt.plot(X,y) plt.show() ``` This problem does not occur when I truncate the continuous time Fourier transform of the function to include the same number of terms (see image below): ``` import sympy from sympy import fourier_series from sympy.abc import x from sympy.utilities.lambdify import lambdify f = x*(x-0.8)*(x+1) fourier_f = fourier_series(f, (x, -1, 1)) lambda_fourier_f = lambdify(x,fourier_f.truncate(25),'numpy') reconstructed_y = lambda_fourier_f(oversampled_X) plt.plot(oversampled_X,reconstructed_y,c='r') plt.plot(X,y) ``` tl;dr ===== My oversampled inverse Discrete Fourier Transform has a terrible aliasing problem as illustrated here: The oversampled inverse Discrete Transform: [![enter image description here](https://i.stack.imgur.com/QaFCR.png)](https://i.stack.imgur.com/QaFCR.png) As opposed to the oversampled inverse Continuous Transform (trucated to the number of terms in the discrete version). [![enter image description here](https://i.stack.imgur.com/FWgVz.png)](https://i.stack.imgur.com/FWgVz.png) What is the intrinsic property of the DFT that causes this? If the DFT coefficients approximate the CFT coefficients, then why doesn't the CFT have this problem? Update: The spectrum ==================== As requested, here is the spectrum of $f$. Note that since $f$ is real, the discrete spectrum (excepting the constant term) is symmetric about n/2. I have not attempted to fix the units. [![enter image description here](https://i.stack.imgur.com/H5jcz.png)](https://i.stack.imgur.com/H5jcz.png) Update2: Extending the function =============================== Per @robertbristow-johnsons suggestion, I decided to check out a slightly different function: $x(x-1)(x+1)$ on $[-1,1]$ (so that the "ends" agree) and I have "repeated" the data a number of times end-to-end. The thought was that this would alleviate some of the weird effects. However, the exact same features appear. (one may wish to open this figure by itself in a new window to enable zooming) [![enter image description here](https://i.stack.imgur.com/x4LHX.png)](https://i.stack.imgur.com/x4LHX.png)
2019/08/26
[ "https://dsp.stackexchange.com/questions/60362", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/33763/" ]
Let me summarize my understanding of what you're trying to do. You have a real-valued sequence $x[n]$, obtained by sampling a real-valued continuous function, and you computed its DFT $X[k]$. The sequence can be expressed in terms of its DFT coefficients: $$x[n]=\frac{1}{N}\sum\_{k=0}^{N-1}X[k]e^{j2\pi nk/N},\qquad n\in[0,N-1]\tag{1}$$ where $N$ is the length of the sequence. Now you want to interpolate that sequence, and I believe you're trying to do this in the following way: $$\tilde{x}[m]=\frac{1}{N}\sum\_{k=0}^{N-1}X[k]e^{j2\pi mk/M},\qquad m\in[0,M-1],\quad M>N\tag{2}$$ This, however, doesn't work. If $M$ happens to be an integer multiple of $N$, then $\tilde{x}[nM/N]=x[n]$ is satisfied, but the other values of $\tilde{x}[m]$ are by no means interpolated values of $x[n]$. Note that these values are not even real-valued. What you *can* do is approximately compute the Fourier coefficients of the original continuous function using the (length $N$) DFT of the sampled function, and then approximately reconstruct samples of the function on a dense grid (of length $M>N$): $$\tilde{x}[m]=\frac{1}{N}\sum\_{k=-K}^KX[k]e^{j2\pi mk/M},\qquad m\in[0,M-1]\tag{3}$$ Note that in $(3)$ the summation indices are symmetric, and the number $K$ cannot exceed $N/2$ because that's the number of independent DFT coefficients you have due to conjugate symmetry of $X[k]$ (because $x[n]$ is assumed to be real-valued). Eq. $(3)$ is just equivalent to zero-padding in the frequency domain, which corresponds to interpolation in the time domain. Note, however, that the zero padding is done in such a way that conjugate symmetry is retained, i.e., the zeros are inserted around the Nyquist frequency, and not simply appended to the DFT coefficients. With $X[-k]=X[N-k]$ and $X[k]=X^\*[N-k]$, Eq. $(3)$ can be rewritten as $$\begin{align}\tilde{x}[m]&=\frac{1}{N}X[0]+\frac{1}{N}\sum\_{k=1}^K\left(X[k]e^{j2\pi mk/M}+X[-k]e^{-j2\pi mk/M}\right)\\&=\frac{1}{N}X[0]+\frac{1}{N}\sum\_{k=1}^K\left(X[k]e^{j2\pi mk/M}+X^\*[k]e^{-j2\pi mk/M}\right)\\&=\frac{1}{N}X[0]+\frac{2}{N}\textrm{Re}\left\{\sum\_{k=1}^KX[k]e^{j2\pi mk/M}\right\},\qquad m\in[0,M-1]\end{align}\tag{4}$$ The following Matlab/Octave code illustrates the above: ``` N = 100; t = linspace (-1,1,N); M = 200; ti = linspace (-1,1,M); x = t .* (t - 0.8) .* (t + 1); x = x(:); X = fft(x); X = X(:); Nc = 20; % # Fourier coefficients (must not exceed N/2) x2 = X(1) + 2*real( exp( 1i * 2*pi/M * (0:M-1)' * (1:Nc-1) ) * X(2:Nc) ); x2 = x2 / N; plot(t,x,ti,x2) ``` [![enter image description here](https://i.stack.imgur.com/Ujau8.png)](https://i.stack.imgur.com/Ujau8.png) Note that the approximation of the blue curve by the green curve in the above figure is two-fold: first, there's only a finite number of Fourier coefficients, and second, the Fourier coefficients are only approximately computed from samples of the original function.
7,060
recently I bought 3 solar panels rated at 5V 200 mA each. I want to use them to charge a 5V battery bank to charge a phone. Thinking about the proper way to put them, I thought i can connect all in parallel to get maximum current, but realized that if the sun light was a little weak it will no generate full 5v thus preventing charging. So I decided to put 2 in parallel to give the equivalent of one 5V solar panel, connected in series with the 3rd panel to give the equivalent of 10v. sacrificing a little current to get higher voltage, to allow the charging to happen on a wider range of sun light power. The following picture shows the wiring and the schematic I intend to replicate. [![enter image description here](https://i.stack.imgur.com/4oFHJt.jpg)](https://i.stack.imgur.com/4oFHJ.jpg) [![enter image description here](https://i.stack.imgur.com/lHrv9t.jpg)](https://i.stack.imgur.com/lHrv9.jpg) Now that I have an equivalent of 10v, 400mA solar panel. I used a 7805 voltage regulator to cut down the excess to 5v. [![enter image description here](https://i.stack.imgur.com/IbnN3t.jpg)](https://i.stack.imgur.com/IbnN3.jpg) Final step, I added a standard diode to prevent the panels from leaking the battery in the shade. and now measuring: [![enter image description here](https://i.stack.imgur.com/A0RIwt.jpg)](https://i.stack.imgur.com/A0RIw.jpg) Questions: 1. I didn't think about this before putting the diode, but is it okay to put the blocking diode on the ground wire? because I know some applications do not use the ground except for safety (i.e. 3 phase system). it would be helpful also to avoid the 0.7v drop across the diode before the regulator. 2. according to previous calculations, I'm supposed to get a maximum of 10v output before regulation, and considering that the sun was pretty shinny today, why was the reading I got not more then 6v? I have measured across each panel seperatly and got around 5.5V, are the connections right?
2016/01/23
[ "https://engineering.stackexchange.com/questions/7060", "https://engineering.stackexchange.com", "https://engineering.stackexchange.com/users/1736/" ]
Putting a single panel in series with two other panels that are in parallel does not accomplish what you think it does. The overall current of such a setup is limited by the single panel to 200 mA, so the three panels will not produce any more power than you'd get by just putting two panels in series. A single solar cell can be thought of as a current source in parallel with a silicon diode. The current source is driven by the incoming light. The diode "shorts out" the current source, which is why the voltage across a single cell can never be more than about 0.65 V, the forward drop of a silicon diode. A 5V panel is approximately 10 such cells connected in series. The current through all of the cells will be limited by the cell that is receiving the least amount of light. Also, the blocking diode in your diagram is pointing the wrong way. If your panels are rated at 5V, and your "battery bank" requires 5V to charge, then you don't need to do anything more than put all three panels in parallel and hook them directly to the battery. Forget about blocking diodes.
73,665,822
Currently struggling to add the .is-active class to my header via javascript. If you add "is-active" to the header classes it works well. But I can't seem to work it out in javascript. I just want the class to be added as soon as you start scrolling, and then removed when returning to the top. Appreciate all the help! HTML: ``` <header class="header"> <div class="header-nav flex container"> <figure class="header-logo"> <a href="#"> <img class="header-logo-light" src="images/logoWhite.png" alt="San Miguel Services Logo"> <img class="header-logo-dark" src="images/logoDark.png" alt="San Miguel Services Logo"> </a> </figure> <nav class="header-menu flex"> <div class="header-menu-li"> <a href="">WELCOME</a> <a href="">SERVICES</a> <a href="">ABOUT</a> <a href="">PORTFOLIO</a> <a href="">CONTACT</a> </div> </nav> <div class="header-btn"> <button href="#" class="button header-btn">REQUEST A QUOTE</button> </div> </div> </header> ``` CSS: ``` .header { position: fixed; z-index: 1; width: 100vw; line-height: 18px; } .header .header-logo-dark { opacity: 0; display: none; } .header .header-logo-light { opacity: 1; display: block; } .header.is-active .header-logo-dark { opacity: 1; display: block; } .header.is-active .header-logo-light { opacity: 0; display: none; } .header.is-active .header-menu-li a { color: $darkBlue; &::before { background: linear-gradient(to right, $mediumGreen, $lightGreen); } } .header.is-active .header-btn button { background: $mediumGreen; color: $white; transition: 300ms ease-in-out; &:hover { box-shadow: inset 0 0 0 2px $darkBlue; color: $darkBlue; background: transparent; } } .header.is-active { background: $white; } .header-nav { padding: 20px 5.5%; position: relative; justify-content: space-between; margin: auto; } .header-logo { position: relative; a img { height: 46px; } } .header-menu { align-items: center; } .header-menu-li { a { position: relative; margin: 0 0.625rem; font-weight: 500; font-size: $font-sm; color: $white; transition: color 300ms ease-in-out; &::before { content: ""; display: block; position: absolute; height: 5px; background: $white; left: 0; right: 0; bottom: -33px; opacity: 0; transition: opacity 300ms ease-in-out; } &:hover { opacity: 0.95; &::before { opacity: 1; } } } } .header-btn { height: 46px; font-size: $font-sm; font-weight: 500; button { background: transparent; border: 1px solid $white; transition: 200ms ease-in-out; &:hover { background: $white; color: $darkBlue; } } } ```
2022/09/09
[ "https://Stackoverflow.com/questions/73665822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17472782/" ]
Try this code: ``` window.addEventListener("scroll", function(){ var header = document.querySelector(".header"); header.classList.toggle("is-active", window.scrollY > 0); }) ```
276,351
We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object?
2016/08/25
[ "https://physics.stackexchange.com/questions/276351", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/45820/" ]
Suppose you throw a ball up into the air. You could ask how the ball manages to move upwards when gravity is pulling it down, and the answer is that it started with an upwards velocity. Gravity pulls on the ball and slows it down so it will eventually reach a maximum height and fall back, but the ball manages to move upwards against gravity because of its initial velocity. Basically the same is true of the expansion of the universe. A moment after the Big Bang everything in the universe was expanding away from everything else with an extremely high velocity. In fact if we extrapolate back to time zero those velocities become infinite. In the several billion years following the Big Bang gravity was slowing the expansion, in basically the same way gravity slows the ball you threw upwards, but the gravity didn't stop the expansion - it only slowed it. The obvious next question is how did the universe get to start off expanding with such high velocities, and the answer is that we don't know because we have no theory telling us what happened at the Big Bang. There is a slight complication that I'll mention in case anyone is interested: dark energy acts as a sort of anti-gravity and makes the expansion faster not slower. This has only become an important effect in the last few billion years, but as a result of dark energy right now gravity isn't slowing the expansion at all - in fact it's making the expansion faster.
2,798,089
I would need to get tweets from my twitter account on my wordpress site. Okey, the basics i could do, but there is one special need. I would need to get only certain tweets. Tweets that have some #hashstag for example only tweets with hashtag #myss would show up on my wordpress site. Is there ready made plugin for this? I have been googlein for hours but have found only basic/normal twitter plugins. Also i would need to able style the feed to look same as my current site. Cheers!
2010/05/09
[ "https://Stackoverflow.com/questions/2798089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336676/" ]
The twitter API is pretty good at doing this sort of thing. You could use the Twitter Search API to construct a url like the following: ``` http://search.twitter.com/search.json?q=from:yourusername+AND+#hashtag ``` You could easily write some javascript to parse this. ``` $.getJSON('http://search.twitter.com/search.json?q=from:yourusername+AND+#hashtag&callback=?', function(data){ $.each(data, function(index, item){ $('#twitter').append('<div class="tweet"><p>' + item.text.linkify() + '</p><p>' + relative_time(item.created_at) + '</p></div>'); }); }); ``` You could quite easily package this into a wordpress plugin.
37,156,313
I want to display data from below url to html page: <https://graph.facebook.com/1041049395967347/posts?access_token=616050815226195|bqcTMDgKwdzdDyOeD8uyIKEYZlo> (to display latest post from facebook). Here it the code so far: ``` <!DOCTYPE html> <html> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url = "https://graph.facebook.com/1041049395967347/posts?access_token=616050815226195|bqcTMDgKwdzdDyOeD8uyIKEYZlo"; xmlhttp.open("GET", url, true); xmlhttp.send(); function myFunction(response) { var arr = JSON.parse(response); var i; var out = "<table>"; for(i = 0; i < arr.length; i++) { out += "<tr><td>" + arr[i].story + "</td><td>" + arr[i].story + "</td><td>" + arr[i].created_time + "</td></tr>"; } out += "</table>"; document.getElementById("id01").innerHTML = out; } </script> </body> </html> ``` But I am not getting any results. Can anyone please help if I am missing anything? Thank you
2016/05/11
[ "https://Stackoverflow.com/questions/37156313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3657517/" ]
Try this ```js $.getJSON("https://graph.facebook.com/1041049395967347/posts?access_token=616050815226195|bqcTMDgKwdzdDyOeD8uyIKEYZlo",null,function(result){ var out = "<table>"; for(i = 0; i < result.data.length; i++) { out += "<tr><td>" + result.data[i].story + "</td><td>" + result.data[i].story + "</td><td>" + result.data[i].created_time + "</td></tr>"; } out += "</table>"; $("#divContent").html(out); }) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="divContent"></div> ```
1,241,853
I have written some code to experiment with opengl programming on Ubuntu, its been a little while but I used to have a reasonable understanding of C. Since c++ i'm told is the language of choice for games programming I am trying to develop with it. This is my first real attempt at opengl with sdl and I have gotten to this far, it compiles and runs but my camera function doesn't seem to do anything. I know there is probably a lot better ways to do this sort of stuff but I wanted to get the basics before I moved on to more advanced stuff. main.cpp ``` #include <iostream> #include <cmath> #include "SDL/SDL.h" #include "SDL/SDL_opengl.h" int screen_width = 640; int screen_height = 480; const int screen_bpp = 32; float rotqube = 0.9f; float xpos = 0, ypos = 0, zpos = 0, xrot = 0, yrot = 0, angle=0.0; float lastx, lasty; SDL_Surface *screen = NULL; // create a default sdl_surface to render our opengl to void camera (void) { glRotatef(xrot,1.0,0.0,0.0); // x-axis (left and right) glRotatef(yrot,0.0,1.0,0.0); // y-axis (up and down) glTranslated(-xpos,-ypos,-zpos); // translate the screen to the position SDL_GL_SwapBuffers(); } int DrawCube(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(0.0f, 0.0f,-7.0f); glRotatef(rotqube,0.0f,1.0f,0.0f); glRotatef(rotqube,1.0f,1.0f,1.0f); glBegin(GL_QUADS); glColor3f(0.0f,1.0f,0.0f); glVertex3f( 1.0f, 1.0f,-1.0f); glVertex3f(-1.0f, 1.0f,-1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glColor3f(1.0f,0.5f,0.0f); glVertex3f( 1.0f,-1.0f, 1.0f); glVertex3f(-1.0f,-1.0f, 1.0f); glVertex3f(-1.0f,-1.0f,-1.0f); glVertex3f( 1.0f,-1.0f,-1.0f); glColor3f(1.0f,0.0f,0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glVertex3f(-1.0f,-1.0f, 1.0f); glVertex3f( 1.0f,-1.0f, 1.0f); glColor3f(1.0f,1.0f,0.0f); glVertex3f( 1.0f,-1.0f,-1.0f); glVertex3f(-1.0f,-1.0f,-1.0f); glVertex3f(-1.0f, 1.0f,-1.0f); glVertex3f( 1.0f, 1.0f,-1.0f); glColor3f(0.0f,0.0f,1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glVertex3f(-1.0f, 1.0f,-1.0f); glVertex3f(-1.0f,-1.0f,-1.0f); glVertex3f(-1.0f,-1.0f, 1.0f); glColor3f(1.0f,0.0f,1.0f); glVertex3f( 1.0f, 1.0f,-1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glVertex3f( 1.0f,-1.0f, 1.0f); glVertex3f( 1.0f,-1.0f,-1.0f); glEnd(); SDL_GL_SwapBuffers(); rotqube +=0.9f; return true; } bool init_sdl(void) { if( SDL_Init( SDL_INIT_EVERYTHING ) != 0 ) { return false; } SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // TODO: Add error check to this screen surface init screen = SDL_SetVideoMode( screen_width, screen_height, screen_bpp, SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE ); return true; } static void init_opengl() { float aspect = (float)screen_width / (float)screen_height; glViewport(0, 0, screen_width, screen_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, 0.1, 100.0); glMatrixMode(GL_MODELVIEW); glClearColor(0.0, 0.0 ,0.0, 0); glEnable(GL_DEPTH_TEST); } void heartbeat() { float xrotrad, yrotrad; int diffx, diffy; SDL_Event event; while(1) { while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: exit(0); break; case SDLK_w: yrotrad = (yrot / 180 * 3.141592654f); xrotrad = (xrot / 180 * 3.141592654f); xpos += (float)sin(yrotrad); zpos -= (float)cos(yrotrad); ypos -= (float)sin(xrotrad); std::cout << "w pressed" << std::endl; break; case SDLK_s: yrotrad = (yrot / 180 * 3.141592654f); xrotrad = (xrot / 180 * 3.141592654f); xpos -= (float)sin(yrotrad); zpos += (float)cos(yrotrad); ypos += (float)sin(xrotrad); break; case SDLK_d: yrotrad = (yrot / 180 * 3.141592654f); xpos += (float)cos(yrotrad) * 0.2; zpos += (float)sin(yrotrad) * 0.2; break; case SDLK_a: yrotrad = (yrot / 180 * 3.141592654f); xpos -= (float)cos(yrotrad) * 0.2; zpos -= (float)sin(yrotrad) * 0.2; break; default: break; } break; case SDL_MOUSEMOTION: diffx=event.motion.x-lastx; //check the difference between the current x and the last x position diffy=event.motion.y-lasty; //check the difference between the current y and the last y position lastx=event.motion.x; //set lastx to the current x position lasty=event.motion.y; //set lasty to the current y position xrot += (float)diffy; //set the xrot to xrot with the addition of the difference in the y position yrot += (float)diffx; //set the xrot to yrot with the addition of the difference in the x position break; case SDL_QUIT: exit(0); break; case SDL_VIDEORESIZE: screen = SDL_SetVideoMode( event.resize.w, event.resize.h, screen_bpp, SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE ); screen_width = event.resize.w; screen_height = event.resize.h; init_opengl(); std::cout << "Resized to width: " << event.resize.w << " height: " << event.resize.h << std::endl; break; default: break; } } DrawCube(); camera(); SDL_Delay( 50 ); } } int main(int argc, char* argv[]) { if( init_sdl() != false ) { std::cout << "SDL Init Successful" << std::endl; } init_opengl(); std::cout << "Hello World" << std::endl; heartbeat(); // this is essentially the main loop SDL_Quit(); return 0; } ``` Makefile ``` all: g++ -o test main.cpp -lSDL -lGL -lGLU ``` It compiles and runs, I guess I just need some help with doing the camera translation. Thanks
2009/08/06
[ "https://Stackoverflow.com/questions/1241853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152122/" ]
Remove the glLoadIdentity() call from DrawCube(). Replace it with glPushMatrix() at the beginning and glPopMatrix() at the end. Now pressing 'w' does something. (I am not entirely sure what it is supposed to do.) The problem is glLoadIdentity clears all the previous transformations set up with glTranslatef and the like. Detailed description: <http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushmatrix.html>
4,923,084
I am working in an ISP company. We are developing a speed tester for our customers, but running into some issues with TCP speed testing. One client had a total time duration on 102 seconds transferring 100 MB with a packet size of 8192. 100.000.000 / 8192 = 12.202 packets. If the client sends an ACK every other packet that seems like a lot of time just transmitting the ACKs. Say the client sends 6000 ACKs and the RTT is 15ms - that's 6000 \* 7.5 = 45.000ms = 45 seconds just for the ACKs? If I use this calculation for Mbit/s: ``` (((sizeof_download_in_bytes / durationinseconds) /1000) /1000) * 8 = Mbp/s ``` I will get the result in Mbp/s, but then the higher the TTL is between the sender and the client the lower the Mbp/s speed will become. To simulate that the user is closer to the server, would it be "legal" to remove the ACK response time in the final result on the Mbp/s? This would be like simulating the enduser is close to the server? So I would display this calculation to the end user: ``` (((sizeof_download_in_bytes / (durationinseconds - 45sec)) /1000)/1000) * 8 = Mbp/s ``` Is that valid?
2011/02/07
[ "https://Stackoverflow.com/questions/4923084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527992/" ]
**HTML5 is still a draft**. Firefox 3.6 doesn't completely support HTML5 yet. And according to the [HTML4 spec](http://www.w3.org/TR/REC-html40/struct/global.html#edef-ADDRESS), `address` can only contain `inline` elements: ``` <!ELEMENT ADDRESS - - (%inline;)* -- information on author --> <!ATTLIST ADDRESS %attrs; -- %coreattrs, %i18n, %events -- > ``` This is why Firefox considers it invalid and your page breaks.
29,346,480
I want to implement a logic for creating a three column table using foreach loop. A sample code will look like this. ``` $array = ['0','1','2','3','4','5','6']; $table = '<table class="table"><tbody>'; foreach($array as $a=>$v){ //if 0th or 3rd???????????wht should be here? $table .= '<tr>'; $table .= '<td>$v</td>'; //if 2nd or 5th??????????and here too??? $table .= '</tr>'; } $table = '</tbody></table>'; ``` Any ideas? Expected output is a simple 3X3 table with the values from the array
2015/03/30
[ "https://Stackoverflow.com/questions/29346480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2775597/" ]
This should work for you: (See that I added a `tr` at the start and end before and after the foreach loop. Also I changed the quotes to double quotes and made sure you append the text everywhere.) ``` <?php $array = ['0','1','2','3','4','5','6']; $table = "<table class='table'><tbody><tr>"; //^^^^ See here the start of the first row foreach($array as $a => $v) { $table .= "<td>$v</td>"; //^ ^ double quotes for the variables if(($a+1) % 3 == 0) $table .= "</tr><tr>"; } $table .= "</tr></tbody></table>"; //^ ^^^^^ end the row //| append the text and don't overwrite it at the end echo $table; ?> ``` output: ``` <table class='table'> <tbody> <tr> <td>0</td> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> <td>5</td> </tr> <tr> <td>6</td> </tr> </tbody> </table> ```
70,053,288
I have a **timeseries data** of **5864 ICU Patients** and my dataframe is like this. Each row is the ICU stay of respective patient at a particular hour. | HR | SBP | DBP | ICULOS | Sepsis | P\_ID | | --- | --- | --- | --- | --- | --- | | 92 | 120 | 80 | 1 | 0 | 0 | | 98 | 115 | 85 | 2 | 0 | 0 | | 93 | 125 | 75 | 3 | 1 | 0 | | 95 | 130 | 90 | 4 | 1 | 0 | | 102 | 120 | 80 | 1 | 0 | 1 | | 109 | 115 | 75 | 2 | 0 | 1 | | 94 | 135 | 100 | 3 | 0 | 1 | | 97 | 100 | 70 | 4 | 1 | 1 | | 85 | 120 | 80 | 5 | 1 | 1 | | 88 | 115 | 75 | 6 | 1 | 1 | | 93 | 125 | 85 | 1 | 0 | 2 | | 78 | 130 | 90 | 2 | 0 | 2 | | 115 | 140 | 110 | 3 | 0 | 2 | | 102 | 120 | 80 | 4 | 0 | 2 | | 98 | 140 | 110 | 5 | 1 | 2 | I want to select the ICULOS where Sepsis = 1 (first hour only) based on patient ID. Like in P\_ID = 0, Sepsis = 1 at ICULOS = 3. I did this on a single patient (the dataframe having data of only a single patient) using the code: ``` x = df[df['Sepsis'] == 1]["ICULOS"].values[0] print("ICULOS at which Sepsis Label = 1 is:", x) # Output ICULOS at which Sepsis Label = 1 is: 46 ``` If I want to check it for each P\_ID, I have to do this 5864 times. Can someone help me with the code using a loop? The loop will go to each P\_ID and then give the result of ICULOS where Sepsis = 1. Looking forward for help.
2021/11/21
[ "https://Stackoverflow.com/questions/70053288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I edited my suggestion.. hope I understood better what u looking for.
24,582,319
We have a developer team of 4 and have recently moved to Git. We want to learn best practices regarding workflow with branching and merging. We are using a lightweight version of Git Flow. We have a dev, staging and a master branch which are all linear with each other. * staging is branched from master * dev is branched from staging On top of that we use feature and hotfix branches to work on new features and fix bugs. I have the following questions: 1. Should we branch feature branches from dev or from master? 2. When a feature branch is ready, should we merge the feature branch into dev, then merge dev into staging, or merge the feature branch into staging and then the feature branch into master? I think we should branch from master and merge the feature branch up, because there might be something in dev that we might not want to merge to staging and master. What is your opinion? What are the best practices?
2014/07/05
[ "https://Stackoverflow.com/questions/24582319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053611/" ]
This always depends on how do you want to work and the team agreement. That said. 1. A feature starts from the dev branch into its own branch. From the master branch you should only branch *hotfixes* because the **master branch should always be the stable** version of your software. 2. When a *feature branch* is done, it should be *merged into dev*, then at some point you should branch your next release from dev (including some features) into a *new 'release/\*' branch* which will be merged into master once it is stabilized and well tested. In the [Atlassian page you have a very nice explanation of this workflow](https://www.atlassian.com/git/workflows#!workflow-gitflow "Atlassian") The whole idea with this kind of workflows is to have a stable version branch in which you can work and fix any bug immediately if you need to with enough confidence that it will still be stable and no new feature or refactorization will slip in without noticing. Also to have isolation and freedom for each new feature which will be developed in its own branch with no noise from other features. Then finally you will merge your features into your dev branch and from there into the master branch for the next release. The only thing I would recommend for you is to learn how to rebase your feature branches on top of the dev branch each time another feature is merged into dev to avoid resolving conflicts on merge time, but in isolation on the feature branch where you know what your changes are. [It also looks like this question was asked before](https://stackoverflow.com/questions/15072243/git-with-development-staging-and-production-branches)
18,794,793
How can I compare a single character from a string, and another string (which may or may not be greater than one character) This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string". ``` #include <iostream> #include <string> using std::cout; using std::string; int main() { string str = "MDCXIV"; string test = "D"; if (test == str[4]) { // This line causes the problems cout << test << endl; } return 0; } ```
2013/09/13
[ "https://Stackoverflow.com/questions/18794793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1521753/" ]
`str[4]` is a `char` type, which will not compare with a `string`. Compare apples with apples. Use ``` test[0] == str[4] ``` instead.
30,127
I've pored over the PHBs, the Rules Compendium, and similar questions at this site and other forums and I'm still confused about how magical weapons enhancements/properties interact with character powers and proficiency. Specifically, I've got two circumstances I need advice on. **First case**: An invoker in my group has a +1 Staff of Earthen Might. Since her class is proficient with staffs, I know that any implement power she uses this with will apply the +1 to her attack and damage rolls with such powers. I get that. Am I correct, though, that the +2 proficiency bonus for this staff (as well as the +1d6 critical damage) only applies when she smacks something with the staff as a basic melee attack (which she would qualify for because she is proficient with simple melee weapons)? I want to make sure that these other weapon stats apply to the weapon when used as a weapon only and not when it's used as an implement. In addition, does anyone that is holding this weapon qualify for the property bonus (+2 to Athletics/Str ability checks when on earth or stone) and the daily action (slowing enemy on hit)? Or do they have to be proficient in staffs as an implement? **Second case**: We recently got Aecris, the +1 magic longsword from H1 Keep on the Shadowfell. The fighter doesn't want it nor does our halfling barbarian (the fighter has built around bonuses from wielding greataxes and the barbarian is a whirling slayer and benefits from having an off-hand weapon). However, we have an Eladrin psion in the group that was eyeing it because although she can't use it as an implement, she *is* proficient with longswords (due to her race, not her class), and it would boost her attack modifier for her basic melee attack. In this case, she would get the +3 attack bonus when she stabs with the sword, but she wouldn't get the +1 enhancement bonus to attack and damage rolls, correct? From what I gather, the enhancement bonus is wasted on her since as a psion she's only proficient in staffs and orbs - is that right? Would she qualify for the daily action of gaining a healing surge when dropping an undead enemy to 0 hp without proficiency? If this is the case, what good is the +1 enhancement bonus on this weapon, then? 'Longswords' aren't listed as an implement proficiency for any class I'm familiar with. **Edited to summarize what I think my primary questions are:** * What are the requirements to benefit from a magical weapon's enhancement bonus (i.e. like a weapon that *doesn't* generally double as an implement, like a +1 magic sickle)? * What are the requirements to have access to the same magical weapon's properties or powers, if any? * If a character can benefit from a magical weapon's enhancement bonus, what power keyword(s) will this bonus be applied to - 'weapon' or 'implement'? Thanks in advance!
2013/11/14
[ "https://rpg.stackexchange.com/questions/30127", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/9816/" ]
There are three issues here, I think: Keywords, the two different kinds of proficiency, and permission by omission. But before I go into those, a word: As always there are explicit features/feats/enchantments which break the rules, and that's why we call D&D an "exception-based" system: it deals in rules which apply universally unless (until) exceptions are made, so there is no need to enumerate the possible exceptions. We simply assume the rule unless told otherwise in a particular instance. Keywords -------- If a power has the `weapon` keyword, and *only* if the power has the `weapon` keyword, does a weapon enchantment (enhancement bonuses and other features) apply to that power. Ditto with the `implement` keyword and implement enchantments. Proficiency and the Proficiency Bonus ------------------------------------- "Proficiency" means that you've had training in the use of a weapon or implement, but mechanically it means totally different things whether you're talking about a weapon or an implement. ### Weapon Proficiency and the Proficiency Bonus Proficiency with a weapon means that you can add that weapon's "proficiency bonus" to attack rolls. Only weapons have proficiency bonuses, they only apply to powers with the `weapon` keyword, and they have nothing to do with whether enhancement bonuses can be applied (see below for that bit). ### Implements, Enhancement Bonuses, and Permission by Omission You need to be proficient with an implement in order to add its enhancement bonus to attacks and damage with implement powers. You do *not* need to be proficient with a weapon in order to add its enhancement bonus to attacks and damage with weapon powers, but you don't get its proficiency bonus to the attack roll. (In either case, you can only add the enhancement bonus of one item at a time to an attack unless you have a rules exception which says otherwise.) I arrived at this conclusion because the magic implement rules say you need to be proficient for the enhancement bonus, but the magic weapon rules don't. Permission by omission is sloppy, but has solid precedent.
71,021,314
In my Anylogic model I succesfully create plots of datasets that count the number of trucks arriving from terminals each hour in my simulation. Now, I want to add the actual/"observed" number of trucks arriving at a terminal, to compare my simulation to these numbers. I added these numbers in a database table (see picture below). Is there a simple way of adding this data to the plot? [![enter image description here](https://i.stack.imgur.com/jdHXw.png)](https://i.stack.imgur.com/jdHXw.png) I tried it by creating a variable that reads the database table for every hour and adding that to a dataset (like can be seen in the pictures below), but this did not work unfortunately (the plot was empty). [![enter image description here](https://i.stack.imgur.com/YN8Oa.png)](https://i.stack.imgur.com/YN8Oa.png)[![enter image description here](https://i.stack.imgur.com/fpsks.png)](https://i.stack.imgur.com/fpsks.png) [![enter image description here](https://i.stack.imgur.com/Gm8kF.png)](https://i.stack.imgur.com/Gm8kF.png)
2022/02/07
[ "https://Stackoverflow.com/questions/71021314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17658498/" ]
Maybe simply delete the variable and fill the dataset at the start of the model by looping through the dbase table data. Use the dbase query wizard to create a for-loop. Something like this should work: ``` int numEntries = (int) selectFrom(observed_arrivals).count(); DataSet myDataSet = new DataSet(numEntries); List<Tuple> rows = selectFrom(observed_arrivals).list(); for (Tuple row : rows) { myDataSet.add(row.get( observed_arrivals.hour ), row.get( observed_arrivals.terminal_a )); } myChart.addDataSet(myDataSet); ```
39,973
I know the differences between a **rangefinder** and a **SLR/DSLR** but what is the real reason to put a mirror in front of a lens to reflect light into the viewfinder? It raises lens prooduction price when you put extra distance between lens and sensor. So why do that? Does it improve image quality somehow? Isn't it logical to use rangefinders only?
2013/06/09
[ "https://photo.stackexchange.com/questions/39973", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/17818/" ]
Simple, it allows you to see exactly what the camera will "see" when you expose the shot. Nir has given you a part of the argument as well which is accuracy. In the "middle ground" of anything around mabye 20-100mm, building a rangefinder is not too difficult and Leica had adapters for longer and wider lenses if I am not mistaken. It takes some effort to calibrate but is doable. However with an SLR you can use even more extreme focal lengths - try a 7mm or 15mm Fisheye lens, how do you get that into an extra viewfinder (which incidentally needs a similar lens system). Or maybe a 400mm, 800mm lens? Every system is a compromise somewhere - and using a mirror to reflect the light from the lens to the viewfinder (or focussing screen if one is finicky) allows the user to fully exploit the flexibility that is offered by the range of available lenses. Coming back to rangefinders, you might have noticed that lenses typically span around 20-135mm and I think there are is at least one lens that offers 17mm on Leicas as well. The extra distance between the sensor and the lens is itself also not disadvantageous given the way that sensors are designed. Leica's sensor uses a specially shifted micro-lens arrangement to improve the light gathering capability of the sensor. Now whether it works is another discussion, in theory it should. Moving the lens closer to the sensor means that the light hits the sensor at an oblique angle rather than a near right angle. Given the nature of "light wells" on a sensor, this increases light loss (hence the shifted microlenses on a Leica). (This is actually the basis for this issue: <http://www.luminous-landscape.com/essays/an_open_letter_to_the_major_camera_manufacturers.shtml> )
2,862,698
I'm still learning undergraduate probability. I was asked this probability puzzle in a recent quantitative developer interview. I solved the first part of the question, using brute-force. I think, brute-force very quickly becomes unwieldy for the sequence ending $THH$ - not sure if my answer is correct. > > A coin is flipped infinitely until you or I win. If at any point, the last three tosses in the sequence are $HHT$, I win. If at any point, the last three tosses in the sequence are $THH$, you win. Which sequence is more likely? > > > **Solution.** $\begin{aligned} P(xHHT)&=P(H^2T)+P(H^3T)+P(H^4T)+\ldots \\ &=\frac{1}{2^3}+\frac{1}{2^4} + \frac{1}{2^5} + \ldots \\ &=\frac{1/8}{1-1/2}\\ &=\frac{1}{4} \end{aligned}$ For the second part, $P(xTHH)$, I have drawn a state-diagram, but there are just too many possible combinations for a sequence ending in $THH$. Is there an easier, or perhaps an intuitive way to look at this? Any hints in the right direction would be great!
2018/07/25
[ "https://math.stackexchange.com/questions/2862698", "https://math.stackexchange.com", "https://math.stackexchange.com/users/247892/" ]
Note: the only way you can possibly get $HHT$ before $THH$ is if the first two tosses are $HH$. Pf: Suppose you get $HHT$ first. Then look at the first occurrence of $HHT$. Go back through the sequence. If you ever encounter a $T$, you must have $THH$ starting with the first $T$ you find. Thus, you can never find a $T$. In particular the first two tosses must both be $H$. Conversely, if the first two tosses are $HH$ then $THH$ can not come first. Thus the answer is clearly $\frac 14$.
36,123,740
Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use?
2016/03/21
[ "https://Stackoverflow.com/questions/36123740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349760/" ]
(1) There is some limited support with [Timeline](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/client/timeline.py) for logging memory allocations. Here is an example for its usage: ``` run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True), options=run_options, run_metadata=run_metadata) train_writer.add_run_metadata(run_metadata, 'step%03d' % i) train_writer.add_summary(summary, i) print('Adding run metadata for', i) tl = timeline.Timeline(run_metadata.step_stats) print(tl.generate_chrome_trace_format(show_memory=True)) trace_file = tf.gfile.Open(name='timeline', mode='w') trace_file.write(tl.generate_chrome_trace_format(show_memory=True)) ``` You can give this code a try with the MNIST example ([mnist with summaries](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py)) This will generate a tracing file named timeline, which you can open with chrome://tracing. Note that this only gives an approximated GPU memory usage statistics. It basically simulated a GPU execution, but doesn't have access to the full graph metadata. It also can't know how many variables have been assigned to the GPU. (2) For a very coarse measure of GPU memory usage, nvidia-smi will show the total device memory usage at the time you run the command. nvprof can show the on-chip shared memory usage and register usage at the CUDA kernel level, but doesn't show the global/device memory usage. Here is an example command: nvprof --print-gpu-trace matrixMul And more details here: <http://docs.nvidia.com/cuda/profiler-users-guide/#abstract>
36,501,768
At our .NET front-end we are using ticks to handle time localization and at the database we are storing all values in UTC. Today we came across an odd rounding error when storing records to the database, we are using the following formula to convert Ticks to a datetime. ``` CAST((@ticks - 599266080000000000) / 10000000 / 24 / 60 / 60 AS datetime) ``` It seemed to work fine for most time values we tried until we discovered the following rounding error: ``` DECLARE @ticks bigint = 635953248000000000; -- 2016-04-04​ 00:00:00.000 SELECT CAST((@Ticks - 599266080000000000) / 10000000 / 24 / 60 / 60 AS datetime) -- Results in 2016-04-03 23:59:59.997 ``` The question is: What is causing this rounding error and what would be the best practice to fix it?
2016/04/08
[ "https://Stackoverflow.com/questions/36501768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048845/" ]
If you capture your calculation in a sql\_variant you can determine what type it is. In your case the calculation uses a numeric type which is not an exact datatype and this is where the rounding is occurring: ``` DECLARE @myVar sql_variant = (@Ticks - 599266080000000000) / 10000000 / 24 / 60 / 60 SELECT SQL_VARIANT_PROPERTY(@myVar,'BaseType') BaseType, SQL_VARIANT_PROPERTY(@myVar,'Precision') Precisions, SQL_VARIANT_PROPERTY(@myVar,'Scale') Scale, SQL_VARIANT_PROPERTY(@myVar,'TotalBytes') TotalBytes, SQL_VARIANT_PROPERTY(@myVar,'Collation') Collation, SQL_VARIANT_PROPERTY(@myVar,'MaxLength') MaxLengths ``` which produces the following output: ``` BaseType Precisions Scale TotalBytes Collation MaxLengths numeric 38 18 17 NULL 13 ``` I have found this code which works from [Extended.Net link](http://extendeddotnet.blogspot.co.uk/2011/10/convert-net-datetimeticks-to-t-sql.html) ``` DECLARE @ticks bigint = 635953248000000000 -- First, we will convert the ticks into a datetime value with UTC time DECLARE @BaseDate datetime; SET @BaseDate = '01/01/1900'; DECLARE @NetFxTicksFromBaseDate bigint; SET @NetFxTicksFromBaseDate = @Ticks - 599266080000000000; -- The numeric constant is the number of .Net Ticks between the System.DateTime.MinValue (01/01/0001) and the SQL Server datetime base date (01/01/1900) DECLARE @DaysFromBaseDate int; SET @DaysFromBaseDate = @NetFxTicksFromBaseDate / 864000000000; -- The numeric constant is the number of .Net Ticks in a single day. DECLARE @TimeOfDayInTicks bigint; SET @TimeOfDayInTicks = @NetFxTicksFromBaseDate - @DaysFromBaseDate * 864000000000; DECLARE @TimeOfDayInMilliseconds int; SET @TimeOfDayInMilliseconds = @TimeOfDayInTicks / 10000; -- A Tick equals to 100 nanoseconds which is 0.0001 milliseconds DECLARE @UtcDate datetime; SET @UtcDate = DATEADD(ms, @TimeOfDayInMilliseconds, DATEADD(d, @DaysFromBaseDate, @BaseDate)); -- The @UtcDate is already useful. If you need the time in UTC, just return this value. SELECT @UtcDate; ```
66,389
Let $G$ be an ample $\mathbb{Q}$-divisor on a smooth variety $X$. Let $D$ be a $\mathbb{Q}$-divisor linearly equivalent to $G$. Let $f: Y\to X$ be a common log resolution of $G$ and $D$. We define the multiplier ideal of a divisor $G$ as $I(G)=f\_\*O\_Y(K\_{Y/X}-[f^\*G])$. Are the multiplier ideals $I(G)$ and $I((1-t)G+tD)$ the same for sufficiently small $t>0$?
2011/05/29
[ "https://mathoverflow.net/questions/66389", "https://mathoverflow.net", "https://mathoverflow.net/users/2348/" ]
I don't think so. Take for example $X=\mathbb{P}^2$, and $G$ and $D$ to be distinct lines. then $I(G)=\mathcal{O}\_X(-G)$ while $I((1-t)g+tD)=\mathcal{O}\_X$ for every small $t>0$. Maybe you might want to look at the multiplier ideal associated to the linear series $|G|$.
44,200,737
I need to remove all occurring patterns except 1, but I haven't been able to get this working in a Bash script. I tried ``` sed -e 's/ /\\ /g' -e 's/\\ / /1' ``` and ``` sed ':a;s/\([^ ]* .*[^\\]\) \(.*\)/\1\\ \2/;ta' ``` but neither do have the desired effect unfortunately. Is someone able to help me out? Thank you in advance!
2017/05/26
[ "https://Stackoverflow.com/questions/44200737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7487227/" ]
**Plain Mockito library** ``` import org.mockito.Mock; ... @Mock MyService myservice; ``` and ``` import org.mockito.Mockito; ... MyService myservice = Mockito.mock(MyService.class); ``` come from the Mockito library and are functionally equivalent. They allow to mock a class or an interface and to record and verify behaviors on it. The way using annotation is shorter, so preferable and often preferred. --- Note that to enable Mockito annotations during test executions, the `MockitoAnnotations.initMocks(this)` static method has to be called. To avoid side effect between tests, it is advised to do it before each test execution : ``` @Before public void initMocks() { MockitoAnnotations.initMocks(this); } ``` Another way to enable Mockito annotations is annotating the test class with `@RunWith` by specifying the `MockitoJUnitRunner` that does this task and also other useful things : ``` @RunWith(org.mockito.runners.MockitoJUnitRunner.class) public MyClassTest{...} ``` --- **Spring Boot library wrapping Mockito library** This is indeed a [Spring Boot class](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html): ``` import org.springframework.boot.test.mock.mockito.MockBean; ... @MockBean MyService myservice; ``` The class is included in the `spring-boot-test` library. It allows to add Mockito mocks in a Spring `ApplicationContext`. If a bean, compatible with the declared class exists in the context, it **replaces** it by the mock. If it is not the case, it **adds** the mock in the context as a bean. Javadoc reference : > > Annotation that can be used to add mocks to a Spring > ApplicationContext. > > > ... > > > If any existing single bean of the same type defined in the context > will be replaced by the mock, if no existing bean is defined a new one > will be added. > > > --- **When use classic/plain Mockito and when use `@MockBean` from Spring Boot ?** Unit tests are designed to test a component in isolation from other components and unit tests have also a requirement : being as fast as possible in terms of execution time as these tests may be executed each day dozen times on the developer machines. Consequently, here is a simple guideline : As you write a test that doesn't need any dependencies from the Spring Boot container, the classic/plain Mockito is the way to follow : it is fast and favors the isolation of the tested component. If your test needs to rely on the Spring Boot container **and** you want also to add or mock one of the container beans : `@MockBean` from Spring Boot is the way. --- **Typical usage of Spring Boot `@MockBean`** As we write a test class annotated with `@WebMvcTest` (web test slice). [The Spring Boot documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests) summarizes that very well : > > Often `@WebMvcTest` will be limited to a single controller and used in > combination with `@MockBean` to provide mock implementations for > required collaborators. > > > Here is an example : ``` import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @WebMvcTest(FooController.class) public class FooControllerTest { @Autowired private MockMvc mvc; @MockBean private FooService fooServiceMock; @Test public void testExample() throws Exception { Foo mockedFoo = new Foo("one", "two"); Mockito.when(fooServiceMock.get(1)) .thenReturn(mockedFoo); mvc.perform(get("foos/1") .accept(MediaType.TEXT_PLAIN)) .andExpect(status().isOk()) .andExpect(content().string("one two")); } } ```
28,022,091
I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated. I need a Regex to find matches for the following: ``` "On Fri, Jan 16, 2015 at 4:39 PM" ``` Where `On` will always be there; then 3 characters for week day; `,` is always there; space is always there; then 3 characters for month name; space is always there; day of month (one or two numbers); `,` is always there; space is always there; 4 numbers for year; space `at` space always there; time (have to match `4:39` as well as `10:39`); space and 2 caps letters for `AM` or `PM`.
2015/01/19
[ "https://Stackoverflow.com/questions/28022091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1772830/" ]
Try this: ``` On\s+(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (?:Jan|Feb|Mar|Apr|May|June|July|Aug|Sept|Oct|Nov|Dec) \d{1,2}, \d{4} at \d{1,2}:\d{2} (?:AM|PM) ``` ![Regular expression visualization](https://www.debuggex.com/i/PVWjcUPX8LIGI_nt.png)
24,283
Reading Matthew 12:26 If Satan drives out Satan, he is divided against himself. How then can his kingdom stand? I cant seem to pin point where is his kingdom? Evil men dont seem to be united?
2013/12/31
[ "https://christianity.stackexchange.com/questions/24283", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/6506/" ]
Let's take a long look at the Scriptures around your referenced Scripture: Matthew 12:25 through 28 KJV > > 25 And Jesus knew their thoughts, and said unto them, Every kingdom divided against itself is brought to desolation; and every city or house divided against itself shall not stand: > > > 26 And if Satan cast out Satan, he is divided against himself; how shall then his kingdom stand? > > > 27 And if I by Beelzebub cast out devils, by whom do your children cast them out? therefore they shall be your judges. > > > 28 But if I cast out devils by the Spirit of God, then the kingdom of God is come unto you. > > > and see if Jesus was actually saying that Satan had a Kingdom to begin with. What Jesus was retorting to was the verse preceding this retort (Matthew 12:24): But when the Pharisees heard it, they said, This fellow doth not cast out devils, but by Beelzebub the prince of the devils. Jesus was incensed by their claim that he was getting his power to do these miracles from Satan, and his angry retort was meant to marginalize them. In verses 26 and 27 He is belittling them by: 1. saying that If Satan is ruining his own plans, If He had a Kingdom by fighting against himself he would be destroying his own Kingdom. 2. Jesus is saying and if as you say I am getting my power from Satan, where are your people getting their power from? The last stone he casts is in verse 28 where he tells them knowing what I have just told you my power must come from another source. and if my source is God then you have just seen the Kingdom of God. Here are some other Scriptures concerning Satan's supposed power which you may find will help you in understanding Satan. Please remember that Jesus himself said that Satan was a liar and the father of lies. Matthew 4:1-11 KJV > > Again, the devil taketh him up into an exceeding high mountain, and sheweth him all the kingdoms of the world, and the glory of them; And saith unto him, All these things will I give thee, if thou wilt fall down and worship me. > > > Mark 3:22-26 KJV > > And the scribes which came down from Jerusalem said, He hath Beelzebub, and by the prince of the devils casteth he out devils. And he called them [unto him], and said unto them in parables, How can Satan cast out Satan? And if a kingdom be divided against itself, that kingdom cannot stand. And if a house be divided against itself, that house cannot stand. And if Satan rise up against himself, and be divided, he cannot stand, but hath an end. > > > In This Scripture what Jesus is pointing to is that if what they were claiming were true then Satan does not have the power of God since he could not do what they claimed and be eternal. Revelation 2:13 KJV > > I know thy works, and where thou dwellest, [even] where Satan's seat [is]: and thou holdest fast my name, and hast not denied my faith, even in those days wherein Antipas [was] my faithful martyr, who was slain among you, where Satan dwelleth. > > > Revelation 12:9-12 KJV > > Therefore rejoice, [ye] heavens, and ye that dwell in them. Woe to the inhabiters of the earth and of the sea! for the devil is come down unto you, having great wrath, because he knoweth that he hath but a short time. > > > Revelation 3:9 KJV > > Behold, I will make them of the synagogue of Satan, which say they are Jews, and are not, but do lie; behold, I will make them to come and worship before thy feet, and to know that I have loved thee. > > > Revelation 12:9-12 KJV > > Therefore rejoice, [ye] heavens, and ye that dwell in them. Woe to the inhabiters of the earth and of the sea! for the devil is come down unto you, having great wrath, because he knoweth that he hath but a short time. > > >
23,032,889
i need help, i am trying to replicate this kind of progress indicator, but i can't figure it out. What i want: [![enter image description here](https://i.stack.imgur.com/d0Ypc.png)](https://i.stack.imgur.com/d0Ypc.png) What i have: <http://jsfiddle.net/AQWdM/> ```css body { font-family: 'Segoe UI'; font-size: 13px; } ul.progress li.active { background-color: #dc9305; } ul.progress li { background-color: #7e7e7e; } ul.progress { list-style: none; margin: 0; padding: 0; } ul.progress li { float: left; line-height: 20px; height: 20px; min-width: 130px; position: relative; } ul.progress li:after { content: ''; position: absolute; width: 0; height: 0; right: 4px; border-style: solid; border-width: 10px 0 10px 10px; border-color: transparent transparent transparent #7e7e7e; } ul.progress li:before { content: ''; position: absolute; width: 0; height: 0; right: 0px; border-style: solid; border-width: 10px 0 10px 10px; border-color: transparent transparent transparent #fff; } ul.progress li.beforeactive:before { background-color: #dc9305; } ul.progress li.active:before { background-color: #7e7e7e; } ul.progress li.active:after { border-color: transparent transparent transparent #dc9305; } ul.progress li:last-child:after, ul.progress li:last-child:before { border: 0; } ul.progress li a { padding: 0px 0px 0px 6px; color: #FFF; text-decoration: none; } ``` ```html <ul class="progress"> <li><a href="">Qualify</a></li> <li class="beforeactive"><a href="">Develop</a></li> <li class="active"><a href="">Propose</a></li> <li><a href="">Close</a></li> </ul> ``` First, my example has "beforeactive" class - i would like to avoid this, so i can just mark item as active. Also, arrows on my example are not best set up - on image where is what i want, it has better set up arrows (the are more thick at starting). I need your help to: 1.) Create better css, clearly i am not good at css, so not to require beforeactive class, also to properly color backgrounds, and to be optimized - there can be hundrets of this lists per page 2.) Create arrow to match the one on the design i want to have 3.) It needs to be dynamic, since sometimes it will be small, somtimes it will be large, it needs to be able to cope with different font sizes (maybe use em or percentage - i used px just to test stuff) 4.) IF - AND ONLY IF IS POSSIBLE SIMPLE WAY - to make it for example whole long 600px; and current active one is longest, others have fixed size, and the active one always fills up the rest of it. So if first is active, it takes 400px, and rest fill in 200px, when we activate second, to animate making others size down, and second one size up. I use jquery, so it's ok to use his anymations, but i prefer css animations (there will be thousands of lines of javascript code - so i try to use javascript as little as possible for ui) Thank you
2014/04/12
[ "https://Stackoverflow.com/questions/23032889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3527152/" ]
You should use one pseudo rotated element and draw it on the far left side. *the first will be out of sight, so no need to worry about last `li`, set `overflow` on `ul` to hide `overflow`ing parts :).* **[DEMO](http://codepen.io/gc-nomade/pen/FnKim/)** and CSS ```css body { font-family: 'Segoe UI'; font-size: 13px; } ul.progress li.active { background-color: #dc9305; } ul.progress li { background-color: #7e7e7e; position: relative; text-indent: 0.5em; } ul.progress li:after { content: ''; position: absolute; right: 100%; margin-right: 0.4em; width: 1.2em; padding-top: 1.2em; ; border: solid white; z-index: 1; transform: rotate(45deg); border-bottom: 0; border-left: 0; box-shadow: 5px -5px 0 3px #7e7e7e } ul.progress li.active:after { box-shadow: 6px -6px 0 3px #dc9305; } ul.progress { list-style: none; margin:2px 0; padding: 0; overflow: hidden; min-width:max-content; } ul.progress li { float: left; line-height: 20px; height: 20px; min-width: 130px; position: relative; transition: min-width 0.5s; } ul.progress li a { padding: 0px 0px 0px 6px; color: #FFF; text-decoration: none; } ul.progress li:hover { min-width: 300px; } ul.progress li:before { content: '\2714' } ul.progress li.active:before, ul.progress li.active~li:before { content: '' } ``` ```html <ul class="progress"> <li class="active"><a href="">Qualify</a></li> <li><a href="">Develop</a></li> <li><a href="">Propose</a></li> <li><a href="">Close</a></li> </ul> <ul class="progress"> <li><a href="">Qualify</a></li> <li class="active"><a href="">Develop</a></li> <li><a href="">Propose</a></li> <li><a href="">Close</a></li> </ul> <ul class="progress"> <li><a href="">Qualify</a></li> <li><a href="">Develop</a></li> <li class="active"><a href="">Propose</a></li> <li><a href="">Close</a></li> </ul> <ul class="progress"> <li><a href="">Qualify</a></li> <li><a href="">Develop</a></li> <li><a href="">Propose</a></li> <li class="active"><a href="">Close</a></li> </ul> ``` --- Do not forget to add vendor-prefix or use a script to care of it. --- over `li` to see them grow with `transition`, check marks added too via CSS to `li` ahead `.active` class
16,214,205
Lets say, I have Product and Score tables. ``` Product ------- id name Score ----- id ProductId ScoreValue ``` I want to get the top 10 Products with the highest AVERAGE scores, how do I get the average and select the top 10 products in one select statement? here is mine which selects unexpected rows ``` SELECT TOP 10 Product.ProductName Score.Score FROM Product, Score WHERE Product.ID IN (select top 100 productid from score group by productid order by sum(score) desc) order by Score.Score desc ```
2013/04/25
[ "https://Stackoverflow.com/questions/16214205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091346/" ]
Give this a try, ``` WITH records AS ( SELECT a.ID, a.Name, AVG(b.ScoreValue) avg_score, DENSE_RANK() OVER (ORDER BY AVG(b.ScoreValue) DESC) rn FROM Product a INNER JOIN Score b ON a.ID = b.ProductID GROUP BY a.ID, a.Name ) SELECT ID, Name, Avg_Score FROM records WHERE rn <= 10 ORDER BY avg_score DESC ``` The reason why I am not using `TOP` is because it will not handle duplicate record having the highest average. But you can use `TOP WITH TIES` instead.
27,470,505
I'm using webapi2 and Castle Windsor. I'm trying to intercept calls to the ApiController to make some logging, but I can't find in the parameter the method called, url, parameters, etc. The method name returned is ExecuteAsync. This is my interceptor call (which is hit) ``` public class LoggingInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { var methodName = invocation.Method.Name; invocation.Proceed(); } } ```
2014/12/14
[ "https://Stackoverflow.com/questions/27470505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/723059/" ]
``` if (invocation.Method.Name == "ExecuteAsync") { var ctx = (HttpControllerContext) invocation.Arguments[0]; Console.WriteLine("Controller name: {0}", ctx.ControllerDescriptor.ControllerName); Console.WriteLine("Request Uri: {0}", ctx.Request.RequestUri); } invocation.Proceed(); ``` Intercepting the ExecuteAsync call, you can get access to the HttpControllerContext but not the HttpActionContext, which contains details about the actual controller action method being invoked. (As far as I can tell this is only available to an ActionFilter). Therefore the detail about the request is limited: for instance, deserialized parameters are not available using this technique. If you wish, you can make your controller action methods `virtual` and these will then also be intercepted, and you can then access the actual action parameters via `invocation.arguments`. However, in your interceptor you will need to somehow differentiate the action methods that you wish to log, from the other methods that get called on the controller (i.e. `Intialize()`, `Dispose()`, `ExecuteAsync()`, `Ok()`, etc.)
207,341
Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power. **What might be the benefits for this same government to sanction certain crime within this important trade city?** Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities.
2021/07/17
[ "https://worldbuilding.stackexchange.com/questions/207341", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/43517/" ]
I wonder if you have a too modern view of the state -- by the people, for the people. Over much of history it was by *some* people, for *some* people. * **Illicit substances** Very much in the eye of the beholder. In much of the West, alcohol is legal (and taxed) and cannabis is not. Say you have strong merchant guilds interested in the trade in those substances, and they might have gained permission to do so. Also consider the [Opium Wars](https://en.wikipedia.org/wiki/Opium_Wars). * **Racketeering** Just who is exploited, and how? Look at the rise of firefighters in [ancient Rome](https://en.wikipedia.org/wiki/Marcus_Licinius_Crassus#Rise_to_power_and_wealth). Early on they were for-profit companies who charged whatever the market would bear when a house was on fire. Or take a medieval craft guild, regulating prices, quality and competition and making sure that guild masters had a decent living. * Special case: **Tax farming** The government sold the right to [collect taxes](https://en.wikipedia.org/wiki/Farm_(revenue_leasing)). The interests who paid a hefty sum now try to squeeze money out of the city to cover their costs and make a profit on top. Not everybody is allowed to racketeer, but from the perspective of the victims some rackets are legal. * **Burglary** This one is difficult. When it is made legal, powerful factions like the merchants and guilds mentioned above must guard their properties without the help of a city watch. But do you know the proverb *only the rich can afford a weak government?* Say burglary is not legal, the rules against it are simply not enforced by the government. That is left to merchants and shop-keepers, who form associations (see *racketeering*) to employ guards and [thief-takers](https://en.wikipedia.org/wiki/Thief-taker). * **Murder** As above, making it a kind of *civil* offense requiring [weregild](https://en.wikipedia.org/wiki/Weregild) if the relatives of the victim are strong enough to insist.
28,731
Sometimes, package updates from MELPA can break some part of emacs and when that happens I'd like to be able to revert back to using an older version of the package. Right now, I can do it in two ways: * I've set emacs to delete files by moving to trash and when I update a package, the older version is trashed. I can retrieve the older version and replace the one in `~/.emacs.d/elpa`. * Go to the github repo of the package that broke functionality, fetch an older version of the package, replace the one in `~/.emacs.d/elpa` with the one from gitub, byte-recompile the file(s). Both these ways involve a lot of manual work moving things around. Is there an easier(preferably automatic) way to downgrade packages installed from MELPA?
2016/11/18
[ "https://emacs.stackexchange.com/questions/28731", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/12247/" ]
When you update your packages through the `M-x list-packages` interface, after the successful installation of the package, you'll get asked if you want to remove the old package. Don't delete them so they stay in place and you could then later remove the newer package through this interface. My current package list shows 4 versions of magit installed in my ~/.emacs.d/elpa/ directory tree. ``` magit 20160827.1549 obsolete A Git porcelain inside Emacs magit 20160907.945 obsolete A Git porcelain inside Emacs magit 20161001.1454 obsolete A Git porcelain inside Emacs magit 20161123.617 installed A Git porcelain inside Emacs ``` You can clean-up old versions later with the key `~` (package-menu-mark-obsolete-for-deletion) to mark all obsolete packages. To delete a certain old version move to its line and press `d` to mark them for deletion. After you marked the packages you'd use `x` to execute the actions as usual. In **Emacs 25** the mark all packages for `U`pgrade functionality automatically sets all old packages for deletion, and doesn't prompt for confirmation after installing. You have to look for lines that start with a capital "D", which you can just unmark (best with the following macro) Type the key or chord on the left of the dash from the following lines. ``` <F3> - start macro recording C-s - isearch-forward C-q - quoted-insert C-j - linefeed character D - the mark at the start of the line <Ret> - stops the isearch on the line with the "D" u - unmark the package for deletion <F4> - stops macro recording - the first package is now unmarked <F4> - executes the macro for the next upgraded package ``` If there are no further matches for the search the macro will ring the bell and stop, so you could `C-u 0 <F4>` to unmark all packages marked for deletion. After this you can e`x`ecute the installations. The function I declared to be changed in my comment has to be changed in a way I cannot grasp yet, as it's important that the last (cond) block has to be successful in order to not loop endlessly.
7,338,824
I have a log line that I am pulling from bash like: ``` There are 5 apples and 7 oranges ``` And I want to get the 5 and 7 into bash variables and am having problems doing so. awk '{ print $3, $6 }' won't work due to the fact that their position might change, if there are bananas. Bonus points if the digits can be associated with their fruits. Thanks in advance
2011/09/07
[ "https://Stackoverflow.com/questions/7338824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/884881/" ]
and to get the fruits: ``` echo 'There are 5 apples and 7 oranges' | grep -o -E '[[:digit:]]+ [[:alpha:]]+' ```
65,263,049
I am using this logic in my button i.e if login the buynow class is working else login modal is open. & code here. ``` <button class="ps-btn ps-btn--sm @if(session()->has('name')){{'buy_now'}}"@else {{data-toggle="modal" data-target="#loginModal"}}@endif>Buy Now<i class="ps-icon-next"></i></button> ```
2020/12/12
[ "https://Stackoverflow.com/questions/65263049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14724522/" ]
You can use below code ``` <button class="ps-btn ps-btn--sm @if(session()->has('name')) buy_now" @else " data-toggle='modal' data-target='#loginModal' @endif>Buy Now<i class="ps-icon-next"></i> </button> ``` **Notice:** We use `{{ $variable }}` for echoing a php variable. It is equivalent to `<?php echo $variable ?>`. For more info refer to [laravel displaying data](https://laravel.com/docs/8.x/blade#displaying-data)
40,193,491
I am working on a project, where I have a domain `xyz.com`, I have been requested that a subdomain example `abc.xyz.com` should point to website which has ipaddress example `http://199.152.57.120/client/` and when a visitor browse `abc.xyz.com` it should open the website hosted on `http://199.152.57.120/client/` but by hidding this ip address the visitor should always see `abc.xyz.com`. I also need to host another website to `xyz.com` domain which is registered with *x* company and webhosting is taken for *z* company both different. It is something similar to Reseller business where Reseller company assign a website to their client on their custom domain.
2016/10/22
[ "https://Stackoverflow.com/questions/40193491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7057429/" ]
Here's the solution for [image2](http://genxcoders.in/demo/TDirectory/2.png) `echo '<select>';` `structureTree(0,0);` `echo '</select>';` `function structureTree($deptParentId, $level){` ``` $result = getDataFromDb($deptParentId); // change this into SQL foreach($result as $result){ echo '<option value="'.$deptParentId.'">'.str_repeat('-',$level).$result['deptName'].'</option>'; structureTree($result['deptId'], $level+2); } ``` `}` `// mocking database record function getDataFromDb($deptParentId) {` ``` $data = array( array( 'deptId' => 1, 'deptName' => 'IT', 'deptParentId' => 0, ), array( 'deptId' => 2, 'deptName' => 'Human Resources', 'deptParentId' => 1, ), array( 'deptId' => 3, 'deptName' => 'Opreational', 'deptParentId' => 1, ), array( 'deptId' => 4, 'deptName' => 'Networking Department', 'deptParentId' => 1, ), array( 'deptId' => 5, 'deptName' => 'Software Development', 'deptParentId' => 1, ), array( 'deptId' => 6, 'deptName' => 'Mobile Software Development', 'deptParentId' => 5, ), array( 'deptId' => 7, 'deptName' => 'ERP', 'deptParentId' => 5, ), array( 'deptId' => 8, 'deptName' => 'Product Development', 'deptParentId' => 5, ), ); $result = array(); foreach ($data as $record) { if ($record['deptParentId'] === $deptParentId) { $result[] = $record; } } return $result; ``` `}` regarding [1.png](http://genxcoders.in/demo/TDirectory/1.png) Here's the `SQL` based on your sample db table `SELEC dep.deptId As DepId` `,dep.deptName As DepartmenName` `,parent.deptId As ParentId` `,parent.deptName As ParentDepartmentName` `FROM tddept As dep` `JOIN tddept As parent ON parent.deptParentId = dep.deptId;`
2,318
We would like to get rid of the Tridion Broker as part of a project and publish content directly to a repository as part of a Storage Extension. My question is, is there any deep dependency that Tridion has on the Broker that might mean things work in a sub-optimal way, or gotchas that I should be aware of? Update - We are going to be using Tridion purely as a content store which will push out JSON. There will be no functionality or any form of business logic/UI.
2013/07/25
[ "https://tridion.stackexchange.com/questions/2318", "https://tridion.stackexchange.com", "https://tridion.stackexchange.com/users/315/" ]
I will assume that what you mean with the Broker is the Tridion Broker database. It is possible to publish everything to the file system, it includes, content, linking info, metadata and references, however this functionality is deprecated and will be removed in future releases, having said that, in future releases, linking, metadata and references will always be stored in the Tridion broker database. If what you want is to override the storage layer and create a custom one, it will for sure affect key features like the Tridion CD API, Dynamic Linking and of course it won't be supported by either Customer Support or R&D. Other key feature that depends on the Tridion Broker database is the Session Preview functionality.
32,869,080
I've a class A like that: ``` public class A { private String id; // Generated on server private DateTime timestamp; private int trash; private Humanity.FeedTypeEnum feedType private List<Property> properties; // ... ``` where `Property` is: ``` public class Property { private Humanity.PropertyTypeEnum type; private string key; private object value; //... ``` I'd like to build a dynamic object that flat `List<Property> properties` A's field to raw properties. For example: ``` A a = new A(); a.Id = "Id"; a.Timestamp = DateTime.Now; a.Trash = 2; a.FeedType = Humanity.FeedTypeEnum.Mail; a.Properties = new List<Property>() { new Property() { Type = Humanity.PropertyTypeEnum.String, Key = "name" Value = "file1.pdf" }, new Property() { Type = Humanity.PropertyTypeEnum.Timestamp, Key = "creationDate", Value = Datetime.Now } } ``` As I've commented I'd like to flat this `a` object in order to access to the properties as: ``` String name = a.Name; DateTime creationDate = a.CreationDate; a.Name = "otherName"; a.CreationDate = creationDate.AddDays(1); ``` I've achieved that using Reflection. However, I'm figuring out that it's a best option using `ExpandoObject`. The question is, how can I do that using `ExpandoObject` class?
2015/09/30
[ "https://Stackoverflow.com/questions/32869080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3227319/" ]
You can do what you want extending `DynamicObject` class: ``` class A : System.Dynamic.DynamicObject { // Other members public List<Property> properties; private readonly Dictionary<string, object> _membersDict = new Dictionary<string, object>(); public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result) { result = null; if (!_membersDict.ContainsKey(binder.Name)) return false; result = _membersDict[binder.Name]; return true; } public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value) { if (!_membersDict.ContainsKey(binder.Name)) return false; _membersDict[binder.Name] = value; return true; } public void CreateProperties() { foreach (Property prop in properties) { if (!_membersDict.ContainsKey(prop.key)) { _membersDict.Add(prop.key, prop.value); } } } } ``` Then use it like that: ``` A a = new A(); ///////// a.Properties = new List<Property>() { new Property() { Type = Humanity.PropertyTypeEnum.String, // Now this property is useless, the value field has already a type, if you want you can add some logic around with this property to ensure that value will always be the same type Key = "name" Value = "file1.pdf" }, new Property() { Type = Humanity.PropertyTypeEnum.Timestamp, Key = "creationDate", Value = Datetime.Now } } a.CreateProperties(); dynamic dynA = a; dynA.name = "value1"; ```
64,018,695
My program always outpout test which should not happen. Its like the program is skipping the case to go to default right away. I don't understand why it does that. I've spent 30 mins to find a solution but I can't understand why it does that. Thanks for helping me ! ``` var ani; let ans; let prix; var total; var arm1; var arm2; let nombrearmure; nombrearmure = 0; ani = prompt("Entrez votre type d'animal : "); switch (ani.toLowerCase) { case 'c' : ans = prompt('Voulez vous acheter une épée pour 100$ ? : '); if (ans.toLowerCase() === 'o'){ prix = 100; nombrearmure = 1; } else { if (ans.toLowerCase() === 'n') { console.log('Épée refusé'); } else { console.log('Réponse non valide'); } } ans = prompt('Voulez vous acheter une corne de licorne pour 500 $ ? : '); if(ans.toLowerCase() === 'o'){ prix = prix+500; nombrearmure = nombrearmure + 2; } else { if (ans.toLowerCase() === 'n'){ console.log('Corne de licorne refusé'); } else { console.log('Réponse invalide'); } } break; case 'l' : ans = prompt('Voulez vous acheter un casque(100-200$) : '); if (ans.toLowerCase() === 'o'){ ans = parseInt(prompt('Appuyez sur 1 pour un casque noir (100$) ou 2 pour un casque multicolore (200$) : ')); switch(ans){ case 1 : prix = 100; nombrearmure = 1; break; case 2 : prix = 200 nombrearmure = 2; break; default : console.log('Réponse invalide') return 1; } } else { if(ans.toLowerCase === 'n'){ console.log('Casque refusé'); } else { } } default: console.log('test'); } ```
2020/09/22
[ "https://Stackoverflow.com/questions/64018695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14323955/" ]
You are doing `ani.toLowerCase`. It should be `ani.toLowerCase()`. Also remove the return 1.
59,973
I want to register a sidebar but I am a little confused about the uses of the `id` argument in [`register_sidebar`](http://codex.wordpress.org/Function_Reference/register_sidebar) function. > > Codex says: id - Sidebar id - Must be all in lowercase, with no spaces > (default is a numeric auto-incremented ID). > > > Of what use is the `id` argument and must it always be in numeric form?.
2012/07/28
[ "https://wordpress.stackexchange.com/questions/59973", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11125/" ]
John Landells’ answer is good and correct. I want to add a **List of forbidden or reserved IDs** – these IDs may appear on the widget config page `/wp-admin/widgets.php`. If you use one of these … strange things will happen due to duplicated IDs. Drag and drop will probably not work anymore. See [Ticket #14466](http://core.trac.wordpress.org/ticket/14466) for the most obvious case: `#footer`. **Update, Sept. 17.:** `#footer` will be [allowed in WP 3.5](http://core.trac.wordpress.org/changeset/21878). **Update, Nov., 06.:** Per [ticket 14466](http://core.trac.wordpress.org/ticket/14466) all widget IDs in `widgets.php` are prefixed with `sidebar-` now. The following list will be obsolete with WordPress 3.5. Probably. Also, an ID should not start with a number, that’s invalid HTML. Installed plugins affecting this list: [Debug Bar](http://wordpress.org/extend/plugins/debug-bar/), [Debug Bar Cron](http://wordpress.org/extend/plugins/debug-bar-cron/), [Monster Widget](http://wordpress.org/extend/plugins/monster-widget/). ```none #_wpnonce_widgets #ab-awaiting-mod #access-off #access-on #adminmenu #adminmenuback #adminmenushadow #adminmenuwrap #adv-settings #available-widgets #collapse-button #collapse-menu #colors-css #contextual-help-back #contextual-help-columns #contextual-help-link #contextual-help-link-wrap #contextual-help-wrap #debug-bar-actions #debug-bar-cron #debug-bar-css #debug-bar-info #debug-bar-menu #debug-bar-wp-query #debug-menu-link-Debug_Bar_Object_Cache #debug-menu-link-Debug_Bar_Queries #debug-menu-link-Debug_Bar_WP_Query #debug-menu-link-ZT_Debug_Bar_Cron #debug-menu-links #debug-menu-target-Debug_Bar_Object_Cache #debug-menu-target-Debug_Bar_Queries #debug-menu-target-Debug_Bar_WP_Query #debug-menu-target-ZT_Debug_Bar_Cron #debug-menu-targets #debug-status #debug-status-db #debug-status-memory #debug-status-php #debug-status-site #footer #footer-left #footer-thankyou #footer-upgrade #icon-themes #menu-appearance #menu-comments #menu-dashboard #menu-links #menu-media #menu-pages #menu-plugins #menu-posts #menu-posts-domicile #menu-settings #menu-tools #menu-users #object-cache-stats #querylist #removing-widget #rss-items-2 #rss-items-__i__ #rss-show-author-2 #rss-show-author-__i__ #rss-show-date-2 #rss-show-date-__i__ #rss-show-summary-2 #rss-show-summary-__i__ #rss-title-2 #rss-title-__i__ #rss-url-2 #rss-url-__i__ #screen-meta #screen-meta-links #screen-options-link-wrap #screen-options-wrap #screenoptionnonce #show-settings-link #tab-link-missing-widgets #tab-link-overview #tab-link-removing-reusing #tab-panel-missing-widgets #tab-panel-overview #tab-panel-removing-reusing #widget-10_recent-posts-__i__ #widget-11_rss-__i__ #widget-12_search-__i__ #widget-13_tag_cloud-__i__ #widget-14_text-__i__ #widget-15_widget_twentyeleven_ephemera-__i__ #widget-16_rss-2 #widget-1_archives-__i__ #widget-2_calendar-__i__ #widget-3_categories-__i__ #widget-4_nav_menu-__i__ #widget-5_links-__i__ #widget-6_meta-__i__ #widget-7_monster-__i__ #widget-8_pages-__i__ #widget-9_recent-comments-__i__ #widget-archives-__i__-count #widget-archives-__i__-dropdown #widget-archives-__i__-savewidget #widget-archives-__i__-title #widget-calendar-__i__-savewidget #widget-calendar-__i__-title #widget-categories-__i__-count #widget-categories-__i__-dropdown #widget-categories-__i__-hierarchical #widget-categories-__i__-savewidget #widget-categories-__i__-title #widget-links-__i__-category #widget-links-__i__-description #widget-links-__i__-images #widget-links-__i__-limit #widget-links-__i__-name #widget-links-__i__-orderby #widget-links-__i__-rating #widget-links-__i__-savewidget #widget-list #widget-meta-__i__-savewidget #widget-meta-__i__-title #widget-monster-__i__-savewidget #widget-nav_menu-__i__-nav_menu #widget-nav_menu-__i__-savewidget #widget-nav_menu-__i__-title #widget-pages-__i__-exclude #widget-pages-__i__-savewidget #widget-pages-__i__-sortby #widget-pages-__i__-title #widget-recent-comments-__i__-number #widget-recent-comments-__i__-savewidget #widget-recent-comments-__i__-title #widget-recent-posts-__i__-number #widget-recent-posts-__i__-savewidget #widget-recent-posts-__i__-title #widget-rss-2-savewidget #widget-rss-__i__-savewidget #widget-search-__i__-savewidget #widget-search-__i__-title #widget-tag_cloud-__i__-savewidget #widget-tag_cloud-__i__-taxonomy #widget-tag_cloud-__i__-title #widget-text-__i__-filter #widget-text-__i__-savewidget #widget-text-__i__-text #widget-text-__i__-title #widget-widget_twentyeleven_ephemera-__i__-number #widget-widget_twentyeleven_ephemera-__i__-savewidget #widget-widget_twentyeleven_ephemera-__i__-title #widgets-left #widgets-right #wp-admin-bar-a8c_developer #wp-admin-bar-comments #wp-admin-bar-debug-bar #wp-admin-bar-edit-profile #wp-admin-bar-logout #wp-admin-bar-my-account #wp-admin-bar-new-content #wp-admin-bar-new-content-default #wp-admin-bar-new-domicile #wp-admin-bar-new-link #wp-admin-bar-new-media #wp-admin-bar-new-page #wp-admin-bar-new-post #wp-admin-bar-new-user #wp-admin-bar-root-default #wp-admin-bar-site-name #wp-admin-bar-site-name-default #wp-admin-bar-top-secondary #wp-admin-bar-updates #wp-admin-bar-user-actions #wp-admin-bar-user-info #wp-admin-bar-view-site #wp_inactive_widgets #wpadminbar #wpbody #wpbody-content #wpcontent #wpwrap #zt-debug-bar-cron-css ``` I collected the IDs with a small plugin that can be used on any page: ```php <?php # -*- coding: utf-8 -*- /* Plugin Name: T5 List IDs */ add_action( 'shutdown', function() { ?> <script> jQuery( function( $ ) { var els = [] $( '[id]' ).each( function() { els.push( this.id ) } ) els.sort() var pre = $( '<pre/>' ).css( 'margin','10px' ).html( '#'+els.join( '<br>#' ) ) $( document.documentElement ).append( pre ) }) </script><?php } ); ```
17,435,950
I am trying to improve the performance of a hammered wordpress DB by adding indexes to queries that appear in the slow query log. In MS SQL you can use query hints to force a query to use an index but it is usually quite easy to get a query to use an index if you cover the columns correctly etc. I have this query that appears in the slow query log a lot ``` SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 18310, 5; ``` I created a covering unique index on `wp_posts` on `post_date, post_status, post_type and post_id` and restarted MySQL however when I run explain the index used is ``` status_password_id ``` and in the possible keys my new index doesn't even appear although it's a covering index e.g I just get ``` type_status_date,status_password_id ``` Therefore neither the used index or the possible choices the "optimiser" if MySQL has one is even considering my index which has post\_date as the first column. I would have thought a query that is basically doing a TOP and ordering by date with ``` ORDER BY wp_posts.post_date DESC LIMIT 18310, 5; ``` Would want to use an index sorted by date for speed, especially one that had all the other fields required to satisfy the query in it as well? Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored. I would love it if Navicat had a Visual Query Execution Plan like MS SQL but it seems EXPLAIN is the best it has to offer. Anyone with any hints on how I can either force the index to be used or work out why its being ignored would be very helpful! Thanks
2013/07/02
[ "https://Stackoverflow.com/questions/17435950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1037545/" ]
> > Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored. > > > [The documentation](http://dev.mysql.com/doc/refman/5.0/en/index-hints.html) answers this question in some detail: > > By specifying `USE INDEX`*`(index_list)`*, you can tell MySQL to use > only one of the named indexes to find rows in the table. The > alternative syntax `IGNORE INDEX`*`(index_list)`* can be used to tell > MySQL to not use some particular index or indexes. These hints are > useful if [`EXPLAIN`](http://dev.mysql.com/doc/refman/5.0/en/explain.html) shows that MySQL is using the wrong index > from the list of possible indexes. > > > You can also use `FORCE INDEX`, which acts like `USE INDEX`*`(index_list)`* > but with the addition that a table scan is assumed to be *very > expensive*. In other words, a table scan is used only if there is no > way to use one of the given indexes to find rows in the table. > > > Each hint requires the names of indexes, not the names of columns. The > name of a `PRIMARY KEY` is `PRIMARY`. To see the index names for a > table, use [`SHOW INDEX`](http://dev.mysql.com/doc/refman/5.0/en/show-index.html). > > > If `USE INDEX` doesn't work, try using `IGNORE INDEX` to see what the optimizer's second choice is (or third, and so on). A simple example of the syntax would be: ``` SELECT * FROM t1 USE INDEX (i1) IGNORE INDEX (i2) WHERE ... ``` There are many more where that came from, in the linked docs. I've linked to the version 5.0 pages, but you can easily navigate to the appropriate version using the left sidebar; some additional syntax options are available as of version 5.1.
51,384,796
I have a table that have logins in one column and phone numbers in another. I need to copy all phone numbers of each login and paste them to another sheet. But i need only unique phone numbers as one login may contain many records with the same phone number. What i have tried and what failed ``` For Each rCell In Sheets("PotentialFraud").Range("B1:B" & IndexValueLastRow("B:B")) .Range("A2").AutoFilter _ field:=12, _ Criteria1:=rCell.Value2 LastRow = .Cells(1, 1).SpecialCells(xlCellTypeVisible).End(xlDown).Row .Range("P1:P" & LastRow).Offset(1, 0).SpecialCells(xlCellTypeVisible).Copy Worksheets("PotentialFraud").Range(rCell.Offset(0, 2).Address).PasteSpecial Transpose:=True Next rCell ``` This Method does not give me an option to copy only unique values. Another option I found was to use Advanced Filter ``` .Range("P2:P" & LastRow).Offset(1, 0).SpecialCells(xlCellTypeVisible).AdvancedFilter _ Action:=xlFilterCopy, _ CopyToRange:=Worksheets("PotentialFraud").Range("A:A"), _ Unique:=True ``` However, this lead to error 1004 saying either **This command requires at least two rows of source data...** even though there are 2500 rows visible. Either **Application-defined or object-defined error** if i change the range to ``` .Range("P:P" & LastRow).Offset(1, 0).SpecialCells(xlCellTypeVisible).AdvancedFilter _ Action:=xlFilterCopy, _ CopyToRange:=Worksheets("PotentialFraud").Range("A:A"), _ Unique:=True ``` *("P2:P") to ("P:P")*
2018/07/17
[ "https://Stackoverflow.com/questions/51384796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5874458/" ]
you can add this ``` onFocus={useTheOnFocus ? onFocusHandler : undefined} ``` or set a handler ``` onFocus={onFocusHandler} ``` and check a condition in a handler ``` onFocusHandler = (ev) => { if(!condition) { return null; } // your code } ```
24,440,216
I have line like this and I am searching for how the input works when the code is executed ``` scanf("%d, %f",&withdrawal ,&balance ); ``` I use Cygwin to compile the code and afterwards I am asked for inputs. Does it mean that I have to write two numbers separated by space ``` 60 120 ``` or there is some trick to do that ? It could be an easy question, but I just would like to understand how it works when it is asked for more then one input value. Thanks
2014/06/26
[ "https://Stackoverflow.com/questions/24440216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3460161/" ]
scanf(), or scan formatted, expects input in the format you specified. scanf("%d, %f") simply means you expect input in this exact format, for example: 62, 2.15 .
42,461,533
i'm developing a java program that shows area and perimeter of two rectangle with fixed width&length, current date and reads input from user to solve a linear equation. I was able to ask a user if they want to re-run the program or not. the problem is that if they input y or Y, the program runs, but if the user enters anything els the program quits. I'd like to check this input and see if: 1- it's a y or Y, re-run 2- it's n or N, quit 3- neither 1 nor 2, ask the user again if he/she wants to re-run the program of not. Here's my code: ``` public static void main(String[] args) { char ch = 'y'; GregorianCalendar calendar = new GregorianCalendar(); LinearEquation le = new LinearEquation(1.0,1.0,1.0,1.0,1.0,1.0); Rectangle rec1 = new Rectangle(4.0,40.0); Rectangle rec2 = new Rectangle(3.5,35.9); Scanner input = new Scanner(System.in); Double a, b, c, d, e,f; do{ System.out.println("First rectangle info is: "); System.out.print(" width is: "+ rec1.getWidth() + "\n height is: " + rec1.getHeight()+ "\n Area is: "+ rec1.getArea() + "\n Perimeter is: " + rec1.getPerimeter()); System.out.println(); System.out.println(); System.out.println("Second rectangle info is: "); System.out.print(" width is: "+ rec2.getWidth() + "\n height is: " + rec2.getHeight()+ "\n Area is: "+ rec2.getArea() + "\n Perimeter is: " + rec2.getPerimeter()); System.out.println(); System.out.println("Current date is: " + calendar.get(GregorianCalendar.DAY_OF_MONTH) + "-" + (calendar.get(GregorianCalendar.MONTH) + 1)+ "-" + calendar.get(GregorianCalendar.YEAR)); System.out.println("Date after applying 1234567898765L to setTimeInMillis(long) is: "); calendar.setTimeInMillis(1234567898765L); System.out.println(calendar.get(GregorianCalendar.DAY_OF_MONTH) + "-" + (calendar.get(GregorianCalendar.MONTH) + 1)+ "-" + calendar.get(GregorianCalendar.YEAR)); System.out.println(); System.out.println("Please, enter a, b, c, d, e and f to solve the equation:"); try{ System.out.println("a: "); a = input.nextDouble(); System.out.println("b: "); b = input.nextDouble(); System.out.println("c: "); c = input.nextDouble(); System.out.println("d: "); d = input.nextDouble(); System.out.println("e: "); e = input.nextDouble(); System.out.println("f: "); f = input.nextDouble(); le.setA(a); le.setB(b); le.setC(c); le.setD(d); le.setE(e); le.setF(f); if(le.isSolvable()){ System.out.println("x is: "+ le.getX() + "\ny is: "+ le.getY()); }else { System.out.println("The equation has no solution."); } //System.out.println("Would you like to re-run the program( y or n)"); //ch = input.next().charAt(0); } catch (Exception ee) { System.out.println("Invalid input"); //System.out.println("Would you like to re-run the program( y or n)"); ch = input.next().charAt(0); } System.out.println("Would you like to re-run the program( y or any other input to quit)"); ch = input.next().charAt(0); }while(ch == 'y' || ch == 'Y'); } ```
2017/02/25
[ "https://Stackoverflow.com/questions/42461533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066392/" ]
You can add a `do while` when you asks the user whether if he wants to repeat the program. Besides, instead of specifying both uppercase and lowercase in statement : `while(ch == 'y' || ch == 'Y');` you can use `Character.toLowerCase()` method to reduce the number of tests to perform. ``` do { System.out.println("Would you like to re-run the program( y or any other input to quit)"); ch = input.next().charAt(0); ch = Character.toLowerCase(ch); } while (ch != 'y' && ch != 'n'); ``` Now your code could look like that : ``` do { .... do { System.out.println("Would you like to re-run the program( y or any other input to quit)"); ch = input.next().charAt(0); ch = Character.toLowerCase(ch); } while (ch != 'y' && ch != 'n'); } while (ch == 'y'); ```
34,778,041
I want to know what `[=]` does? Here's a short example ``` template <typename T> std::function<T (T)> makeConverter(T factor, T offset) { return [=] (T input) -> T { return (offset + input) * factor; }; } auto milesToKm = makeConverter(1.60936, 0.0); ``` How would the code work with `[]` instead of `[=]`? I assume that ``` std::function<T (T)> ``` means an function prototype which gets `(T)` as argument and return type `T`?
2016/01/13
[ "https://Stackoverflow.com/questions/34778041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4503737/" ]
The `[=]` you're referring to is part of the *capture list* for the lambda expression. This tells C++ that the code inside the lambda expression is initialized so that the lambda gets a copy of all the local variables it uses when it's created. This is necessary for the lambda expression to be able to refer to `factor` and `offset`, which are local variables inside the function. If you replace the `[=]` with `[]`, you'll get a compiler error because the code inside the lambda expression won't know what the variables `offset` and `factor` refer to. Many compilers give good diagnostic error messages if you do this, so try it and see what happens!
51,206,456
I have restructured my project folders. I see that i lost commit history before restructuring of files in my remote repository. I have the history before restructuring locally. Right now everyone who clone the repository doesn't have the commit history before restructuring. Is there anyway i can rebuild the commit history and merge it to the remote repository? When i try this command : ``` git log --follow pom.xml ``` I can see full history of file, but when i dont use --follow the log stops at restructuring commit.I would like that it shows all the history. Is there any way to fix this?
2018/07/06
[ "https://Stackoverflow.com/questions/51206456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1057347/" ]
The only way to lose history in Git is to remove commits. This is because the commits *are* the history. There is no file history; there are only commits. When you use `git log --follow pom.xml`, you are telling Git to *synthesize* a file history, by wandering through the commit history and noting when a file named `pom.xml` is touched. The `--follow` option tells Git that in addition to checking to see if `pom.xml` is *changed* in that commit, it should also check to see if it is *renamed* in that commit. If so, Git checks *earlier* commits for the *old name* (including its full directory path) instead of the new name—so Git is no longer looking for `new/pom.xml` but now looking for `old/pom.xml` or whatever, and constructing a file history for *that* file. If you use an IDE, the IDE must do the same thing as Git—synthesize a file history by selecting commits that change that file, and check for rename operations in the process, if that's what you want it to do.
7,515,167
What I want is when checkbox1 is selected both checkbox labelled 1 will get selected and background will be removed [here is the fiddle](http://jsfiddle.net/rigids/D2vCf/) for eg if i select checkbox1 it should select both checkbox labelled checkbox1
2011/09/22
[ "https://Stackoverflow.com/questions/7515167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791441/" ]
The problem is that searching for ID $("#somethin") is not possible to select more than one element. IF you search for class, then your example works.. well, with [some minor changes](http://jsfiddle.net/D2vCf/11/) :) ``` $(document).ready(function() { $('input[type=checkbox]').change(function(){ var pos; pos = this.id; // global hook - unblock UI when ajax request completes $(document).ajaxStop($.unblockUI); if($(this).prop("checked")) { $("."+pos).parent().removeClass("highlight"); $("."+pos).prop('checked', true) //ajax to add uni } else { //ajax to remove uni $("."+pos).parent().addClass("highlight"); $("."+pos).prop('checked', false) } }); }); ```
4,195,726
I want to create a custom TableViewCell on which I want to have UITextField with editing possibility. So I created new class with xib. Add TableViewCell element. Drag on it UITextField. Added outlets in my class and connect them all together. In my TableView method cellForRowAtIndexPath I create my custom cells, BUT they are not my custom cells - they are just usual cells. How can I fix this problem, and why it is? thanx! //EditCell. h ``` #import <UIKit/UIKit.h> @interface EditCell : UITableViewCell { IBOutlet UITextField *editRow; } @property (nonatomic, retain) IBOutlet UITextField *editRow; @end ``` //EditCell.m ``` #import "EditCell.h" @implementation EditCell @synthesize editRow; #pragma mark - #pragma mark View lifecycle - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; self.editRow = nil; } @end ``` //in my code ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"EditCell"; EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[EditCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } cell.editRow.text = @"some text to test"; return cell; } ```
2010/11/16
[ "https://Stackoverflow.com/questions/4195726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449007/" ]
Do not use UITableViewCell's initializer, but make the cell load from your nib: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"EditCell"; EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"YourNibNameHere" owner:self options:nil]; cell = (EditCell *)[nib objectAtIndex:0]; } cell.editRow.text = @"some text to test"; return cell; } ``` Of course, you need to specify the correct nib name.
19,796,235
I'm new to Android programming and working with Retrofit. I've done a bunch of research on this topic, but haven't been able to find a solution specific to my needs. I'm working with our API and trying to make a POST request. I successfully achieved this with the following non-Retrofit code: ``` private class ProcessLogin extends AsyncTask<Void, String, JSONObject> { private ProgressDialog pDialog; String email,password; protected void onPreExecute() { super.onPreExecute(); inputEmail = (EditText) findViewById(R.id.email); inputPassword = (EditText) findViewById(R.id.password); email = inputEmail.getText().toString(); password = inputPassword.getText().toString(); pDialog = new ProgressDialog(LoginActivity.this); pDialog.setTitle("Contacting Servers"); pDialog.setMessage("Logging in ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } protected JSONObject doInBackground(Void... params) { HttpURLConnection connection; OutputStreamWriter request = null; URL url = null; String response = null; String parameters = "username="+email+"&password="+password; try { url = new URL("http://.../api/login"); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestMethod("POST"); request = new OutputStreamWriter(connection.getOutputStream()); request.write(parameters); request.flush(); request.close(); String line = ""; InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader reader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } // Response from server after login process will be stored in response variable. response = sb.toString(); // You can perform UI operations here isr.close(); reader.close(); } catch(IOException e) { // Error } System.out.println(response); JSONObject jObj = null; // Try to parse the string to a JSON Object try { jObj = new JSONObject(response); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // Return the JSONObject return jObj; } protected void onPostExecute(JSONObject json) { String status = (String) json.optJSONArray("users").optJSONObject(0).optJSONObject("user").optString("login"); pDialog.dismiss(); if (status.equals("Failed")) { loginMessage.setText("Login Failed"); } else if (status.equals("Success")) { loginMessage.setText("Success!"); startActivity(new Intent(getApplicationContext(), DActivity.class)); } } } ``` Now, I'm trying to get the same results using Retrofit, but I'm not sure how to get the JSON back from our API using Callbacks (I'm assuming this call should happen asynchronously?): I've made an interface with the following method: ``` @FormUrlEncoded @POST("/login") public void login(@Field("username") String username, @Field("password") String password, Callback<JSONObject> callback); ``` And instantiated the RestAdapter, etc in my Activity's onCreate method. When the user presses the "login" button (after entering their username and password), the following is called inside the button's onClick method: ``` service.login(email, password, new Callback<JSONObject>() { @Override public void failure(final RetrofitError error) { android.util.Log.i("example", "Error, body: " + error.getBody().toString()); } @Override public void success(JSONObject arg0, Response arg1) { } } ); ``` This is not working as intended however, and I really don't think I'm approaching this correctly. I want to be able to make a POST to our server, which sends back a block of JSON formatted data about that user. If anyone could point me in the right direction, that would be really appreciated. Thank you in advance
2013/11/05
[ "https://Stackoverflow.com/questions/19796235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2957545/" ]
One of the benefits of Retrofit is not having to parse the JSON yourself. You should have something like: ``` service.login(email, password, new Callback<User>() { @Override public void failure(final RetrofitError error) { android.util.Log.i("example", "Error, body: " + error.getBody().toString()); } @Override public void success(User user, Response response) { // Do something with the User object returned } } ); ``` Where `User` is a POJO like ``` public class User { private String name; private String email; // ... etc. } ``` and the returned JSON has fields that match the `User` class: ``` { "name": "Bob User", "email": "[email protected]", ... } ``` If you need custom parsing, the place for that is when setting the REST adapter's converter with [.setConverter(Converter converter)](http://square.github.io/retrofit/javadoc/retrofit/RestAdapter.Builder.html#setConverter(retrofit.converter.Converter)): > > The converter used for serialization and deserialization of objects. > > >
93,391
I am designing a campaign and I have a couple of evil power blocs vying for control. I would really like to have one of them directly interacting with the party and I think I really want it to be a devil because I love the idea of the lawful evil tricking them while still being true to its word. So my question would it be possible to disguise a devil as a human\* using canon mechanics? I know I could just house rule that the devil has the spell polymorph or something but I was wondering if there was a way to do it within the rules as written for 5e? Now, this doesn't have to be an undetectable disguise. I am fine with the players discovering he is a devil in disguise if they look hard enough. Also, the type of Devil can change if needed, though I would prefer to have a more prestigious Devil that is calling the shots. I have read the entire section on Devils in the Monster Manual and there isn't anything obvious. I was thinking of an Erinyes with a Hat of Disguise Self but I don't think Disguise Self would be able to conceal the wings, so they would have to pretend to be an Angel which I wouldn't really consider "normal" to be interacting with. As for making a custom monster according to the DMG I would consider that akin to house ruling it. Which is definitely something I can fall back to, but I was trying to think of something more direct from the rules. \*Or anything else that would normally interact with a party around a town.
2017/01/18
[ "https://rpg.stackexchange.com/questions/93391", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/29455/" ]
Hide in plain sight. There are two good options for this: **Erinyes** Based on the picture on MM 73, these creatures are mostly humanoid, but have wings. The horns on the helmet may or may not cover any natural horns; it's unclear. Either way, you could throw on a cloak to hide your wings, then claim to be a Tiefling. Depending on the campaign world, there may be any number of them around, trying to redeem their unsavory lineage. **Asmodeus** If you'd like to go straight to the top, you could send in the lord of the lowest of the Nine Hells. He's described as "a handsome, bearded humanoid with small horns protruding from his forehead, piercing red eyes, and flowing robes." He can also assume other forms. He should easily pass as a Tiefling.
61,330,119
Have some arduino code for temp loggers that is VERY NEARLY working....! I've built an OTA routine so I can update them remotely, however the delay() loop I had to ensure it only logged temperatures every 15 mins is now causing problems as it effectively freezes the arduino by design for 15mins, meaning OTA wouldn't work whilst it is in this state. Some suggestions say just to flip to millis() instead, but I can't seem to get this working and it's logging ~20 records every second at the moment. Ideally I just want delay\_counter counting up to the value in DELAY\_TIME, then running the rest of the code and resetting the counter. Can anyone help me and point out what I'm doing daft in my code??? ``` // v2 Temp sensor // Connecting to Home NAS #include <DHT.h> #include <DHT_U.h> #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <WiFiUdp.h> #include <ESP8266mDNS.h> #include <ArduinoOTA.h> #include <InfluxDbClient.h> #define SSID "xxx" //your network name #define PASS "xxx" //your network password #define VersionID "v3" #define SensorName "ServerUnit" //name of sensor used for InfluxDB and Home Assistant // Temp Sensor 1 - GardenTropical // Temp Sensor 2 - GardenRoom // Temp Sensor 3 - Greenhouse // Temp Sensor 4 - OutsideGreenhouse // Temp Sensor 5 - ServerUnit // Connection Parameters for Jupiter InfluxDB #define INFLUXDB_URL "http://192.168.1.5:8086" #define INFLUXDB_DB_NAME "home_assistant" #define INFLUXDB_USER "xxx" #define INFLUXDB_PASSWORD "xxx" // Single InfluxDB instance InfluxDBClient client(INFLUXDB_URL, INFLUXDB_DB_NAME); // Define data point with measurement name 'DaveTest` Point sensor("BrynyneuaddSensors"); #define PORT 80 #define DHTPIN 4 // what pin the DHT sensor is connected to #define DHTTYPE DHT22 // Change to DHT22 if that's what you have #define BAUD_RATE 115200 //Another common value is 9600 #define DELAY_TIME 900000 //time in ms between posting data to Home Server unsigned long delay_counter = 0; DHT dht(DHTPIN, DHTTYPE); //this runs once void setup() { Serial.begin(BAUD_RATE); // Connect to WIFI WiFi.begin(SSID, PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("*"); } // Initialise OTA Routine ArduinoOTA.onStart([]() { Serial.println("Start"); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); Serial.println("Ready"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); //initalize DHT sensor dht.begin(); // set InfluxDB database connection parameters client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DB_NAME, INFLUXDB_USER, INFLUXDB_PASSWORD); // Add constant tags - only once sensor.addTag("device", SensorName); // Check server connection if (client.validateConnection()) { Serial.print("Connected to InfluxDB: "); Serial.println(client.getServerUrl()); } else { Serial.print("InfluxDB connection failed: "); Serial.println(client.getLastErrorMessage()); Serial.println(client.getServerUrl()); Serial.println("Exiting DB Connection"); } } //this runs over and over void loop() { ArduinoOTA.handle(); float h = dht.readHumidity(); Serial.print("Humidity: "); Serial.println(h); // Read temperature as Fahrenheit (isFahrenheit = true) float c = dht.readTemperature(); Serial.print("Temperature: "); Serial.println(c); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(c)) { Serial.println("Reading DHT22 Failed, exiting"); return; } //update Influx DB channel with new values updateTemp(c, h); Serial.print("Writing to InfluxDB: "); //INFLUXDB - clear temp data so it doesn't repeat sensor.clearFields(); // Update Influx DB sensor.addField("Temperature", c); sensor.addField("Humidity", h); Serial.println(sensor.toLineProtocol()); // Write data client.writePoint(sensor); //wait for delay time before attempting to post again if(millis() >= DELAY_TIME){ delay_counter += 0; } //Increment Delay Counter delay_counter++; } bool updateTemp(float tempC, float humid) { WiFiClient client; // Create a WiFiClient to for TCP connection Serial.println("Receiving HTTP response"); while (client.available()) { char ch = static_cast<char>(client.read()); Serial.print(ch); } Serial.println(); Serial.println("Closing TCP connection"); client.stop(); return true; } ```
2020/04/20
[ "https://Stackoverflow.com/questions/61330119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/528013/" ]
Set a `TimerObject`. [this](https://playground.arduino.cc/Code/ArduinoTimerObject/) seems to be what you want. 1. Download the [Arduino TimerObject code](https://github.com/aron-bordin/ArduinoTimerObject) from github and follow the installation instructions 2. `#include "TimerObject.h"` 3. Create the callback function 4. Create the `TimerObject` 5. Setup the `TimerObject` and periodically call `update()` in your `loop()`: ``` // make sure to include the header #include "TimerObject.h" ... // setup your TimerObject TimerObject* sensor_timer = new TimerObject(15 * 60 * 1000); // milliseconds ... // define the stuff you want to do every 15 minutes and // stick it in a function // not sure what from your loop() needs to go in here void doSensor() { float h = dht.readHumidity(); Serial.print("Humidity: "); Serial.println(h); // Read temperature as Fahrenheit (isFahrenheit = true) float c = dht.readTemperature(); Serial.print("Temperature: "); Serial.println(c); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(c)) { Serial.println("Reading DHT22 Failed, exiting"); return; } //update Influx DB channel with new values updateTemp(c, h); Serial.print("Writing to InfluxDB: "); //INFLUXDB - clear temp data so it doesn't repeat sensor.clearFields(); // Update Influx DB sensor.addField("Temperature", c); sensor.addField("Humidity", h); Serial.println(sensor.toLineProtocol()); // Write data client.writePoint(sensor); } ... // add the timer setup to your setup() // probably at the end is a good place void setup() { ... // lots of stuff above here sensor_timer->setOnTimer(&doSensor); sensor_timer->Start(); } // modify your loop() to check the timer on every pass void loop() { ArduinoOTA.handle(); sensor_timer->Update(); } ``` If you don't want to wait 15 minutes for the first call of `doSensor`, you can explicitly call it at the end of your `setup()` function before you start the timer.
16,849,302
I want to start my `MainActivity` with a new `Intent` in my other `Activity`. The two Activities are in the same app, and the second Activity is actually started from the MainActivity. So the scenario is like this: 1. MainActivity is created with an Intent 2. MainActivity starts SecondActivity (but MainActivity is not destroyed yet. It is just stopped) 3. SecondActivity starts MainActivity with a new Intent (SecondActivity is not closed) The MainActivity is not flagged. I mean, the Activity's launch mode in the manifest is not set (so, it's default). I want to know what happens to MainActivity's lifecycle and intent. Is the Activity re-created? Is `onCreate()` called? Then is `onCreate()` called twice, without `onDestory()`? Or the new MainActivity is newly created and there will be two MainActivities? Will the Intent from `getIntent()` overwritten? I know `Activity.onNewIntent()` is called for singleTop Activities. Then in my situation `onNewIntent()` is not called? Thanks in advance.
2013/05/31
[ "https://Stackoverflow.com/questions/16849302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/869330/" ]
Create a table with single autoincrement column. When you need another unique id - just insert `null` into that column and retrieve last insert id. For oracle - create a sequence and use `SELECT sequence_name.nextval` FROM DUAL` For sql server - create a sequence and fetch it with `NEXT VALUE FOR`
107,980
I took a bunch of screenshots and I want to make them pages in a single PDF. Selecting all four in Preview and exporting to PDF only exports two (?), separately. The "Export to PDF" File menu function adds a strange white border around the screenshots (and orients the page as portrait). So I converted each to PDFs individually and then combined them manually. I tried the solutions [here](https://apple.stackexchange.com/q/11163/21351), but Mavericks' Preview doesn't appear to work that way anymore. What's the best, free, hopefully built-in way to automate this?
2013/11/01
[ "https://apple.stackexchange.com/questions/107980", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/21351/" ]
You can use the `convert` command if you install **ImageMagick**. ImageMagick isn't always a simple install, but if you install Xcode and [Homebrew](http://brew.sh) it should be fairly painless. `convert *.png foobar.pdf` <http://www.imagemagick.org/script/convert.php>
54,439,830
How will i set selected value=Booking. ```js $('#status').val("Booking"); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select name="status" class="form-control"> <option value="" id="status">New</option> <option value="">Follow</option> <option value="">DND</option> <option value="">Dead</option> </select> ```
2019/01/30
[ "https://Stackoverflow.com/questions/54439830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10954362/" ]
try to follow the below example. there is no booking option in your select add it like below code ``` $('#mySelect') .append($("<option></option>") .attr("value",key) .text("Booking")); ```
13,177,124
In a Hashmap the hash code of the key provided is used to place the value in the hashtable. In a Hashset the obects hashcode is used to place the value in the underlying hashtable. i.e the advantage of the hashmap is that you have the flexibility of deciding what you want as the key so you can do nice things like this. ``` Map<String,Player> players = new HashMap<String,Player>(); ``` This can map a string such as the players name to a player itself. My question is is what happens to to the lookup when the key's Hashcode changes. This i expect isn't such a major concern for a Hashmap as I wouldn't expect nor want the key to change. In the previous example if the players name changes he is no longer that player. However I can look a player up using the key change other fields that aren't the name and future lookups will work. However in a Hashset since the entire object's hashcode is used to place the item if someone slightly changes an object future lookups of that object will no longer resolve to the same position in the Hashtable since it relies on the entire objects Hashcode. Does this mean that once data is in a Hashset it shouldnt be changed. Or does it need to be rehashed? or is it done automatically etc? What is going on?
2012/11/01
[ "https://Stackoverflow.com/questions/13177124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1701264/" ]
In your example, a String is immutable so its hashcode cannot change. But hypothetically, if the hashcode of an object did change while was a key in a hash table, then it would *probably disappear* as far as hashtable lookups were concerned. I went into more detail in this Answer to a related question: <https://stackoverflow.com/a/13114376/139985> . (The original question is about a `HashSet`, but a `HashSet` is really a `HashMap` under the covers, so the answer covers this case too.) It is safe to say that if the keys of either a HashMap or a TreeMap are mutated in a way that affects their respective `hashcode()` / `equals(Object)` or `compare(...)` or `compareTo(...)` contracts, then the data structure will "break". --- > > Does this mean that once data is in a Hashset it shouldn't be changed. > > > Yes. > > Or does it need to be rehashed? or is it done automatically etc? > > > It won't be automatically rehashed. The `HashMap` won't notice that the hashcode of a key has changed. Indeed, you won't even get recomputation of the hashcode when the `HashMap` resizes. The data structure *remembers* the original hashcode value to avoid having to recalculate all of the hashcodes when the hash table resizes. If you know that the hashcode of a key is going to change you need to remove the entry from the table BEFORE you mutate the key, and add it back afterwards. (If you try to `remove` / `put` it after mutating the key, the chances are that the `remove` will fail to find the entry.) > > What is going on? > > > What is going on is that you violated the contract. Don't do that! The contract consists of two things: 1. The standard hashcode / equals contract as specified in the [javadoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html) for `Object`. 2. An additional constraint that an object's hashcode must not change while it is a key in a hash table. The latter constraint is not stated specifically in the `HashMap` [javadoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/HashMap.html), but the [javadoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html) for `Map` says this: > > *Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects `equals` comparisons while the object is a key in the map.* > > > A change that affects equality (typically) also affects the hashcode. At the implementation level, if a `HashMap` entry's key's hashcode changes, the entry will typically *now* be in the wrong hash bucket and will be invisible to `HashMap` methods that perform lookups.
1,780,461
I have a shared library(.so) that I preload before executing an application and I have a few global data structures in the shared library that the application uses. The application can create other processes say using fork() and these processes can update the global data structures in the shared library. I would like to keep a consistent view of these global data structures across all the processes. Is there any way I can accomplish this in Linux? I have tried using shm\_\* calls and mmap() to map the global data of the shared library to a shared segment but it does not work.
2009/11/22
[ "https://Stackoverflow.com/questions/1780461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216682/" ]
To phrase this most clearly: you cannot do exactly what you asked. Linux does not support sharing of global variables that are laid out by the linker. That memory will be in unsharable mapped-to-swap space. A general recipe I can offer is this: 1. define a struct that lays out your data. No Pointers! Just offsets. 2. first process creates a file in /tmp, sets access rw as needed. Open, mmap with MAP\_SHARED. 3. Subsequent processes also open, mmap with MAP\_SHARED. 4. everybody uses the struct to find the pieces they reference, read, or write. 5. Look Out For Concurrency! If you really only care about a parent and it's forked children, you can use an anonymous mapping and not bother with the file, and you can store the location of the mapping in a global (which can be read in the children).
35,573
I'm looking for all possible sources of clinically tested human SNPs. There is a handful of databases that store SNPs (like dbSNP), but I only need those that have validated presence/absence of phenotypic effects with some additional metadata. Thank you in advance.
2015/06/27
[ "https://biology.stackexchange.com/questions/35573", "https://biology.stackexchange.com", "https://biology.stackexchange.com/users/13338/" ]
You can search by traits (mostly diseases) for genome wide association, in these databases: * [Gwasdb2](http://jjwanglab.org/gwasdb) * [Human genome variation Database](https://gwas.biosciencedbc.jp/): it also links to a Copy number Variation (CNV) database.
73,368,824
`$ echo file.txt` ``` NAME="Ubuntu" <--- some of this VERSION="20.04.4 LTS (Focal Fossa)" <--- and some of this ID=ubuntu ID_LIKE=debian VERSION_ID="20.04" BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/" PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy" VERSION_CODENAME=focal ``` I want this: `Ubuntu 20.04.4 LTS`. I managed with two commands: ```bash echo "$(grep '^NAME="' ./file.txt | sed -E 's/NAME="(.*)"/\1/') $(grep '^VERSION="' ./file.txt | sed -E 's/VERSION="(.*) \(.*"/\1/')" ``` How could I simplify this to one command using grep/sed or perl?
2022/08/16
[ "https://Stackoverflow.com/questions/73368824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9971404/" ]
With your shown samples try following `awk` code. ```bash awk -F'"' '/^NAME="/{name=$2;next} /^VERSION="/{print name,$2}' Input_file ``` ***Explanation:*** * Setting field separator as `"` for all the lines here. * Checking condition if line starts with `Name=` then create variable name which has 2nd field. `next` will skip all further statements from there of `awk` program, they needed not to be executed. * Then checking if a line starts from `VERSION=` then print name and 2nd field here as per requirement.
44,419,907
I am trying to integrate a version/source control system with my unity project. [This answer](http://answers.unity3d.com/answers/1251608/view.html) directed me towards using source/version control. (I dont know the difference.) The answer links to a tutorial which explains creating the repository and pushing it to a remote service. I followed the whole tutorial. But I still don't understand how this integrates with my current projects. My question is that. 1. how can I do this locally 2. how will this make it possible to revert to previously-saved versions?
2017/06/07
[ "https://Stackoverflow.com/questions/44419907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5640537/" ]
This is simple math, the php code does exactly what it looks like it does. Am I missing something? loop 1: ``` $i = 1 $s = 0 + (2*1 + 5) = 7 ``` loop 2: ``` $i = 2 $s = 7 + (2*2 + 5) = 7 + 4 + 5 = 16 ``` loop 3: ``` $i = 3 $s = 16 + (2*3 + 5) = 16 + 6 + 5 = 27 ``` loop 4: ``` $i = 4 $s = 27 + (2*4 + 5) = 27 + 8 + 5 = 40 ```
4,668,309
I'm currently implementing a rather large interface and some of its methods are not applicable to the implementation. Should I do something akin to: ``` /** * @throws UnsupportedOperationException always. This method is not applicable. */ public void fooMethod() { throw new UnsupportedOperationException("This method is not applicable for this implementation."); } ``` or just silently ignore it, doing nothing: ``` public void fooMethod() { } ``` The former way would alert a user of the class that it doesn't do a portion of what the interface provides, but might perhaps clash with legacy code where the class is used as a drop-in replacement (which it isn't, though). Is there a general rule regarding this?
2011/01/12
[ "https://Stackoverflow.com/questions/4668309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73070/" ]
I think that simply depends on the contract defined by the method. If for example "remove" is not supported by your "List" implementation, you should throw an exception to indicate that this behavior is missing because the client relies on an expected result. If the feature is optional in the sense that the **contract** says for example "this method should inform the user about an ongoing activity" you're free to make a dummy implementation.
1,745,183
> > I want to show that the ideals $(x,y)$ and $(2,x,y)$ of $\mathbb{Z}[x,y]$ are prime ideals. > > > --- Could you give some hints how we could do that? Do we have to show that $\mathbb{Z}[x,y]/(x,y)$ and $\mathbb{Z}[x,y]/(2,x,y)$ are integral domains? How could we do that? Could you give me a hint? $$$$ **EDIT:** Do we have that $\phi :\mathbb{Z}[x,y]\rightarrow \mathbb{Z}$ is an homomorphism because of the following? $$$$ Let $f(x,y)\in \mathbb{Z}[x,y]$, then $f(x,y)=\sum\_{j=0}^m\sum\_{i=0}^{n(j)}\alpha\_ix^iy^j$. We have that $$f\_1(x,y)+f\_2(x,y)=\sum\_{j=0}^{m\_1}\sum\_{i=0}^{n\_1(j)}\gamma\_ix^iy^j+\sum\_{j=0}^{m\_2}\sum\_{i=0}^{n\_2(j)}\beta\_ix^iy^j=:\sum\_{j=0}^m\sum\_{i=0}^{n(j)}\alpha\_ix^iy^j=:f(x,y)$$ Then $$\phi (f\_1(x,y)+f\_2(x,y))=\phi (f(x,y))=f(0,0)=f\_1(0,0)+f\_2(0,0)=\phi (f\_1(x,y))+\phi (f\_2(x,y))$$ We also have that $$f\_1(x,y)\cdot f\_2(x,y)=\left (\sum\_{j=0}^{m\_1}\sum\_{i=0}^{n\_1(j)}\gamma\_ix^iy^j\right )\cdot \left (\sum\_{j=0}^{m\_2}\sum\_{i=0}^{n\_2(j)}\beta\_ix^iy^j\right )=:\sum\_{j=0}^m\sum\_{i=0}^{n(j)}\alpha\_ix^iy^j=:f(x,y)$$ Then $$\phi (f\_1(x,y)\cdot f\_2(x,y))=\phi (f(x,y))=f(0,0)=f\_1(0,0)\cdot f\_2(0,0)=\phi (f\_1(x,y))\cdot \phi (f\_2(x,y))$$
2016/04/16
[ "https://math.stackexchange.com/questions/1745183", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
Show that $\mathbb{Z}[x,y]/(x,y)$ is isomorphic to $\mathbb{Z}$ using the evaluation map at $0$ and $\mathbb{Z}[x,y]/(2,x,y)$ is isomorphic $\mathbb{Z}/2\mathbb{Z}$ by reducing the coefficents of the polynomial modulo $2$. In both cases consider the kernel of the map and use the first isomorphism theorem.
160,890
I have the following MWE ``` \documentclass[10pt, a4paper]{article} \usepackage{amsfonts, amsmath, amssymb, amsfonts} \begin{document} \begin{align} \sum_i{ c_i} &= \cos \sin\cos \sin\cos \sin\cos \sin\cos \sin \\ \sum_i{ c_i} &= \delta \cos \sin\cos \sin\cos \cos \sin\cos \sin\cos \cos \sin\cos \sin\cos \cos \sin\cos \\ &\hphantom{{}=} \delta^2\sin\cos \cos \sin\cos \sin\cos \cos \end{align} \end{document} ``` How do I align the last equation with the two above it? I have previously had success with `phantom`, but doesn't work here.
2014/02/17
[ "https://tex.stackexchange.com/questions/160890", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/19396/" ]
Or use `\hphantom{{}={}}`: ``` \documentclass[10pt, a4paper]{article} \usepackage{amsfonts, amsmath, amssymb, amsfonts} \begin{document} \begin{align} \sum_i{ c_i} &= \cos \sin\cos \sin\cos \sin\cos \sin\cos \sin \\ \sum_i{ c_i} &= \delta \cos \sin\cos \sin\cos \cos \sin\cos \sin\cos \cos \sin\cos \sin\cos \cos \sin\cos \\ &\hphantom{{}={}} \delta^2\sin\cos \cos \sin\cos \sin\cos \cos \end{align} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/1tWNR.png) A better option would be to indent successive lines of an expression that breaks across lines, so it becomes clear that it's the continuation of a previous expression; something like ``` \documentclass[10pt, a4paper]{article} \usepackage{amsfonts, amsmath, amssymb, amsfonts} \begin{document} \begin{align} \sum_i{ c_i} &= \cos \sin\cos \sin\cos \sin\cos \sin\cos \sin \\ \sum_i{ c_i} &= \delta \cos \sin\cos \sin\cos \cos \sin\cos \sin\cos \cos \sin\cos \sin\cos \cos \sin\cos \\ &\hphantom{{}={}}\quad\delta^2\sin\cos \cos \sin\cos \sin\cos \cos \end{align} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/C8x4a.png)
30,341,842
In this program I try to get data from SQL into a list of strings and show them in a `messageBox`. The program should start searching when I type one character in `textBox` and use this in the query as below: ``` string sql = " SELECT * FROM general WHERE element='" + textBox1.Text + "' OR element='" + textBox2.Text + "' OR element='" + textBox3.Text + "' OR element='" + textBox4.Text + "'"; MySqlConnection con = new MySqlConnection("host=localhost;user=mate;password=1234;database=element_database"); MySqlCommand cmd = new MySqlCommand(sql, con); con.Open(); MySqlDataReader reader = cmd.ExecuteReader(); string rd; rd = reader.ToString(); int i=0; List<string> item = new List<string>(); while (reader.Read()) { item.Add(rd["element"].ToString());//i got error in this line } for (i = 0; i < item.Count;i++ ) { MessageBox.Show(item[i]); } ``` What am I doing wrong?
2015/05/20
[ "https://Stackoverflow.com/questions/30341842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4909030/" ]
What are you doing wrong? a bunch of things: In your question you write you gen an error but don't tell us what it is. Exceptions has messages for a reason: so that you will be able to know what went wrong. As to your code: * You are concatenating values into your select statement instead of using [parameterized queries.](https://msdn.microsoft.com/en-us/library/vstudio/bb738521(v=vs.100).aspx) This creates an opening for [sql injection attacks.](https://xkcd.com/327/) * You are using an `SqlConnection` outside of a `using` statement. You should always use the `using` statement when dealing with `IDisposable` objects. * You assume that `rd["element"]` always have a value. If it returns as `null` from the database, you will get a null reference exception when using .ToString() on it. The proper way is to put it's value into a local variable and check if this variable is not null before using the `.ToString()` method. * You are using `rd` instead of `reader` in your code. the `rd` variable is meaningless, as it only contain the string representation of `MySqlDataReader` object.
23,408,853
My program is running fine when i run it on VS with my own 'main()' function but i have to submit this where main is hidden from me I only know that it will pass arguements to my functions and check their return result. But it is giving segmentation fault error when I try to use arguement passed to my function. Here is the code: ``` //I don't know what 'main' is passing to this function string ExpressionManager::infixToPostfix(string infixExpression) { cout<<infixExpression<<endl; // first it was giving error on below 'if' condition, //now i have written this statement it prints nothing but gives //Segmentation Fault (core dumped) error here cout<<"Hey"<<endl //it doesn't print this line if( infixExpression[0] == '\0' ) { return ""; } int size = infixExpression.length(); if(!isValidInfixExpression(infixExpression)) return "Invalid Expression"; ... //some code here } ``` Can Anyone Elaborate when string class behave this way?
2014/05/01
[ "https://Stackoverflow.com/questions/23408853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3592832/" ]
Shouldn't it be? ``` var d = value.FirstOrDefault(x => String.Equals(x.Culture, Thread.CurrentThread.CurrentCulture.Name, StringComparison.InvariantCultureIgnoreCase)); ```
4,029
I plan to ask about how to restore some defunct human genes. The GULO pseudo gene is the first one I am going to ask about. Should the question maybe be split into several question? The intended question is as follows. A lot of base pairs in the defunct GULO pseudo gene in humans are missing to make a functional enzyme. Should we take a whole gene from a close relative like a strepsirrhine, or maybe just fill in what is missing based on what? Which cells should be transfected/infected and how? Where should the working gene be put in the genome? Should the defunct gene be kept or replaced? Transcription levels for the GULO pseudo gene are too low to make enough enzymes to increase ascorbate levels above levels achievable by consumption. How can that be increased? I am not asking if this is beneficial or not nor about regulatory or ethical questions. Such questions are also meaningful but should be discussed in other questions.
2020/01/10
[ "https://biology.meta.stackexchange.com/questions/4029", "https://biology.meta.stackexchange.com", "https://biology.meta.stackexchange.com/users/11654/" ]
**NO: we should stick to the current threshold of 5.** I have noticed wayy too many circumstances in which a question was being voted to be closed by 2-3 users *inappropriately* (i.e., the close votes were unfounded/not supported or the wrong close reason was chosen). Reasons for these inappropriate VTCs range from novice voters, rushed voting, malicious voting, and difference of opinion. By reducing the close-vote requirement, we will undoubtedly close more questions that do not fit the description for being closed. We have two current problems on this SE site: (1) lack of review tasks being performed by current community members, and (2) decline in engaged users (+ an overall drop in visits overall!). I think this current VTC proposal is indirectly trying to account for these issues. * A 3rd issue is that the overall quality of posts has declined sharply in the last 2-3 years. I (among others) still hold posts to a higher standard based on older expectations of this community (i.e., one *for scientists*). Truthfully, the community has shifted much more toward consisting of novices and students here asking simple questions. At some point, our expectations just can't outweigh the masses asking the questions... [I digress...] However, I don't think the close-vote proposal will have the intended effect. The root of our problem is community engagement. By changing the VCT threshold we would not be changing that engagement level. Instead, we would be allowing decisions for the whole community to be made by an [even fewer] select active individuals. In summary: We have a community engagement problem on Bio.SE (perhaps an irreversible one), but I don't think the current proposal will fix that root issue. Instead, such a proposal will just give more closing power to the select individuals (<1% I'm sure of all users) who do vote. I'm afraid that such "power" would come off as a form of elitism as it does on some other SE sites, and may even result in a further decline in community engagement.
18,771,268
I'm having trouble with 1 line of code I've run it over and over again but I don't know what I'm doing wrong, I'm thinking it's the `if` statement but I'm not sure. The line I'm having trouble with is in the comment. I don't know how to write it so it works properly. ``` import random print"Hello hero, you are surrounded by a horde of orcs" print"that span as far as the eye can see" print"you have 5 health potions, 200 health" print"you can either fight, run, or potion" h=200 #health w=0 #wave o=0 #orc p=5 #potion while h>=0: print"you run into a horde of orcs what will you do?" a=raw_input("fight, run, potion") if a=="fight": print"you draw your sword and begin to fight" d=random.randint(1, 20) w+=1 o+=1 p=5 h-=d print"you survive this horde" print("you have, "+str(h)+" health left") elif a=="potion": print"you have used a potion" h+=20 p=p-1 print"you have recovered 20 health" print("you now have, "+str(h)+" health") if p==0: #supposed to be if potion = 0 print (you dont have any left) print"you dont have any left" elif a=="run": h-=5 print"you got away but suffered 5 damage" print("you have, "+str(h)+" health left") print"you have fought well but alas hero you were defeated" print("you survived, "+str(w)+" waves and have killed, "+str(o)+" orcs") ```
2013/09/12
[ "https://Stackoverflow.com/questions/18771268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2423223/" ]
I think you want to test if you have any potions before you award the benefits of using one. Like this: ``` elif a=="potion": if p==0: #supposed to be if potion = 0 print (you dont have any left) print"you dont have any left" else: print "you have used a potion" h+=20 p=p-1 print "you have recovered 20 health" print "you now have, "+str(h)+" health" ``` Also you have a lot of little things related to how you are using print that you should sort out, here is a cleaned up version of your original Python script (which I tested, and it appears to work, good luck with your game :) ``` import random print "Hello hero, you are surrounded by a horde of orcs" print "that span as far as the eye can see" print "you have 5 health potions, 200 health" print "you can either fight, run, or potion" h=200 #health w=0 #wave o=0 #orc p=5 #potion while h>=0: print "you run into a horde of orcs what will you do?" a=raw_input("fight, run, potion") if a=="fight": print "you draw your sword and begin to fight" d=random.randint(1, 20) w+=1 o+=1 p=5 h-=d print "you survive this horde" print "you have, "+str(h)+" health left" elif a=="potion": if p==0: #supposed to be if potion = 0 print (you dont have any left) print "you dont have any left" else: print "you have used a potion" h+=20 p=p-1 print "you have recovered 20 health" print "you now have, "+str(h)+" health" elif a=="run": h-=5 print "you got away but suffered 5 damage" print "you have, "+str(h)+" health left" print "you have fought well but alas hero you were defeated" print "you survived, "+str(w)+" waves and have killed, "+str(o)+" orcs" ```
3,146,767
I know that if we have $3$ points $a$, $b$,and $c$ in $\mathbb R^3$, the area of the triangle is given by: $\frac{1}{2}\|\vec{ab}\times \vec{ac}\|$. This means that the area of the triangle equals half the length of the normal of the plane on which the triangle lays. I don't quite understand how this can be. What other geometrical interpretation can be made of $\frac{1}{2}\|\vec{ab}\times \vec{ac}\|$? [![Triangle](https://i.stack.imgur.com/i3oah.jpg)](https://i.stack.imgur.com/i3oah.jpg)
2019/03/13
[ "https://math.stackexchange.com/questions/3146767", "https://math.stackexchange.com", "https://math.stackexchange.com/users/649007/" ]
The [geometric interpretation](https://en.wikipedia.org/wiki/Cross_product#Geometric_meaning) of the magnitude of the cross product $\left\|\vec v \times \vec w\right\|$ is the area of the **parallellogram** spanned by the vectors $\vec v$ and $\vec w$ and the triangle with vertices $\vec o$, $\vec v$ and $\vec w$ is exactly half of that parallellogram, hence its area is given by $\tfrac{1}{2}\left\|\vec v \times \vec w\right\|$. This interpretation can be clear from the definition (depending on how you define the cross product), or it follows from the formula $\left\|\vec v \times \vec w\right\|=\left\|v\right\|\left\|v\right\|\sin\theta$ (*"base times height"*) where $\theta$ is the angle between $\vec v$ and $\vec w$.
4,295,758
I have set my compression like this for my **NSMutableUrlRequest** on my iphone app (I use Monotouch, but it's a 1:1 API match): ``` var req = new NSMutableUrlRequest (new NSUrl (str), NSUrlRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, 20) req["Accept-Encoding"] = "compress, gzip"; ``` When I download a resource (REST xml file) and monitor the bandwidth in the iPhoneSimulator, it indicates that the file is being downloaded at its raw file size (20 meg, zipped should be 3 meg-ish). On my IIS 6 server I have set compression universally. Using a browser to the file works fine with compression when I monitor its bandwidth usage. Ideas why? ![alt text](https://i.stack.imgur.com/PHcgV.png)
2010/11/28
[ "https://Stackoverflow.com/questions/4295758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172861/" ]
``` if (contents[0] == '\n') memmove(contents, contents+1, strlen(contents)); ``` Or, if the pointer can be modified: ``` if (contents[0] == '\n') contents++; ```
49,290,374
I have a table who have creation date like: ``` SELECT [CreationDate] FROM Store.Order ``` So each register have one datetime like: ``` 2018-03-14 00:00:00.000 2017-04-14 00:00:00.000 2017-06-14 00:00:00.000 ``` I want to know how to `COUNT` only register of Date equals to current month and year, for example in this case,if I only have one register in month 03 I just get 1 on count, how can I achieve it? Regards
2018/03/15
[ "https://Stackoverflow.com/questions/49290374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9452841/" ]
Here is one option: ``` SELECT COUNT(*) FROM Store.Order WHERE CONVERT(varchar(7), [CreationDate], 126) = CONVERT(varchar(7), GETDATE(), 126); ``` [Demo ----](http://rextester.com/NLHQPE86189) We can convert both the creation date in your table and the current date into `yyyy-mm` strings, and then check if they be equal.
45,735,671
I am using [GlideJS](http://glide.jedrzejchalubek.com/) to display a carousal. The height of each item in this carousal is different and I have therefore set the property: ``` autoheight: true ``` The problem is when I try to display the carousal in a collapsed div with the autoheight property set to 'true' the carousal is not displayed. When the autoheight property is set to false the carousal does display but then the height of the items is fixed. To illustrate this problem I have created the following Fiddle: <https://jsfiddle.net/7dma7L84/21/> How can I display the carousal in a collapsed div with auto height for each item?
2017/08/17
[ "https://Stackoverflow.com/questions/45735671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3398797/" ]
What you need to do is codesplitting. Without code splitting + are loaded at the first start ``` import Login from './Login' import Home from './Home' const App = ({ user }) => ( <Body> {user.loggedIn ? <Route path="/" component={Home} /> : <Redirect to="/login" />} <Route path="/login" component={Login} /> </Body> ) ``` With code splitting: ``` import Async from 'react-code-splitting' import Login from './Login' const Home = () => <Async load={import('./Home')} /> const LostPassword = props => <Async load={import('./LostPassword')} componentProps={props}/> const App = ({ user }) => ( <Body> {user.loggedIn ? <Route path="/" component={Home} /> : <Redirect to="/login" />} <Route path="/login" component={Login} /> <Route path="/lostpassword" component={LostPassword} /> </Body> ) ``` There are several ways of doing this, for example: <https://github.com/didierfranc/react-code-splitting>
58,255,047
How do I display the information data using the ID in the url example is www.thatsite.com/?id=1092 and it will display the data of the 1092 ID ``` <?php $connect = mysqli_connect("localhost", "xxxxxxx", "xxxx","xxxx"); $query = "SELECT `name`, `age`, `xxxxx` , `xxxxx`, `image` FROM `profiles` WHERE `id` = $id LIMIT 1"; $id=$_GET['id']; $result = mysqli_query($connect, $query,$id); while ($row = mysqli_fetch_array($result)) { echo $row['name']; echo $row['xxxx'];x echo $row['age']; echo $row['xxxxxxx']; echo $row['image']; } ?> ```
2019/10/06
[ "https://Stackoverflow.com/questions/58255047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your code is full of security holes. It is prone to sql injection, xss attack, csrf, html injection. I have re-written it to circumvent all the issues. **1.) Sql Injection** is now mitigated using prepare queries **2.) Html injection** is mitigated using **intval** for integer variables and **strip\_tags** for strings. you can read more about data validations and sanitization in php to see more options available **3.) xss attack** has been mitigated via **htmlentities()**. you can also use **htmlspecialchars()**. Read more about all this things see better secured codes below ``` <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "ur dbname"; // Create connection $connect = new mysqli($servername, $username, $password, $dbname); // Check connection if ($connect->connect_error) { die("Connection failed: " . $connect->connect_error); } // ensure that the Id is integer using intval $id = intval($_GET["id"]); // if id is a string. you can strip all html elements using strip_tags //$id = strip_tags($_GET["id"]); //Avoid sql injection using prepared statement // prepare and bind $stmt = $connect->prepare("SELECT name, age , xxxxx, image FROM profiles WHERE id = ? LIMIT 1"); // id is integer or number use i parameter $stmt->bind_param("i", $id); // id is integer or number use s parameter //$stmt->bind_param("s", $id); $stmt->execute(); $stmt -> store_result(); $stmt -> bind_result($name, $age, $xxxxx, $image); while ($stmt -> fetch()) { // ensure that xss attack is not possible using htmlentities echo "your Name: .htmlentities($name). <br>"; echo "your age: .htmlentities($age). <br>"; echo "your xxxxx: .htmlentities($). <br>"; echo "your image name: .htmlentities($image). <br>"; } $stmt->close(); $connect->close(); ?> ```
71,729,307
I'm a beginner in Python and flask. I am going through the Flask tutorial up to [Define and Access the Database](https://flask.palletsprojects.com/en/2.1.x/tutorial/database/) section. wrote up all the codes, saved, and execute the command below to initalise the DB. `flask init-db` However, I get the error on the terminal as flows `FileNotFoundError: [Errno 2] No such file or directory: /Desktop/flask-tutorial/instance/schema.sql'` I double-checked the codes to find out what was wrong, searched through StackOverflow,w and find some similar issues but they end up not working for me. **--Addition--** **\_\_init\_\_py** ``` import os from flask import Flask def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, world! this is my first flask app' from . import db db.init_app(app) return app ``` **db.py** ``` import sqlite3 import click from flask import current_app, g from flask.cli import with_appcontext def init_db(): db = get_db() with current_app.open_instance_resource('schema.sql') as f: db.executescript(f.read().decode('utf8')) @click.command('init-db') @with_appcontext def init_db_command(): """Clear the existing data and create new tables.""" init_db() click.echo('Initialized the database.') def get_db(): if 'db' not in g: g.db = sqlite3.connect( current_app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES ) g.db.row_factory = sqlite3.Row return g.db def close_db(e=None): db = g.pop('db', None) if db is not None: db.close() def init_app(app): app.teardown_appcontext(close_db) app.cli.add_command(init_db_command) ``` **Tree** ``` . ├── flaskr │   ├── db.py │   ├── __init__.py │   ├── __pycache__ │   │   ├── db.cpython-39.pyc │   │   └── __init__.cpython-39.pyc │   └── schema.sql ├── instance │   └── flaskr.sqlite ```
2022/04/03
[ "https://Stackoverflow.com/questions/71729307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18600140/" ]
Your code has `open_instance_resource`, which is looking for `instance/schema.sql` - but your `schema.sql` is not there. The original code has `open_resource`, which looks relative to `root_path`.
30,975,060
i'm new to android developing and started to develop an booking app. There is a calendar view and i want to disable booked dates in that calendar. I found out that disabling feature is not there in android default calendar. so could you please help me to find a good custom calendar view that can disable specific dates. I need a resource or a library. Thank you!
2015/06/22
[ "https://Stackoverflow.com/questions/30975060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2214782/" ]
Include CalendarPickerView in your layout XML. ``` <com.squareup.timessquare.CalendarPickerView android:id="@+id/calendar_view" android:layout_width="match_parent" android:layout_height="match_parent"/> ``` In the onCreate of your activity/dialog or the onCreateView of your fragment, initialize the view with a range of valid dates as well as the currently selected date. ``` Calendar nextYear = Calendar.getInstance(); nextYear.add(Calendar.YEAR, 1); CalendarPickerView calendar = (CalendarPickerView) findViewById(R.id.calendar_view); Date today = new Date(); calendar.init(today, nextYear.getTime()).withSelectedDate(today); ``` ![enter image description here](https://i.stack.imgur.com/Jv9Mc.png) github link- <https://github.com/square/android-times-square>
12,106,280
In my code, I want to remove the img tag which doesn't have src value. I am using **HTMLAgilitypack's HtmlDocument** object. I am finding the img which doesn't have src value and trying to remove it.. but it gives me error Collection was modified; enumeration operation may not execute. Can anyone help me for this? The code which I have used is: ``` foreach (HtmlNode node in doc.DocumentNode.DescendantNodes()) { if (node.Name.ToLower() == "img") { string src = node.Attributes["src"].Value; if (string.IsNullOrEmpty(src)) { node.ParentNode.RemoveChild(node, false); } } else { ..........// i am performing other operations on document } } ```
2012/08/24
[ "https://Stackoverflow.com/questions/12106280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1567913/" ]
It seems you're modifying the collection during the enumeration by using `HtmlNode.RemoveChild` method. To fix this you need is to copy your nodes to a separate list/array by calling e.g. [`Enumerable.ToList<T>()`](http://msdn.microsoft.com/en-us/library/bb342261.aspx) or [`Enumerable.ToArray<T>()`](http://msdn.microsoft.com/en-us/library/bb298736.aspx). ``` var nodesToRemove = doc.DocumentNode .SelectNodes("//img[not(string-length(normalize-space(@src)))]") .ToList(); foreach (var node in nodesToRemove) node.Remove(); ``` If I'm right, the problem will disappear.
13,615,562
Hi I really have googled this a lot without any joy. Would be happy to get a reference to a website if it exists. I'm struggling to understand the [Hadley documentation on polar coordinates](http://docs.ggplot2.org/current/coord_polar.html) and I know that pie/donut charts are considered inherently evil. That said, what I'm trying to do is 1. Create a donut/ring chart (so a pie with an empty middle) like the [tikz ring chart](https://tex.stackexchange.com/questions/17898/how-can-i-produce-a-ring-or-wheel-chart-like-that-on-page-88-of-the-pgf-manu) shown here 2. Add a second layer circle on top (with `alpha=0.5` or so) that shows a second (comparable) variable. Why? I'm looking to show financial information. The first ring is costs (broken down) and the second is total income. The idea is then to add `+ facet=period` for each review period to show the trend in both revenues and expenses and the growth in both. Any thoughts would be most appreciated Note: Completely arbitrarily if an MWE is needed if this was tried with ``` donut_data=iris[,2:4] revenue_data=iris[,1] facet=iris$Species ``` That would be similar to what I'm trying to do.. Thanks
2012/11/28
[ "https://Stackoverflow.com/questions/13615562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675004/" ]
I don't have a full answer to your question, but I can offer some code that may help get you started making ring plots using `ggplot2`. ``` library(ggplot2) # Create test data. dat = data.frame(count=c(10, 60, 30), category=c("A", "B", "C")) # Add addition columns, needed for drawing with geom_rect. dat$fraction = dat$count / sum(dat$count) dat = dat[order(dat$fraction), ] dat$ymax = cumsum(dat$fraction) dat$ymin = c(0, head(dat$ymax, n=-1)) p1 = ggplot(dat, aes(fill=category, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) + geom_rect() + coord_polar(theta="y") + xlim(c(0, 4)) + labs(title="Basic ring plot") p2 = ggplot(dat, aes(fill=category, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) + geom_rect(colour="grey30") + coord_polar(theta="y") + xlim(c(0, 4)) + theme_bw() + theme(panel.grid=element_blank()) + theme(axis.text=element_blank()) + theme(axis.ticks=element_blank()) + labs(title="Customized ring plot") library(gridExtra) png("ring_plots_1.png", height=4, width=8, units="in", res=120) grid.arrange(p1, p2, nrow=1) dev.off() ``` ![enter image description here](https://i.stack.imgur.com/dFKY5.png) **Thoughts:** 1. You may get more useful answers if you post some well-structured sample data. You have mentioned using some columns from the `iris` dataset (a good start), but I am unable to see how to use that data to make a ring plot. For example, the ring plot you have linked to shows proportions of several categories, but neither `iris[, 2:4]` nor `iris[, 1]` are categorical. 2. You want to "Add a second layer circle on top": Do you mean to superimpose the second ring directly on top of the first? Or do you want the second ring to be inside or outside of the first? You could add a second internal ring with something like `geom_rect(data=dat2, xmax=3, xmin=2, aes(ymax=ymax, ymin=ymin))` 3. If your data.frame has a column named `period`, you can use `facet_wrap(~ period)` for facetting. 4. To use `ggplot2` most easily, you will want your data in 'long-form'; `melt()` from the `reshape2` package may be useful for converting the data. 5. Make some barplots for comparison, even if you decide not to use them. For example, try: `ggplot(dat, aes(x=category, y=count, fill=category)) + geom_bar(stat="identity")`
50,462,402
I starting getting this error on my Angular app: > > The Angular Compiler requires TypeScript >=2.7.2 and <2.8.0 but 2.8.3 > was found instead > > > and when I try to downgrade typescript to the right version doing: `npm install -g [email protected]` it says updated 1 package. when I verify typescript version using `npm view typescript version` I still get 2.8.3 I even tried removing typescript entirely using `npm uninstall -g typescript` but when I verify typescript version again `npm view typescript version` I still get 2.8.3 What are the commands to properly purge and restore typescript to a previous version such as 2.7.2? I'm running node v10.0.0 and npm v6.0.1 When I run `npm list -g typescript` I see the correct version coming 2.7.2 but still version 2.8.3 is installed somehow globally
2018/05/22
[ "https://Stackoverflow.com/questions/50462402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/931511/" ]
You should do `npm install typescript@'>=2.7.2 <2.8.0'`. This will install the correct typescript your project needs. Make sure you run this inside your Angular project. On Windows, you should use double quotes instead of single quotes, like so: ``` npm install typescript@">=2.7.2 <2.8.0" ``` Otherwise, you'll get `The system cannot find the file specified.`.
21,871
(I am learning Buddhism/dharma in Chinese.) 为什么合掌鞠躬叫"问讯"? 或是说: 为什么现在的"问讯"不是用讲的? "问"和"讯"都是动词吗?还是动词+名词?
2016/11/17
[ "https://chinese.stackexchange.com/questions/21871", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/15752/" ]
依[香光莊嚴](http://www.gaya.org.tw/magazine/v1/2005/59/art1.htm)解釋: 在漢語的構詞上,問訊是由「問」與「訊」二個同義詞所組成的詞彙。 「問」是動詞,意思是「恤問」。 「訊」是動詞,意思是「詢問」。 如果「訊」作名詞,在非佛教場合也還是可以用的。如:打聽消息。 現在的"問訊"也還是有用講的,但通常只在人少的時候。當很多人同時向佛或法師表達恭敬時,沒辦法大家都講,所以就只有身體的動作。 問訊 is composed of two synonyms, 問 and 訊. Both are verbs, meaning "comfort and ask". If 訊 is a noun, it can still be used in non-Buddhist cases. Such as: to inquire about something. Nowadays, 問訊 can still be used orally, but usually only in the cases of 2 or 3 people. When many people express respectful to the Buddha or the masters at the same time, they cannot speak all together. So they only show the body movements.
27,411,468
I'm trying to get my code to go through and pop-out after some math has been done. The file being summed is just lists of numbers on separate lines. Could you give me some pointers to make this work because I am stumped. **EDIT:** I'm trying to get the transition from the main function to Checker function working correctly. I also need some help with slicing. The numbers being imported from the file are like this: ``` 136895201785 155616717815 164615189165 100175288051 254871145153 ``` So in my `Checker` funtion I want to add the odd numbers from left to right together. For example, for the first number, I would want to add `1`, `6`, `9`, `2`, `1`, and `8`. Full Code: ``` def checker(line): flag == False odds = line[1 + 3+ 5+ 9+ 11] part2 = odds * 3 evens = part2 + line[2 + 4 +6 +8 +10 +12] part3 = evens * mod10 last = part3 - 10 if last == line[-1]: return flag == True def main(): iven = input("what is the file name ") with open(iven) as f: for line in f: line = line.strip() if len(line) > 60: print("line is too long") elif len(line) < 10: print("line is too short") elif not line.isdigit(): print("contains a non-digit") elif check(line) == False: print(line, "error") ```
2014/12/10
[ "https://Stackoverflow.com/questions/27411468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4347640/" ]
`lambda args: expr` is not a special magic feature, it's just nice shorthand for ``` def someFunc(args): return expr ``` which is mainly useful when you need a small function with a simple expression for its body and you don't care about the name. If we used familiar syntax, the `closest()` method would be: ``` def closest(self,*points): def keyFunc(x): return float(x-self) return min(points,key=keyFunc) ``` that is, it creates a small, one off function which does a little bit of calculation depending on `self` and its argument `x`, and passes that into the `min()` builtin function. As Ostrea explains, `min(seq, key=f)` returns the item *x* in `seq` which minimizes `f(`*x*`)`
218,488
My house's 240v circuit for the cooktop is a /2 cable. (black, white and bare copper). The new whirlpool cooktop has a 3 wire connection (black,red and bare copper). Whirlpool's instructions do not cover this wiring example. Their 3 wire to 3 wire example assumes you have a red wire from the house. Is there an easy path to wiring up the cooktop?
2021/03/10
[ "https://diy.stackexchange.com/questions/218488", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/131410/" ]
If that is indeed a 240V circuit, the white wire *kinda shoulda* been re-marked with tape to indicate that it is a hot wire. Prior to about 20 years ago, they were allowed to skip the marking "if the usage was obvious". The reason for the change is that their "obvious" is not your "obvious". If you are confident that it is indeed 240V, remark that white wire with black or colored electrical tape. (red is *perfectly fine*). --- Code does not require you to mark different *kinds* of hot by their function... *any* hot can be *any* color not reserved for other things. \* White and gray are reserved for neutral. Green, yellow w/green stripe, and bare are reserved for safety ground. \* with an *extremely* obscure exception relating to 3-phase power, that isn't even worth mentioning.
3,588
I am getting a 404 error when trying to go to my admin page was working fine earlier today. Haven't changed anything since I last logged in and the only thing I was doing was assigning products to categories. <http://mytempsite.net/gotie/admin> **WHAT IVE TRIED SO FAR** Delete the following file:- app/etc/use\_cache.ser <-- **I could not find the file in ftp or ssh** then tried doing this Opened PhpMyAdmin - Went to my database - Clicked SQL - Ran the following SQL Query: SET FOREIGN\_KEY\_CHECKS=0; UPDATE `core_store` SET store\_id = 0 WHERE code='admin'; UPDATE `core_store_group` SET group\_id = 0 WHERE name='Default'; UPDATE `core_website` SET website\_id = 0 WHERE code='admin'; UPDATE `customer_group` SET customer\_group\_id = 0 WHERE customer\_group\_code='NOT LOGGED IN'; SET FOREIGN\_KEY\_CHECKS=1;
2013/05/09
[ "https://magento.stackexchange.com/questions/3588", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/1847/" ]
First, are you the only admin user? Second, In your app/etc/local.xml, look for: ``` <admin> <routers> <adminhtml> <args> <frontName><![CDATA[admin]]></frontName> </args> </adminhtml> </routers> </admin> ``` Does it say admin or something else? Third, go in your core\_config\_data table and try to locate these variables (lines 226 + 229): admin/url/custom admin/url/custom\_path ![core_config_data](https://i.stack.imgur.com/8379L.png) Do you have any caching enabled, or have any redirects setup? Delete the Cache manually (var/cache/). I would enable your server logs (a quick look at GoDaddy has this tutorial showing how to do it: [Working with Error Logs](http://support.godaddy.com/help/article/1197/working-with-error-logs) Attempt to turn on Magento Logging (it should be on for dev sites). You can do this by going into "core\_config\_data" and look for a dev/log/active. It should be set to 1 for logging (yours is probably set to 0). ![Logging](https://i.stack.imgur.com/FEvEj.png) I would also go further and turn on Developer Mode (which should also be on for dev sites). You can do this by going to your index.php file and changing this: ``` if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) { Mage::setIsDeveloperMode(true); } #ini_set('display_errors', 1); ``` to this: ``` //if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) { Mage::setIsDeveloperMode(true); //} ini_set('display_errors', 1); ``` **After talking to the user, it turns out it was a file error. I referred him to setup a Diff of his core files and setup a version control system.**
42,570,539
When I run `docker-compose up -d`, docker always creates container name and network name prepended with the folder name that contains `docker-compose.yml`file. I can specify the container name as follows: ``` nginx: container_name: nginx build: context: . dockerfile: .docker/docker-nginx.dockerfile ``` But how can I specify the network name so that it doesn't prepend folder name to it? Thanks.
2017/03/03
[ "https://Stackoverflow.com/questions/42570539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1072698/" ]
Docker Prepends the current folder name with all the components name created using docker compose file. Eg : If the current folder name containing the docker-compose.yml file is test, all the volumes,network and container names will get test appended to it. In order to solve the problem people earlier proposed the idea of using **-p** flag with docker-compose command but the solution is not the most feasible one as a project name is required just after the -p attribute. The project name then gets appended to all the components created using docker compose file. The **Solution** to the above problem is using the **name** property as in below. ``` volumes: data: driver: local name: mongodata networks: internal-network: driver: bridge name: frontend-network ``` This volume can be referred in the service section as ``` services: mongo-database: volumes: - data:/data/db networks: - internal-network ``` The above **name** attribute will prevent docker-compose to prepend folder name. Note : For the container name one could use the property **container\_name** ``` services: mongo-database: container_name: mongo ```
61,852
*How do you even read these runes?* [![Wingdinglish](https://i.stack.imgur.com/7yv5Qm.png)](https://i.stack.imgur.com/7yv5Q.png) *Note: Click image for full size*
2018/03/13
[ "https://puzzling.stackexchange.com/questions/61852", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/46455/" ]
As described in [Gareth's answer](https://puzzling.stackexchange.com/a/61853/20521) (go upvote that if you haven't already), the first step is to notice that: > > the white background isn't all quite white, and a bit of colour remapping produces [this image](https://i.stack.imgur.com/IoRmt.png). > > > From there, a bit of cryptogram work led us to what was written in the texts, as well as the scripts they were written in: > > Alphabet: Aquarion Alphabet > > SAYAKA MIKI: Puella Magi Madoka Magica character > > SONY STORAGE FORMAT USING ATRAC: MiniDisc > > > > Alphabet: Human Alphabet in "Is It Wrong to Try to Pick Up Girls in a Dungeon?" > > SHADOW ANGEL: main antagonists of Genesis of Aquarion > > LEAD WEAPON IN CLUE: pipe > > > > Alphabet: Konosuba Alphabet > > DOKUROXY: Villain in Mahou Tsukai Pretty Cure! > > LAST BUT BLANK LEAST: not > > > > Alphabet: Luna Alphabet (Little Witch Academia) > > ELSIE: The World God Only Knows character > > SPEEDY PARR KID: Dash > > > > Alphabet: Precure Alphabet > > CH POSTAL COMPANY: Company in Violet Evergarden > > TYPE OF CORRECTION OR RAY: gamma > > > > Alphabet: Imanity Alphabet (No Game No Life) > > DR. GEL: antagonist in Space Dandy > > GARACHINE AIRPORT CODE: GHE > > > > Alphabet: Unovian Alphabet (Pokémon) > > ORARIO: City in Is It Wrong to Try to Pick Up Girls in a Dungeon? > > MUSICAL BUILDUP OF LOUDNESS: crescendo > > > > Alphabet: Witch runes (Puella Magi Madoka Magica) > > EXPLOOOSION: Megumin's [signature spell chant](https://www.youtube.com/watch?v=coYieIF8I5M) in Konosuba > > TRACK EIGHT FROM STARRS ALBUM RINGO: "Six O'Clock" > > > > Alphabet: Space Dandy Alphabet > > ENCHANTED PARADE: Little Witch Academia series subtitle > > WORD AFTER ZERO FLUTE RHYMING WITH DRINK: countersink > > > > Alphabet: Zentradi Alphabet (Super Dimension Fortress Macross) > > BEST WISHES: Pokémon series subtitle > > WORD AFTER EUROPEAN OR TRADE: union > > > > Alphabet: Leiden Alphabet (Violet Evergarden) > > OLD DEUS: race in No Game No Life > > THINK WORK SERVE SCHOOL INITS: TSU > > > > Alphabet: Hell Alphabet (The World God Only Knows) > > MY BOYFRIEND IS A PILOT (Super Dimension Fortress Macross song) > > EARLY BYZANTINE GOLD COIN: solidus > > > We can notice that for each block of text, > > The first line refers to one of the anime the scripts come from, and the second line gives a word that represents a symbol. For instance, solidus is another name for slash, and the mathematical symbol for union is ∪. > > > Then @Deusovi brilliantly noticed that > > The symbols described are all part of the [Moon type](https://en.wikipedia.org/wiki/Moon_type) writing system, giving the letters, in order: HIMTEEKIVUDS > > > The final step is to > > Reorder the blocks in a cycle, in which the anime reference for one block is where the alphabet for the next block in the cycle comes from. The starting point of the cycle is the Luna Alphabet block, as indicated by the arrow pointing to it in the image. Doing so gives us the letters TSUKIHIME DEV: > > > > [![enter image description here](https://i.stack.imgur.com/ALjYR.png)](https://i.stack.imgur.com/ALjYR.png) > > > Giving us the final answer... > > Type-Moon. Quite fitting. > > > As a side note, > > The initials to this puzzle's title, Unintelligible Batch of Wingdinglish, are the same as those of Unlimited Blade Works, another TYPE-MOON creation. > > >
3,070,274
I'm looking for a way to do something like this: ``` // style.css @def borderSize '2px'; .style { width: borderSize + 2; height: borderSize + 2; } ``` where the width and height attributes would end up having values of 4px.
2010/06/18
[ "https://Stackoverflow.com/questions/3070274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317404/" ]
Sometimes I use the following: ``` @eval BORDER_SIZE_PLUS_2 2+2+"px"; /* GWT evaluates this at compile time! */ ``` Oddly, this only works, if you don't put any spaces between the `+` operator and the operands. Also, in @eval you can't use constants that were previously defined by @def. You can however use constants that are defined as static fields in one of your Java classes: ``` @eval BORDER_SIZE_PLUS_2 com.example.MyCssConstants.BORDER_SIZE+2+"px"; ``` Or you could let the calculation be performed completely by Java: ``` @eval WIDTH com.example.MyCssCalculations.width(); /* static function, no parameters! */ @eval HEIGHT com.example.MyCssCalculations.height(); .style { width: WIDTH; height: HEIGHT; } ``` But what I would actually like to do is very similar to your suggestion: ``` @def BORDER_SIZE 2; .style { width: value(BORDER_SIZE + 2, 'px'); /* not possible */ height: value(BORDER_SIZE + 3, 'px'); } ``` I don't think that's possible in GWT 2.0. Maybe you find a better solution - here's the [Dev Guide](http://code.google.com/webtoolkit/doc/latest/DevGuideClientBundle.html#CssResource) page on this topic.
49,470,764
Suppose you have 14 bits. How do you determine how many integers can be represented in binary from those 14 bits? Is it simply just 2^n? So 2^14 = 16384? Please note this part of the question: "how many INTEGERS can be represented in BINARY...". That's where my confusion lies in what otherwise seems like a fairly straightforward question. If the question was just asking how many different values or numbers can be represented from 14 bits, than yes, I'm certain it's just 2^n.
2018/03/24
[ "https://Stackoverflow.com/questions/49470764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8716929/" ]
The answer depends on whether you need signed or unsigned integers. If you need unsigned integers then using `2^n` you can represent integers from 0 to 2^n exclusive. e.g. n=2; 2^2=4 you can represent the integers from 0 to 4 exclusive (0 to 3 inclusive). Therefore with n bits, you can represent a maximum unsigned integer **value** of `2^n - 1`, but a total count of `2^n` different integers including 0. If you need signed integers, then half of the values are negative and half of the values are positive and 1 bit is used to indicate whether the integer is positive or negative. You then calculate using using `2^n/2`. e.g. n=2; 2^2/2=2 you can represent the integers from -2 to 2 exclusive (-2 to +1 inclusive). 0 is considered postive, so you get 2 negative values (-2, -1) and 2 positive values (0 and +1). Therefore with n bits, you can represent signed integers **values** between `(-) 2^n/2` and `(+) 2^n/n - 1`, but you still have a total count of `2^n` different integers as you did with the unsigned integers.
186,718
The Bearer: Background ---------------------- --- On Alternate Earth, studies and cases have shown that a *small percentage of the population (10%) is responsible for 90% of the bad luck*. **These people are targeted by bad luck**, almost by cosmic forces: they are struck by lightning out of a sunny day, hit by cars whose brakes give out, and slip on banana peels in a no-eating zone. Perhaps the luck is equalized somehow, because these people generally survive or are compensated for the situation. The general populace once labelled these people as 'clumsy airheads', but following some high profile cases, they have since come to be known as **'Bearers'**, generally ranked class-F through class-A, each about 10x rarer and with worse luck than the next. **Most of the time, disasters from Bearers do little harm to others**, and class-F through class-B have relatively tame bad luck, ranging respectively from the frequent stubbing of toes and slipping on bananas, to occasional injury and minor destruction of property. Class-A bearers have a grade of bad luck involving weekly escapes from death, ranging from car crashes, apartment fires, and lightning strikes. However, at a level 100x rarer and deadlier than class A, Class S Bearers are very rare, sitting at 1/100,000,000 people **but are disproportionately represented in history**: The Explosion of Black Tom Island (1875), the gunpowder explosion of Abbeville (1773), multiple unstoppable wildfires, the 1987 Stock Market Crash, and a [failed rocket launch that killed a cow in Cuba](http://www.digitaljournal.com/tech-and-science/science/herd-shot-around-the-world-the-last-east-coast-polar-launch/article/567614) (1986), to name a few. Eventually, the world came to know about the potential disasters that could be wreaked by a single bearer in recent times, in Robert's Case (Misc section). After being hit by multiple tsunamis, hurricanes, and other natural disasters caused by one Bearer, the governments decided to change their stance on bearers, to prevent similar tragedies. Summary: Bearer Information --------------------------- --- [![Tetroid vs Earthquakes in Damage](https://i.stack.imgur.com/J1vD2.jpg)](https://i.stack.imgur.com/J1vD2.jpg) * A Bearer's bad luck is related to the recently discovered *Tetroid Waves* * **The Bad Luck rating can be measured from Tetroid waves** * E is 10x more bad luck (Tetroids) than F, D is 10x stronger than E, and so on. * The Tetroid rating from F to S can be equated to local earthquakes (diagram above) * All humans emit tetroids, Bearers are simply humans with more Tetroids * It is easy to track Bearers, especially B to S-class, but Tetroid waves can be blocked by some common metals * Blocking Tetroid waves does not prevent disasters, but does impact interference (see below)\* * The strength of Tetroid waves emitted prior correspond to the bad luck event that will ensue * Luck seems to follow laws of conservation; an event of bad luck is equalized by almost equal good luck eventually * A Bearer can emit Tetroids above their class when in distress, and generally the event triggered aims to solve the Bearer's problems * Tetroid wave interference happens when two or more Bearers are nearby * **Paradoxically, destructive interference (cancellation of bad luck) happens when multiple Bearers share similar harmonious emotional states** * Conversely, constructive interference (amplification of bad luck) happens when multiple Bearers are emotionally chaotic Question -------- --- How should the World interact with Bearers, knowing that their numbers are steadily increasing, to best mitigate global and local disasters? The best answer would also be *humane, properly integrate modern society with the Bearers, and prevent unwarranted discrimination where possible*. Also, out of interest, who is responsible for the compensation, in the even of an accident? Will insurance rates for Bearers be disproportionately high, or will a common fund exist to support them? Note: This happens on Alternate Earth, in reality we unfortunately cannot blame stubbed toes on Tetroid waves. Misc: Robert's Case ------------------- --- The following case is for background and humor, does not provide too much for question details: > > Up until a certain historically significant case, Bearers were not well-quantified or tracked. Domestic Class-S Bearers were not well-monitored or mitigated, and many remained unknown. > > > > This all changed after a case dealing with Robert 'Bob' Murphy, a seemingly ordinary, if not bad, conductor, who, unknown at the time, was also an S-class Bearer. After a failed concert, the depressed Bob was further implicated by an issue with pyrotechnics, which resulted in multiple casualties and many injuries. Following which Bob was framed by a Syndicate organization, and, charged with multiple murders, sentenced to the electric chair. > > > > As it turns out, Bob was certainly a bad orchestra conductor, but a good conductor in general; on the hour of his scheduled execution, a critical lightning storm erupted and struck the facility and multiple backup power plants, during which Bob escaped electrocution at the chair for electrocution from the sky. Seizing the chaos, Bob escaped the facility. > > > > All following attempts to capture Bob were primarily successful, but no results at containment or execution worked: prison vehicles carrying Bob would get flat tires or get into uncanny accidents. Eventually the government gave up and decided to just exile Bob into the ocean with some supplies and a fishing boat, hoping he'd maybe drift onto the shores of their rival country. **This was their worst idea yet.** > > > > Bob had the bad luck to end up in several tsunamis and hurricanes across the world, causing immense damage to multiple countries, before the United Nations, after an intense investigation, unanimously agreed to compensate him and exonerate him of the crimes he did not commit. To this day, Robert Murphy lives somewhere on an undisclosed island in the Bermuda Triangle. > > > > Since then, governments around the world have changed their stance and system on the treatment of Bearers, hoping to prevent a similar tragedy. > > >
2020/10/03
[ "https://worldbuilding.stackexchange.com/questions/186718", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/68848/" ]
***Two Roads:*** There are two directions your society can take with regards to bearers, and it somewhat depends on how the actual "ability" functions. The tetroid wave situation is complex, and I think only you fully understand it. Both of these solutions can be applied, or can be exclusive. It's up to you. 1. **Exile**: If the ability doesn't effect disasters outside the bearers, find a geologically stable place isolated from the bulk of humanity and offer a sliding scale of requirements and incentives to these folks to go there. S-scale people might be required to go there but offered vast sums of money in compensation for their troubles, in the same way a typhoid carrier might be required to isolate from those who are at risk. Those with the mildest cases will have no requirement, but will be offered lucrative jobs and compensations to go there. This will be a shifting solution, as asteroids crash there, aliens show up, and hurricanes materialize out of no where to lash (for example) the Aleutian Islands or Siberia. Concentrating these folks may magnify the effect (additive), or bad luck/good luck might cancel itself out and these folks will balance. If there is a hereditary element to this, there is a risk in concentrating this much potential into one breeding population. 2. **Control**: If there is a net total of good and bad luck in the world, and these people just concentrate it, then use them as a guide for these forces. Hurricanes will track towards them, so shift weather patterns to end droughts or avoid direct impacts on major cities. In a real crisis, an S-class talent can probably avert a nuclear attack because the bomb will fizzle out. Nations can pay into an international fund and buy, sell, and trade bad luck in the form of residence for these folks. Cuba gets hit with hurricanes all the time, so why not get paid to sponsor people, then make your nation hurricane-proof?
128,386
I have these scripts I made that work absolutely perfectly as I need them to. Is there any improvements that can be done to these scripts and make them more efficient for Mobile Platforms? Or even just combine them into one script? These 4 scripts are just about identical except that each one controls a different obstacle and I have it that way so I can have more control over each individual obstacle. Does that make sense? (For instance, I want one obstacle to start spawning 10 seconds into the game and another to spawn RIGHT when the game starts). Obstacle 1: ``` using UnityEngine; using System.Collections; [System.Serializable] // Serialize this so it looks neater in the inspector public class Obstacle1 // Hammer Obstacle { public GameObject hammer; // The first obstacle gameobject. This is attached in the inspector. public Vector3 spawnHPosValues; // Where the first obstacle will be spawned at on the X,Y,Z plane. public int hCount; // This is the count of the first obstacle in a given wave. // public float hSpawnWait; // Time in seconds between next wave of obstacle 1. public float hStartGameWait; // Time in seconds between when the game starts and when the first obstacle start spawning. public float hWaveSpawnWait; // Time in seconds between waves when the next wave of obstacle 1 will spawn. } public class SpawnHammers : MonoBehaviour { public Obstacle1 obstacle1; // Reference to the Obstacle 1 class // void Start () { StartCoroutine (SpawnHammer ()); // at the beginning of the game, start to function SpawnHammer() // } IEnumerator SpawnHammer () { yield return new WaitForSeconds(obstacle1.hStartGameWait); while (true) { for (int i = 0; i < obstacle1.hCount; i++) { Vector3 spawnPosition = new Vector3 (Random.Range(-obstacle1.spawnHPosValues.x, obstacle1.spawnHPosValues.x), obstacle1.spawnHPosValues.y, obstacle1.spawnHPosValues.z); // I choose where I spawn the obstacles on the X,Y,Z planes. Only the X // plane will be random Quaternion spawnRotation = Quaternion.identity; // Spawn with NO rotation Instantiate (obstacle1.hammer, spawnPosition, spawnRotation); // Bring the object into the scene yield return new WaitForSeconds(obstacle1.hSpawnWait); // Spawn a new obstacle } yield return new WaitForSeconds (obstacle1.hWaveSpawnWait); // Start the new wave of obstacles } } } ``` Obstacle 2: ``` using UnityEngine; using System.Collections; [System.Serializable] public class Obstacle2 // Road Barrier Obstacle { public GameObject roadBarrier; // The second obstacle gameobject. This is attached in the inspector. public Vector3 spawnRBPosValues; // Where the second obstacle will be spawned at on the X,Y,Z plane. public int rbCount; // This is the count of the second obstacle in a given wave. // public float rbSpawnWait; // Time in seconds between next wave of obstacle 2. public float rbStartGameWait; // Time in seconds between when the game starts and when the second obstacle will start spawning. public float rbWaveSpawnWait; // Time in seconds between waves when the next wave of obstacle 2 will spawn. } public class SpawnRoadBarriers : MonoBehaviour { public Obstacle2 obstacle2; void Start () { StartCoroutine (SpawnRoadBarrier ()); } IEnumerator SpawnRoadBarrier () { yield return new WaitForSeconds(obstacle2.rbStartGameWait); while (true) { for (int i = 0; i < obstacle2.rbCount; i++) { Vector3 spawnPosition = new Vector3 (Random.Range(-obstacle2.spawnRBPosValues.x, obstacle2.spawnRBPosValues.x), obstacle2.spawnRBPosValues.y, obstacle2.spawnRBPosValues.z); Quaternion spawnRotation = Quaternion.identity; Instantiate (obstacle2.roadBarrier, spawnPosition, spawnRotation); yield return new WaitForSeconds(obstacle2.rbSpawnWait); } yield return new WaitForSeconds (obstacle2.rbWaveSpawnWait); } } } ``` Obstacle 3: ``` using UnityEngine; using System.Collections; [System.Serializable] public class Obstacle3 // Cone Obstacle { public GameObject cone; // The third obstacle gameobject. This is attached in the inspector. public Vector3 spawnCPosValues; // Where the third obstacle will be spawned at on the X,Y,Z plane. public int cCount; // This is the count of the third obstacle in a given wave. public float cSpawnWait; // Time in seconds between next wave of obstacle 3. public float cStartGameWait; // Time in seconds between when the game starts and when the third obstacle start spawning. public float cWaveSpawnWait; // Time in seconds between waves when the next wave of obstacle 3 will spawn. } public class SpawnCones : MonoBehaviour { public Obstacle3 obstacle3; void Start () { StartCoroutine (SpawnCone ()); } IEnumerator SpawnCone () { yield return new WaitForSeconds(obstacle3.cStartGameWait); while (true) { for (int i = 0; i < obstacle3.cCount; i++) { Vector3 spawnPosition = new Vector3 (Random.Range(-obstacle3.spawnCPosValues.x, obstacle3.spawnCPosValues.x), obstacle3.spawnCPosValues.y, obstacle3.spawnCPosValues.z); Quaternion spawnRotation = Quaternion.Euler(0f,0f,90f); // rotate 90 degrees on the Z axis Instantiate (obstacle3.cone, spawnPosition, spawnRotation); yield return new WaitForSeconds(obstacle3.cSpawnWait); } yield return new WaitForSeconds (obstacle3.cWaveSpawnWait); } } } ``` Obstacle 4: ``` using UnityEngine; using System.Collections; [System.Serializable] public class Obstacle4 // Barrel Obstacle { public GameObject barrel; // The fourth obstacle gameobject. This is attached in the inspector. public Vector3 spawnBPosValues; // Where the fourth obstacle will be spawned at on the X,Y,Z plane. public int bCount; // This is the count of the fourth obstacle in a given wave. public float bSpawnWait; // Time in seconds between next wave of obstacle 4. public float bStartGameWait; // Time in seconds between when the game starts and when the fourth obstacle start spawning. public float bWaveSpawnWait; // Time in seconds between waves when the next wave of obstacle 4 will spawn. } public class SpawnBarrels : MonoBehaviour { public Obstacle4 obstacle4; void Start () { StartCoroutine (SpawnBarrel ()); } IEnumerator SpawnBarrel () { yield return new WaitForSeconds(obstacle4.bStartGameWait); while (true) { for (int i = 0; i < obstacle4.bCount; i++) { Vector3 spawnPosition = new Vector3 (Random.Range(-obstacle4.spawnBPosValues.x, obstacle4.spawnBPosValues.x), obstacle4.spawnBPosValues.y, obstacle4.spawnBPosValues.z); Quaternion spawnRotation = Quaternion.Euler(0f,0f,90f); // rotate 90 degrees on the Z axis Instantiate (obstacle4.barrel, spawnPosition, spawnRotation); yield return new WaitForSeconds(obstacle4.bSpawnWait); } yield return new WaitForSeconds (obstacle4.bWaveSpawnWait); } } } ```
2016/05/14
[ "https://codereview.stackexchange.com/questions/128386", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/103199/" ]
1. **Bracket alignment**. For some reason, all obstacle classes and `while`-loops are written with vertically aligned bracket, while the `MonoBehaviour`s are egyptians. > > [Coding style] create a consistent look to the code, so that readers can focus on content, not layout. - [C# Coding Convention](https://msdn.microsoft.com/en-us/library/ff926074.aspx) > > > And, the commonly agreed convention for this one is vertically aligned, 2. **Naming**. 1. Do not abbreviate the variable name... Go for the full name, with exception of some **short** lambda functions', event handlers' parameters and `for`-loops' variables. At first, I thought they were some kind of hungarian notation, and had trouble figuring out what kind of handles are they? It was until I saw the next obstacle class that I realize it was `h` for `Hammer`! ``` public class Obstacle1 // Hammer Obstacle { public GameObject hammer; // The first obstacle gameobject. This is attached in the inspector. public Vector3 spawnHPosValues; // Where the first obstacle will be spawned at on the X,Y,Z plane. public int hCount; // This is the count of the first obstacle in a given wave. // public float hSpawnWait; // Time in seconds between next wave of obstacle 1. public float hStartGameWait; // Time in seconds between when the game starts and when the first obstacle start spawning. public float hWaveSpawnWait; // Time in seconds between waves when the next wave of obstacle 1 will spawn. } ``` So, do use the full name, like `spawnHammerPosition`, `hammerCount` and so on... It does irk a bit, but I will refactor this with other `Obstacle`s later. 2. In this bit of code ``` var spawnRotation = Quaternion.identity; // Spawn with NO rotation Instantiate(hammer.GameObject, spawnPosition, spawnRotation); // Bring the object into the scene ``` Instead of `spawnRotation`, you could have gone with `noRotation` and gotten rid of the comment. ``` var noRotation = Quaternion.identity; Instantiate(hammer.GameObject, spawnPosition, noRotation); // Bring the object into the scene ``` Or, if you are proficient enough, just inline it. 3. Normally, you should use PascalCase for `public` menbers, and not camelCase. However, Unity3D seems favor the latter. Therefore, it is up to you to decide. (`Quaternion.identity` `*twiches eye*`) 4. When your method name is already `SpawnObstacles`, you don't also have to name the local variable `spawnPosition`, just `position` should suffice. 5. Class name should never be plurial, and never a verb or verb+complement. > > This distinguishes type names from methods, which are named with verb phrases. - [Names of Classes, Structs, and Interfaces](https://msdn.microsoft.com/en-us/library/ms229040(v=vs.110).aspx) > > > `SpawnHammers` -> `HammerSpawner` 3. I don't understand, why you have 4 different classes with the same properties and copy-pasta comments, and, most importantly, shareing the same role of obstacle. Combine them into a single class, subclass if you had to keep the class name for distinction : ``` [Serializable] public abstract class Obstacle { public GameObject gameObject; public Vector3 spawnPosition; public int spawnCount; public float spawnWait; public float startGameWait; public float waveSpawnWait; } public class Hammer : Obstacle { } public class RoadBarrier : Obstacle { } public class Cone : Obstacle { } public class Barrel : Obstacle { } ``` 4. Try keep the line width not too long and don't align the parameters : ``` // compare these two : Vector3 spawnPosition = new Vector3(Random.Range(-cone.spawnCPosValues.x, cone.spawnCPosValues.x), cone.spawnCPosValues.y, cone.spawnCPosValues.z); Vector3 spawnPosition = new Vector3( Random.Range(-cone.spawnCPosValues.x, cone.spawnCPosValues.x), cone.spawnCPosValues.y, cone.spawnCPosValues.z); ``` 5. As you have already noticed, all 4 spawners' implementation are quite repetitive, namely the waiting part. However, each obstacle has its own spawn rotation and position. So, we will have to extract the former while isolating the latter : ``` public abstract class ObstacleSpawnerBase : MonoBehaviour { public Obstacle obstacle; void Start() { StartCoroutine(SpawnObstacles()); } // the repeated pattern in SpawnXXXXs has been extracted to here IEnumerator SpawnObstacles() { yield return new WaitForSeconds(obstacle.startGameWait); while (true) { foreach (var obstacle in SpawnObstaclesImpl()) yield return new WaitForSeconds(obstacle.spawnWait); yield return new WaitForSeconds(obstacle.waveSpawnWait); } } // with the actual implementation detail separated for customization protected abstract IEnumerable<WaitForSeconds> SpawnObstaclesImpl(); } ``` And the concrete obstacle spawner classes : ``` public class HammerSpawner : ObstacleSpawnerBase { protected override IEnumerable SpawnObstaclesImpl() { for (int i = 0; i < obstacle.spawnCount; i++) { // randomize x-axis var position = new Vector3( Random.Range(-obstacle.spawnPosition.x, obstacle.spawnPosition.x), obstacle.spawnPosition.y, obstacle.spawnPosition.z); // bring the object into the scene yield return Instantiate(obstacle.gameObject, position, Quaternion.identity); } } } public class RoadBarrierSpawner : ObstacleSpawnerBase { protected override IEnumerable SpawnObstaclesImpl() { for (int i = 0; i < obstacle.spawnCount; i++) { var position = new Vector3( Random.Range(-obstacle.spawnPosition.x, obstacle.spawnPosition.x), obstacle.spawnPosition.y, obstacle.spawnPosition.z); yield return Instantiate(obstacle.gameObject, position, Quaternion.identity); } } } public class ConeSpawner : ObstacleSpawnerBase { protected override IEnumerable SpawnObstaclesImpl() { for (int i = 0; i < obstacle.spawnCount; i++) { var position = new Vector3( Random.Range(-obstacle.spawnPosition.x, obstacle.spawnPosition.x), obstacle.spawnPosition.y, obstacle.spawnPosition.z); // rotate 90 degrees on the Z axis var rotation = Quaternion.Euler(0f, 0f, 90f); yield return Instantiate(obstacle.gameObject, position, rotation); } } } public class BarrelSpawner : ObstacleSpawnerBase { protected override IEnumerable SpawnObstaclesImpl() { for (int i = 0; i < obstacle.spawnCount; i++) { var position = new Vector3( Random.Range(-obstacle.spawnPosition.x, obstacle.spawnPosition.x), obstacle.spawnPosition.y, obstacle.spawnPosition.z); // rotate 90 degrees on the Z axis var rotation = Quaternion.Euler(0f, 0f, 90f); yield return Instantiate(obstacle.gameObject, position, rotation); } } } ``` Normally, I would use generic here, but Unity3D seems to have some problems with generic `MonoBehaviour`, so I left it out. However, do give them a try : ``` public abstract class ObstacleSpawnerBase<TObstacle> : MonoBehaviour where TObstacle : Obstacle { // ... } public class HammerSpawner : ObstacleSpawnerBase<Hammer> { /*...*/ } public class RoadBarrierSpawner : ObstacleSpawnerBase<RoadBarrier> { /*...*/ } public class ConeSpawner : ObstacleSpawnerBase<Cone> { /*...*/ } public class BarrelSpawner : ObstacleSpawnerBase<Barrel> { /*...*/ } ```
40,802
I need to compute the Drazin inverse $A^D$ of a singular M-matrix $A$, i.e., a matrix in the form $A=\lambda I -P$, where $P$ has nonnegative entries and $\lambda$ is the spectral radius (Perron value) of $P$. I already know the right and left eigenvectors $v$ and $u^T$ of $P$ with eigenvalue $\lambda$ (that is, the vectors in the left and right kernel of $A$). 1) Is there a Matlab subroutine around for computing Drazin inverses? I can't seem to find any, so I had to create my own (which is probably very inefficient) 2) Is there a way to exploit the knowledge of the two nullspaces (and the fact that they are 1-dimensional) to speed up this computation?
2010/10/02
[ "https://mathoverflow.net/questions/40802", "https://mathoverflow.net", "https://mathoverflow.net/users/1898/" ]
If you have access to Matlab, and the matrix is not gigantic you can use the following to calculate the Drazin inverse: 1. Determine the index of $A$, i.e, does $\mathrm{rank}(A^k) = \mathrm{rank}(A^{k+1})$ 2. Solve the linear system $A^{k+1} X = A^k$ 3. Use the fact that $A^D$, the Drazin inverse, is given by $$A^D = A^k X^{k+1}$$ Jim Shoaf, N. C. Central University
4,315
Fred has a puzzle. The instruction sheet, which is separate from the equation,simply says: "Make this equation true. You may ONLY draw ONE, PERFECTLY straight line". The equation is all alone on a blank piece of paper and reads: ``` 5+5+5=550 ``` There are 4 acceptable answers. You must get all 4 for a correct answer.
2014/11/12
[ "https://puzzling.stackexchange.com/questions/4315", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/5180/" ]
1. > > Cross out the equals sign > > > 2. > > Turn the first $+$ into a 4 giving $545+5=550$ > > > 3. > > Turn the second $+$ into a 4 giving $5+545=550$ > > > 4. > > Turn the equals sign into less than or equal to > > >
345,024
I found a theme I really like: <https://de.wordpress.org/themes/online-consulting/> Unfortunately, the "Read more" button is in a position I don't really like: [![enter image description here](https://i.stack.imgur.com/DHg0E.png)](https://i.stack.imgur.com/DHg0E.png) I would vastly prefer if the button was below the post. Sadly, I'm quite unfamiliar with wordpress and don't really know where to get started. I suppose this could be done using CSS? I'm hoping someone can point me in the right direction.
2019/08/13
[ "https://wordpress.stackexchange.com/questions/345024", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173432/" ]
If you go into your Admin section, under Appearance > Edit CSS, you will be able to override the CSS of the theme. In order to find out what the class is, you might want to Inspect the control with Google Chrome's Developer Tools.
65,483,417
I get error: "UnhandledPromiseRejectionWarning: Error [ERR\_HTTP\_HEADERS\_SENT]: Cannot set headers after they are sent to the client", guessing that the problem is with promises, but I don't understand how to fix it. How do I fix my code to avoid this error, but keep the logic and work with the database? ``` router.post("/addNote", (req, res) => { let currentTime = new Date(); currentTime.setUTCHours(currentTime.getUTCHours() + 3); const post = new PostModel({ title: req.body.inputHeader, text: req.body.inputText, author: req.body.author, createdAt: currentTime }); post.save().then(() => { res.json({status: "saved"}); })}); router.get("/getNotes", (req, res) => { PostModel.find().sort({createdAt: 'descending'}).then( (err, notes) => { if (err) res.json(err); res.json(notes); }); }); router.delete("/deleteNote/:id", (req, res) => { PostModel.deleteOne( { _id: req.params.id } ).then((notes) => { if (notes) res.json({status: "deleted"}); res.json({status: "error while deleting"}); }); }); router.put("/updateNote/:id", (req, res) => { PostModel.findByIdAndUpdate( req.params.id, { $set: req.body }, err => { if (err) res.send(err); res.send({status: "updated"}) } ).then((notes) => { if (notes) res.json({status: "update"}); res.json({status: "error while updating"}); }); }); router.get("/getNote", (req, res) => { PostModel.findOne({ _id: req.params.id}).then(post => { if (!post){ res.send({error: "not found"}); } else { res.json(post) } }); }); router.post("/authorize", (req, res) => { // bcrypt.hash ("", saltRounds, (err, hash) => { // console.log(hash); // }); let resultAuthorization = false; if (req.body.login === authorization.login) { resultAuthorization = bcrypt.compareSync(req.body.password, authorization.password); } if (resultAuthorization) res.json({statusAuthorization: "correct"}); res.json({statusAuthorization: "incorrect"}); }); module.exports = router; ```
2020/12/28
[ "https://Stackoverflow.com/questions/65483417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14866914/" ]
You can declare listOfFileSignatures globally, but the signatures are computed asynchronously, so the list will be empty directly after the for loop. FileReader is always asynchronous, so you can't avoid that. One possibility to handle this is to check if the list is full inside onloadend (`listOfFileSignatures.length == uploadedFiles.length`) and then do what you want there. A nicer approach is to use promises, like this: ``` var uploadedFiles = document.getElementById("notes").files; Promise.all([...uploadedFiles].map(file => new Promise((resolve, reject) => { var blob = file; var fileReader = new FileReader(); fileReader.onloadend = function readFirstFourBytes(e) { var arr = (new Uint8Array(e.target.result)).subarray(0, 4); var fileSignature = ""; for (var i = 0; i < arr.length; i++) { fileSignature += arr[i].toString(16); }; resolve(fileSignature); }; fileReader.readAsArrayBuffer(blob); }))).then(function(listOfFileSignatures) { // this will be called once, when all results are collected. console.log(listOfFileSignatures); }); ``` Additionally, reading all bytes and then select just the first 4 byte is inefficient. Improved version: ``` Promise.all([...uploadedFiles].map(file => new Promise((resolve, reject) => { var blob = file; var fileReader = new FileReader(); fileReader.onloadend = function readFirstFourBytes(e) { var arr = new Uint8Array(e.target.result); var fileSignature = ""; for (var i = 0; i < arr.length; i++) { fileSignature += arr[i].toString(16); }; resolve(fileSignature); }; fileReader.readAsArrayBuffer(blob.slice(0, 4)); }))).then(function(listOfFileSignatures) { // this will be called once, when all results are collected. console.log(listOfFileSignatures); }); ```
73,603,252
I have the following data: ``` structure(list(cells = c("Adipocytes", "B-cells", "Basophils", "CD4+ memory T-cells", "CD4+ naive T-cells", "CD4+ T-cells", "CD4+ Tcm", "CD4+ Tem", "CD8+ naive T-cells", "CD8+ T-cells", "CD8+ Tcm", "Class-switched memory B-cells", "DC", "Endothelial cells", "Eosinophils", "Epithelial cells", "Fibroblasts", "Hepatocytes", "ly Endothelial cells", "Macrophages", "Macrophages M1", "Macrophages M2", "Mast cells", "Melanocytes", "Memory B-cells", "Monocytes", "mv Endothelial cells", "naive B-cells", "Neutrophils", "NK cells", "pDC", "Pericytes", "Plasma cells", "pro B-cells", "Tgd cells", "Th1 cells", "Th2 cells", "Tregs"), Response = c(0, 8, 0, 5, 4, 4, 3, 3, 2, 3, 8, 5, 3, 0, 1, 1, 0, 2, 1, 5, 3, 3, 2, 2, 7, 4, 3, 5, 2, 2, 8, 0, 1, 2, 3, 3, 2, 8), No_Response = c(6, 0, 1, 1, 2, 2, 1, 3, 3, 1, 1, 2, 1, 2, 3, 5, 2, 2, 3, 1, 1, 2, 2, 1, 0, 0, 5, 0, 1, 0, 0, 3, 1, 1, 5, 3, 1, 3)), class = "data.frame", row.names = c(NA, -38L )) ``` I want to make a bar chart, so that for each cell type, I get the `Response` number in blue, and the `No_Response` number in red. Something that looks like this more or less: (cells in the x-axis and the values in the y-axis): [![enter image description here](https://i.stack.imgur.com/2vH9f.png)](https://i.stack.imgur.com/2vH9f.png)
2022/09/04
[ "https://Stackoverflow.com/questions/73603252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17945841/" ]
`string` isn't a byte buffer, it has very hard rules for encoding. I can easily see how the normal encoding rules will lengthen or shorten the resulting bytes that you're then using to convert to an integer. In fact, even if everything works perfectly, your string has twice as many bytes as the resulting integer. Have you given half a thought about what happens to the other 4 bytes you're silently dropping? Either do the right thing and use byte buffers (or even better spans), or do your own manual decoding from strings to integers and the other way around. Writing something equally broken, but at least well defined, is pretty trivial: ``` static int CVL(string s) => s[3] << 24 | s[2] << 16 | s[1] << 8 | s[0]; ```
68,548,658
i am working on an online shopping application using retrofit, coroutine, livedata, mvvm,... i want to show progress bar before fetching data from server for afew seconds if i have one api request i can show that but in this app i have multiple request what should i do in this situation how i should show progress bar?? **Api Service** ``` @GET("homeslider.php") suspend fun getSliderImages(): Response<List<Model.Slider>> @GET("amazingoffer.php") suspend fun getAmazingProduct(): Response<List<Model.AmazingProduct>> @GET("handsImages.php") suspend fun getHandsFreeData( @Query( "handsfree_id" ) handsfree_id: Int ): Response<List<Model.HandsFreeImages>> @GET("handsfreemoreinfo.php") suspend fun gethandsfreemoreinfo(): Response<List<Model.HandsFreeMore>> @GET("wristmetadata.php") suspend fun getWristWatchMetaData( @Query( "wrist_id" ) wrist_id: Int ): Response<List<Model.WristWatch>> ``` **repository** ``` fun getSliderImages(): LiveData<List<Model.Slider>> { val data = MutableLiveData<List<Model.Slider>>() val job = Job() applicationScope.launch(IO + job) { val response = api.getSliderImages() withContext(Main + SupervisorJob(job)) { data.value = response.body() } job.complete() job.cancel() } return data } fun getAmazingOffer(): LiveData<List<Model.AmazingProduct>> { val data = MutableLiveData<List<Model.AmazingProduct>>() val job = Job() applicationScope.launch(IO + job) { val response = api.getAmazingProduct() withContext(Main + SupervisorJob(job)) { data.value = response.body() } job.complete() job.cancel() } return data } fun getHandsFreeData(handsree_id: Int): LiveData<List<Model.HandsFreeImages>> { val dfData = MutableLiveData<List<Model.HandsFreeImages>>() val job = Job() applicationScope.launch(IO + job) { val response = api.getHandsFreeData(handsree_id) withContext(Main + SupervisorJob(job)) { dfData.value = response.body() } job.complete() job.cancel() } return dfData } fun getHandsFreeMore(): LiveData<List<Model.HandsFreeMore>> { val data = MutableLiveData<List<Model.HandsFreeMore>>() val job = Job() applicationScope.launch(IO + job) { val response = api.gethandsfreemoreinfo() withContext(Main + SupervisorJob(job)) { data.value = response.body() } job.complete() job.cancel() } return data } ``` **VIEWMODEL** ``` fun getSliderImages() = repository.getSliderImages() fun getAmazingOffer() = repository.getAmazingOffer() fun recieveAdvertise() = repository.recieveAdvertise() fun dailyShoes(context: Context) = repository.getDailyShoes(context) ``` i will appreciate your help
2021/07/27
[ "https://Stackoverflow.com/questions/68548658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16530334/" ]
I couldn't help but notice that your repository contains lots of repetitive code. first point to learn here is that all that logic in `Repository`, it usually goes in the `ViewModel`. second thing is that you are using `applicationScope` to launch your `coroutines`, which usually is done using `viewModelScope`(takes care of cancellation) object which is available in every `viewModel`. So first we have to take care of that repetitive code and move it to `ViewModel`. So your viewModel would now look like ``` class YourViewModel: ViewModel() { // Your other init code, repo creation etc // Live data objects for progressBar and error, we will observe these in Fragment/Activity val showProgress: MutableLiveData<Boolean> = MutableLiveData() val errorMessage: MutableLiveData<String> = MutableLiveData() /** * A Generic api caller, which updates the given live data object with the api result * and internally takes care of progress bar visibility. */ private fun <T> callApiAndPost(liveData: MutableLiveData<T>, apiCall: () -> Response<T> ) = viewModelScope.launch { try{ showProgress.postValue(true) // Show prgress bar when api call is active if(result.code() == 200) { liveData.postValue(result.body()) } else{ errorMessage.postValue("Network call failed, try again") } showProgress.postValue(false) } catch (e: Exception){ errorMessage.postValue("Network call failed, try again") showProgress.postValue(false) } } /******** Now all your API call methods should be called as *************/ // First declare the live data object which will contain the api result val sliderData: MutableLiveData<List<Model.Slider>> = MutableLiveData() // Now call the API as fun getSliderImages() = callApiAndPost(sliderData) { repository.getSliderImages() } } ``` After that remove all the logic from `Repository` and make it simply call the network methods as ``` suspend fun getSliderImages() = api.getSliderImages() // simply delegate to network layer ``` **And finally to display the progress bar**, simply observe the `showProgress` `LiveData` object in your `Activity`/`Fragment` as ``` viewModel.showProgress.observer(this, Observer{ progressBar.visibility = if(it) View.VISIBLE else View.GONE } ```
64,206
As the title suggests, a friend and I are writing a manga-plot and there is this character that is having the speech disorder - he stutters. --- Writing the question directly to avoid confusion. Afterwards providing some attempts to clarify both what the question is about & details. Finally I will add *Background*, and then some *Context* and *References*. --- #### Question How should I write a character - that suffers from a speech disorder (stuttering)? I'll add some examples below, as the question might seem broad. --- ### Examples Some previous attempts of mine have been: * To write about how I myself as a stutterer feel (that is, I write on my phone). + However, other (stutterers) might disagree(everyone is different) other stutterers maybe, don't use any help at all (and talks either way) * Because we all are different I try to be "inclusive" or, how to put it. I try to make it more "general" Instead of only writing how I myself feel about stuttering. --- ### Background I have this speech disorder myself, I stutter so much so I write on notepads/my phone and show it to the person instead of talking in real life. **What does this have to do with the question?** It is, that I am unsure how to write the person (*not the stuttering-itself*). --- ### Context and References **I have tried to search for specifically writing about the speech (disorder) and not the usual, brief stuttering one might get when scared or surprised.** Like 'wow!' > > "Ww-w-wow!" > > > or 'really'? > > "r-really?" > > > What I actually mean is more like, actually **having difficulties**(actively struggling) to say the word "wow" or, "really". --- #### A more concrete example My real name is William. So I often have (major) difficulties saying my own name because of the 'W'. So I end up just saying > > my name is W-www-w (...) > > > And then - after a few attempts - literally writing on my phone "William" and showing. **But I didn't find any question** that is directly about what I am asking. Note: some might think stuttering appears when there is a stressful situation, like "introduce yourself in front of a class" but, my stutter is, regardless if I am stressed or not. **that is, I stutter as much as alone as if I would be in front of a class**. #### Comments One thing I considered doing is, having the character just write on phone, (in some anime/mangas they write in notebooks so it's - kind of the same but different) We can also of course use sign language; (both of which has been in manga before) As a attempt to re-phrase what the question really is asking it is: * How should I go with writing how the character feels, but so it doesn't feel as a cliche, because I guess writing about myself is not that good (I think?) this is my first question so sorry if trivial parts is missing. --- ### Internal References Some references that were (in)directly helpful were: Indirectly helpful: * [Is there such thing as too much concept at a character and how do you know so?](https://writing.stackexchange.com/questions/63204/is-there-such-thing-as-too-much-concept-at-a-character-and-how-do-you-know-so/63242#63242) * [How does one write a character smarter than oneself?](https://writing.stackexchange.com/questions/6670/how-does-one-write-a-character-smarter-than-oneself) Directly helpful: * [Should you always write a strong antagonist?](https://writing.stackexchange.com/q/64202/47418) * [How to make sure that you don't end up writing a Self-Insert?](https://writing.stackexchange.com/q/26748/47418) ### External References * <https://www.nidcd.nih.gov/health/stuttering> * <https://en.wikipedia.org/wiki/Stuttering>
2023/01/15
[ "https://writers.stackexchange.com/questions/64206", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/47418/" ]
So if I'm interpreting this correctly, you want to write a character who stutters based off yourself, but want to know how to avoid them coming off as cliché or offending other people who stutter/stutterers due to being nonrepresentative, right? And have attempted to search for resources only to find a sum total of nothing useful? (can attest to this, the advice out there is terrible.) I stutter myself and also often wrestle with how to bring this into fiction, so you're not alone! If you don't mind, I'm going to divide this answer into two parts: **Avoiding cliché** You would think that, especially because the clichés about stuttering are not exactly true to life, this would be easy to do. However. A trap it's easy to fall into here is accidentally writing in a way that lets people project the clichés into your story, even though they're not actually there. This is because there are a few narratives about stuttering that are *incredibly* common in fiction (although, IMO, not realistic and actually fairly offensive), to the point where people will actively expect to see them if a stuttering character shows up. The three main ones I know are: * stuttering as a symptom of cowardice * stuttering as a symptom of shyness, anxiety, low self esteem, or similar * the stutter magically vanishing, typically as a reward for character development As someone who stutters myself and knows that RL doesn't work this way, I am not primed to look for these the way fluent people not familiar with stuttering outside fiction are. I have multiple times been surprised to find a stuttering character interpreted in a way that fits into these tropes when I didn't think it was there in the text. (Examples: Khalid from the video game Baldur's Gate 1 being treated as cowardly, Simon from Terry Pratchett's book Equal Rites losing his stutter and that being interpreted as a reward for his character development through the book by fluent readers) I've been taken aback to find that the cultural narrative here is *just that strong* that people will just... bring their own clichés. This means that it's probably not enough to just not write these tropes, especially because you as a stutterer cannot judge very well whether a fluent reader will read them into your work anyway. I would suggest going to the effort of actively subverting or undermining them, or in SOME place spelling out clearly that the trope will not be happening. Things like - the stuttering character is brave to the point of recklessness, maybe saying that since they have to run a gauntlet just to order coffee every day everything else seems manageable. Or lampshading in a scene in which someone says something a la thinking the stutter will go away if they get over their Issues (TM), or suggesting that why don't they try singing instead of speaking? And the stuttering character rolling their eyes and telling them they've obviously been reading too much bad fiction, if it was that easy they wouldn't stutter. For the record, needing to do this sucks. I don't think I'll ever be able to write a character who stutters who is also generally nervous because I know it'll be interpreted as causative - this sucks. The fact that if you manage to avoid these clichés you've probably already produced a refreshing unusually well-portrayed stuttering character is good for you in the moment, but overall also sucks. But with the state of stuttering portrayals it's the advice I have to give. **Avoiding offending other people who stutter** This is a reasonable worry, because as you may know the stuttering community has a lot of veeery different experiences and attitudes towards stuttering. I've worried about this myself a lot because I know my own attitude is an outlier. That said. The fact that you stutter yourself means that if you base your character's attitudes on yourself they will definitely be representative of **one** person who stutters - you. And they will almost certainly *not* be representative of some other people who stutter, just because it's such a diverse condition. So where to go from there? My main advice would be to make sure that you depict everything the character is going through and what they think and feel as *that character's experience of stuttering* and not The Way Stuttering Is, Always, For Everyone. An easy way to do this, if you can swing it, is to bring in another character who stutters at some point (potentially for a bit part) who has a very different experience and outlook on life. If that's not possible, maybe give your character some history of interacting with other stutterers with a different experience. Even something as simple as a memory of interacting with someone in a shop once who also stuttered and was significantly [more/less] accepting of it can help avert this. If you're not sure what other experiences and takes there *are*, I suggest checking out the stuttering community - some of the podcasts on [Stuttertalk](https://stuttertalk.com/) may be a place to start.
2,897,262
Example Question : $3m + 4n = 70$, $m,n$ are natural numbers. How many values can $m$ have? I learned a method to solve this kind of problem, but I've never thought about that before. for n=1 => m=22 n=4 => m=18 . . n=16 => m=2 So n increase 3 by 3 and m decrease 4 by 4 How do we proof this works everytime?
2018/08/28
[ "https://math.stackexchange.com/questions/2897262", "https://math.stackexchange.com", "https://math.stackexchange.com/users/587885/" ]
Once you have an initial solution, say $(m\_0, n\_0)$ such that $3m\_0 + 4n\_0 = 70$ then you can add (or subtract) any multiple of $3$ to $n\_0$ as long as you subtract (or add) the same multiple of $4$ from $m\_0$. This is because $3(m\_0-4k) + 4(n\_0+3k) = 3m\_0-12k + 4n\_0+12k = 3m\_0 + 4n\_0=70$
13,110,276
I'm working on a regular expression where I need to verify a input text that contains 4 distinct words separated by a comma. > > input text words: - one, two, three, four. Each of these words should not be repeated more than once. > so, it can be: two, three, four, one or three, four, two, one and not one, one, one, one > > > Here is what I wrote and found a partial solution by doing separate searches ``` ^\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b ``` But the problem with solution is words are getting repeated, and the test for "one, one, one, one" fails. Can you please let me know how to avoid the duplicates and where am I doing a mistake?
2012/10/28
[ "https://Stackoverflow.com/questions/13110276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1781007/" ]
It would be far easier to NOT do this particular problem with a single regular expression. First off, `\b` is zero-width. So you do not need to follow it using a `?`, your intention is probably `\s?`. Next, regex is pretty much stateless, in the general case, which means that you'd need to construct your regex as follows. ``` ^\s*(one\s*,(two\s*,(three\s*,four|four\s*,three)|three\s*,(two\s*,four|four\s*,two)... ``` As you can see, you have to manually deal with combinatoric explosion. Which is far less than ideal. You should instead, split on `,` and use java to check. > > Thanks for replying. From what i understand, you want me not use regex rather use java.can you detail a bit on how to check in java > > > Try this (untested code, will be bugs): ``` public parseList(String input) { String[] numbers = { "one", "two", "three", "four" }; bool foundNumbers = { false, false, false, false }; String delims = "\s*,"; String[] tokens = input.split(delims); if (tokens.length != 4) { //deal with error case as you wish } for (int i = 0; i < numbers.length; ++i) { for (int j = 0; j < tokens.length; ++j) { if (numbers[i].equals(tokens[j])) { if (!foundNumbers[i]) { foundNumbers[i] = true; } else { //deal with error case as you wish } } } } for (int i = 0; i < foundNumbers.length; ++i) { if (!foundNumbers[i]) { //deal with error case as you wish } } //success } ```
37,208,644
I want to add new row to gridcontrol at every button click. I tried many ways but no success. I am sending my code. ``` private void B_Click(object sender, EventArgs e) { Button bt = (Button)sender; int productId = (int)bt.Tag; AddProductDataContext db = new AddProductDataContext(); decimal Quantity; decimal.TryParse(txtCalculator.Text, out Quantity); var results = from inv in db.Inventories where inv.RecId == productId select new { inventoryName = inv.InventoryName, Quantity, Total = Quantity * inv.InventoryPrice }; DataTable dt = new DataTable(); dt.Columns.Add("inventoryName"); dt.Columns.Add("Quantity"); dt.Columns.Add("Total"); foreach (var x in results) { DataRow newRow = dt.Rows.Add(); newRow.SetField("inventoryName", x.inventoryName); newRow.SetField("Quantity", x.Quantity); newRow.SetField("Total", x.Total); } gridControl1.DataSource = dt; gridView1.AddNewRow(); } ```
2016/05/13
[ "https://Stackoverflow.com/questions/37208644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6325555/" ]
For god sake, protect your query against SQL injection : ``` $sql = "DELETE from utilisateur where pseudo = '".mysqli_real_escape_string($con, $pseudo)."'"; ```
49,240,739
I wanted to export data from *netezza database* to *CSV* file. The format for the data will be: ``` col1,col2,col3 ``` OR: ``` "col1","col2","col3" ``` I am using the query: ``` CREATE EXTERNAL TABLE 'H:\\test.csv' USING ( DELIMITER ',' REMOTESOURCE 'ODBC' ) AS SELECT * FROM TEST_TABLE ``` Above query is not working when *col3* has the field including comma as it is saying to export it using escape char as '\'. Example table: ``` A | B | C a | b | Germany, NA ``` I tried that too, but I am getting as output in *csv*: ``` a,b,Germany\, NA ``` or by adding quotes to each column I am getting output: ``` "a","b","Germany\, NA" ``` Here, I am getting extra '\' character in field. I am looking for the solution to resolve it using the *nzsql* or external table query method or writing own script methods only. My expected output without changing field data: "a","b","Germany, NA"
2018/03/12
[ "https://Stackoverflow.com/questions/49240739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3863192/" ]
Desired output can be achieved by using nzsql command line statement.The only limitation of this approach is max file will limit to **2 GB** .Here is the link from IBM KB [Sending query results to an output file](http://www-01.ibm.com/support/docview.wss?crawler=1&uid=swg21567479) ``` [nz@netezza ~]$ nzsql -d test -A -t -c "select quote_ident(col1),quote_ident(col2), quote_ident(col3) from test" -o '/nzscratch/test.csv' ``` **Output :** ``` [nz@netezza ~]$ cat /nzscratch/test.csv "A"|"B"|"C" a|b|"Germany, NA" ```
70,444,674
Hey all so I'll keep it short. I know there've been some questions asked similar to this but none of them are able to answer what I'm trying to achieve. This is what I want the code to do: * Show a div when forward slash "/" is typed in textarea * Not show a div when forward slash is not typed * hide the pop up when the forward slash is deleted/backspaced I can achieve the first two with the following code I'm working with right now: <https://jsfiddle.net/jtk37vs8/1/>. However the problem is, whenever I type forward slash and then delete it, the pop up still stays there. I'm new to JS and the code is kinda unorganized but it's quite easy to understand. So basically I'd appreciate if any of you could at least tell me if there is any straightforward way to achieve this? Thank you for your patience and reading my query. ``` function getCaretCoordinates() { let x = 0, y = 0; const isSupported = typeof window.getSelection !== "undefined"; if (isSupported) { const selection = window.getSelection(); // Check if there is a selection (i.e. cursor in place) if (selection.rangeCount !== 0) { // Clone the range const range = selection.getRangeAt(0).cloneRange(); // Collapse the range to the start, so there are not multiple chars selected range.collapse(true); // getCientRects returns all the positioning information we need const rect = range.getClientRects()[0]; if (rect) { x = rect.left; // since the caret is only 1px wide, left == right y = rect.top; // top edge of the caret } } } return { x, y }; } function getCaretIndex(element) { let position = 0; const isSupported = typeof window.getSelection !== "undefined"; if (isSupported) { const selection = window.getSelection(); // Check if there is a selection (i.e. cursor in place) if (selection.rangeCount !== 0) { // Store the original range const range = window.getSelection().getRangeAt(0); // Clone the range const preCaretRange = range.cloneRange(); // Select all textual contents from the contenteditable element preCaretRange.selectNodeContents(element); // And set the range end to the original clicked position preCaretRange.setEnd(range.endContainer, range.endOffset); // Return the text length from contenteditable start to the range end position = preCaretRange.toString().length; } } return position; } $("#contenteditable").bind("keypress", function toggleTooltip(e) { const tooltip = document.getElementById("tooltip"); if(String.fromCharCode(e.keyCode) == '/') { const { x, y } = getCaretCoordinates(); $(".tooltip").show(); // tooltip.setAttribute("aria-hidden", "false"); tooltip.setAttribute( "style", `display: inline-block; left: ${x - -10}px; top: ${y - 160}px` ); } else if (document.getElementById('contenteditable').innerHTML.indexOf("/") != -1) { // $(".tooltip").hide(); // tooltip.setAttribute("aria-hidden", "true"); tooltip.setAttribute("style", "display: none;"); } // else if (document.getElementById('contenteditable').innerHTML.indexOf("/") >=0) { // tooltip.setAttribute("aria-hidden", "true"); //tooltip.setAttribute("style", "display: none;"); // } else { // $(".tooltip").hide(); // tooltip.setAttribute("aria-hidden", "true"); //tooltip.setAttribute("style", "display: none;"); } } ) ```
2021/12/22
[ "https://Stackoverflow.com/questions/70444674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16663406/" ]
I think the problem is a combination of Stencil's tree-shakable API and a problem with its build-time analysis of dynamic imports. Stencil tries to ship as little "Stencil" code as possible, so it will analyze your project to find out which features you're actually using and only include those in the final bundle. If you check the `./build/index-{hash}.js` (in a dev www build) on line 2 you'll find a list of which features it detected. I created my own quick reproduction and compared this file when using a dynamic and static import. Here are the differences: **Dynamic Import** ``` { vdomAttribute: false, vdomListener: false } ``` **Static Import** ``` { vdomAttribute: true, vdomListener: true } ``` So it seems that Stencil isn't aware of the features you're only using in the dynamically imported template and therefore doesn't include it in the build. But if you use the same features in any component (or file that is statically imported into a component), Stencil should include it. So a simple work around would be to attach any listener to any element in any component of your project. And you'd have to do that for every single Stencil feature you're currently only using in a dynamically loaded template. Another option is to create a Stencil component that statically includes all your dynamic templates. AFAIK this would detect all used features and enable them for the project even without having to use this new component anywhere. **Example:** ``` import { Component, Host, h } from '@stencil/core'; import { Template1 } from "../../templates/template1"; import { Template2 } from "../../templates/template2"; import { Template3 } from "../../templates/template3"; @Component({ tag: 'template-imports', }) export class TemplateImports { render() { return ( <Host> <Template1></Template1> <Template2></Template2> <Template3></Template3> </Host> ); } } ```
19,767,553
I am using a `UIAlertView` to prompt users for a password. If the password is correct, I'd like the alert view to go away normally; if the password is incorrect, I'd like the alert view to remain (with the text changed to something like "Please try again."). How do I alter the default behaviour so that the view doesn't go away when a button is pressed? I've tried the subclassing method suggested at [Is it possible to NOT dismiss a UIAlertView](https://stackoverflow.com/questions/2051402/is-it-possible-to-not-dismiss-a-uialertview), but the `dismissWithClickedButtonIndex` wasn't being called in my subclass. After reading the documentation I see that subclassing `UIAlertView` isn't supported, so I'd like to try another approach. If this isn't possible with `UIAlertView`, is the best option to simply make a password view from scratch? Thanks for reading.
2013/11/04
[ "https://Stackoverflow.com/questions/19767553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1781058/" ]
You could design a **UIView** similar to the alertview and can cal the functions inside this. Removing a UIView is controlled by you.
4,229,732
initially, my textarea has a value of Enter Comment... set via `<textarea>Enter Comment...</textarea>` I have a .focus like: `$("textarea.commentTextArea").live('focus', function() { if($(this).val() == "Enter Comment...") { $(this).val(''); } });` and a .blur() like: `$("textarea.commentTextArea").live('blur', function() { if($(this).val() == "Enter Comment..." || $(this).val() == "") { $(this).text("Enter Comment..."); $(this).parent().addClass("hide"); $(this).parent().hide(); } });` However, after I set the val in the .blur() function, and try to retrieve the value using .val(), it's always returning 'Enter Comment...' as opposed to the text that was user inputted. I'm at a loss here. Thanks for the help! Edit- I have a more in depth selector for the "textarea", that's not the issue. It wouldn't be returning "Enter Comment" if the selector was returning null. Thanks for trying though. Same goes with my .focus() function. I just wanted to show the core of what's going on
2010/11/19
[ "https://Stackoverflow.com/questions/4229732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/409993/" ]
You don't have quotes around the word 'textarea' in the second statement. Also, your focus event will delete anything the user entered if they return to the textarea to edit again. do this to solve the second problem (same trick you used on the blur event): ``` $("textarea").focus(function() { if ($(this).val() == 'Enter Comment...') $(this).val(''); }); ```