qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
3,569,183
When a user tries to access our website via a link (for instance going to www.website.com/privatepage) they are redirected to a login page. Once they login, we want to redirect them to that intended URL - how do you do this? Also we have a use case where a user logs in from the homepage, or goes directly to the login page with no intended URL - in this case we'd like to redirect them to a default page. Can anyone help me figure this out?
2010/08/25
[ "https://Stackoverflow.com/questions/3569183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364969/" ]
in your login page: if you go to **www.example.com/private\_page** using CodeIgniter (on private page) ``` // if user is not logged in... $_SESSION['redirect'] = $this->uri->segment(1); redirect('login'); ``` on login page ``` // successfully logged in.. if (isset($_SESSION['redirect'])) { redirect($_SESSION['redirect']); } else { // redirect to default page } ```
I usually store the page in a PHP session before I redirect to the login page. After logging in, see if the session value is set, if it is then redirect back to that page.
6,445,274
How do I set watermark for a texbox in MVC3 .Also if there are multiple textboxes in a web page, how do you write different watermark text for each textbox? ``` <%:Html.TextBoxFor(mdl => mdl.inputTextSearch, Model.inputTextSearch )%> ``` Appreciate your response
2011/06/22
[ "https://Stackoverflow.com/questions/6445274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/811007/" ]
If I understand your question, you can just pass in: ``` new { placeholder = "my watermark" } ``` as the htmlAttributes parameter in Html.TextBoxFor. Edit: You can also add support for older browsers by using Javascript as outlined here: <http://www.standardista.com/html5-placeholder-attribute-script>
Try this Jquery .You need to create an image with the watermark text. ``` $(document).ready(function () { /*Watermark for date fields*/ if ($("#dob").val() == "") { $("#dob").css("background", "#ebebeb url('/Content/images/DateWaterMark.png') no-repeat 1px 0px"); } $("#dob").focus(function () { if (watermark == 'MM/DD/YYYY') { $("#dob").css("background-image", "none"); $("#dob").css("background-color", "#fff"); } }).blur(function () { if (this.value == "") { $("#dob").css("background", "#ebebeb url('/Content/images/DateWaterMark.png') no-repeat 1px 0px"); } }); $("#dob").change(function () { if (this.value.length > 0) { $("#dob").css("background", "#fff"); } }); } ```
23,078,287
I'm trying to vectorize the following MATLAB operation: > > Given a column vector with indexes, I want a matrix with the > same number of rows of the column and a fixed number of columns. The > matrix is initialized with zeroes and contains ones in the locations > specified by the indexes. > > > Here is an example of the script I've already written: ``` y = [1; 3; 2; 1; 3]; m = size(y, 1); % For loop yvec = zeros(m, 3); for i=1:m yvec(i, y(i)) = 1; end ``` The desired result is: ``` yvec = 1 0 0 0 0 1 0 1 0 1 0 0 0 0 1 ``` Is it possible to achieve the same result without the for loop? I tried something like this: ``` % Vectorization (?) yvec2 = zeros(m, 3); yvec2(:, y(:)) = 1; ``` but it doesn't work.
2014/04/15
[ "https://Stackoverflow.com/questions/23078287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556141/" ]
Two approaches you can use here. **Approach 1:** ``` y = [1; 3; 2; 1; 3]; yvec = zeros(numel(y),3); yvec(sub2ind(size(yvec),1:numel(y),y'))=1 ``` **Approach 2 (One-liner):** ``` yvec = bsxfun(@eq, 1:3,y) ```
Yet another approach: ``` yvec = full(sparse(1:numel(y),y,1)); ```
4,899,800
So lets say I have two models: Thingy and Status. `Thingy` has a `Status`, and Status has many Thingies. It's typical "Object and Object type relationship". I have a view where I just want the number of thingies in each status. Or basically a list of Status.Name and Status.Thingies.Count. I could do exactly this, but is the "**right**" thing to do to create a view model in the form: ``` ThingiesByStatusViewModel -StatusName -StatusThingiesCount ``` and hook it up with something like AutoMapper. For such a trivial example, it probably doesn't make much of a difference, but it would help me understand better the proper 'separation of concerns'.
2011/02/04
[ "https://Stackoverflow.com/questions/4899800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2009/" ]
> > Should I use a viewmodel here? > > > Is this a rhetorical question? Your view model would look exactly as you propose and it is perfectly adapted to what you are trying to display here: ``` public class ThingiesByStatusViewModel { public string StatusName { get; set; } public int StatusThingiesCount { get; set; } } ``` and then your controller would return an `IEnumerable<ThingiesByStatusViewModel>`. Then in your view you could simply use a display template: ``` @Html.DisplayForModel() ``` and the corresponding display template (`~/Views/Shared/DisplayTemplates/ThingiesByStatusViewModel.cshtml`): ``` @model AppName.Models.ThingiesByStatusViewModel <div> <span>StatusName: @Model.StatusName</span> <span>Number of thingies: @Model.StatusThingiesCount</span> </div> ``` Now let's look at the mapping layer. Suppose that we have the following domain: ``` public class Thingy { } public class Status { public string StatusName { get; set; } public IEnumerable<Thingy> Thingies { get; set; } } ``` and we have an instance of `IEnumerable<Status>`. The mapping definition could look like this: ``` Mapper .CreateMap<Status, ThingiesByStatusViewModel>() .ForMember( dest => dest.StatusThingiesCount, opt => opt.MapFrom(src => src.Thingies.Count()) ); ``` and finally the controller action would simply be: ``` public ActionResult Foo() { IEnumerable<Status> statuses = _repository.GetStatuses(); IEnumerable<ThingiesByStatusViewModel> statusesVM = Mapper.Map<IEnumerable<Status>, IEnumerable<ThingiesByStatusViewModel>>(statuses); return View(statusesVM); } ```
I, personally, don't like to send non-trivial types to the view because then the person designing the view might feel obligated to start stuffing business logic into the view, that that's bad news. In your scenario, I'd add a StatusName property to your view model and enjoy success.
18,744
"Mitzvah gedola le'heyos be'simcha..." many of us have heard this. I am wondering if there is an actual mitzvah to be be'simcha? (I am looking for sourced comments and not just idea's). I know that simcha is not counted as a mitzvah by the Rishonim, but I think the question still stands. I have heard that the Chasam Sofer (in parshas VaYechi) says that it is a mitzvah deoraysah and explains why the Rishonim don't count it, but I couldn't find it.
2012/08/25
[ "https://judaism.stackexchange.com/questions/18744", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/1769/" ]
I believe that having inner simcha (happiness) is a branch of the Mitzva to love Hashem "with all your heart, all your soul, and all your possessions [(Deuteronomy 6:5)](http://www.sefaria.org/Deuteronomy.6)" which many Rishonim consider a Mitzvah, and some consider it a constant one (Sefer HaChinuch). If you love someone, you are naturally happy, especially, when you love the source of life itself. It's simple logic. Further, [Talmud Bavli (Brachot 60B)](http://hebrewbooks.org/shas.aspx?mesechta=1&daf=60b&format=text) teaches, based on the aforementioned verse, that one has to bless Hashem for bad occurrences just like by good occurrences; and explains that you have to accept the bad with **simcha** (as Rashi explains לברך על מדת פורענות **בלבב שלם**). If the Torah expects us to do this with bad, then we certainly must be happy with everything else in life. The Gemarah goes on to bring other verses in Tanach to back up this idea, and then brings the famous story about Rabbi Akiva, in which he remarks that "Everything the Merciful One (viz. Hashem) does is for good." How can one not always be happy if they live with such an attitude?! (I think the confusion is centered more around how much external joy Hashem wants us to express. Different situations in life call for varying emotional displays ranging from mourning to elatedness. Also, the degree of emotional expression will be in accordance with one's level of inner happiness combined with their personality type, and ultimately should be based on their decision precisely how to express themselves (depending on how much self-control they have). However, I assure you, if you are happy within, it will naturally show on the outside.)
“You shall be glad with all the goodness that Hashem, your G-d, has given you and your household…” [Devarim 26:11]
34,498,132
Why if I write some other letter or number(not y\n) the order ``` printf("\nWould you like to play again? (y/n):"); ``` run twice? ``` int ans= 0,i=1; do { printf("\nWould you like to play again? (y/n):"); ans = getchar(); if (ans=='y') { printf("yyyyyyyyyyy"); i = i-1; } else if ( ans == 'n') { printf("nnnnnnnnnnn"); i=i-1; } else { printf("not y or n"); } } while(i); ```
2015/12/28
[ "https://Stackoverflow.com/questions/34498132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Probably because your `getchar` call is picking up the newline from your input. So if you press 'X', the first time through the loop `ans` is 'X' and the newline was buffered. The second time through the loop `ans` is '\n'. You can put a loop around your input call like this: ``` do ans = getchar(); while (isspace(ans)); ```
Another solution: ``` char c = 'x'; // Initialize to a character other than input while( c != 'y' || c != 'n') { // You can also use strchr as @Olaf mentioned printf ("\nPlay again (y/n): "); c = getchar (); } ```
25,510,184
I want to check a string for a list of phrases. If those phrases exist I want to remove them and return a new string. ``` For Example: String: Lower Dens - Propagation (Official Music Video) Result: Lower Dens - Propagation ``` This is what I have so far, but it does not work. This would work for single words, but not phrases. I am using underscore for the each loop, but I am open to any solution. ``` formatVideoTitle = function(videoTitle){ var phrases = [ '(Official Music Video)', '(Official Video)', '(Music Video)' ], newVideoTitle = videoTitle; _.each(phrases, function(phrase){ newVideoTitle.replace(phrase, ''); }); return newVideoTitle; }; ```
2014/08/26
[ "https://Stackoverflow.com/questions/25510184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2083111/" ]
set newVideoTitle to the result of the replace operation it works. I would make a jsfiddle but am too lazy to include underscore. [heres a fiddle](http://jsfiddle.net/uxea8vLo/1/) ``` formatVideoTitle = function(videoTitle){ var phrases = [ '(Official Music Video)', '(Official Video)', '(Music Video)' ], newVideoTitle = videoTitle; _.each(phrases, function(phrase){ newVideoTitle = newVideoTitle.replace(phrase, ''); }); return newVideoTitle; }; ```
`replace` returns a value, so you need to assign the replaced variable to a new variable (or the same one): ``` _.each(phrases, function(phrase) { newVideoTitle = newVideoTitle.replace(phrase, ''); }); ``` [**DEMO**](http://jsfiddle.net/6Le5spuy/2/)
13,725,060
I have multiple UserControl XAML files that use a similar structure. I want to remove this duplication and thought to use a Style that overrides the Template of the UserControl (and then use ContentPresenter for the custom part). But apparently the Template of a UserControl can't be overwritten. How do I this the clean way? Derive from something else then UserControl? ``` <UserControl x:Class="Class1"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <sdk:Label Grid.Row="0" Content="Title1" Style="{StaticResource Header1}" /> <Border Grid.Row="1"> ... </UserControl> <UserControl x:Class="Class2"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <sdk:Label Grid.Row="0" Content="Title2" Style="{StaticResource Header1}" /> <Border Grid.Row="1"> ... </UserControl> ```
2012/12/05
[ "https://Stackoverflow.com/questions/13725060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91002/" ]
You could define a custom control like this. (I'm not sure if you need to specify the Title separate from the content, but here it is just in case.) ``` public class MyControl : ContentControl { public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(MyControl), new PropertyMetadata(null)); public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } // ... other properties ... } ``` Then define its template: ``` <ControlTemplate x:Key="MyControlTemplate" TargetType="mynamespace:MyControl"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <sdk:Label Grid.Row="0" Content="{TemplateBinding Title}" Style="{StaticResource Header1}" /> <Border Grid.Row="1"> <ContentPresenter /> ... </Grid </ControlTemplate> ``` You could then define a default style, as shown here. (Alternatively, you could give it an x:Key and explicitly set the style each time you use MyControl. You could also just set the Template property each time you use MyControl, instead of specifying this Style at all.) ``` <Style TargetType="mynamespace:MyControl"> <Setter Property="Template" Value="{StaticResource MyControlTemplate}" /> </Style> ``` Then to use it: ``` <mynamespace:MyUserControl Title="Title1"> <!-- Content here --> </mynamespace:MyUserControl> <mynamespace:MyUserControl Title="Title2"> <!-- Content here --> </mynamespace:MyUserControl> ```
Perhaps you need to use [ContentControl](http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.aspx) as a base class for your controls (It should be not User Control but Custom Control). Then you'll be able to define `ControlTemplate` and use `ContentPresenter` within it. Than you need to set `Content` property for your controls to define control's content.
39,781,420
With the upcoming [RxJava2 release](https://github.com/ReactiveX/RxJava/tree/2.x) one of the important changes is that `null` is no longer accepted as a stream element, i.e. following code will throw an exception: `Observable.just(null)` Honestly, I have mixed feelings about this change and part of me understands that it will enforce clean APIs, but I can see a number of use cases when this might be a problem. For instance, in my app I have an in-memory cache: ``` @Nullable CacheItem findCacheItem(long id); ``` CacheItem might not be present in cache, so method might return null value. The way it is used with Rx\* - is as following: ``` Observable<CacheItem> getStream(final long id) { return Observable.fromCallable(new Callable<CacheItem>() { @Override public CacheItem call() throws Exception { return findCacheItem(id); } }); } ``` So with this approach, I might get null in my stream which is totally valid situation, so it is handled properly on receiving side - let's say UI changes its state if item is not present in cache: ``` Observable.just(user) .map(user -> user.getName()) .map(name -> convertNameToId(name)) .flatMap(id -> getStream(id)) .map(cacheItem -> getUserInfoFromCacheItem(cacheItem)) .subscribe( userInfo -> { if(userInfo != null) showUserInfo(); else showPrompt(); } ); ``` With RxJava2 I am no longer allowed to post `null` down the stream, so I either need to wrap my CacheItem into some other class and make my stream produce that wrapper instead or make quite big architectural changes. Wrapping every single stream element into nullable counterpart doesn't look right to me. Am I missing something fundamental here? It seems like the situation like mine is quite popular, so Im curious what is the recommended strategy to tackle this problem given new "no null" policy in RxJava2? **EDIT** Please see follow-up conversation in [RxJava GitHub repo](https://github.com/ReactiveX/RxJava/issues/4644)
2016/09/29
[ "https://Stackoverflow.com/questions/39781420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1277362/" ]
Well, there are several ways to represent what you want. One option is to use `Observable<Optional<CacheItem>>`: ``` Observable<Optional<CacheItem>> getStream(final long id) { return Observable.defer(() -> { return Observable.just(Optional.ofNullable(findCacheItem(id))); }); } public static <T> Transformer<Optional<T>, T> deoptionalize() { return src -> src.flatMap(item -> item.isPresent() ? Observable.just(item.get()) : Observable.empty(); } ``` You then use `.compose(deoptionalize())` to map from the optional to the non-optional Observable.
You can use [`RxJava2-Nullable`](https://github.com/XDean/RxJava2-Nullable) to handle null value in RxJava2. For your situation, you can do: ``` Observable<CacheItem> getStream(final long id) { return RxNullable.fromCallable(() -> findCacheItem(id)) .onNullDrop() .observable(); } ``` To invoke `showPrompt` when it's null, you can do: ``` Observable.just(user) .map(user -> user.getName()) .map(name -> convertNameToId(name)) .flatMap(id -> getStream(id).onNullRun(() -> showPrompt())) .map(cacheItem -> getUserInfoFromCacheItem(cacheItem)) .subscribe(userInfo -> showUserInfo()); NullableObservable<CacheItem> getStream(final long id) { return RxNullable.fromCallable(() -> findCacheItem(id)).observable(); } ```
17,970,410
So here is my first question and my first C# program: I need function that could permanently change a connection string. My program has this structure: Main form is `Form1`, when I click the button, `Options`, I get new from - `Form3`, where user can log in (password protects changing options) and if login is successfull I create new form - `Form4`. In constructor of `Form4`, I pass a `SqlConnection` object from `Form1`. I want to change my database name by clicking on button, so here is the code: ``` var config = ConfigurationManager .OpenExeConfiguration(ConfigurationUserLevel.None); var connectionStringsSection = (ConnectionStringsSection)config .GetSection("connectionStrings"); var x = connectionStringsSection .ConnectionStrings["App.Properties.Settings.ppsConnectionString"] .ConnectionString; String[] words = x.Split(';'); words[1] = "Initial Catalog="+textBoxDB.Text; x=String.Join(";", words); connectionStringsSection .ConnectionStrings["App.Properties.Settings.ppsConnectionString"] .ConnectionString = x; //above, this variable x in debug mode looks right //I read this line below should update file, so change would be permamently config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings"); ``` But it doesn't change anything, and I have no idea how to change this Settings file so user could change database name and when they restart the app, they should have this new changed connection string. **EDIT :** Thanks for the responses it turns out that I should run this code from bin/Release .exe version, not under Debug in VS and it actually changes this config file.
2013/07/31
[ "https://Stackoverflow.com/questions/17970410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1967428/" ]
Did you try enabling persistence in ActiveMQ? Which version of ActiveMQ do you use? I looked in to ActiveMQ 5.8 and it uses KahaDB which is a file based DB as the default persistence configuration. The persistence approach can be changed based on you requirement. To enable persistance; 1) Go to file [ActiveMQ\_HOME] --> conf --> activemq.xml 2) Check if below configurations are enabled for broker; ``` <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" persistent="true" dataDirectory="${activemq.data}"> <persistenceAdapter> <kahaDB directory="${activemq.data}/kahadb"/> </persistenceAdapter> ``` * Within broker tag, attribute set to persistent="true". * configurations are pointing to KahaDB. The default KahaDB files can be found under the below location; [ActiveMQ\_HOME]/data/kahadb/ Check if this satisfies your requirement. For more information, please refer [ActiveMQ Persistence](http://activemq.apache.org/persistence.html). The latter part contains KahaDB persistence configurations. BTW in ActiveMQ console, what is refered to as "Messages Enqueued" is the count since last reset. This will set to 0 whenever you restart the server. The actual available message count is shown by the count under "Number Of Pending Messages". I haven't tried this with WSO2 MB. Will try it sometime and keep you posted.
If you are using JMS Message Store, even if the server crashes, the messages which were enqueued before (and processing not yet completed) will still be there. This is because the messages are persisted in the JMS queue. If you use In Memory Message Store, upon server crash, your messages will be lost. In JMS case, you can browse any pending messages inside message store or message processor by clicking on the name link of each store/ processor instance. To be able to browse the messages inside the processor, the processor should be in inactive state. But upon server restart, the messages seems to vanish in ESB 4.7.0. Will look in to this further and keep you posted. I tried with ActiveMQ case and figured that the error message details can be viewed there for failed messages. 1) Log in to ActiveMQ console. 2) Click on "Queues". 3) Click on your message store queue name. List of pending messages will be displayed. 4) Click on a message id. The message details will be displayed, including the failure message. Hope this helped.
47,593,409
I created runtime image using jlink on my Linux machine. And I see `linux` folder under the `include` folder. Does it mean that I can use this runtime image only for Linux platform? If yes, are there any ways to create runtime images on one platform for another (e.g. on Linux for Windows and vice versa)
2017/12/01
[ "https://Stackoverflow.com/questions/47593409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5883307/" ]
The `include` directory is for header files, such as `jni.h`, that are needed when compiling C/C++ code that uses JNI and other native interfaces. It's nothing to do with `jlink`. The `jlink` tool can create a run-time image for another platform (cross targeting). You need to download two JDKs to do this. One for the platform where you run `jlink`, the other for the target platform. Run `jlink` with `--module-path $TARGET/jmods` where `$TARGET` is the directory where you've unzipped the JDK for the target platform.
Being generally unable to add anything to Alan Bateman's answers in terms of information, I'll offer a working example. [This example](https://github.com/codetojoy/easter_eggs_for_java_9/tree/master/egg_22_JLink_Cross_Platform) illustrates using `jlink` on Mac OS and then running the binary on Ubuntu in a Docker container. The salient points are as follows. Given two simple modules, we compile on Mac OS: ``` javac -d build/modules \ --module-source-path src \ `find src -name "*.java"` jar --create --file=lib/net.codetojoy.db@1.0.jar \ -C build/modules/net.codetojoy.db . jar --create --file=lib/net.codetojoy.service@1.0.jar \ -C build/modules/net.codetojoy.service . ``` Assuming that the Linux 64 JDK is unpacked in a local directory (specified as command-line arg), we call `jlink` (on Mac OS in this example). **`JAVA_HOME` is the crux** of the solution: ``` # $1 is ./jdk9_linux_64/jdk-9.0.1 JAVA_HOME=$1 rm -rf serviceapp jlink --module-path $JAVA_HOME/jmods:build/modules \ --add-modules net.codetojoy.service \ --output serviceapp ``` Then, assuming we've pulled the `ubuntu` image for Docker, we can execute the following in a Docker terminal (i.e. Linux): ``` docker run --rm -v $(pwd):/data ubuntu /data/serviceapp/bin/java net.codetojoy.service.impl.UserServiceImpl TRACER : hello from UserServiceImpl ``` To re-iterate this feature of Java 9/`jlink`: Linux does not have Java installed and the Linux binary was built on Mac OS.
4,261,785
I think I have a bug in one plugin. I would like to load only this plugin, without having to delete all the other bundles in my pathogen's bundle folder, to debug. Is it possible?
2010/11/23
[ "https://Stackoverflow.com/questions/4261785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198553/" ]
*vim --noplugin* In this case vim will not load any plugins but your vimrc will be used. After you can load your plugin in vim: *:source 'your plugin path'*
Why not just: 1. rename the current bundle directory 2. create a new empty bundle directory 3. put your test plugin files into the new bundle dir? When done put everything back the way it was. (The suggested method of loading Vim without plugins and sourcing the plugin file would work if it's a simple one-file plugin, but if you're doing an ftplugin then moving dirs around is probably best way and not that hard.)
4,280,970
I did not realize that: 'have a web.config in a separate class library and' was reading the web.config app setting from different web application. I am using VS2010 target framework 3.5 I don't know what is wrong here but I am getting `null` when I try to get `ConfigurationManager.AppSettings["StoreId"];` ``` private string _storeid = GetStoreId; public static string GetStoreId { get { return ConfigurationManager.AppSettings["StoreId"]; } } ``` **web.config:** ``` <appSettings> <add key="StoreId" value="123" /> </appSettings> ```
2010/11/25
[ "https://Stackoverflow.com/questions/4280970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/275390/" ]
and: ``` <appSettings> <add key="StoreId" value="123" /> </appSettings> ``` is located in the `web.config` file of your ASP.NET application and not in some `app.config` file you've added to your class library project in Visual Studio, right? You can't be possibly getting `null` if this is the case. If you've added this to an `app.config` of you class library project in Visual Studio then getting null is perfectly normal behavior.
I tried all of these solutions but none worked for me. I was attempting to use a 'web.config' file. Everything was named correctly and the files were in the proper location, but it refused to work. I then decided to rename my 'web.config' file to 'app.config' and just like that, it worked. So if you are having this issue with a 'web.config' file be sure to rename it to 'app.config'.
396,053
I have been unable to trigger an **onselect** event handler attached to a **<div>** element. Is it possible to force a **<div>** to emit **select** events?
2008/12/28
[ "https://Stackoverflow.com/questions/396053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27122/" ]
You can achieve what you want by using `onMouseUp` event. See below... ``` <html> <body> <div id="container" style="border: 1px solid #333" contentEditable="true" onMouseUp="checkMe()">Type text here</div> </body> <script language="javascript"> function checkMe() { var txt = ""; if (window.getSelection) { txt = window.getSelection(); } else if (document.getSelection) { txt = document.getSelection(); } else if (document.selection) { txt = document.selection.createRange().text; } alert("Selected text is " + txt); } </script> </html> ```
Use `OnClick`. `:select` only applies to some form elements.
16,735,454
In my model I have this: ``` validates :name, :presence => true, :uniqueness => true ``` In my controller I have: ``` ... if @location.save format.html { redirect_to @location, :notice => 'Location was successfully created.' } format.json { render :json => @location, :status => :created } ... ``` which successfully creates a record if there isn't already a record with this name in the table. I think it's good practice to check before inserting a possibly duplicate record instead of relying on the DB constraints? I guess I should add something to the controller to check? What's the correct way to do this? Many thanks.
2013/05/24
[ "https://Stackoverflow.com/questions/16735454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/478513/" ]
Add a unique index in your database. That way, if something slips through the model validations (rare, but technically possible), the query to save to the database will fail.
Your validation is correct. Just like all the other answers above, however assuming you want to validate multiple fields for example assuming you have a wishlist, that takes the `user_id` and the `item_id`, you need each item to be added only once by a user, for this kind of scenario add this type of validation to your model ``` Class class_name < ActiveRecord::Base validates_uniqueness_of :item_id, scope: :user_id end ```
44,993,393
I have an hidden div which will contain some HTML inputs which some are needed to be required as part of a form. the div is visible by checking the checkbox and the code looks like this: ```js $(function() { var checkbox = $("#checkbox01"); var hidden = $("#div01"); hidden.hide(); checkbox.change(function() { if (checkbox.is(':checked')) { hidden.show(); } else { hidden.hide(); $("#username").val(""); } }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label><input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label> <div id="div01"> <input name="username" type="text" required> </div> ``` You can see the code in action on [JSfiddle](https://jsfiddle.net/yktnq2aL/) As you can see the div is hidden when the checkbox is unchecked and also the username is cleaned when the div is hidden (checkbox unchecked). How can I make the `required` be added to HTML **only if checkbox is checked**, so user won't get prompt to enter value when the div is hidden by Jquery... ?
2017/07/09
[ "https://Stackoverflow.com/questions/44993393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8052221/" ]
You could just toggle the type to `hidden`, that way it's no longer required ``` $("#checkbox01").on('change', function() { $("#div01").toggle(this.checked) .find('input').prop('type', this.checked ? 'text' : 'hidden') .val(''); }).trigger('change'); ``` ```js $(function() { $("#checkbox01").on('change', function() { $("#div01").toggle(this.checked).find('input').prop('type', this.checked ? 'text' : 'hidden').val(''); }).trigger('change'); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label> <input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label> <div id="div01"> <input name="username" type="text" required="required"> </div> <input type="submit"> </form> ```
Try this: (**JavaScript**) ```js $(function() { var checkbox = $("#checkbox01"); var hidden = $("#div01"); hidden.hide(); checkbox.change(function() { if (checkbox.is(':checked')) { hidden.show(); document.getElementById("username").required = true; } else { hidden.hide(); $("#username").val(""); document.getElementById("username").required = false; } }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label><input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label> <div id="div01"> <input name="username" id="username" type="text"> </div> ``` **jQuery** ``` $("#username").prop('required',true); //to add $("#username").prop('required',false); //to remove ```
27,711,046
apologies for the n00b question, but I have a VBScript that I generated with SAP. This script works just fine. I modified the same script by adding lines (basically just copy/paste and modify field numbers) and I am getting an the error which I will describe below. The redacted WORKING VBScript is below: <http://pastebin.com/iv9AZQkp> The NON-working VBScript is below: <http://pastebin.com/zFBJMdKU> When I run the "non-working" script, it executes up to line 33, then errors when executing line 34 to the end. I receive a prompt "SAP Frontend Server." Error: "The control could not be found by id.-" Does the code in the second VBScript look wrong in any way? I don't understand why the first example works and the second does not. Thank you in advance. Steve Working Script, Lines 31-48: ``` 31 session.findById("wnd[0]").sendVKey 0 32 session.findById("wnd[1]").sendVKey 0 33 session.findById("wnd[1]").sendVKey 0 34 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,0]").text = "PAN-PA-2050-TP-HA2-R" 35 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,1]").text = "PAN-PA-2050-TP-HA2-R" 36 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,2]").text = "PAN-PA-2050-TP-HA2-R" 37 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,3]").text = "PAN-PA-2050-TP-HA2-R" 38 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,4]").text = "PAN-PA-2050-URL2-HA2-R" 39 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,5]").text = "PAN-PA-2050-URL2-HA2-R" 40 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,0]").text = "1" 41 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,1]").text = "1" 42 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,2]").text = "1" 43 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,3]").text = "1" 44 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,4]").text = "1" 45 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,5]").text = "1" 46 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,2]").setFocus 47 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,2]").caretPosition = 19 48 session.findById("wnd[0]").sendVKey 0 ``` Non-working script, Lines 31-64: ``` 31 session.findById("wnd[0]").sendVKey 0 32 session.findById("wnd[1]").sendVKey 0 33 session.findById("wnd[1]").sendVKey 0 34 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,0]").text = "PAN-PA-2050-TP-HA2-R" 35 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,1]").text = "PAN-PA-2050-TP-HA2-R" 36 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,2]").text = "PAN-PA-2050-TP-HA2-R" 37 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,3]").text = "PAN-PA-2050-TP-HA2-R" 38 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,4]").text = "PAN-PA-2050-URL2-HA2-R" 39 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,5]").text = "PAN-PA-2050-URL2-HA2-R" 40 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,6]").text = "PAN-PA-2050-URL2-HA2-R" 41 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,7]").text = "PAN-PA-2050-URL2-HA2-R" 42 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,8]").text = "PAN-PA-500-TP-HA2-R" 43 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,9]").text = "PAN-PA-500-TP-HA2-R" 44 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,10]").text = "PAN-PA-500-TP-HA2-R" 45 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,11]").text = "PAN-PA-500-TP-HA2-R" 46 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,12]").text = "PAN-PA-500-TP-HA2-R" 47 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/ctxtRV45A-MABNR[1,13]").text = "PAN-PA-500-TP-HA2-R" 48 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,0 ]").text = "1" 49 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,1 ]").text = "1" 50 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,2 ]").text = "1" 51 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,3 ]").text = "1" 52 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,4 ]").text = "1" 53 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,5 ]").text = "1" 54 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,6 ]").text = "1" 55 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,7 ]").text = "1" 56 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,8 ]").text = "1" 57 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,9 ]").text = "1" 58 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,10]").text = "1" 59 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,11]").text = "1" 60 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,12]").text = "1" 61 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,13]").text = "1" 62 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,2]").setFocus 63 session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSUBSCREEN_BODY:SAPMV45A:4411/subSUBSCREEN_TC:SAPMV45A:4912/tblSAPMV45ATCTRL_U_ERF_ANGEBOT/txtRV45A-KWMENG[2,2]").caretPosition = 19 64 session.findById("wnd[0]").sendVKey 0 ```
2014/12/30
[ "https://Stackoverflow.com/questions/27711046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4396611/" ]
char type is always padded with spaces to it's length (in your case 8000), you need to use varchar to prevent padding, you can also try to [TRIM](http://msdn.microsoft.com/en-us/library/ee634558.aspx) to get actual text here is from <http://msdn.microsoft.com/en-us/library/ms176089.aspx> > > char [ ( n ) ] > > > > ``` > Fixed-length, non-Unicode string data. n defines the string length and must be a value from 1 through 8,000 > > ``` > > or you can turn off padding > > If SET ANSI\_PADDING is OFF when either CREATE TABLE or ALTER TABLE is > executed, a char column that is defined as NULL is handled as varchar. > > > **UPDATE:** I suppose you have at least 1 row with actual length 8000, which is why max returned it, if you want to calculate number of rows with different length, you can use: ``` SELECT LEN(change) as ChangeLength, COUNT(*) as LengthCount FROM dbo.tAudit GROUP BY LEN(change) ORDER BY 1 ```
There are no CHAR columns involved here. The issue is that a TEXT column always shows a length of 8000, irrespective of the actual length of the string, and no padding spaces have been stored. ANSI\_PADDING ON *allows* trailing spaces to be stored, but again, that is not the case here, as none of the rows I have inspected have even one trailing space.
37,758,137
Problem Statement: I need my result set to include records that would not naturally return because they are NULL. I'm going to put some simplified code here since my code seems to be too long. Table `Scores` has `Company_type`, `Company`, `Score`, `Project_ID` ``` Select Score, Count(Project_ID) FROM Scores WHERE company_type= :company_type GROUP BY Score ``` Results in the following: ``` Score Projects 5 95 4 94 3 215 2 51 1 155 ``` Everything is working fine until I apply a condition to company\_type that does not include results in one of the 5 score categories. When this happens, I don't have 5 rows in my result set any more. It displays like this: ``` Score Projects 5 5 3 6 1 3 ``` I'd like it to display like this: ``` Score Projects 5 5 4 0 3 6 2 0 1 3 ``` I need the results to always display 5 rows. (Scores = 1-5) --- I tried one of the approaches below by Spencer7593. My simplified query now looks like this: SELECT i.score AS `Score`, IFNULL(count(\*), 0) AS `Projects` FROM (SELECT 5 AS score UNION ALL SELECT 4 UNION ALL SELECT 3 UNION ALL SELECT 2 UNION ALL SELECT 1) i LEFT JOIN Scores ON Scores.score = i.score GROUP BY Score ORDER BY i.score DESC And gives the following results, which is accurate except that the rows with 1 in Projects should actually be 0 because they are derived by the "i". There are no projects with a score of 5 or 2. ``` Score Projects 5 1 4 5 3 6 2 1 1 3 ``` --- Solved! I just needed to adjust my count to specifically look at the project count - count(project) rather than count(\*). This returned the expected results.
2016/06/10
[ "https://Stackoverflow.com/questions/37758137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6452068/" ]
You can specify the [actual column name](http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/basic_use.html#defining-attributes) (if different from the attribute name) as the first argument to `Column`: ``` emp_d = Column("employee_desgination", String) ```
// tested on sqlalchemy1.4 if use this form define: // for others come here ``` sqlalchemy.Table('sometable', metadata, Column('from', Intege) ) ``` alias can be define by this: ``` t1 = Table('sometable', metadata, Column('from', Integer, key='from_') ) ``` and use column by ``` t1.c.from_ ``` but, in result, still use `record.from` ref: <https://groups.google.com/g/sqlalchemy/c/0mV5R2KUZgI/m/fpI7dC_mGrsJ>
170,706
What is the easiest way to get the IP address from a hostname? I was thinking about trying a [`ping`](http://en.wikipedia.org/wiki/Ping_%28networking_utility%29) and parse it from the output. However, that doesn't seem very nice and will probably not work the same way on all systems. I searched a bit around and found solutions with [`nslookup`](https://en.wikipedia.org/wiki/Nslookup), but that doesn't work for hostnames in `/etc/hosts`.
2010/08/14
[ "https://serverfault.com/questions/170706", "https://serverfault.com", "https://serverfault.com/users/48295/" ]
This ancient post seem to have many creative solutions. If I need to make sure also `/etc/hosts` gets accessed, I tend to use `getent hosts somehost.com` This works, at least if `/etc/nsswitch.conf' has been configured to use files (as it usually is).
Using `ping` is not that bad since you generally do not have any strong dependencies. Here is the function I used on Linux systems : ``` getip () { ping -c 1 -t 1 $1 | head -1 | cut -d ' ' -f 3 | tr -d '()' ; } ```
30,168,779
So I wanted to link to RealmSwift in my own framework and these are the steps I took: 1. Add `RealmSwift` as a subproject ![enter image description here](https://i.stack.imgur.com/wEtYj.png) 2. Link the framework: ![enter image description here](https://i.stack.imgur.com/wPKXM.png) 3. Add the dependency ![enter image description here](https://i.stack.imgur.com/DDr4k.png) 4. Import `RealmSwift` into the Swift file: ![enter image description here](https://i.stack.imgur.com/beTg8.png) And I got the error: `Missing required modules: 'Realm.Private', 'Realm'`. How can I solve this issue? Thanks!
2015/05/11
[ "https://Stackoverflow.com/questions/30168779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I had the same issue, turns out that the file that showed the error was used by two different targets. When adding Realm with SPM, we can only select one target. I solved the with the following steps: 1. In the Project Navigator, select the target that lacks Realm 2. In `Build Phases > Link Binary With Libraries`, add `RealmSwift` and `Realm`.
Something similar happened to me when I did the pod install... Make sure you open the appname.xcworkspace file not the appname.xcodeproj after doing the pod-install with CocoaPods. The error No such module 'RealmSwift' will occur from any file where 'import RealmSwift' is set up if not opened from appname.xcworkspace.
10,388,564
How do I make the background in an image transparent? Most of my images have a white background. When I use them in my website with my body background color black it looks awkward. I have unsuccessfully tried using [Fireworks](http://en.wikipedia.org/wiki/Adobe_Fireworks) magic wand tool to remove the white background. I have also applied the CSS transparent property but it does not work for me either. What is the best means of making the background color of an image transparent?
2012/04/30
[ "https://Stackoverflow.com/questions/10388564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366440/" ]
Use photoshop to remove the background and save it as .png remove it like this: <http://www.addictivetips.com/windows-tips/how-to-remove-image-background-in-photoshop-tutorial/> or using magic eraser. good luck!
If you don't have Photoshop - the easiest way to do it is with MS Word (2010). 1. Change a background of your page to black (Page Layout --> Page Color --> Set to the color of your website) 2. Insert --> Picture 3. Once your have inserted pickture, go to **Picture Tools** and find **Background Removal** tool under **Picture Tools**. 4. Select area you want to remove and click "Remove" and then "Done"
48,603,244
Technically speaking, based on posts I've read here, Hash table is indeed O(n) time lookup in the worst case. But I don't get how the internal mechanics guarantee it to be O(1) time on average. My understanding is that given some n elements, the ideal case is there are n buckets, which result in O(1) space. This is where I'm stuck. Suppose I want to lookup whether a key is in the dictionary, this definitely takes me O(n) time. So why does it make a difference when I want to search whether an element is in the hash table by using its key's hash value? To put it concisely, searching using raw key values gives O(n) time but using hash values it's O(1) time. Why is that? Wouldn't I still need to look up the hash values one by one to see which one matches? Why does the hashing let me know immediately which element to retrieve or whether such an element exists or not?
2018/02/03
[ "https://Stackoverflow.com/questions/48603244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8845060/" ]
Great question! Assume 1. We want to map `string`s to `value`s 2. `hashFunction(string) => hashedIndex : int` in O(1) 3. `valueArray : [any]` stores `value`s 4. `valueIndex : int` is the first empty index in `valueArray` 5. `lookupArray : [int]` stores each `valueIndex` at `hashedIndex` 6. array lookups are O(1). ```js // Setting a value valueArray[valueIndex] = value hashedIndex = hashFunction(string) lookupArray[hashedIndex] = valueIndex // Looking up a value hashedIndex = hashFunction(string) // O(1) valueIndex = lookupArray[hashedIndex]; // O(1) array lookup value = valueArray[valueIndex]; // O(1) array lookup ``` Lots of details omitted to answer your question clearly. Hope that helps!
i think the word "hash" is scaring people. Behind the scene, hash tables are data structures that stores the key/value pairs in an array. The only difference here is, we do not care about the position of the key value pair. There is no INDEX here. Look up for an array item O(1). it is independent of size of the array and independent of position. you just enter index number, and item is retrieved. so how much time did look up need to complete. it is O(1). In hash tables, when you store key/value pair, key value gets hashed and stored in the corresponding memory slot. ``` {name:"bob"} //name will be hashed hash(name) = ab1234wq //this is the memory address [["name","bob"]] // will be store at memory adress ab1234wq ``` when you look up for "name", it will get hashed and as the main feature of hashing functions, it will return same the result "ab1234wq". So the programming engine will look at this address, will see the array and will return the value. As you can see, this operation is same as array look up.
51,742,698
I have designed code as: ``` import csv import numpy as np data = [['Diameter', 'color', 'no']] with open('samp1.csv', 'w') as f: writer = csv.writer(f, delimiter=',') for row in data: writer.writerow(row) for i in np.arange(20,30,0.2): writer.writerow(i) f.close() ``` And I want to save numbers from 20-30 with an increment of 0.2 in the *diameter* column, but it's giving errors and not even saving the CSV file. Can someone suggest any solution? Even there are various ranges for other columns too, so I need the same method to work for that code. CSV example ``` diameter color number 20 2 3 20 2.5 3 20 3 3 20 3.5 3 20.2 2 3 20.2 2.5 3 20.2 3 3 20.2 3.5 3 . . . . 22 2 4 22 2.5 4 22 3 4 22 3.5 4 22.2 2 4 22.2 2.5 4 22.2 3 4 22.2 3.5 4 ```
2018/08/08
[ "https://Stackoverflow.com/questions/51742698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10174453/" ]
Don't forget to add ``` android.useAndroidX=true android.enableJetifier=true ``` to your gradle.properties. I always forget this when I get on a new machine because gradle.properties is not in source control. Would be great if we got a sensible error in this case.
I have this problem too. When use this library in dependencies ``` implementation 'com.google.android.material:material:1.0.0' ``` Give this : > > Manifest merger failed : Attribute application@appComponentFactory > value=(androidx.core.app.CoreComponentFactory) from > [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 is also > present at [com.android.support:support-compat:28.0.0] > AndroidManifest.xml:22:18-91 > value=(android.support.v4.app.CoreComponentFactory). Suggestion: add > 'tools:replace="android:appComponentFactory"' to element at > AndroidManifest.xml:5:5-40:19 to override. > > > I have this problem by switching to AndroidX Going to Refactor->Migrate to AndoridX (in toolbar of android studio 3.2 and above) And my problem solve [refrence](https://developer.android.com/jetpack/androidx/migrate)
45,081,579
I searched for how to initialise requestPermissions and found the code below: ``` if (ActivityCompat.checkSelfPermission((Activity)mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions((Activity)mContext, new String[]{ android.Manifest.permission.ACCESS_FINE_LOCATION }, Integer constant required); ``` It requires a third parameter which is Inter constant for FINE LOCATION. I could not find that. Please help me with this.
2017/07/13
[ "https://Stackoverflow.com/questions/45081579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8302211/" ]
In CMD you'd do something like this: ``` @echo off set "basedir=C:\some\folder" set "outfile=C:\path\to\output.txt" (for /r "%basedir%" %f in (*.txt) do type "%~ff") > "%outfile%" ``` For use in batch files you need to change `%f` to `%%f` and `%~ff` to `%%~ff`. --- In PowerShell you'd do something like this: ``` $basedir = 'C:\some\folder' $outfile = 'C:\path\to\output.txt' Get-ChildItem $basedir -Include *.txt -Recurse | Get-Content | Set-Content $outfile ```
Code 3 is not bad but it won't work with spaces in a path because you use the standard `delims` as you're not providing one. Also there a several other errors about working with spaces in a path. The following code works and combine all `txt files` in all subdirectories. It will create a new file `list.txt` in the folder where this batch file is located. If there is already an existing `list.txt` it will be overwritten. Note that it's a batch file: ```cmd @echo off set "folder=C:\Users\user\Desktop\DummyFolder\" rem create new empty file: list.txt in directory of batch file: %~dp0 break>"%~dp0list.txt" rem loop through all output lines of the dir command, unset delimns rem so that space will not separate for /F "delims=" %%a in ('dir /b /s "%folder%"') do ( rem just look for txt files if "%%~xa" == ".txt" ( rem don't use the list.txt if not "%%a" == "%~dp0list.txt" ( rem append the output of the whole block into the file (echo/------------------------------ type "%%a" echo/)>>"%~dp0list.txt" ) ) ) ``` If you don't understand something it's quite easy to find something good on the internet because there are several great batch scripting sites. Further you can always use `echo This is a message visible on the command prompt` to display something that might be useful e.g. variables etc. With that you can "debug" and look what happens. Some explanations beyond the comments (`rem This is a comment`) in the code: **1. `break` command:** To clear a file I use the break command which will produce no output at all. That empty output I redirect to a file, read it here: <https://stackoverflow.com/a/19633987/8051589>. **2. General variables:** You set variables via `set varname=Content` I prefer the way as I do it with quotes: `set "varname=Content"` as it works with redirection characters also. Use the variable with one starting `%` and one trailing `%` e.g. `echo %varname%`. You can read a lot of it on <https://ss64.com/nt/set.html>. I think ss64 is probably the best site for batch scripting out there. **3. Redirection `>` and `>>`:** You can redirect the output of a command with `>` or `>>` where `>` creates a new file and overwrites existing files and `>>` appends to a file or create one if not existing. There are a lot more thing possible: <https://ss64.com/nt/syntax-redirection.html>. **4. `for /f` loop:** In a batch file you loop through the lines of a command output by using a `for /f` loop. The variable that is used will be written with 2 `%` in front of it, here `%%a`. I also set the delimiter `delimns` to nothing so that the command output will not be separated into several tokens. You can read a lot of details about a `for /f` loop at: <https://ss64.com/nt/for_cmd.html>. **5. Special variable syntax `%%~xa` and `%~dp0`:** The variable `%%a` which hold one line of the `dir` command can be expand to the file extension only via: `%%~xa` as explained here: <https://stackoverflow.com/a/5034119/8051589>. The `%~dp0` variable contains the path where the batch file is located see here: <https://stackoverflow.com/a/10290765/8051589>. **6. Block redirection `( ... )>>`:** To redirect multiple commands at once you can open a block `(`, execute commands, close the block `)` and use a redirection. You could also execute every command and redirect that only that would have the same effect.
19,073,959
Newbie here typesetting my question, so excuse me if this don't work. I am trying to give a *bayesian classifier* for a multivariate classification problem where input is assumed to have *multivariate normal distribution*. I choose to use a discriminant function defined as **log(likelihood \* prior)**. However, from the distribution, $${f(x \mid\mu,\Sigma) = (2\pi)^{-Nd/2}\det(\Sigma)^{-N/2}exp[(-1/2)(x-\mu)'\Sigma^{-1}(x-\mu)]}$$ i encounter a term -log(det($S\_i$)), where $S\_i$ is my sample covariance matrix for a specific class i. Since my input actually represents a square image data, my $S\_i$ discovers quite some correlation and resulting in det(S\_i) being zero. Then my discriminant function all turn Inf, which is disastrous for me. I know there must be a lot of things go wrong here, anyone willling to help me out? --- UPDATE: Anyone can help how to get the formula working?
2013/09/29
[ "https://Stackoverflow.com/questions/19073959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2255305/" ]
`add_resource` accepts two arguments, `resource_class_args` and `resource_class_kwargs`, used to pass arguments to the constructor. ([source](http://flask-restful-cn.readthedocs.io/en/0.3.5/intermediate-usage.html#passing-constructor-parameters-into-resources)) > > So you could have a Resource: > > > ``` from flask_restful import Resource class TodoNext(Resource): def __init__(self, **kwargs): # smart_engine is a black box dependency self.smart_engine = kwargs['smart_engine'] def get(self): return self.smart_engine.next_todo() ``` > > You can inject the required dependency into TodoNext like so: > > > ``` smart_engine = SmartEngine() api.add_resource(TodoNext, '/next', resource_class_kwargs={ 'smart_engine': smart_engine }) ```
based on @Greg answer I've added an initialization check in the **init** method: creating and calling Todo Resource class for flask-restful api: ``` todo = Todo.create(InMemoryTodoRepository()) api.add_resource(todo, '/api/todos/<todo_id>') ``` The Todo Resource class: ``` from flask_restful import reqparse, abort, Resource from server.ApiResources.DTOs.TodoDTO import TodoDTO from server.Repositories.ITodoRepository import ITodoRepository from server.Utils.Exceptions import InvalidInstantiationError from server.Utils.GeneralUtils import member_exists class Todo(Resource): """shows a single todo item and lets you delete a todo item use the 'create' class method to instantiate the class """ def __init__(self): if not member_exists(self, "todo_repository", of_type=ITodoRepository): raise InvalidInstantiationError("Todo", "todo_repository", "ITodoRepository", "create") self._parser = reqparse.RequestParser() self._parser.add_argument('task', type=str) @classmethod def create(cls, todo_repository): """ :param todo_repository: an instance of ITodoRepository :return: class object of Todo Resource """ cls.todo_repository = todo_repository return cls ``` the member\_exists helper methods: ``` def member_exists(obj, member, of_type): member_value = getattr(obj, member, None) if member_value is None: return False if not isinstance(member_value, of_type): return False return True ``` and the custom exception class: ``` class InvalidInstantiationError(Exception): def __init__(self, origin_class_name, missing_argument_name, missing_argument_type, instantiation_method_to_use): message = """Invalid instantiation for class '{class_name}': missing instantiation argument '{arg}' of type '{arg_type}'. Please use the '{method_name}' factory class method""" \ .format(class_name=origin_class_name, arg=missing_argument_name, arg_type=missing_argument_type, method_name=instantiation_method_to_use) # Call the base class constructor with the parameters it needs super(InvalidInstantiationError, self).__init__(message) ``` Thus, trying to use the default constructor will end up in getting this exception: **server.Utils.Exceptions.InvalidInstantiationError: Invalid instantiation for class 'Todo': missing instantiation argument 'todo\_repository' of type 'ITodoRepository'. Please use the 'create' factory class method** edit: this can be useful for using dependency injection with flask-restful api Resource classes (with or without IoC) edit 2: we can even go cleaner and add another help function (ready to import): ``` def must_have(obj, member, of_type, use_method): if not member_exists(obj, member, of_type=of_type): raise InvalidInstantiationError(obj.__class__.__name__, member, of_type.__name__, use_method) ``` and then use it in the constructor like that: ``` from server.Utils.GeneralUtils import must_have class Todo(Resource): def __init__(self): must_have(self, member="todo_repository", of_type=ITodoRepository, use_method=Todo.create.__name__) ```
8,364,918
In the ARM NEON documentation, it says: > > [...] some pairs of instructions might have to wait until the value is written back to the register file. > > > I haven't come across a list that defines the instruction pairs that *can* use forwarded results and the instruction pairs that have to wait for write back. Does anyone know of a table or documentation that lists these pairs?
2011/12/03
[ "https://Stackoverflow.com/questions/8364918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1028638/" ]
You can group adjacent items in a sequence using the [GroupAdjacent Extension Method](https://stackoverflow.com/a/8364977/76217) (see below): ``` var result = unorderedList .OrderBy(x => x.date) .GroupAdjacent((g, x) => x.A == g.Last().A && x.B == g.Last().B && x.date == g.Last().date.AddDays(1)) .ToList(); ``` *Example:* ```none (1,1) 2011-01-01 \ (1,1) 2011-01-02 > Group 1 (1,1) 2011-01-03 __/ (2,1) 2011-01-04 \ (2,1) 2011-01-05 > Group 2 (2,1) 2011-01-06 __/ (1,1) 2011-01-07 \ (1,1) 2011-01-08 > Group 3 (1,1) 2011-01-09 __/ (1,1) 2011-02-01   \ (1,1) 2011-02-02    >  Group 4 (1,1) 2011-02-03 __/ ``` *Extension Method:* ``` static IEnumerable<IEnumerable<T>> GroupAdjacent<T>( this IEnumerable<T> source, Func<IEnumerable<T>, T, bool> adjacent) { var g = new List<T>(); foreach (var x in source) { if (g.Count != 0 && !adjacent(g, x)) { yield return g; g = new List<T>(); } g.Add(x); } yield return g; } ```
If I understood you well, a simple Group By would do the trick: ``` var orderedList = unorderedList.OrderBy(o => o.date).GroupBy(s => new {s.A, s.B}); ``` Just that. To print the results: ``` foreach (var o in orderedList) { Console.WriteLine("Dates of group {0},{1}:", o.Key.A, o.Key.B); foreach(var s in o){ Console.WriteLine("\t{0}", s.date); } } ``` The output would be like: ``` Dates of group 2,3: 02/12/2011 03/12/2011 Dates of group 4,3: 03/12/2011 Dates of group 1,2: 04/12/2011 05/12/2011 06/12/2011 ``` Hope this helps. Cheers
39,781,069
I have an Event model with `parent_id` and `date` attributes: Event.rb ``` has_many :children, :class_name => "Event" belongs_to :parent, :class_name => "Event" ``` I have no issues calling `event.parent` or `event.children`. A child event never has a child itself. I am trying to add a scope to this model so that I can return the child with the nearest future date for every parent. Something like: ``` scope :future, -> { where("date > ?", Date.today) } scope :closest, -> { group('"parent_id"').having('date = MAX(date)') } Event.future.closest ==> returns the closest child event from every parent ``` But the above `:closest` scope is returning more than one child per parent.
2016/09/29
[ "https://Stackoverflow.com/questions/39781069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4621100/" ]
Ignoring Rails for a moment, what you are doing in SQL is the [greatest-n-per-group](/questions/tagged/greatest-n-per-group "show questions tagged 'greatest-n-per-group'") problem. Here are [lots of solutions](https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group/25534279). I would choose either `DISTINCT ON` or `LEFT OUTER JOIN LATERAL`. Here is how it might look in Rails: ``` scope :closest, -> { select("DISTINCT ON (parent_id) events.*"). order("parent_id, date ASC") } ``` This will give you **the child objects**. (You probably also want a condition to exclude rows with no `parent_id`.) From your own solutions, it sounds like that's what you want. If instead you want **the parent objects**, with an optional attached child object, then use a lateral join. That is a little trickier to translate into ActiveRecord though. If it's acceptable to do it in two queries, this looks like it should work (sticking with `DISTINCT ON`): ``` has_one :closest_child, -> { select("DISTINCT ON (parent_id) events.*"). order("parent_id, date ASC") }, class_name: Event, foreign_key: "parent_id" ``` Then you can say `Event.includes(:closest_child)`. Again, you probably want to filter out all the non-parents though.
Your own answer looks good, but I would refine it the following way: ``` scope :closest, -> { where.not(parent_id: nil).group(:parent_id).minimum(:date) } ``` And very important or else in production you would always get the deployment date as `Date.today` because it will only reload in development: ``` scope :future, -> { where("date > ?", Proc.new { Date.today }) } ```
764,385
We have seen the argument for proving the above statment using Zorn's Lemma by asserting the existence of a maximal linearly independent set which serves a basis. In finite dimensional vector space, a basis is same as a maximal linearly independent and also same as a minimal spanning set. Does the notion of minimal spanning set make sense for arbitrary vector spaces? Moreover, can the statement that every vector space has a basis be proved using the partially ordered set $\Sigma = \lbrace A \subset V \vert Span(A) =V \rbrace $ with the partial order $A \leq B$ iff $B \subset A $? Can one say intersection of a chain of spanning sets in this poset is also a spanning set?
2014/04/22
[ "https://math.stackexchange.com/questions/764385", "https://math.stackexchange.com", "https://math.stackexchange.com/users/138157/" ]
It doesn't work. See Keith Conrad's [note](http://www.math.uconn.edu/~kconrad/blurbs/zorn1.pdf) (namely page 16). Here is a relevant screenshot. ![enter image description here](https://i.stack.imgur.com/AyuSv.png)
*Does the notion of minimal spanning set make sense for arbitrary vector spaces?* Sure: why not? The notion has a sensible definition. A minimal spanning set $S$ is one for which $\langle S'\rangle \subsetneq \langle S\rangle $ whenever $S'$ is a proper subset of $S$. If instead $S'$ were a proper subset of $S$, and yet $\langle S'\rangle = \langle S\rangle $, then it would follow that every element of $S\setminus S'$ is a linear combination of the elements of $S'$, and hence linearly dependent upon the elements of $S'$. So, elements could be removed from $S$ while preserving the span, and $S$ would not be a minimal spanning set. --- > > *..can the statement that every vector space has a basis be proved using the partially ordered set $\Sigma = \lbrace A \subset V \vert Span(A) =V \rbrace $ and define partial order $A \leq B$ iff $B \subset A $. Can one say intersection of all totally ordered spanning set is also a spanning set?* > > > (Prism's answer tells why the answer is negative.) --- So in summary, the poset of spanning sets ordered by inclusion (and the poset of spanning sets ordered by reverse-inclusion) have perfectly well-defined minimal (respectively maximal) elements. It's just that the hypotheses of Zorn's lemma are not satisfied, and therefore it can't successfully be applied to deduce the existence of such minimal (resp. maximal) elements.
11,726,678
I want to display only `div.card1` when a user clicks on a selection menu I have made ``` <table id="flowerTheme"> <tr> <td> <div class="card1"> <div class="guess"><a href="#" id="flower1" class="quickFlipCta"><img src="Test Pictures/QuestionMark.gif" /></a></div> <div class="remember"><a href="#" class="quickFlipCta"><img src="Test Pictures/flower.gif" /></a></div> </div> </td> <td> <div class="card2"> <div class="guess"><a href="#" id="flower1" class="quickFlipCta"><img src="Test Pictures/QuestionMark.gif" /></a></div> <div class="remember"><a href="#" class="quickFlipCta"><img src="Test Pictures/flower.gif" /></a></div> </div> </td> </tr> </table> ``` I have a function that toggles the class 'selected' when the user clicks on an image. The following works perfectly: ``` if($('.flowerThemePic').hasClass('selected') && $('.sixCardLayout').hasClass('selected')) { $('#flowerTheme').css('display', 'inline'); ``` However, as I stated before, I would like to have `card2` to not be displayed. I have tried: ``` if($('.flowerThemePic').hasClass('selected') && $('.sixCardLayout').hasClass('selected')) { $('#flowerTheme').not('.card2').css('display', 'inline') ``` But this does not do anything. I have also tried: ``` if($('.flowerThemePic').hasClass('selected') && $('.sixCardLayout').hasClass('selected')) { $('#flowerTheme').find('div').not('.card2').css('display', 'inline') ``` But this hides both cards. What would be the right method of displaying `card1` and not `card2`?
2012/07/30
[ "https://Stackoverflow.com/questions/11726678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1464197/" ]
``` $('#flowerTheme').css('display', 'inline'); $('.card2').hide(); ```
You can write a javascript function to hide children... ``` function hideSpecificChildren(childClass){ var child = document.getElementByClass(childClass); if(tab.style.display == "block") { tab.style.display = "none"; }else { tab.style.display = "block"; } } ```
818,132
I have thumbnails on a page, as such: ``` <div id="credits"> <a href="largeimage1.jpg" alt="credits1.php"><img src="thumb1"></a> <a href="largeimage2.jpg" alt="credits2.php"><img src="thumb2"></a> <a href="largeimage3.jpg" alt="credits3.php"><img src="thumb3"></a> </div> <div id="zoom"></div> <div id="credits"></div> ``` I'm looking to do the following: * user clicks thumb1 > largeimage1 loads in #zoom AND credits1.php loads in #credits * user clicks thumb2 > largeimage2 loads in #zoom AND credits2.php loads in #credits * etc. Is this possible with jquery? ie. is it possible to make TWO (2) ajax calls on the same page with one click as in above? I currently have the following code working for the LARGE image ajax call: ``` <script type="text/javascript"> $(document).ready(function(){ $("a").click(function(){ var largePath = $(this).attr("href"); $("#zoom img").fadeOut("slow", function() { $(this).attr({ src: largePath }).fadeIn("slow"); }); return false; }); }); </script> ``` and it works like a charm - but I now have a situation where I'd like to load up credits for the images in another div. Any help is greatly appreciated. :)
2009/05/03
[ "https://Stackoverflow.com/questions/818132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99112/" ]
Above this line: ``` return false; ``` Add this: ``` $('#credits').load($(this).attr('alt')); ``` The whole point of asynchronous requests is that you can fire as many as you want while you keep going. You might want to have some kind of loading indicator that something is happening when you use load, as well as maybe some error handling, but the above should do the trick at a basic level.
Just to make sure I'm not missing something about jquery (I'm more familiar with mootools), your first bit of code won't work unless you have an image already inside the zoom div. I don't see anything in your code that injects a new image into the div... it only targets an existing image and updates its attributes. Or am I missing something?
14,486,101
> > **Possible Duplicate:** > > [Should you access a variable within the same class via a Property?](https://stackoverflow.com/questions/271318/should-you-access-a-variable-within-the-same-class-via-a-property) > > > I ran into this recently and was curious if there was some sort of standard for which one you should reference while inside a class. I mean really it shouldn't make a difference whether you access the member variable directly or go through the property (unless you need to dodge some custom setter code), but I wanted to be sure there wasn't a best practice for it. ``` partial class MyClass { private string foo; internal string Foo { get { return foo; } private set { foo=value; // I do other stuff } } public void DoSomething() { //Option 1; Foo="some string"; //Option 2; foo="some string"; } } ```
2013/01/23
[ "https://Stackoverflow.com/questions/14486101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1454813/" ]
This shouldn't be a choice you really make. Either the code in the setter is supposed to run, in which case use the property, or it's not, in which case you use the member variable. In most all situations one is right and one is wrong. Neither is always right/wrong in the general case, and it's unusual for it to "not matter". For example, if the setter code is firing a "changed" event, do you want external objects to be notified that it changed, or not? If you're changing it in response to a previous change, probably not (infinite recursion anyone?) if no, you probably want to make sure it's fired (so that you're not changing a value and not notifying anyone of changes). If it's just validating that the value being set is valid, then either you know that, in this context, the value is already validated and must be valid, in which case there is no need to validate again; set the property. If you haven't yet validated what you're about to set then you *want* the validation logic to run, so use the property.
If you wrapped the field `foo` in the property `Foo`, you probably did so for a reason (conversion, events, validation, etc). So, generally speaking, the only place you should be referencing the field `foo` is in the getters and setters for the property `Foo`. The rest of the code should reference the property `Foo`. I'm sure there exists some obscure situation where you would need to bypass the property's getters and setters, and that's certainly okay to do, but such situations would be the exception to the rule.
18,522
So I did some algebraic topology at university, including homotopy theory and basic simplicial homology, as well as some differential geometry; and now I'm coming back to the subject for fun via Hatcher's textbook. A problem I had in the past and still have now is how to understand projective space RP^n - I just can't visualise it or think about it in any concrete way. Any ideas? edit: Essentially RP^n is always the example I don't understand. So when for example Hatcher says that S^n is of a CW complex with two cells e^0 and e^n, I can picture what's going on because I know what spheres look like and I can imagine the attachment in some concrete-ish way. But when he says "we see that RP^n is obtained from RP^{n-1} by attaching an n-cell [...] it follows by induction on n that RP^n has a cell complex structure e^0 U e^1 U ... e^n" - my brain just gives up.
2010/03/17
[ "https://mathoverflow.net/questions/18522", "https://mathoverflow.net", "https://mathoverflow.net/users/1256/" ]
You can "visualize" the cell structure on $\mathbb{R}P^n$ rather explicitly as follows. The set of tuples $(x\_0, ... x\_n) \in \mathbb{R}^{n+1}$, not all equal to zero, under the equivalence relation where we identify two tuples that differ by multiplication by a nonzero real number, can be broken up into pieces depending on which of the $x\_i$ are equal to zero. * If $x\_0 \neq 0$, the corresponding points can be written $(1, x\_1, ... x\_n)$, and they form a subspace isomorphic to $\mathbb{R}^n$. * If $x\_0 = 0$ and $x\_1 \neq 0$, the corresponding points can be written $(0, 1, x\_2, ... x\_n)$, and they form a subspace isomorphic to $\mathbb{R}^{n-1}$. And so forth. One way to say this is that the tuples where $x\_0 \neq 0$ form an affine slice or affine cover of $\mathbb{R}P^n$ and the tuples where $x\_0 = 0$ constitute the "points at infinity," which themselves form a copy of $\mathbb{R}P^{n-1}$.
A Point in $RP^n$ corresponds to a pair of antipodal points on $S^n$ - so just practice visualizing two antipodal points on a sphere every time you say Point. Such an approach is clearly equivalent to other definitions, but I find it good for "seeing." The standard cell structure is then defined by a Point being in the interior of the $i$-cell if and only if the first $n-i$ coordinates of the corresponding pair of points vanish. You can also visualize Lens spaces in this way: a single point in a Lens space is seen as a collection of some $k$ points on the unit sphere in some ${\mathbb C}^n$, which are all related by multiplication by some $k$th rood of unity.
50,739,802
I am trying to extend an open source automation testing framework which uses ExtJS. I am new to ExtJS and have tried to play around around with its views. Now I wish to use grid grouping in such a way that when I click on an icon on the group header, it should append all the data of its children in an array and fire that event in the controller along with the data. I tried adding groupclick to my listeners but it does not seem to work. Snapshot of my page looks like this: [1]: <https://i.stack.imgur.com/7LeMn.png> Following is my code of its view: ``` Ext.define('Redwood.view.Reportsgrid', { extend: 'Ext.grid.Panel', alias: 'widget.reportsgrid', store: 'Reports', selType: 'rowmodel', title: "[All Executions]", features: [{ ftype:'grouping', groupHeaderTpl: "Test Case Name: {name}", // enableGroupingMenu:true }], listeners:{ groupclick: function (view, node, group, e, eOpts) { view.features[0].collapseAll(); view.features[0].expand(group); } }, viewConfig: { markDirty: false }, minHeight: 150, height: 500, plugins: [ "bufferedrenderer"], manageHeight: true, initComponent: function () { var reportsView = this; var me = this; this.tbar ={ xtype: 'toolbar', dock: 'top', items: [ ] }; this.columns = [ /* { xtype: 'actioncolumn', header: 'Action', width: 75, weight: 1, align: 'center', items: [ { icon: 'images/symbol_sum.png', tooltip: 'Aggregated Report', itemId: "aggregationReport", handler: function(grid, rowIndex, colIndex) { var report = this.up("reportsView"); report.fireEvent('aggregate') } } ] }, */ { header: 'Executions', dataIndex: 'name', flex: 1, width: 200, weight: 2, summaryType: 'count', summaryRenderer: function(value,metaData,record){ return "<p style='font-weight:bold;color:#000000'>"+value+"</p>"; } }, ]; this.callParent(arguments); } }); ```
2018/06/07
[ "https://Stackoverflow.com/questions/50739802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8186671/" ]
``` someOperation(me.flatMap(_.secondName)) ``` See [ScalaDoc](https://www.scala-lang.org/api/2.12.6/scala/Option.html#flatMap[B](f:A=%3EOption[B]):Option[B]). You can use `map` for non-`Option` properties: `me.map(_.age)` is `Option[Int]`.
As I understood, you need to extract person fields and pass it into the method someOperation. Right? If so, you can use pattern matching for this: ``` someOperation( me match { case Some(person) => person.firstName case None => None } ) ```
45,092,274
I'm fairly new to C, and today I was introduced to Valgrind. I installed it and ran it on my C calculator/equation parser that I'm working on to figure out why I was having a segmentation fault (core dumped), and I got this: ``` ==20== Process terminating with default action of signal 11 (SIGSEGV): dumping core ==20== General Protection Fault ==20== at 0x4008E27: _dl_map_object (dl-load.c:2317) ==20== by 0x40014DD: map_doit (rtld.c:642) ==20== by 0x4010193: _dl_catch_error (dl-error.c:187) ==20== by 0x4002169: do_preload (rtld.c:831) ==20== by 0x4002169: handle_ld_preload (rtld.c:929) ==20== by 0x4004DEE: dl_main (rtld.c:1667) ==20== by 0x40176F4: _dl_sysdep_start (dl-sysdep.c:249) ==20== by 0x4001BB7: _dl_start_final (rtld.c:347) ==20== by 0x4001BB7: _dl_start (rtld.c:573) ==20== by 0x4001267: ??? (in /lib/x86_64-linux-gnu/ld-2.19.so) ==20== by 0x1: ??? ==20== by 0x1FFF0008AE: ??? ==20== by 0x1FFF0008BB: ??? ``` Of course, I have no idea what it means, and the other things I've found about similar errors haven't made much sense to me. Can someone explain this in a relatively simple way that someone like me can understand? EDIT: I tried running it through gdb (ass suggested by @pm100), and only got this: `Program received signal SIGSEGV, Segmentation fault. 0x000000000040067b in ?? ()` EDIT: Since my code was asked for, here it is. I'm probably doing a lot wrong. ``` #include <stdlib.h> #include <string.h> #include <stdio.h> void write(char** dest, char* src, int index) { int i = 0; for (i = 0; src[i] != '\0'; i++) { dest[index][i] = src[i]; } dest[index][i] = '\0'; return; } void crite(char** dest, char src, int index) { int i = 0; dest[index][0] = src; dest[index][1] = '\0'; return; } void evaluate(char* args) { int i = 0; int j = 0; const char* numbers = "1234567890"; const char* operators = "+-*/"; int chunk = 0; char** chunks = calloc(24, sizeof(char*)); char* current = calloc(24, sizeof(char)); for (i = 0; strchr("\0\n", args[i]) == NULL; i++) { //printf("Args[i]:%c\n\n", args[i]); if (strchr(numbers, args[i]) != NULL) { //printf("Number added to current: %c\n\n", args[i]); current[j] = args[i]; //printf("\nCurrent: %s\n", current); j++; } else if (strchr(operators, args[i]) != NULL) { write(chunks, current, chunk); chunk++; crite(chunks, args[i], chunk); chunk++; j = 0; free(current); current = calloc(24, sizeof(char)); //printf("Terminated with operator and operator added.\n\n"); } else { printf("ERROR: Encountered invalid token.\n\n"); return; } } for (i = 0; chunks[i] != NULL; i++) //printf("\n-Chunk: %s\n\n", chunks[chunk]); return; } int main(int argc, char** argv) { evaluate(argv[1]); } ``` The command I used to compile it was `gcc calculator.c -g -o calculator` Sample command: `./calculator 1*2` UPDATE: The issue with Valgrind was caused by the Windows subsystem I was using, so as long as you're running Valgrind on linux it should be fine. I tried it in a VM and it worked. Also, thanks for helping me fix my Segmentation Fault even though that wasn't what the question was originally about:)
2017/07/13
[ "https://Stackoverflow.com/questions/45092274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8218230/" ]
This is a stack trace from deep within the Linux loader. Valgrind creates a sandbox execution environment and loads your program into that, where its various tools can insert their own instrumentation code into your instruction stream. This is exotic stuff: very dependent a good valgrind build and care in building your program under test correctly. This tiny stack trace alone can't possibly explain what's going wrong. The loader could be dying while trying to load valgrind. Or perhaps its dying within the sandbox as its trying to load you program. The problem could be in the valgrind binary or the binary for your program, causing the Linux loader to fail. It's even possible (I don't know) that valgrind includes its own copy of the loader, and that copy built incorrectly and so is dying. The bigger picture is that valgrind isn't a good tool do debug a simple seg fault in your (I expect) small program. Two things much more likely to bear fruit are to build and run the program correctly so that `gdb` produces a correct symbolic stack trace and to simply insert `fprintf`s. This ought to produce a stack trace with gdb: ``` $ gcc calculator.c -g -o calculator $ gdb ./calculator (gdb) run ``` If you need command line args to trigger the bug, you can give them with `set args`, e.g. ``` (gdb) set args 1*2 (gdb) run ``` If you're not seeing a stack trace, your build environment is almost certainly broken: there's something wrong with your compiler or gdb. The other technique, which isn't very elegant but nonetheless can be effective is to add `fprintf(stderr, ...)`s starting with the first line in `main()` and periodically after. The last output tells you how far the execution got. When you're a beginning programmer, it can be more efficient to avoid learning new tools until you're familiar with the language, compiler, and write-compile-debug-revise cycle.
When I run your program I get a complaint from gdb about line 8 (my cut and paste wont work) It seems like there is somehting serioulsy wrong with your toolchain Can you even write and run a hello world program? ``` #include <stdio.h> int main() { printf("hello world\n"); } ```
1,474,688
If I have a bunch of elements like: ``` <p>A paragraph <ul><li>Item 1</li><li>Apple</li><li>Orange</li></ul></p> ``` Is there a built-in method in Nokogiri that would get me all `p` elements that contain the text "Apple"? (The example element above would match, for instance).
2009/09/24
[ "https://Stackoverflow.com/questions/1474688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/178779/" ]
Here is an XPath that works: ``` require 'nokogiri' doc = Nokogiri::HTML(DATA) p doc.xpath('//li[contains(text(), "Apple")]') __END__ <p>A paragraph <ul><li>Item 1</li><li>Apple</li><li>Orange</li></ul></p> ```
You can also do this very easily with [Nikkou](https://github.com/tombenner/nikkou): ```rb doc.search('p').text_includes('bar') ```
34,147,508
I want to use CSS variables in a Bootstrap theme so I can conveniently change the theme's color scheme in the future. [This chart shows that Firefox is the only browser at the moment that supports CSS variables](http://caniuse.com/#feat=css-variables). Question -------- > > **How do I use Polymer's Polyfills to shim cross-browser support for CSS variables?** > > > I scaffolded this project using the Polymer Starter Kit from the Yeoman Polymer Generator. I replaced the PSK `app` directory with the Bootstrap theme and renamed the original app directory to `app1` and the theme directory to `app`. I know everything is configured correctly because it works as expected using Firefox. So I just need to focus on getting the Polyfills to work. I tried the following in my `index.html`. But it doesn't work. index.html ``` <head> ... <link rel="stylesheet" type="text/css" href="css/theme-mod.css"> ... <script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script> <!-- Tried with and without the following --> <script type="text/javascript" src="scripts/app.js"></script> ... </head> ``` **Edit:** Other questions [relative to Polystyles](https://poly-style.appspot.com/demo/). > > *The documentation is confusing. For example, what is the url parameter supposed to be and do? Is it like an import? Can it point to an internal path or file if my dom-module is a local file? Also, is the dom-module a .css file or is it a .html file like the other DOM modules / elements I've seen?* > > >
2015/12/08
[ "https://Stackoverflow.com/questions/34147508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1640892/" ]
Try to use this (better when you link CSS via a CDN): <https://poly-style.appspot.com/demo/> or this is probably better in your case: <https://github.com/MaKleSoft/gulp-style-modules>
[I found this demo in the github repository for Polystyles](https://github.com/PolymerLabs/polystyles/blob/master/demo/elements.html). <https://github.com/PolymerLabs/polystyles/blob/master/demo/elements.html> It uses the following import, which suggests the `url` parameter should link to a `.css` file. ``` <link rel="import" href="../?id=polymer-styles&url=https://www.polymer-project.org/css/polymer.css"> ```
48,126,230
I have qwebengine that i have overwritten its context menu with a custom pop up menu and i am need to add menu item that when i right click a url it gives me the option to open in new tab, how i can achieve this? I have no idea how to do it so i have no code to show and there isn't enough topics out there but in qt simple broswer they have the below code but it's not understood for me as i never worked with qt here is the example: ``` void WebView::contextMenuEvent(QContextMenuEvent *event) { QMenu *menu = page()->createStandardContextMenu(); const QList<QAction*> actions = menu->actions(); auto it = std::find(actions.cbegin(), actions.cend(), page()->action(QWebEnginePage::OpenLinkInThisWindow)); if (it != actions.cend()) { (*it)->setText(tr("Open Link in This Tab")); ++it; QAction *before(it == actions.cend() ? nullptr : *it); menu->insertAction(before, page()->action(QWebEnginePage::OpenLinkInNewWindow)); menu->insertAction(before, page()->action(QWebEnginePage::OpenLinkInNewTab)); } menu->popup(event->globalPos()); } ``` If someone can explain the above code and provide simple snippet on how i can achieve it in pyqt, I would be so thankful.
2018/01/06
[ "https://Stackoverflow.com/questions/48126230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9084265/" ]
Please modify button tag ``` <button type="submit" name="submit" id="feedbackSubmit" class="btn btn-primary btn-lg" style=" margin-top: 10px;"> Verstuur</button> ```
Use name = submit in button tag. ``` <button type="submit" name="submit" id="feedbackSubmit" class="btn btn-primary btn-lg" style=" margin-top: 10px;"> Verstuur</button> ``` After that also check your spam folder. Sometime you don't get messages in inbox.
58,018,923
Write a recursive function named get\_first\_capital(word) that takes a string as a parameter and returns the first capital letter that exists in a string using recursion. This function has to be recursive; you are not allowed to use loops to solve this problem. ``` def get_first_capital(word): if word[0].isupper(): return word[0] + get_first_capital(word[1:]) else: return None print(get_first_capital('helLo')) except: print(get_first_capital('helLo')) ```
2019/09/19
[ "https://Stackoverflow.com/questions/58018923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10379890/" ]
I am not really sure what your trying to achieve here. But i would suggest using a class that will allow you to have better control over your variables. ``` class Game: def __init__(self): self.hp = 100 def takeInput(self): self.current = input() self.computeScore() def computeScore(self): if self.input ==="Something": self.hp -= 25 if self.checkValidScore(): self.takeInput() else: print "game over" def checkValidScore(self): return self.hp < 0 ```
Not sure what you want to achieve. If it keeps that simple you could also go in the following direction... ``` def test1(hp): test = input("yes no") stop_msg = None if test == "yes": print("not ok") hp -= 25 elif test == "no": print("ok") stop_msg = "dead end" else: raise Exception("Expected input to be 'yes' or 'no'.") return hp, stop_msg def test2(hp): test = input("yes no") stop_msg = None if test == "yes": print("'yes' sucks") hp -= 25 elif test == "no": print("ok") stop_msg = "another dead end" else: raise Exception("Expected input to be 'yes' or 'no'.") return hp, stop_msg def run_game(hp=100): print("start...") tests = [test1, test2] for test in tests: hp, stop_msg = test(hp) print("hp: {}".format(hp)) if stop_msg: print(stop_msg) return if __name__ == "__main__": run_game() ``` Remarks: * If you want to implement a more complex decision tree, you could use any simple tree representation. * If you have always the same structure within `testX` functions, introduce one function with parameters for questions, answer, etc.
11,171,060
I have a web application that I am trying to make more efficient by reducing the number of database queries that it runs. I am inclined to implement some type of Comet style solution but my lack of experience in this department makes me wonder if a more simple solution exists. For the sake of brevity, let's just say that I have a database that contains a list of systems on a network and their current status (whether they are up or down). A user can sign into the web app and select which systems she is interested in monitoring. After which she can visit the monitoring page which displays the number of systems that are currently down. As of now the count is refreshed using Ajax... every minute the client sends a request to the server which in turn runs a query against the database to get the current count and returns the result to the client. I know this in inefficient; for every client that logs in, another query is run against the database every minute. O(n) = bad! I know that I can use some type of caching, such as memcached, but it still means there is a request for every user every minute. Better, but I still feel as if it's not the best solution. I envision something more like this: * Every minute the server runs a query to pull a count for all the systems that are currently down. * The server then pushes this data to the interested clients. That way it doesn't matter how many users are logged in and watching the monitoring page, the server only ever runs one query per minute. O(1) = good! The problem is that even after all of the research I've done I can't quite figure out how to implement this. To be honest I don't completely understand what it is that I am looking for, so that makes it very difficult to research a solution. So I am hoping that more enlightened developers can lead me in the right direction.
2012/06/23
[ "https://Stackoverflow.com/questions/11171060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42388/" ]
To enumerate the words in a string, you should use `-[NSString enumerateSubstringsInRange:options:usingBlock:]` with `NSStringEnumerationByWords` and `NSStringEnumerationLocalized`. All of the other methods listed use a means of identifying words which may not be locale-appropriate or correspond to the system definition. For example, two words separated by a comma but not whitespace (e.g. "foo,bar") would not be treated as separate words by any of the other answers, but they are in Cocoa text views. ``` [aString enumerateSubstringsInRange:NSMakeRange(0, [aString length]) options:NSStringEnumerationByWords | NSStringEnumerationLocalized usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){ if ([substring rangeOfString:@"ll" options:NSCaseInsensitiveSearch].location != NSNotFound) /* do whatever */; }]; ``` As documented for `-enumerateSubstringsInRange:options:usingBlock:`, if you call it on a mutable string, you can safely mutate the string being enumerated *within the `enclosingRange`*. So, if you want to replace the matching words, you can with something like `[aString replaceCharactersInRange:substringRange withString:replacementString]`.
If you could write your criteria with regular expressions, then you could probably do a regular expression matching to fetch these words and then pass them to your `convert:` method. You could also do a split of string into an array of words using `componentsSeparatedByString:` or `componentsSeparatedByCharactersInSet:`, then go over the words in the array and detect if they fit your criteria somehow. If they fit, then pass them to `convert:`. Hope this helps.
1,745,570
I recently noticed that I couldn't write files (or delete files) to any external usb storage using my PC. Here is what happens when I try to create a new folder. ![Creating new folder 1st window popup](https://i.stack.imgur.com/krUxS.png) ![Creating new folder 2nd window popup](https://i.stack.imgur.com/tpLgI.png) I can't get past the 2nd window popup. It just repeats. I also can't format the usb drive. Once I click the "Format..." in the right-click context menu, it gives me this message: ![Format drive popup](https://i.stack.imgur.com/7H5OJ.png) I hope someone can help me find what's causing this and how to fix it so that my pc could write to external USB storage devices. Here is a list of notable things: * Flash drive is brand new. I can copy files to it using my sister's laptop and PC. I can't on my PC. * The file system doesn't matter. Can't write to NTFS or FAT32. * Can't write to flash drive or external HDD * My PC has no malware/virus * Tried booting in Safe Mode. Still couldn't write. * Can copy files from flash drive into my internal SSD/HDD. Basically I can still read the files. * What's weird is I can write files to my Phone Storage. Windows treats it differently for some reason. ![Phone Storage screenshot](https://i.stack.imgur.com/iB3dX.png) * I can copy files from another computer to my internal drives through LAN and vice versa. * The OS is Windows 10 pro. Windows is updated. No other updates in the queue. * I am using a Local Account. It has Administrator privileges. I even created a new local user with admin privileges and it can't write to the storage either. * Tried creating a text file using CMD with elevated privilege. It gave an "Access is denied" message. ![CMD message](https://i.stack.imgur.com/PR4gJ.png) * This is my own PC. It is not a company/corporate owned PC. I have tried everything I could find on the internet (except for re-installing Windows) and nothing works. I would like to save the re-installing of windows as a last resort. Here is a list of fixes I have already tried and didn't work: * Checked registry values for WriteProtect. It didn't exist at first. I added it and set it to 0. * Defective device. Bought a new one. It turns out even the old one works on my sister's laptop/PC. * Add full control permissions in Security tab. By default, it already had the "Authenticated Users" group. I still added the "Everyone" group afterwards. (This is for NTFS only) * Uninstalled USB controllers in Device Manager and restarted the PC. * Used diskpart to try to remove read-only attribute. [USB drive wasn't even read only to begin with](https://i.stack.imgur.com/HVoub.png) * Tried different USB ports. Couldn't write using any. * Checked Local Group Policies if the "Deny write access" in the Removable Storage Access settings is set to Enable. It wasn't. * Used DISM/sfc. It ran successfully for both. It didn't fix the problem. * Download latest drivers from Asus (x570 motherboard) and reinstall. * Did an In-place Upgrade of Windows I'm really hoping someone will be able to help me with this.
2022/10/03
[ "https://superuser.com/questions/1745570", "https://superuser.com", "https://superuser.com/users/1735529/" ]
I finally found the fix for this issue! I should have done this the first time I was looking into it but it makes sense why I didn't. --- It was a local group policy all along. Specifically this setting, Computer Configuration > Administrative Templates > System > Removable Storage Devices > Removable Disks: Deny write access. Usually, if this is the cause, it should be in an "Enabled" State. The fix for that is to set it from "Enabled" to "Disabled" or "Not Configured" and you should be able to write to external drives. But its State on my PC was set as Not configured, so I immediately wrote it off as the possible cause of the issue. [![Local Group Policy](https://i.stack.imgur.com/g3nK5.png)](https://i.stack.imgur.com/g3nK5.png) After doing almost everything except for reinstalling Windows, I tried to look back on the fixes that I went through and noticed that I technically didn't do the steps for this fix. So I went for it. I set it to "Enabled". Applied the change. And then set it back to "Not configured" and applied the change again. Lo and behold, it worked! I can write to any USB drive. --- Maybe the true setting just wasn't being displayed in the Local Group Policy Editor. I don't really know what caused the issue, I'm just glad that it is fixed now. I can finally rest. Thanks to everyone who helped out! The lesson I learned is always try to turn it on and off again or vice versa. XD
You have done almost everything conceivable for solving the problem. The problem is probably in Windows, not in hardware, so I suggest doing these checks (in order of gravity): * Check for drivers on the manufacturer's website that might be connected: USB controller, chipset and motherboard. Check also for a BIOS update (update carefully and don't force it). * Run `chkdsk` * Test disk SMART status by software such as [Speccy](https://www.ccleaner.com/speccy) * Testing Windows integrity by: + [Dism /Online /Cleanup-Image /RestoreHealth](https://www.tenforums.com/tutorials/7808-use-dism-repair-windows-10-image.html) + [sfc /scannow](https://www.tenforums.com/tutorials/2895-run-sfc-command-windows-10-a.html) * [Repair Install with an In-place Upgrade](https://www.tenforums.com/tutorials/16397-repair-install-windows-10-place-upgrade.html). This is the same as doing a major Windows update, so mind your backups. * Reinstall Windows from scratch * If nothing helps : Send the computer to a repair-shop for the USB controller to be checked.
2,603,190
Anyone have any idea why shuffle() would only return 1 item? when using: ``` $array2 = shuffle($array1); ``` with the following array($array1): ``` Array ( [0] => 1 [1] => 5 [2] => 6 [3] => 7 [4] => 8 [5] => 10 [6] => 11 [7] => 12 [8] => 13 [9] => 14 ) ``` The output of: ``` print_r($array2); ``` is simply: **1** Any idea as to why it would not only not shuffle the array, but knock off the remaining 9 items in the array? thanks!
2010/04/08
[ "https://Stackoverflow.com/questions/2603190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/201255/" ]
shuffle changes the original array. So in your case the shuffled array is `$array1`. `$array2` is simply a boolean value. The function returns true or false.
Please read a function description before use <http://php.net/shuffle> it may work other than you expect.
575,639
Between German and English, there are quite equivalent words “Fahrer” / “driver” and “Passagier” / “passenger”. But German has another word “Insasse” which is used for anyone inside a car or bus, that is driver, passengers, possibly the bus conductor if there is one. Is there an English word for this at all? (Google explains the word correctly, but then suggests “inmate” which is completely wrong.) Example in English: In a terrific car accident, the driver and his three passengers died. Equivalent to the German sentence: In a terrific car accident, all four (Insassen) died.
2021/09/26
[ "https://english.stackexchange.com/questions/575639", "https://english.stackexchange.com", "https://english.stackexchange.com/users/73713/" ]
In English, we would call those *occupants*: > > **occupant** *noun* > > > **a person who is in a car, room, seat, place, or position:** > *One of the occupants of the car was slightly injured.* > > > Source: [Cambridge Dictionary — > *occupy*](https://dictionary.cambridge.org/us/dictionary/english/occupant) > > > Here are some examples from the *Corpus of Contemporary American English* for *vehicle occupants*: <https://www.english-corpora.org/coca/?c=coca&q=100970269>
Possibly [occupant](https://dictionary.cambridge.org/it/dizionario/inglese/occupant): > > a person who is in a car, room, seat, place, or position. > > > *In a terrific accident all four occupants were killed.*
347,595
If $z$ is an integer, the sum of the series $$\sum\_{k=1}^\infty \left(\frac{1}{k}-\frac{1}{k+z}\right)$$ is easy since it is a telescoping series. But if $z$ is a fraction, say $z=3/2$, I don't see why the series sums to $$\frac{8}{3}-\ln 4$$ Is there a formula for $z=m/n$, where $m,n$ are positive integers and $n\neq 1$?
2013/03/31
[ "https://math.stackexchange.com/questions/347595", "https://math.stackexchange.com", "https://math.stackexchange.com/users/3249/" ]
To complete Marvis' (and now Mhenni's) answer let's notice that your series is, up to the Euler $\gamma$ constant ($0.577215\cdots$), the [digamma $\psi$ function](http://en.wikipedia.org/wiki/Digamma_function#Recurrence_formula_and_characterization) i.e. $$\psi(z+1)+\gamma=\sum\_{k=1}^\infty \left(\frac{1}{k}-\frac{1}{k+z}\right)$$ The formula for any fraction is well known too and named [Gauss's digamma theorem](http://en.wikipedia.org/wiki/Digamma_function#Gauss.27s_digamma_theorem) : $$\psi\left(\frac mk\right)=-\gamma-\ln(2k)-\frac{\pi}2\cot\left(\frac{m\pi}k\right)+2\sum\_{n=1}^{\lfloor(k-1)/2\rfloor}\cos\left(\frac{2\pi nm}k\right)\ln\left(\sin\left(\frac{n\pi}k\right)\right)$$ This is valid for $\,0<m<k$. For other fractions (including negative non integer values) use repetitively $\;\displaystyle\psi(x+1)=\frac{1}{x}+\psi(x)$. Concerning polygamma $\;\psi^{(n)}\left(\frac mk\right)\,$ for $n\in\mathbb{N}\ $ a formula was proposed by K. S. Kölbig in : ["The polygamma function and the derivatives of the cotangent function for rational arguments"](https://cds.cern.ch/record/298844).
Recalling the identity of the [$\psi$ function](http://en.wikipedia.org/wiki/Digamma_function) $$ \psi(z)=-\gamma+\sum\_{n=0}^{\infty}\left(\frac{1}{n+1}-\frac{1}{n+z}\right)\qquad z\neq0,-1,-2,-3,\ldots, $$ your series can be readily expressed in terms of the $\psi$ function $$ \sum\_{k=1}^\infty \left(\frac{1}{k}-\frac{1}{k+z}\right)= \psi(z+1)+\gamma. $$ Note that, for $z=\frac{m}{n},\, m,n\in \mathbb{N}$, you will not have a problem, since the singularities of the $\psi$ function are at $z=0,-1,-2,\dots.$
49,109,243
My website works perfect on `localhost` but when moved to live server which is `Ubuntu 16.04 LTS` I got this error > > [Mon Mar 05 11:11:28.968821 2018] [:error] [pid 19322] [client 156.212.75.255:61635] PHP Parse error: syntax error, unexpected '?', expecting variable (T\_VARIABLE) in XXXXXXXXXX/vendor/symfony/finder/Comparator/NumberComparator.php on line 42 > [Mon Mar 05 11:11:28.968895 2018] [:error] [pid 19322] [client 156.212.75.255:61635] PHP Fatal error: Exception thrown without a stack frame in Unknown on line 0 > [Mon Mar 05 11:11:28.969374 2018] [:error] [pid 19322] [client 156.212.75.255:61635] PHP Parse error: syntax error, unexpected '?', expecting variable (T\_VARIABLE) in XXXXXXXXXX/vendor/symfony/finder/Comparator/NumberComparator.php on line 42 > [Mon Mar 05 11:11:28.969390 2018] [:error] [pid 19322] [client 156.212.75.255:61635] PHP Fatal error: Exception thrown without a stack frame in Unknown on line 0 > > > How can I fix that and what is the right way to remove the public directory?
2018/03/05
[ "https://Stackoverflow.com/questions/49109243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2825410/" ]
If you look at the source [code](https://github.com/symfony/finder/blob/master/Comparator/NumberComparator.php#L42). ``` /** * @param string|int $test A comparison string or an integer * * @throws \InvalidArgumentException If the test is not understood */ public function __construct(?string $test) { ``` The `?string`, it's called `Nullable` Type. This feature comes after php `7.1` (see documentation [here](http://php.net/manual/en/migration71.new-features.php)). So you need to upgrade php version on your server. Make sure you get minimum php version `7.1`. Or make it same with your local environment.
Check your php version, it's very likely that's it: For ubuntu family: ``` > a2dismod php5.6 #current version > a2enmod php7.1 #required version ( 7.0, 7.1, 7.2 ) > service apache2 restart ```
6,276
In a previous [question](https://aviation.stackexchange.com/questions/786/is-it-even-remotely-feasible-to-turnback-a-single-engine-aircraft-with-an-engine) the case about if a turnback would be feasible, specifically for a single engine aircraft, has been analysed. But given a *twin-engine* general aviation aircraft and a *single* engine failure immediately after lift-off, considering that my Pilot handbook says: > > A continued take-off is not recommended if the steady rate of climb according to "Section XX" is less than Y%. > > > Considering the quite dangerous setting, I would say that is quite impractical to go and check that table in such a situation. What kind of indicators might I look for to check if it safe to continue? Should I learn by heart such table? (I am not sure this is practical either, is a quite complex table) In case I am unsure what to do, apart from trying to climb for a while then turn around or immediately try land in front of me (granted that there is enough space), are there, generally speaking, other options? In the [accepted answer](https://aviation.stackexchange.com/a/857/1467) of the listed question is said that > > It's not reasonable to try it [a turnaround] without knowing what altitude is needed for it at current conditions. > > > is it possible to estimate this quickly inside the cockpit?
2014/06/11
[ "https://aviation.stackexchange.com/questions/6276", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/1467/" ]
What you really should learn by heart is the flight speed for best climb with one engine inoperative. Try to trim that immediately and you will win more time to make a decision. The rest is really depending on circumstances: Is there a landing opportunity ahead? Are you high enough to do a 180 and land on the same runway in opposite direction? Or are you high enough (and the aircraft does not lose altitude) that you can fly a pattern and land normally? Testing the aircraft at altitude with one engine throttled is highly recommended, but be aware that the remaining thrust / drag of the throttled engine might be different from that of the stopped engine.
You are more likely to kill yourself in a stall/spin trying to turn back than you are from a forced landing straight ahead. Since the altitude required to make a successful 180 turn is quite considerable the chances are if you are high enough you will be too far from the runway to make it back. I remember seeing an article in plane and pilot magazine back in 1974 dealing with that topic and I seem to recall anything below 780ft AGL was a no-go
375,484
I have a button which is a quick action and I am calling a LWC and the logic is handled in the invoke method. Below is the LWC structure. ``` @wire(getRecord) . . @wire(getRelatedListRecords) . . @api invoke(){ .. } ``` I want to call @wire(getRelatedListRecords) in the invoke method or I want to reload the LWC component on clicking the button. Is this possible?
2022/05/06
[ "https://salesforce.stackexchange.com/questions/375484", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/82367/" ]
Data fetched from Wire Callouts are stored in browser cache. If you want to refresh the cached data please use `refreshApex()`. ```js import { refreshApex } from '@salesforce/apex'; @wire(getRecord) theRecord; wiredValues; @wire(getValues) theValues(value) { this.wiredValues = value; } handlerMethod(){ refreshApex(this.theRecord) refreshApex(this.wiredValues) } ``` Please go through the [documentation](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_result_caching).
Wire methods are called automatically and cannot be called directly. Simply accessing the data in the invoke method should already have the data you want to access.
63,786,136
So I have been trying to locate the username input box on python using selenium. I have tried xpath, id, class name, etc. I am also aware of explicit wait for the elements to load. However, depite all this, no luck. I checked to see if the element is in an iframe that I overlooked, but I couldn't find it. Here is the user input box element. ``` <div class="panel-body"> <h1 class="text-normal" role="banner">Sign in to your account</h1> <form action="/idp/profile/SAML2/Redirect/SSO?execution=e1s1" method="post"> <legend> Login to Qualtrics - co1 </legend> <div class="form-group"> <label for="username" class="hidden">Username</label> <div class="input-group"> <input id="username" name="j_username" type="text" class="form-control" tabindex="0" placeholder="Username" autocorrect="off" autocapitalize="none" spellcheck="false" aria-label="Username"> <div class="input-group-addon">@manhattan.edu</div> </div> </div> <div class="form-group"> <label for="password" class="hidden">Password</label> <input id="password" value="" name="j_password" type="password" class="form-control" placeholder="Password" aria-label="Password" autocomplete="off"> </div> <div class="form-element-wrapper"> <input type="checkbox" name="donotcache" value="1" id="donotcache"> <label for="donotcache">Don't Remember Login</label> </div> <div class="form-element-wrapper"> <input id="_shib_idp_revokeConsent" type="checkbox" name="_shib_idp_revokeConsent" value="true"> <label for="_shib_idp_revokeConsent">Clear prior granting of permission for release of your information to this service.</label> </div> <div class="form-element-wrapper"> <button class="btn btn-default" type="submit" name="_eventId_proceed" onclick="this.childNodes[0].nodeValue='Logging in, please wait...'">Login</button> </div> <div class="clearfix"></div> </form> <img src="https://s.qualtrics.com/login/static/xm_logo-16.png" alt="Qualtrics - co1"> <hr> <ul class="create-account"> <li><a href="https://start.manhattan.edu/"> Forgot your password?</a></li> <li>New student? <a href="https://start.manhattan.edu/">Get your JasperNet ID and password.</a></li> <li><a href="https://inside.manhattan.edu/offices/its/client-services-hours-and-support.php"> Need Help?</a></li> </ul> </div> ``` Here is the code that I wrote up to locate the element. ``` WebDriverWait(browser,10).until(EC.presence_of_element_located((By.XPATH, '/html/body/div/div/div/div/div[3]/div[1]/div[1]/div/ul/li[1]/a'))) browser.find_element_by_xpath('/html/body/div/div/div/div/div[3]/div[1]/div[1]/div/ul/li[1]/a').send_keys("test") ```
2020/09/08
[ "https://Stackoverflow.com/questions/63786136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14238455/" ]
Try to place the modal outside the mypost map, maybe this is why the modal won't show up. You may need another state for the src path of the selected image. ``` import { Modal } from "antd"; function Profile() { const [visible, setVisible] = useState(false); const [selectedImgSrc, setSelectedImgSrc] = useState(""); const imgClick = (imgSrc) => { setSelectedImgSrc(imgSrc); setVisible(true); }; return ( <> {myposts.map((mypost, index) => { return ( <> <img key={index} className="item" onClick={() => { imgClick(`http://localhost:5000/uploads/${mypost.photo}`); }} src={`http://localhost:5000/uploads/${mypost.photo}`} /> </> ); })} <Modal title="Basic Modal" visible={visible} onOk={() => setVisible(false)} onCancel={() => setVisible(false)} > <img src={selectedImgSrc} /> </Modal> </> ); } ```
it seems like the problem is here in your code. ```html <Modal title="Basic Modal" visible={visible} onOk={setVisible(false)} onCancel={setVisible(false)} > <p>Some contents...</p> <p>Some contents...</p> <p>Some contents...</p> </Modal> ``` ``` onOk={setVisible(false)} onCancel={setVisible(false)} ``` The problem is these lines. When you click an image it opens your modal, but when the modal being to render, these lines are setting visible state as `false`. So the modal will be deleted from DOM soon. That's why you can not see your modal on clicking an image. Please try with this. ``` onOk={() => setVisible(false)} onCancel={() => setVisible(false)} ``` You should pass a function for onOk and onCancel props.
200,922
I have a Bad-Elf Surveyor unit which claims accuracy ~1m when post-processed, but I am at a loss to find software that can differentially correct the raw NMEA/UBX logs that the unit will record. I checked the bad-elf site to see if they had a list of apps that could do it, but couldn't find anything. Anyone know what will take the .UBX file and correct it?
2016/07/04
[ "https://gis.stackexchange.com/questions/200922", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/25644/" ]
If you can convert them to rinex format you can use the online Precise Point Positioning (PPP) service provided by the Canadian Geodetic Survey. You can find out more at <http://www.nrcan.gc.ca/earth-sciences/geomatics/geodetic-reference-systems/tools-applications/10925#ppp>, or google NRCAN and PPP It's a great service, but I'm not sure if it is intended only for Canadian data. I'm sure there are other PPP services out there as well.
Once you have used the raw data logger to output a RINEX file, you can use the [RTKLib](http://www.rtklib.com/) to post-process your data using either * a) DGPS, using RINEX data from a known base station (CACS in Canada or CORS in the US) or * b) [PPP](https://gis.stackexchange.com/questions/112718/how-is-precise-point-positioning-ppp-exactly-done), using satellite clock and ephemeris data (.sp3 and .clk files available from [NASA CDDIS](https://cddis.nasa.gov/Data_and_Derived_Products/GNSS/broadcast_ephemeris_data.html) and [IGS](https://igscb.jpl.nasa.gov/components/prods_cb.html)). Bad Elf has an explanation of how to correct your data with DGPS on their website [here](https://bad-elf.com/pages/post-processing-gnss-data-with-rtklib-introduction). Also see tutorials from Latitude51 ([1](http://blog.latitude51.ca/rtklib-part-1-getting-started/), [2](http://blog.latitude51.ca/rtklib-part-2-rtk-processing/), and [3](http://blog.latitude51.ca/rtklib-part-3-precise-point-positioning-with-igs-products/); note, however, Latitude 51 is using L1/L2 data) and [Rtkexplorer](https://rtklibexplorer.wordpress.com/2016/02/13/kinematic-solution-with-rtkpost/). You can also find a more detailed discussion of L1-only PPP at this [GPSWorld article.](http://gpsworld.com/innovation-guidance-for-road-and-track/) However, I've been a little frustrated with the available explanation of how the ublox chips work and how to best implement the bad-elf's capabilities, so I've opened another question [here](https://gis.stackexchange.com/questions/237687/how-to-achieve-optimal-accuracy-with-rinex-post-processing-for-bad-elf-or-ublox); possibly someone has some additional insights that they would like to share.
104,526
I am not a dba. I have general knowledge of SQL Server and T-SQL. Our company currently has a SQL Server 2008 R2 hosting about 30 databases. I've been asked to research adding a second server for HA/Failover. My question is, should I be considering upgrading the current server to at least 2012, and build the new server the same? I had initially thought about building another 2008 R2 server, but it looks like clustering and HA is much improved in 2012. Also, not being an expert, is this going to be something a journeyman administrator can accomplish (obviously you can't gauge my skill level) or will we be looking at engaging a consultant? I know that question may be hard to answer.
2015/06/19
[ "https://dba.stackexchange.com/questions/104526", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/68862/" ]
Given the sample data: ``` CREATE TABLE dbo.Data ( ID integer PRIMARY KEY, A0 character(1) NULL, A1 character(1) NULL, A2 character(1) NULL, A3 character(1) NULL, A4 character(1) NULL ); INSERT dbo.Data (ID, A0, A1, A2, A3, A4) VALUES (14, 'A', 'B', 'A', 'C', 'A'), (15, 'A', 'A', 'A', 'A', 'A'); ``` An alternative way to compare all non-ID columns for equality is: ``` SELECT D.* FROM dbo.Data AS D WHERE EXISTS ( -- All columns except the last one SELECT D.A0, D.A1, D.A2, D.A3 INTERSECT -- All columns except the first one SELECT D.A1, D.A2, D.A3, D.A4 ); ``` If there are many columns, this may be easier to write than a query with multiple `AND` clauses (and will often be more compact). In Management Studio, you can [drag the Columns node from Object Explorer](http://dattatreysindol.com/2012/06/08/tips-n-tricks-ssms-quickest-way-to-select-and-query-all-columns-from-a-table-in-sql-server/) to a text window to generate a comma-separated column list. Offsetting that list for the second part of the `INTERSECT` is trivial as well. The execution plan generated by this query is just as efficient as the multiple `AND` clause version. Semantically, it is slightly different in that `NULL` data items will compare equal to each other. ![Execution plan](https://i.stack.imgur.com/jt33C.png)
Another example using cross apply. The idea is to transpose a0, a1, ..., to rows and then check where max and min equals: ``` select d.id from dbo.data as d cross apply ( values (d.a0),(d.a1),(d.a2),(d.a3),(d.a4) ) as x(a) group by d.id having min(a) = max(a); ```
12,732,664
I have the following function: ``` function array_duplicates($array) { $duplicates = array(); $unique = array_unique($array); for ($i = 0; $i < count($array); $i++) { if (!array_key_exists($i, $unique)) { $duplicates[] = $array[$i]; } } return $duplicates; } ``` This function obviously doesn't apply to any certain model, and it's not a template helper. Where would be the appropriate place to put this function? (Please don't say "anywhere you want.")
2012/10/04
[ "https://Stackoverflow.com/questions/12732664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/199712/" ]
This might be the type of thing you'd put into a service. Create a class like this: ``` class ArrayUtils { function array_duplicates($array) { ... return $duplicates; } } ``` And then define it as a service. If you're using YAML, you'd put something like this into your config.yml file: ``` services: arrayUtils: class: Full\Path\To\ArrayUtils ``` Under this configuration, Symfony will create a single instance of your ArrayUtils, and give all your controllers access to it. Then you can call it like this: ``` class SomeController { public function someAction() { ... $duplicates = $this->get("arrayUtils")->array_duplicates($array); ... } } ``` This is all part of Symfony's dependency injection framework. It's pretty cool, and I recommend reading up on it here: <http://symfony.com/doc/2.0/book/service_container.html> *Alternative Option* Now, that might be a little overkill for such a small chunk of code. If you're only going to be using this in a single bundle, then you might want to just put it into a base controller, and have all your other controllers extend that base controller. ``` class BaseController { function array_duplicates($array) { ... } } class SomeController extends BaseController { function someAction() { $this->array_duplicates($array); } } ```
By convention, utility classes go under the `Util` namespace. If you use bundles, a class would go into the `YourBundle\Util` namespace. If you [don't](https://stackoverflow.com/questions/9999433/should-everything-really-be-a-bundle-in-symfony-2), it would go into the `Acme\Util` namespace — the `src/Acme/Util` folder.
7,887
WP 3.0.4 local installation, multisite network enabled theme: Twentyten plugin: [List Category Posts](http://wordpress.org/extend/plugins/list-category-posts/) v .15, network activated I've created the folder `list-category-posts` inside my theme folder, and placed `default.php` inside it. Edited `default.php` and saved as `lcp_template_1.php` inside same folder. However, the changes are not appearing at all. I'm trying to change the style of the lcp output from the default `<ul>` to `<div>` classes defined in my theme (child)'s `style.css`. NOT WORKING. That is, the plugin is functioning, but the style changes are not working. Code for my template file is up at <http://wordpress.pastebin.com/EGmrkerQ> Please help. Sorry, no url for viewing the output, because this is a local installation. Oh, btw, I should mention that in the shortcode I have called for the new template, as follows: `[catlist id=1 template=lcp_template_1]`.
2011/01/27
[ "https://wordpress.stackexchange.com/questions/7887", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
Hey you just opened the plugin's tag on WordPress Answers :D Can you paste the code of the generated html? From what you describe, you are using it correctly, so I just want to see if the template is being loaded to detect if the problem is on the template side, or a bug on the plugin's code. **UPDATE**: Ok, I checked your template on a new WordPress install. It was getting the template, but there was some code error, here's what worked for me: I created the list-category-posts folder under wp-content/themes/twentyten and added a new php file called "lcp\_template\_1.php" with your code. Then created a new post with: ``` [catlist template=lcp_template_1] ``` Now, I started editing your template, I fixed the Show Category code and it's currently working with this code: ``` <?php /* Plugin Info & license stuff... */ $lcp_output = ''; //Show category? if ($atts['catlink'] == 'yes'){ $cat_link = get_category_link($lcp_category_id); $cat_title = get_cat_name($lcp_category_id); $lcp_output = '<div class="topic-heading"><a href="' . $cat_link . '" title="' . $cat_title . '">' . $cat_title . '</a></div>'; } $lcp_output .= '<div class="post">';//For default ul //Posts loop: foreach($catposts as $single): $lcp_output .= '<h2 class="entry-title"><a href="' . get_permalink($single->ID) . '">' . $single->post_title . '</a></h2>'; //Show comments? if($atts['comments'] == yes){ $lcp_output .= ' (' . $single->comment_count . ')'; } //Style for date: if($atts['date']=='yes'){ $lcp_output .= ' <div class="entry-meta"> ' . get_the_time($atts['dateformat'], $single) . '</div>'; } //Show author? if($atts['author']=='yes'){ $lcp_userdata = get_userdata($single->post_author); $lcp_output .=' <div class="entry-meta">' .$lcp_userdata->display_name . '</div>'; } //Show thumbnail? if($atts['thumbnail']=='yes'){ $lcp_output .= '<div class="lcp_thumbnail"><a href="' . get_permalink($single->ID) . '">' . get_the_post_thumbnail($single->ID, array('40','40')) .'</a></div>'; } //Show content? if($atts['content']=='yes' && $single->post_content){ $lcpcontent = apply_filters('the_content', $single->post_content); // added to parse shortcodes $lcpcontent = str_replace(']]>', ']]&gt', $lcpcontent); // added to parse shortcodes $lcp_output .= '<p>' . $lcpcontent . '</p>'; // line tweaked to output filtered content } //Show excerpt? if($atts['excerpt']=='yes' && !($atts['content']=='yes' && $single->post_content) ){ $lcp_output .= lcp_excerpt($single); } endforeach; $lcp_output .= '</div>'; ?> ``` Please let me know if this works for you. I should update the default template since the show category code is old and buggy. Will be done for next version. **UPDATE:** 0.15.1 includes a fix for the undeclared lcp\_output variable. Also, regarding the thumbnail not displaying, please make sure you've modified the theme according to the [get\_the\_post\_thumbnail documentation](http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail). > > To enable post thumbnails, the current > theme must include add\_theme\_support( > 'post-thumbnails' ); in its > functions.php file. add\_theme\_support( > 'post-thumbnails' ); must be called > before the init hook is fired. That > means it needs to be placed directly > into functions.php or within a > function attached to the > after\_setup\_theme hook. > > > **SOLVED:** As we found out on the comments, the problem was with using STYLESHEETPATH instead of TEMPLATEPATH. This change will be included on the next release. Thanks Das for the feedback :D
Shortcode: [catlist template=lcp\_template\_1 id=9 orderby=date numberposts=1 date=yes author=yes excerpt=yes catlink=yes thumbnail=yes ] In the plugin folder > list\_cat\_posts.php, these are the instances for 'thumbnail': > > File list\_cat\_posts.php; line 56: > 'thumbnail' => 'no', > > > File list\_cat\_posts.php; line 168: if > ($atts['thumbnail']=='yes'){ > > > File list\_cat\_posts.php; line 169: > $lcp\_display\_output .= > lcp\_thumbnail($single); > > > File list\_cat\_posts.php; line 229: \* > @see > <http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail> > > > File list\_cat\_posts.php; 232: function > lcp\_thumbnail($single){ > > > File list\_cat\_posts.php; line 233: > $lcp\_thumbnail = ''; > > > File list\_cat\_posts.php; line 234: if > ( has\_post\_thumbnail($single->ID) ) { > > > File list\_cat\_posts.php; line 235: > $lcp\_thumbnail = > get\_the\_post\_thumbnail($single->ID); > > > File list\_cat\_posts.php; line 237: > return $lcp\_thumbnail; > > > And in my template, these are the instances for 'thumbnail': > > //Show thumbnail? > if($atts['thumbnail']=='yes'){ > $lcp\_output .= '<div > class="lcp\_thumbnail"><a href="' > . get\_permalink($single->ID) . > '">' . > get\_the\_post\_thumbnail($single->ID, > array('40','40')) > .'</a></div>'; } > > > So there is no misspelling, as far as I can see. I had already seen the forum thread you're referring to, and made the correction to the default template. The thumbnail is displaying as expected in the original post, so I don't know why LCP is not pulling it along with the post. Unless it doesn't do that with excerpts?
4,278,701
Consider the polynomial $F(t)= 2021t^7+6t^6+2017t^5-2t^4-t^3+2t^2-t+5$ , this is irreducible in $\mathbb{Q}[t]$ because it's irreducible in $\mathbb{F}\_2[t]$ (it has no factors of degree 1,2 or 3) , so now we consider one of its complex roots $α$ . We obviously have $\mathbb{Q}(α^3) \subset \mathbb{Q}(α)$ , but for the converse I have no idea on how to proceed. I thought of trying to find a polynomial for which $α^3$ is a root (and possibly find its minimal polynomial), but the expressions are very messy and I can't find one.
2021/10/16
[ "https://math.stackexchange.com/questions/4278701", "https://math.stackexchange.com", "https://math.stackexchange.com/users/740138/" ]
The series *[Math Girls](https://rads.stackoverflow.com/amzn/click/com/0983951306)* by Hiroshi Yuki is both amusing and instructive. We explore together with at first two later three female students some highlights in mathematics like Fermat's last theorem or Gödel's incompleteness theorems. Currently there are four volumes in this series, the first with this *[MAA review](https://www.maa.org/press/maa-reviews/math-girls)*.
The popular mathematics book [*Dialogues on Mathematics*](https://rads.stackoverflow.com/amzn/click/com/B0006BQH6Y) (original title: *Dialoge über Mathematik*) by Alfréd Rényi is a set of fictional dialogues about the *nature* of mathematics between some historical characters (Socrates and Hippocratis in the first chapter, Archimedes and Hieron in the second one, and Torricelli, Niccolini and Galileo in the last chapter).
25,420,191
I’m writing an application which checks whether a (ublox) GPS module is installed in a machhine and if so it reads out the data via the serial interface. I do not know on which port, the module is working, so the program checks all COM ports for incoming signals at 4800 and 9600 baud. The Ublox GPS module actually adapts to the baud rate (4800 or 9600). The application often freezes during the search, turing GPS module off and on again solves this problem. The problem occurs sporadically directly after opening the COM port to which the GPS module is connected. I have provided the SerialPort with a ReadTimeout, which however makes no changes in the error screen. ``` public static List<GPSDevicePort> DetectGPSSerialPorts() { List<GPSDevicePort> ret = new List<GPSDevicePort>(); List<int> baudrates = new List<int> { 4800, 9600 }; foreach (string portName in SerialPort.GetPortNames()) { foreach (int br in baudrates) { try { bool detected = false; using (SerialPort port = new SerialPort(portName, br)) { port.ReadTimeout = 1000; port.DtrEnable = true; // Auf GPS Daten warten... Console.Write(string.Format("Opening {0} @ {1} Baud", portName, br)); port.Open(); int i = 0; while(i < 5) { Console.Write("*"); string s = port.ReadExisting(); if (s.Contains("$GP")) { Console.WriteLine(string.Format("***[{0}@{1}]: {2}", portName, br, s)); GPSDevicePort devInfo = new GPSDevicePort(portName, port.BaudRate); ret.Add(devInfo); detected = true; break; } i++; } Console.WriteLine(""); port.Close(); port.Dispose(); } Thread.Sleep(1000); if (detected) break; } catch (Exception ex) {} } } return ret; } ```
2014/08/21
[ "https://Stackoverflow.com/questions/25420191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/613155/" ]
You can use `text-right` first you have to wrap it in a `div` like this: ``` <div class="text-right"> <button class="btn-info btn">Log in</button> </div> ``` [LIVE-DEMO](http://jsfiddle.net/8x4fmcq9/) ========================================== Here is the full code ``` <div role="form"> <div class="form-group"> <label>Username</label> <input type="text" class="form-control"/> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control"/> </div> <div class="checkbox"> <label> <input type="checkbox"/> Remember Me </label> </div> <div class="text-right"> <!--You can add col-lg-12 if you want --> <button class="btn-info btn">Log in</button> </div> </div> ``` ![enter image description here](https://i.stack.imgur.com/M3VHP.png)
If you are inside a container with rows and columns in Bootstrap4, all the floats don't work properly. Instead you have to add a spacer column to get things to align. ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <p>Float right demo inside a container-fluid, Bootstrap 4</p> <div class="container-fluid"> <div class="row"> <div class="col bg-warning"></div><!-- This is the filler column --> <div class="col-auto bg-success">.col-auto (Like a Float Right)</div> </div> </div> ``` Hope that helps.
29,361
What can you do when your child comes back from school with tears in her eyes or her heart because of an **incompetent teacher**? Three examples to illustrate: * she told her class that humans can hear radio waves. Without a radio! She teaches physics in high school. * On another occasion she said that if the moon was not around the earth, it would not have a great influence on ocean tides because the sun was also responsible for ocean tides on the earth. * She often has to stop her explanations in class because she is confused herself about what she is teaching. The correction of her exams and labs changes from one copy to the other and she rarely accepts to make corrections. There are mistakes or missing elements in the questions of her exams. On three occasions she did not try the lab herself before the class and, therefore, could hardly explain it. She forgets regularly to check the material for the labs. The list goes on, growing since September. I am a parent, but also a retired teacher. The only bright light: my daughter has 11 weeks to go before being *liberated* from high school. She is one of the best students of her school, so you can imagine the other students. **What can we do and say**, as parents, when this happens?
2017/03/15
[ "https://parenting.stackexchange.com/questions/29361", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/22362/" ]
Teach your kid on how to deal with incompetent superiors. In a manner which is acceptable to the other side, of course. Unfortunately, this is not really easy to learn for young people - especially not if they are very intelligent. A child will be able to play the role of the attentive student who admires the teacher, but acting like this all the time can be difficult. Even for an adult. It is, actually, some kind of self-humiliation, and most people have a limit on how much bullshit can be fed to them. The danger is that the child might "shut down" and begin to behave like a robot which emits pleasant phrases while trying to provide a minimal attack surface. This might be an advantage for a future politician, but might be something you might want to avoid. So make sure that your child also understands how to monitor herself so she'll recognize when she's about to turn into a politician. As a kid, this was very hard to swallow for me. I wasn't very good at acting like this, and I sort of resigned under the constant exposure to incompetence. My grades dropped. What I did was to change the school and select challenging courses with competent teachers. I was good at physics, so I chose biology instead of physics. And some years later, in yet another school, I actually came back to physics course, with a very competent teacher. Oh, yes, and hearing RF without a radio is possible. But the teacher should have explained how this works.
**Many thanks to all of you**, I appreciate the time you took to answer. At the beginning, as noted A.I. Breveleri, my question did not show evidence of this teacher's incompetence. My mistake. I edited the original text to explain more about it. I first gave the impression that it was a question of physics, but it was more a question of educational practice. *"Based on a quick fact check on the science you brought up, it sounds like the teacher may be competent and current in the science but not so much as a teacher (or burned out and ready to quit)."* No the teacher was not competent, I met her and discuss physics with her. She could not explain many basic things in physics, I could have given the course myself to the class. My daughter had about 10 "bad" teachers in the last 5 years but most of the time they were just exhausted with teaching. This time was different and I decided to help my daughter. Being a teacher myself I know when a teacher is incompetent. **Here is what happened with my complain.** The administration of the school really took action on the issue, I was surprised myself. The director went personally in her classroom on two occasions and five more students decided to talk and complain like we did. Many students complained that this particular teacher had discouraged them two, three or four years ago. Bottom line, the teacher took the only solution available to her: she went on sick leave for the rest of the year. Within a week, more students started to tell their stories to the direction. **My answer to "What can a parent do when his child has an incompetent teacher" is :** * Make sure it is really incompetence in educational practices. Most of the time the teacher is close to a burnout or disillusioned about the school. * Avoid being emotional or aggressive about the issue. * First meet the teacher personally, then meet the director. * Write a letter, short, concise to explain your points. * If the director wants to talk to your child, insist on being present to this meeting. **Two extracts I especially appreciated in your answers :** * \*"It is a grave accusation, but if you do not say anything, then perhaps no one else will. It might be that the school is aware, but unable to do anything because there have not yet been any complaints." **I am very happy with what I did and so are many students in the school.** * Your daughter "will have many opportunities in life with making the most out of poor or bad situations if you help her gain the tools. Most of us have had bad bosses, co-workers or even friends."\* **And that is what we have to do with our children, show them how to cope with incompetence.**
3,279,373
In Spivak's *Calculus* (4th edition), Chapter 13, problem 15, the author asks to prove: > > For $a,b>1$ prove that: > $$\int\_1^a\frac 1tdt+\int\_1^b\frac1tdt=\int\_1^{ab}\frac1tdt$$ > The result is used in some problems in the following chapter, but I can't find in it's proof why $a,b$ must greater than 1, and the problem 14-28(c)(shown in the end) do use it regardless $a,b$'s range. > > > Here's the proof in answer book: > > Notice that > $$ > \frac1b\cdot \inf\{ \frac1t:t\_{i-1}\leq t\leq t\_i \}=\inf\{\frac1t:bt\_{i-1}\leq x\leq bt\_i \} > $$ > Denoting the first $\inf$ by $m\_i$ and the second by $m\_i^\prime$, we have > \begin{aligned} > L(f,P\prime) > &=\sum\_{i=1}^nm\_i^\prime(bt\_i-bt\_{i-1})\\ > &=\sum\_{i=1}^nbm\_i^\prime(t\_i-t\_{i-1})\\ > &=\sum\_{i=1}^nm\_i(t\_i-t\_{i-1})\\ > &=L(f,P). > \end{aligned} > So > $$ > \int\_b^{ab}\frac1tdt=\sup\{L(f,P\prime)\}=\sup\{L(f,P)\}=\int\_1^a\frac1tdt. > $$ > > > Finally, in Chapter 14 problem 28-c, in the answer book, he just say: > > Problem 13-15 implies that > $$\int\_{1/2}^1\frac1xdx+...+\int\_{1/2}^1\frac1xdx=\int\_{1/2^n}^1\frac1xdx$$ > > > even reverse$\int\_{1/2}^1$ to $-\int\_1^{1/2}$, still doesn't make sense if $a,b$ can not be less than $1$.
2019/07/01
[ "https://math.stackexchange.com/questions/3279373", "https://math.stackexchange.com", "https://math.stackexchange.com/users/401653/" ]
If I recall correctly, in chapter 13, Spivak only defined $\int\_a^b f$ for $a < b$. So the upper limit is greater than the lower limit. It is only in chapter 14 that he defines the integral $\int\_a^bf$ when $b\leq a$. I think this is why he imposes the condition $a,b > 1$ in your question. After defining things appropriately, it should be pretty easy to deduce the equality even when $a,b \leq 1$. --- Edit: I just checked my copy of Spivak (3rd Edition). He actually defines $\int\_a^b$ for $b \leq a$ in chapter 13, right after Theorem 13-4. In the $3$rd edition, the question reads > > Prove that > \begin{align} > \int\_1^a \dfrac{1}{t} \, dt + \int\_1^b \dfrac{1}{t} \, dt = \int\_1^{ab} \dfrac{1}{t} \, dt > \end{align} > Hint: ...... > > > So, he actually doesn't impose any restriction on $a,b$ (the only restriction we should impose is $a,b > 0$). So, actually, you might have to do some case work. If in your edition he says $a,b > 1$, then that's fine, but eventually he'll make use of this property for all $a,b > 0$, so you should see how to extend to proof to all cases. --- Additional Remark: Spivak proves this equality using the Fundamental Theorem of Calculus in Theorem 18-1, for all $a,b > 0$. Even though it is more work, you should still try to see how to extend the "proof by partitions" to all cases.
This is the fact $\ln ab=\ln a+\ln b$. This is true for any $a,b\gt0$.
35,678
I want to hang something like <http://www.skychairs.com/> or similar in my living room. If the joists were exposed I would mount a beam between two of them and hang over or through that. However, when the joists are hidden behind drywall or sheetrock or other ceiling material this doesn't seem to be an option. Putting an eye screw into the middle of a joist might be ideal, but scares me in a few ways (strength of the screw, weakening the joist, unscrewing over time, etc). What is the best way to approach this problem?
2013/11/12
[ "https://diy.stackexchange.com/questions/35678", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/999/" ]
Just because you can't see the joists doesn't mean you cannot use your beam approach for exposed rafters. The structure is essentially the same, except for a thin layer of sheetrock between the two, which has little impact on the forces involved. The best thing to do is distribute any concentrated load over multiple connections. Use a flat 2x4, or better yet 2x6 that's long enough to span 4 joists, about 4 to 6 feet. Place the chair connection at the center using a large through eye bolt, using an over sized washer to spread the load into the wood. The nut and bolt end will end up punching into the ceiling, but that's OK. Holes are easy to patch if the beam is ever removed, otherwise, it doesn't show anyway. Attach the 2x beam to each joist with two 1/4" dia. lag screws. Use a screw long enough to penetrate 2 inches into the joist material, probably 4 inches. Drill a 5/32 inch pilot hole before placing each lag to prevent splitting the joist. The resulting 8 screws is more than adequate to support any adult and will not significantly weaken the joists.
Drywall is a repairable material. When needed, be prepared to rip it open, do what you need to do, and patch it afterwards. If you are not **absolutely sure** how the ceiling is built, you can be lead astray following lines of nails/screws in drywall, if the ceiling was strapped with 1 x 3 running crossways to the joists before drywalling, rather than direct-attached to the joists. A studfinder or a magnet locating the drywall nails/screws will show the 1 X 3, not the joists.
4,186,744
Let's say a have the following code: ``` <nav id="main-navigation"> <ul> <li><a href="#">Link 1 Level 1</a></li> <li><a href="#">Link 1 Level 1</a></li> <ul> <li><a href="#">Link 1 Level 2</a> </ul> </ul> </nav> ``` And now I want to to set first `ul`'s height to 100px and second `ul` should be 300px. When I try ``` nav ul { height: 100px } ``` Second `ul` also inherits this value. I was trying "~", "+", ">", first-childs etc. but don't know how to do that, even with documentation. Is there a good explained (preferably with demos/screens) guide to new css3 selectors? W3 Table is too nerdy for me. Thanks!!!
2010/11/15
[ "https://Stackoverflow.com/questions/4186744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/443957/" ]
To select direct children of an element, and not any descendant, you should use the `>` syntax. In your case (after you put the second `ul` inside a `li`) you need: ``` nav > ul { height: 100px; } nav > ul > li > ul { height: 300px; } ``` ~~*Extra: It doesn't really make sense to have a 300px item inside a 100px item. Why do you want that?*~~ *Another extra: Try to read the w3c docs, it will save you some time in the long run. What you don't understand you can always ask on SO.*
Firstly, how imporant is browser compatibility to you? All of those selectors you mentioned have issues in various versions of IE (IE8 is obviously better than IE7, but even IE8 is missing a lot of CSS selectors) Simple nested selectors (ie just a space between the CSS names) will work for you - although as you say, setting `nav li {height:100px;}` sets it for all the LIs, you can override that with `nav li li {height:300px;}` to set the inner one back the way you want it. If you want to use the 'correct' selectors, the one you want is `>`. ``` nav>ul>li { height:100px; } ``` This will only affect the outer LI elements, not the inner one. However as I say, it won't work in older versions of IE (fortunately it does work in IE7 and up, so it's only an issue if you want to support IE6). You say that you've found the various selectors quite hard to grasp. I recommend you visit [Quirksmode](http://www.quirksmode.org/css/contents.html). For a start, it's got a very handy compatibility chart showing which browsers support which selectors, but it's also got excellent examples of how each selector works, which should help you understand them a bit better.
45,824,504
Trying to understand, but I am not able to get the perfect answer. ``` #include<iostream> using namespace std; int main(){ unsigned char ch = '150'; int count=0;//just to get a count for the loop cout << (int)ch<<endl; for (int i = 0; i <= ch * 2; i++){ cout << "Hello" << endl; count++; } cout << count; return 0; } ``` When I am assigning: ``` unsigned char ch = '250'; ``` If is printing the same output. What I am understanding from the output is that, it is taking the last index of number i.e 0, and from the ASCII lookup table giving me the integer value as 48 for ``` unsigned char ch = '186'; ``` Gives me the integer value as 54,(Which is the ASCII value of number 6) ``` unsigned char ch = '154'; ``` Gives me the integer value as 52, (Which is the ASCII value of number 2) Is my understanding correct? and will this be applicable for any number assigned to unsigned char in single quote?[![I have attached the screenshot of the Ascii look up table](https://i.stack.imgur.com/VqVsb.png)](https://i.stack.imgur.com/VqVsb.png). I am not getting any error or warnings.[![No error in the compiler](https://i.stack.imgur.com/QiDOh.png)](https://i.stack.imgur.com/QiDOh.png)
2017/08/22
[ "https://Stackoverflow.com/questions/45824504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8380523/" ]
There are some ways to declare `unsigned char` character literals: ``` unsigned char ch1 = 150; unsigned char ch2 = 0x96; unsigned char ch3 = '\150'; unsigned char ch4 = '\x96'; unsigned char ch5 = '\0226'; unsigned char ch6 = 0226; unsigned char ch7 = 0b10010110; ``` Choose the one which is most readable in your application if you cast to `int` your var is printed as number, not as character. If you want character, don't cast ``` cout << ch << endl; ```
There's a great difference between: ``` unsigned char ch = '150'; // wrong way unsigned char ch = 150; // correct way (conversion from integer to char according to ASCII standard) ``` As you can see i the first line as long as ch is of type char and you assign it a string (multi-char constant). Here no conversion will occur from ASCII to int or the contrary but in face you get a warning from the compiler: ``` warning C4309: 'initializing' : truncation of constant value ``` The correct way is to assign only one character to one character variable: ``` unsigned char ch = '1'; // or any other character. ``` In the second statement: ``` unsigned char ch = 150; ``` Above the value `150` is integer value not a string so the compiler will convert it to character according to ASCII Table which is `û`. Another example: ``` char ch = 65; // which is capital a `A` in ASCII. std::cout << ch << std::endl; // A ```
65,155,356
i want to search data based nama\_kegiatan or tanggal\_kegiatan where these two name form my table field, this code from my controller : ``` public function search(Request $request){ $cari = $request->search; $caritanggal = date($request->datekeg); $infokeg = Infokeg::where(function ($query) use ($cari) { $query->where('nama_kegiatan','like',"%$cari%")->get(); })->orWhere(function($query) use ($caritanggal) { $query->where('tanggal_kegiatan', $caritanggal)->get();; })->paginate(10); return view('infokeg/infokeg', ['infokeg' => $infokeg]); } ``` when i am using like on nama\_kegiatan, tanggal\_kegiatan didnt work and just display all data, but when i delete like from nama\_kegiatan, its work, but i cant search nama\_kegiatan using like, so how to solve it ?
2020/12/05
[ "https://Stackoverflow.com/questions/65155356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10485539/" ]
Maybe you can try to get() all the result after the query? Somethings like ``` $infokeg = Infokeg::where('name_kegiatan','LIKE','%'.$cari.'%')->orWhere('tanggal_kegiatan',$caritanggal)->get(); ``` IMO the get() and paginate() cannot be use at the same time if I have not get it wrong. If you need to paginate after all the result, you can do create Paginator manually. Maybe [this link can help you](https://stackoverflow.com/questions/25338456/laravel-union-paginate-at-the-same-time/25342133#25342133). Hope this will help you and please correct me if anything wrong. Thanks!
If you want to see what is run in the database use dd(DB::getQueryLog()) after query to see what queries exactly were run. ``` $infokeg = Infokeg::where('nama_kegiatan','like', "%" . $cari ."%") ->orWhere(function($query) use ($caritanggal) { $query->where('tanggal_kegiatan', $caritanggal); })->paginate(10); ```
1,750,671
This is the common structure of all of my classes: ``` public class User { public int ID { get;set; } public string User_name { get; set; } public string Pass_word { get; set; } public string UserTypeCode { get; set; } public int SaveOrUpdate() { int id = -1; if (this._ID <=0) { id = this.Save(); } else { bool success = this.Update(); if(success) { id = this._ID; } else { throw new Exception("Update failed!"); } } return id; } private int Save() { } private bool Update() { } public static User Get(int id) { } public static List<User> Get() { } public bool Delete() { } } ``` I was using these classes smoothly with winforms. But while working with ASP.NET, when I try to configure the object data source for a GridView, I don't find the method-names in the `Data Source Configuration Wizard`. I.e. they are not showing up. So my methods became useless. I can't change this general structure of all of my classes. I have also a code generator written for them. And I must use `ObjectDataSources`. My first question is, why don't they show up? And, what should I do to make them show up?
2009/11/17
[ "https://Stackoverflow.com/questions/1750671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159072/" ]
ObjectDataSources look for methods within the type specified that match the signature of the update/insert method name and the update/insert parameters provided. Your `SaveOrUpdate` method is on an instantiated class, and the ObjectDataSource will not find a matching method signature. From what you have, if you must use ObjectDataSources, you may want to consider using a wrapper method. [Example.](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.update.aspx)
I am not quite sure, but you can try to mark this class with [DataObjectAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataobjectattribute.aspx) and CRUD methods with [DataObjectMethodAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataobjectmethodattribute.aspx). I did not use `ObjectDataSource` for ages, so can forget something.
8,235,852
I am trying in an iPhone app to set the possibility for the user to choose the fonts. I have already made progress using the UIFont class. Here is my question : When the choice of a Font within a Font Family is made how to I know the possibilities the user has for the size? Is there a way to list them? I did not see anything like that in the UIFont documentation or anywhere I looked on the net. Thanks for any piece of information.
2011/11/23
[ "https://Stackoverflow.com/questions/8235852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/611201/" ]
These two functions do exactly the same thing. `Keys.Contains` exists because `Keys` is an `ICollection<TKey>`, which defines a `Contains` method. The standard `Dictionary<TKey, TValue>.KeyCollection` implementation (the class, not the interface) defines it as ``` bool ICollection<TKey>.Contains(TKey item){ return dictionary.ContainsKey(item); } ``` Since it's implemented explicitly, you can't even call it directly. --- You're either seeing the interface, which is what I explained above, or the LINQ `Contains()` extension method, which will also call the native implementation since it implements `ICollection<T>`.
Although they are pretty much equivalent for `Dictionary<,>`, I find it's much safer to stick with `ContainsKey()`. The reason is that in the future you may decide to use `ConcurrentDictionary<,>` (to make your code thread-safe), and in that implementation, `ContainsKey` is significantly faster (since accessing the `Keys` property does a whole bunch of locking and creates a new collection).
33,538,637
I have a `Series` as following: ``` In [37]: ser Out[37]: Aa 0 Ab 1 Ac 2 Ba 3 Bb 4 Bc 5 Ca 6 Cb 7 Cc 8 dtype: int3 ``` I want to rearrange it to a `DataFrame` as: ``` a b c A 0 1 2 B 3 4 5 C 6 7 8 ``` Here is what I had try with no luck: ``` In [38]: ser.groupby(lambda i: i[0]).apply(lambda x: x.rename({i: i[1] for i in x.index}).to_frame()) Out[38]: A B C A a 0 NaN NaN b 1 NaN NaN c 2 NaN NaN B a NaN 3 NaN b NaN 4 NaN c NaN 5 NaN C a NaN NaN 6 b NaN NaN 7 c NaN NaN 8 ``` **EDIT** I have found the following close reuslt: ``` In [50]: ser.groupby(lambda i: i[0]).apply(lambda x: x.rename({i: i[1] for i in x.index}).to_frame().transpose()) Out[50]: a b c A A 0 1 2 B B 3 4 5 C C 6 7 8 ``` However, it has a `MultiIndex`。
2015/11/05
[ "https://Stackoverflow.com/questions/33538637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172677/" ]
Here you go: ``` ser.groupby(lambda i: i[0]).apply(lambda x: x.rename({i: i[1] for i in x.index})).unstack() ``` You were close!
``` In [235]: df = pd.DataFrame(data = { 'key' : ser.index.values , 'value' :ser.values }) df Out[235]: key value 0 Aa 0 1 Ab 1 2 Ac 2 3 Ba 3 4 Bb 4 5 Bc 5 6 Ca 6 7 Cb 7 8 Cc 8 In [251]: df['key_1'] = df.key.str.extract('(^\w)') df Out[251]: key value key_1 0 Aa 0 A 1 Ab 1 A 2 Ac 2 A 3 Ba 3 B 4 Bb 4 B 5 Bc 5 B 6 Ca 6 C 7 Cb 7 C 8 Cc 8 C In [252]: df['key_2'] = df.key.str.extract('(\w$)') df Out[252]: key value key_1 key_2 0 Aa 0 A a 1 Ab 1 A b 2 Ac 2 A c 3 Ba 3 B a 4 Bb 4 B b 5 Bc 5 B c 6 Ca 6 C a 7 Cb 7 C b 8 Cc 8 C c In [253]: df.pivot(index='key_1' , columns='key_2' , values='value') Out[253]: key_2 a b c key_1 A 0 1 2 B 3 4 5 C 6 7 8 ```
32,530,952
I am receiving a message using the [Go NSQ library](http://github.com/bitly/go-nsq) where a field is a slice of `map[string]string`'s. I feel like I should be able to type assert this field as `value.([]map[string]string)` but it's failing and I can't tell if this is expected or not. This snippet replicates the behavior <https://play.golang.org/p/qcZM880Nal> Why does this type assertion fail?
2015/09/11
[ "https://Stackoverflow.com/questions/32530952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/210547/" ]
The conversion referred to doesn't work as described in Jim's answer. However, if you actually have the type you claim, and the interface you state it implements is just `interface{}` then the type assertion works fine. I don't want to speculate on the details of why the other doesn't work but I believe it's because you would have to unbox it in two phases as the `map[string]string`'s inside the slice are actually being viewed as some `interface{}` themselves. Here's an example; ``` package main import "fmt" func main() { var value interface{} value = []map[string]string{{"address": string("this is interface literal")}} // value = []map[string]string{{"address": "this is map literal"}} AssertIt(value) } func AssertIt(value interface{}) { if str, ok := value.([]map[string]string); ok && len(str) > 0 { fmt.Println(str[0]["address"]) } else { fmt.Println("nope") } } ``` <https://play.golang.org/p/hJfoh_havC>
you can do it by reflect in 2022 ```golang res := `[ { "name": "jhon", "age": 35 }, { "name": "wang", "age": 30 } ]` // res := `{ // "name": "jhon", // "age": 35 // }` var rst any err := json.Unmarshal([]byte(res), &rst) if err != nil { panic(err) } t := reflect.TypeOf(rst).Kind() fmt.Println(t) ```
5,026,805
I'm experiencing validation errors in the checkout and user registration workflows of my Magento (version 1.4.2) install. Example: During checkout, I get a "Customer email is required" error even if the field is correctly filled out. In the registration process, I get the error "Field xx must be greater or equal to a characters" It's interesting that it says "a" characters and not a specific number, but what does this refer to? I want to figure out how to disable form validation so I can troubleshoot the problem and find out what is causing the errors.
2011/02/17
[ "https://Stackoverflow.com/questions/5026805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/100382/" ]
comment out the line in the specific phtml files inside the tags that looks like: ``` var dataForm = new VarienForm('name-of-form'); ``` Otherwise, comment out the line in page.xml with: ``` <action method="addJs"><script>prototype/validation.js</script></action> ``` **EDIT** open `DOCROOT\js\prototype\validation.js` and comment out the contents of validate (lines 124-155) and insert `return true;` instead if you want to bypass validation and submit the form. HTH, JD
If you want to disable the validation for a certain form field, you will have to remove the validation class of the input tag. The input tags are looking like this: ``` <input type="text" name="email" class="input-text validate-email required-entry" /> ``` Just remove the "validate-email" part from the class attribute. Then this field will no longer be validated via JavaScript. To disable the Server-Side Validation for addresses you will have to override the Mage\_Customer\_Model\_Address\_Abstract::validate() function and add a "return true" to the beginning of the method. But I would not recommend that.
5,542,412
I've read a lot about openid in recent few days and found out it's not as easy on a standard web space. I've only follow available in the web space: * CGI Exec * PHP 5 (cURL Similar) * Apache 2 * IM, GD, FTP ect. * No openid setup. * No options to install apps. Is it possible to setup openid or which one?
2011/04/04
[ "https://Stackoverflow.com/questions/5542412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/678611/" ]
The emulator on its own doesn't provide any "fake GPS" support, but there are a few emulator tricks around to allow you to fake GPS data: e.g. * <http://phone7.wordpress.com/2010/08/19/gps-sim-update-generic-model-and-dll/> - see <http://phone7.wordpress.com/2010/08/02/no-device-no-gps-no-matter-with-code/> for pictures * <http://wp7gps.codeplex.com/> * the official one is <http://windowsteamblog.com/windows_phone/b/wpdev/archive/2011/01/28/windows-phone-gps-emulator.aspx> I've previously used <http://wp7gps.codeplex.com/> solution - I chose it before the official one was out as it gives you the same data each time (helped with testing)
Above codeplex link have fake.cs file that is not working at all. and other link u folks are provided are expired. If there is any good solution to **simulate fake gps** or **find current location** on emulator then post any sample App please
47,939,166
I have a singleton instance defined like this: ``` public class Singleton { private static Singleton INSTANCE = new Singleton(); private Singleton() { } public Singleton getInstance() { return INSTANCE; } } ``` Now, due to some changes, this class has to depend on a few(3) dependencies. So, those dependencies have to be **injected** here. How can we achieve dependency injection for a Singleton class designed this way? The problem is that there are already a lot of callers on `Singleton.getInstance()` and hence cannot make the getInstance method to accept the dependencies. P.S: I understood using Singletons are not always a cleaner way :) (This is existing code and I have to live with it:)) P.S: I'm using Guice for dependency injection.
2017/12/22
[ "https://Stackoverflow.com/questions/47939166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4405757/" ]
You could refactor your class as a dependency while keeping the same API for clients. With Spring for example : ``` @Component public class Singleton { private Foo foo; private Bar bar; private Any any; // inject dependencies @Autowired // annotation not required in recent Spring versions public Singleton (Foo foo, Bar bar, Any any){ this.foo = foo; this.bar = bar; this.any = any; } public Singleton getInstance() { return this; } } ``` And from the client side you can either inject the bean or retrieve it from the bean container if the client class is not a bean. Example of accessing from a bean class : ``` public class SingletonClient{ @Autowired private Singleton singleton; public void foo(){ singleton.getInstance().method(); } } ``` --- Idea to avoid changes from the client classes. Disclaimer : I don't promote this way as it is both counter-intuitive, error prone and above all maintain the technical debt of the static access for the singleton. It is acceptable as a temporary solution but a refactoring of the exiting code should really be performed as soon as possible. So the idea is storing the bean instance in the static field during the constructor invocation. In this way, `Singleton.getInstance()` return the bean. ``` @Component public class Singleton { private Foo foo; private Bar bar; private Any any; private static Singleton instance; // inject dependencies @Autowired // annotation not required in recent Spring versions public Singleton(Foo foo, Bar bar, Any any) { this.foo = foo; this.bar = bar; this.any = any; instance = this; } public static Singleton getInstance() { return instance; } } ```
If you are using Spring you can achieve dependency injection even without a public constructor. Just mark the dependencies @Autowired. Spring will inject them via reflection. :)
52,643,734
I have an HTML video player that runs random videos. I have the following function that tests if the video is marked completed based on the video seen percentage. VideoCompletionPercentage is a global variable that is set by reading it from the database. I have to test for two conditions as follows: 1. verify video is marked complete if it is seen till a VideoCompletionPercentage set from the DB. 2. verify video is not marked complete if it is skipped forward and seen till 100% I am switching between two while loops based on a skip bool variable. Is there any way to combine these two do while loops into one by manipulating the while condition or any other way? Thanks in advance for your inputs. ```js private void VideoPecentageCompletion(bool skip) { double videoSeenPercentage; if (skip) { do { double.TryParse(Driver.FindElement(By.CssSelector("div[class=played]")).GetAttribute("aria-valuemax"), out double totalVideo); double.TryParse(Driver.FindElement(By.CssSelector("div[class=played]")).GetAttribute("aria-valuenow"), out double videoProgress); videoSeenPercentage = Math.Floor(videoProgress / totalVideo * 100); } while (videoSeenPercentage < VideoCompletionPercentage); } else { do { double.TryParse(Driver.FindElement(By.CssSelector("div[class=played]")).GetAttribute("aria-valuemax"), out double totalVideo); double.TryParse(Driver.FindElement(By.CssSelector("div[class=played]")).GetAttribute("aria-valuenow"), out double videoProgress); videoSeenPercentage = Math.Floor(videoProgress / totalVideo * 100); } while (videoSeenPercentage < 100); } } ```
2018/10/04
[ "https://Stackoverflow.com/questions/52643734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9810043/" ]
you could just use operateur "?" ``` do { : : }while (videoSeenPercentage < (skip ? VideoCompletionPercentage : 100)); ```
``` private void VideoPecentageCompletion(bool skip) { double videoSeenPercentage; double percentage; do { TryGetAttributeValue("aria-valuemax", out double totalVideo); TryGetAttributeValue("aria-valuenow", out double videoProgress); videoSeenPercentage = Math.Floor(videoProgress / totalVideo * 100); percentage = skip ? VideoCompletionPercentage : 100; } while (videoSeenPercentage < percentage); } private bool TryGetAttributeValue(string attributeName, out double value) { string attributeValue = Driver.FindElement(By.CssSelector("div[class=played]")).GetAttribute(attributeName); return double.TryParse(attributeValue, out value); } ```
46,581,564
I wanted to make a shell script that accepts a vowel and prints the number of occurrences of that vowel inside the text file "abc.txt". The following script works perfectly (a script to print the number of occurrences of the vowel "a" inside the text file "abc.txt"): ``` #!/bin/bash grep -o [aA] abc.txt|wc -l ``` But I want to implement this for all the vowels so I did this: ``` #!/bin/bash echo -n "Enter the desired vowel: " read ch case ch in a) grep -o [aA] abc.txt|wc -l;; A) grep -o [aA] abc.txt|wc -l;; e) grep -o [eE] abc.txt|wc -l;; . . . U) grep -o [uU] abc.txt|wc -l;; esac ``` The code executes but after I enter the desired vowel nothing is displayed. I've also tried this (but the results are the same as those of the code above): ``` #!/bin/bash x=0 echo -n "Enter the desired vowel: " read ch case ch in a) x=grep -o [aA] abc.txt|wc -l;echo $x;; A) x=grep -o [aA] abc.txt|wc -l;echo $x;; e) x=grep -o [eE] abc.txt|wc -l;echo $x;; . . . U) x=grep -o [uU] abc.txt|wc -l;echo $x;; esac ``` I'm lost as to why the `grep` statements aren't displaying anything when I put them inside a `case` statement.
2017/10/05
[ "https://Stackoverflow.com/questions/46581564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7337777/" ]
Multiple issues, but the one mostly causing your problem is not using a variable in the `case` construct. Use `ch` is just a constant and does not match any of the expressions below. ``` case "$ch" in # ^^^^^ This needs to be a variable used in read command ``` Also, to store the output of a command, you need to use command-substitution syntax of type `$(cmd)`. Also instead of `grep .. | wc -l` you can just use the `-c` flag to return the total count of matched strings. ``` x=$(grep -oc '[aA]' abc.txt); echo "$x" ``` (or) an even improved `grep` command would be to enable case-insensitive match with the `-i` flag ``` x=$(grep -oci 'a' abc.txt); echo "$x" ```
Your problem is not the case statement, but that you're using the variable assignment in a wrong way ``` x=grep -o [aA] abc.txt|wc -l;echo $x ``` you're assigning `grep` to the variable x for running `-o [aA] abc.txt`, as `var=something command` assigns the variable just for running `command`. This of course doesn't make sense, but you can be glad you didn't try something like `x=something rm *` which would have deleted your files. The correct syntax is ``` x="`grep -o '[aA]' abc.txt|wc -l`" ``` which means execute `grep|wc` in a subshell and assign the result to the variable x. I added quotes, as you get a problem without quotes when your command does not return anything, as `x=` is a syntax error while `x=""` is perfectly fine. In bash you have the nice syntax (which can be nested) ``` x="$(grep -o '[aA]' abc.txt|wc -l)" ``` which does the same. But be sure to begin your script with `#!/bin/bash`, as `/bin/sh` often is another shell than bash where the syntax may not work. The `$()` should work on every [fully POSIX compatible shell](https://stackoverflow.com/a/3789934/893159), but `/bin/sh` may not be fully compatible, so using a specific shell is a good idea anyway.
41,161,006
I am trying to read some logs from a Hadoop process that I run in AWS. The logs are stored in an S3 folder and have the following path. bucketname = name key = y/z/stderr.gz Here Y is the cluster id and z is a folder name. Both of these act as folders(objects) in AWS. So the full path is like x/y/z/stderr.gz. Now I want to unzip this .gz file and read the contents of the file. I don't want to download this file to my system wants to save contents in a python variable. This is what I have tried till now. ``` bucket_name = "name" key = "y/z/stderr.gz" obj = s3.Object(bucket_name,key) n = obj.get()['Body'].read() ``` This is giving me a format which is not readable. I also tried ``` n = obj.get()['Body'].read().decode('utf-8') ``` which gives an error **utf8' codec can't decode byte 0x8b in position 1: invalid start byte.** I have also tried ``` gzip = StringIO(obj) gzipfile = gzip.GzipFile(fileobj=gzip) content = gzipfile.read() ``` This returns an error **IOError: Not a gzipped file** Not sure how to decode this .gz file. Edit - Found a solution. Needed to pass n in it and use BytesIO ``` gzip = BytesIO(n) ```
2016/12/15
[ "https://Stackoverflow.com/questions/41161006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2358427/" ]
You can use AWS S3 **SELECT Object Content** to read gzip contents S3 Select is an Amazon S3 capability designed to pull out only the data you need from an object, which can dramatically improve the performance and reduce the cost of applications that need to access data in S3. Amazon S3 Select works on objects stored in Apache Parquet format, JSON Arrays, and BZIP2 compression for CSV and JSON objects. Ref: <https://docs.aws.amazon.com/AmazonS3/latest/dev/selecting-content-from-objects.html> ``` from io import StringIO import boto3 import pandas as pd bucket = 'my-bucket' prefix = 'my-prefix' client = boto3.client('s3') for object in client.list_objects_v2(Bucket=bucket, Prefix=prefix)['Contents']: if object['Size'] <= 0: continue print(object['Key']) r = client.select_object_content( Bucket=bucket, Key=object['Key'], ExpressionType='SQL', Expression="select * from s3object", InputSerialization = {'CompressionType': 'GZIP', 'JSON': {'Type': 'DOCUMENT'}}, OutputSerialization = {'CSV': {'QuoteFields': 'ASNEEDED', 'RecordDelimiter': '\n', 'FieldDelimiter': ',', 'QuoteCharacter': '"', 'QuoteEscapeCharacter': '"'}}, ) for event in r['Payload']: if 'Records' in event: records = event['Records']['Payload'].decode('utf-8') payloads = (''.join(r for r in records)) try: select_df = pd.read_csv(StringIO(payloads), error_bad_lines=False) for row in select_df.iterrows(): print(row) except Exception as e: print(e) ```
Just like what we do with variables, data can be kept as bytes in an in-memory buffer when we use the io module’s Byte IO operations. Here is a sample program to demonstrate this: ``` mport io stream_str = io.BytesIO(b"JournalDev Python: \x00\x01") print(stream_str.getvalue()) ``` The `getvalue()` function takes the value from the Buffer as a String. So, the @Jean-FrançoisFabre answer is correct, and you should use ``` gzip = BytesIO(n) ``` For more information read the following doc: <https://docs.python.org/3/library/io.html>
22,374,882
I am new to Javascript, and i run into some big problems. I got some functions, which I can type into a text field and press enter, and the functions works. But i have created 4 buttons, which i want to connect to the actions.. i got 4 actions: "UP","DOWN","LEFT" and "RIGHT". This is the js fiddle over my code: <http://jsfiddle.net/n24gQ/> I have made the buttons like this but I dont know what to write inside the OnClick tag? ``` <div id="gamebuttons"> <button id="up" button onClick="">UP</button> <button id="down" button onClick="">DOWN</button> <button id="left" button onClick="">LEFT</button> <button id="right" button onClick="">RIGHT</button> </div> ``` I hope you can understand what my problem is. I made 4 javascript cases which I want to bind to 4 html buttons if possible.. :) It is the cases: "frem" "tilbage" "hoejre" and "venstre" i need to bind.. Sorry not everything in the code is english, but it should be understandable..
2014/03/13
[ "https://Stackoverflow.com/questions/22374882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3414678/" ]
Instead of using inline handlers (bad practice) or multiple handlers for each button, I would use event delegation on your button wrapper, like so ``` $('#gamebuttons').on('click', 'button', function() { /* get the id attribute of the clicked button */ var button_id = this.id; case (button_id) { "UP" : /* code for up button */ break; "DOWN" : /* code for down button */ break; "LEFT" : /* code for left button */ break; "RIGHT" : /* code for right button */ break; } }); ```
Please pass the function name inside the OnClick tag for example if you want to associate **playGame** function to DOWN button write ``` <button id="down" onclick="playGame();">DOWN</button> ```
52,507,482
I need to know how to hide the bottom label. I've tried the following: > > tabBarShowLabels: 'hidden', tabbarlabelvisible: false. > > > I also removed the `tabbarlabel: 'Home'` and it still shows Any help would be appreciated or if someone could point me to the right direction. [![enter image description here](https://i.stack.imgur.com/fd5Fk.png)](https://i.stack.imgur.com/fd5Fk.png) ``` import {createBottomTabNavigator} from 'react-navigation' import Icon from 'react-native-vector-icons/Ionicons' const Tabs = createBottomTabNavigator ({ Home:{ screen: Home, navigationOptions:{ tabBarIcon: ({ focused, tintcolor }) => ( <Icon name="ios-home" size={24} /> ) } }, Inbox:{screen: Inbox, navigationOptions:{ tabBarIcon: ({ tintcolor }) => ( <Icon name="ios-mail" size={24} /> ) } }, Search:{screen: Search, navigationOptions:{ tabBarIcon: ({ tintcolor }) => ( <Icon name="ios-search" size={24} /> ) } }, Favorites:{screen: Favorites, navigationOptions:{ tabBarIcon: ({ tintcolor }) => ( <Icon name="ios-heart" size={24} /> ) } }, Settings:{screen: Settings, navigationOptions:{ tabBarIcon: ({ tintcolor }) => ( <Icon name="ios-settings" size={24} /> ) } } } }); export default class App extends Component { render() { return <Tabs /> } } ```
2018/09/25
[ "https://Stackoverflow.com/questions/52507482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10364763/" ]
You have to define `showLabel: false` as the [docs](https://reactnavigation.org/docs/bottom-tab-navigator/#showlabel) says, just as ``` const Tabs = createBottomTabNavigator ({ Home:{ screen: Home, navigationOptions:{ tabBarIcon: ({ focused, tintcolor }) => ( <Icon name="ios-home" size={24} /> ) } }, ... , Settings:{screen: Settings, navigationOptions:{ tabBarIcon: ({ tintcolor }) => ( <Icon name="ios-settings" size={24} /> ) } } } }, { tabBarOptions: { showLabel: false } }); ```
On the new versions of React Navigation, you just need to pass `showLabel` prop as `false` ``` <Tab.Navigator tabBarOptions={{ showLabel: false }}> ```
3,397,873
I would like to be able to pull back 15 or so records from a database. I've seen that using `WHERE id = rand()` can cause performance issues as my database gets larger. All solutions I've seen are geared towards selecting a single random record. I would like to get multiples. Does anyone know of an efficient way to do this for large databases? edit: **Further Edit and Testing:** I made a fairly simple table, on a new database using MyISAM. I gave this 3 fields: `autokey` (unsigned auto number key) `bigdata` (a large blob) and `somemore` (a medium int). **I then applied random data to the table and ran a series of queries using Navicat. Here are the results:** `Query 1: select * from test order by rand() limit 15` ``` Query 2: select * from test join (select round(rand()*(select max(autokey) from test)) as val from test limit 15) as rnd on rnd.val=test.autokey;` ``` (I tried both select and select distinct and it made no discernible difference) and: ``` Query 3 (I only ran this on the second test): SELECT * FROM ( SELECT @cnt := COUNT(*) + 1, @lim := 10 FROM test ) vars STRAIGHT_JOIN ( SELECT r.*, @lim := @lim - 1 FROM test r WHERE (@cnt := @cnt - 1) AND RAND(20090301) < @lim / @cnt ) i ``` ``` ROWS: QUERY 1: QUERY 2: QUERY 3: 2,060,922 2.977s 0.002s N/A 3,043,406 5.334s 0.001s 1.260 ``` I would like to do more rows so I can see how query 3 scales, but at the moment, **it seems as though the clear winner is query 2**. Before I wrap up this testing and declare an answer, and while I have all this data and the test environment set up, **can anyone recommend any further testing?**
2010/08/03
[ "https://Stackoverflow.com/questions/3397873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/153110/" ]
> > **Update**: Check out the accepted answer in [this question](https://stackoverflow.com/questions/1244555/how-can-i-optimize-mysqls-order-by-rand-function). It's pure mySQL and even deals with even distribution. > > > The problem with `id = rand()` or anything comparable in PHP is that you can't be sure whether that particular ID still exists. Therefore, you need to work with `LIMIT`, and that can become slow for large amounts of data. As an alternative to that, you could try using a loop in PHP. What the loop does is * Create a random integer number using `rand()`, with a scope between `0` and the number of records in the database * Query the database whether a record with that ID exists * If it exists, add the number to an array * If it doesn't, go back to step 1 * End the loop when the array of random numbers contains the desired number of elements this method could cause a lot of queries in a fragmented table, but they should be pretty fast to execute. It *may* be faster than `LIMIT rand()` in certain situations. The `LIMIT` method, as outlined by @Luther, is certainly the simplest code-wise.
You could do a query with all the results or however many limited, then use mysqli\_fetch\_all followed by: ``` shuffle($a); $a = array_slice($a, 0, 15); ```
2,969,003
I am hoping this question fares a little better than the similar [Create a table without columns](https://stackoverflow.com/questions/2438321/create-a-table-without-columns). Yes, I am asking about something that will strike most as pointlessly academic. It is easy to produce a SELECT result with 0 rows (but with columns), e.g. `SELECT a = 1 WHERE 1 = 0`. **Is it possible to produce a SELECT result with 0 columns (but with rows)?** e.g. something like `SELECT NO COLUMNS FROM Foo`. (This is not valid T-SQL.) I came across this because I wanted to insert several rows without specifying any column data for any of them. e.g. (SQL Server 2005) ``` CREATE TABLE Bar (id INT NOT NULL IDENTITY PRIMARY KEY) INSERT INTO Bar SELECT NO COLUMNS FROM Foo -- Invalid column name 'NO'. -- An explicit value for the identity column in table 'Bar' can only be specified when a column list is used and IDENTITY_INSERT is ON. ``` One can insert a single row without specifying any column data, e.g. `INSERT INTO Foo DEFAULT VALUES`. One can query for a count of rows (without retrieving actual column data from the table), e.g. `SELECT COUNT(*) FROM Foo`. (But that result set, of course, has a column.) I tried things like ``` INSERT INTO Bar () SELECT * FROM Foo -- Parameters supplied for object 'Bar' which is not a function. -- If the parameters are intended as a table hint, a WITH keyword is required. ``` and ``` INSERT INTO Bar DEFAULT VALUES SELECT * FROM Foo -- which is a standalone INSERT statement followed by a standalone SELECT statement. ``` I can do what I need to do a different way, but the apparent lack of consistency in support for degenerate cases surprises me. I read through the relevant sections of BOL and didn't see anything. I was surprised to come up with nothing via Google either.
2010/06/03
[ "https://Stackoverflow.com/questions/2969003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200993/" ]
No it's a SQL limitation. SQL has lots of warts, contradictions and asymmetries. It's unfortunately not mathematically precise or complete unlike the relational theory and algebra it was inspired by and meant to be used to work with.
If I remember correctly, `SELECT NULL FROM table_name;` is valid syntax, but I don't remember whether this counts as having zero columns or one column (containing NULL for each row).
5,498,937
My question is simple. When do we need to have a default constructor? Please refer to the code below: ``` class Shape { int k; public: Shape(int n) : k(n) {} ~Shape() {} }; class Rect : public Shape { int l; public: Rect(int n): l(n) {} //error C2512: 'Shape' : no appropriate default constructor available ~Rect() {} }; ``` 1. Why is the compiler not generating the zero argument default constructor implicitly in the class Rect? 2. As per my knowledge, if a class (Rect) is derived from another class (Shape) that has default constructor (either implicitly generated or explicitly provided), the default constructor should be generated by the compiler.
2011/03/31
[ "https://Stackoverflow.com/questions/5498937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683589/" ]
Compiler generates default constructor in case when you have not define any constructor. But if you have defined any constructor that takes some argument or not. The compiler will use that constructor and will not generate default constructor with zero argument.
The default constructor is generated only if you have not defined any other constructors. Supposedly, if you need some special initialization in the class, the default constructor would not do the right thing.
36,214,999
I've recently started using application insights with a web api. It will be really helpful to configure app insights to post error messages in a slack channel. I've seen there is a slack connector but I am not sure how to use it, my guess is that this can be solved with the slack connector and a azure logic app, any tips? tutorials?
2016/03/25
[ "https://Stackoverflow.com/questions/36214999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/261363/" ]
You may have a look at this link: <https://github.com/Azure/azure-quickstart-templates/tree/master/demos/alert-to-slack-with-logic-app>. I followed the instruction and it worked for me. The tricky part is you need to click the "Deploy to Azure" button on this link page. It would redirect you to Azure Portal, and you will need to specify which channel you want the alert message to be sent e.g. #somechannel. Don't use direct message like @yourname, it has some problem with that and the logic app couldn't deploy for me. Then you just follow the instruction to find the deployed logic app and authenticate it by logging into slack. And you also need get the logic app URI from the deployment output as in the instruction. Once you put the URI into the alert webhook, you are ready to go!
The most easiest path that I found to integrate was using an app named Slack Email which sends email alerts to slack. Once you subscribe this email id to alerts in Application Insights it will start sending the messages on the specific channel you have linked the email to. <https://teamesub.slack.com/apps/A0F81496D-email>
23,834,624
How to remove first and last character from std::string, I am already doing the following code. But this code only removes the last character ``` m_VirtualHostName = m_VirtualHostName.erase(m_VirtualHostName.size() - 1) ``` How to remove the first character also?
2014/05/23
[ "https://Stackoverflow.com/questions/23834624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2623557/" ]
Well, you could [`erase()`](http://en.cppreference.com/w/cpp/string/basic_string/erase) the first character too (note that `erase()` modifies the string): ``` m_VirtualHostName.erase(0, 1); m_VirtualHostName.erase(m_VirtualHostName.size() - 1); ``` But in this case, a simpler way is to take a substring: ``` m_VirtualHostName = m_VirtualHostName.substr(1, m_VirtualHostName.size() - 2); ``` Be careful to validate that the string actually has at least two characters in it first...
My BASIC interpreter chops beginning and ending quotes with ``` str->pop_back(); str->erase(str->begin()); ``` Of course, I *always* expect well-formed BASIC style strings, so I will abort with failed `assert` if not: `assert(str->front() == '"' && str->back() == '"');` Just my two cents.
19,436,975
Ok so I have a question relating to the output of the following code (which is 111222223) ``` #include <iostream> struct C { virtual int eq(const C& other) const { return 1; } }; struct SC : C { virtual int eq(const C& other) const { return 2; } virtual int eq(const SC& other) const { return 3; } }; void go(const C& c, const C& c1, const SC& sc) { using namespace std; cout << c.eq(c) << endl; cout << c.eq(c1) << endl; cout << c.eq(sc) << endl; cout << c1.eq(c) << endl; cout << c1.eq(c1) << endl; cout << c1.eq(sc) << endl; cout << sc.eq(c) << endl; cout << sc.eq(c1) << endl; cout << sc.eq(sc) << endl; } int main(int argc, const char* argv[]) { go(C(), SC(), SC()); return 0; } ``` So I understand that I am using the dot operator with a reference that will dynamically bind the proper virtual method based on the run-time type of the caller (would need -> with pointers but OK for dynamic minding here). What I don't understand is why the second to last cout line prints '2' and not '3'. Is this because the method signature is static, so the method is selected based on the static signature in the proper derived type SC? Thanks for the help in advance!
2013/10/17
[ "https://Stackoverflow.com/questions/19436975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1628702/" ]
First, the declared type of `CircuitData` should be a pointer: ``` ListNodeType* CircuitData; ``` To set the address stored in `CircuitData` (inside the ReadFile function) you would write ``` *CircuitData = newPtr; ``` This sets the data at the address `CircuitData` to the address stored in `newPtr`, which is what you want to do. You also need to properly pass the address of the CircuitData pointer to the ReadFile function by calling ``` ReadFile(&CircuitData, ...) ```
Define CircuitData as (ListNodeType \*), and in function ReadFile, pass &CircuitData
30,054,149
Here it is... By the way, it is misaligned in jsFiddle. In my actual webpage it's aligned, so no worries there. <http://jsfiddle.net/j8oawqL4/> I tried using code inspired by [http://jsbin.com/umubad/2/](http://jsbin.com/umubad/2/edit?html,js,output) but I couldn't figure out how to successfully implement it. HTML ``` <ul class="navbar cf"> <li> <a href="#" class="ActiveListItem">Category</a> <ul> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li><a href="#">6</a></li> <li><a href="#">7</a></li> </ul> </li> </ul> </div> ``` CSS ``` ul.navbar { border-style:solid; border-width:1px; border-color:#739FE0; width: 100px; /*Widthchanger1*/ border-radius: 4px; margin-left:0px; margin-right:0px; font-size:14px; height:33px; } ul.navbar li a.ActiveListItem { background:url(../images/downarrowblue.png) !important; background-repeat: no-repeat !important; background-size: 10px 10px !important; background-position: 83px 13px !important; color:white; !important; background-color:#222 !important; padding:7.5px 0px !important; font-weight:normal !important; margin-left:0px; /*Widthchanger2, got the activeitem centered with list text this way*/ margin-right:0px; border-radius: 4px; height:18px; width:100px; /*kinda messes with width of text*/ margin-bottom:1px; } ul.navbar li { position: relative; width:100px; /*Changes width of actual list*/ } ul.navbar li a { display: block; color: white; padding:10px 5px; text-decoration:none; transition: all .1s ease-in; } ul.navbar li a:hover, ul.navbar li:hover > a { /*background:black; */ background:#739FE0; color:#FFFFFF; /*font-weight:600;*/ /*border-bottom-color:#FFFFFF; border-bottom-style:solid;*/ /*border-color:#FFFFFF; border-style:solid; border-width:1px; */ } ul.navbar li ul { margin-top: 0px; /*Controls space from listdropdown to listchooser*/ position: absolute; background: #222; font-size: 14px; /* min-width: 200px; */ display: none; z-index: 99; box-shadow: inset 0 0px 3px rgba(0,0,0,.6), 0 5px 10px rgba(0,0,0,.6); } ol, ul { list-style: outside none none; } .hidden { display: none; } ``` JS ``` $(function() { $('.navbar ul li a').click(function(){ $('.navbar > li:first-child > a').text($(this).text()); $('.navbar > li > ul').addClass('hidden'); $('.navbar li ul').slideToggle(100); }); $('.navbar > li').mouseenter(function(){ $(this).find('ul').removeClass('hidden'); }); $('.ActiveListItem').click(function(){ $('.navbar li ul').slideToggle(300); }); }); ```
2015/05/05
[ "https://Stackoverflow.com/questions/30054149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4725638/" ]
``` $(document).click(function (event) { alert(event.target.id); if (event.target.id != 'category') { $('.navbar li ul').slideToggle(300); } ``` })
What about ? ``` $("body").on("click", function(e){ if(!$(e.target).is(".navbar *")){ $('.navbar li ul').slideUp(100); } }); ``` <http://jsfiddle.net/j8oawqL4/7/>
39,757,948
Hi there trying to create my first meteor project on my desktop. When I try initialize my project after creation by entering the directory and entering meteor get and error. I am working on windows 10. I tried uninstalling/installing & deleting the .meteor folder. I am on node 5.6.0 and meteors 1.4.1.1. ``` C:\Users\Alex\AppData\Local.meteor\packages\meteor-tool\1.4.1_1\mt-os.windows.x86_32\dev_bundle\lib\node_modules\meteor-promise\promise_server.js:165 throw error; ^ TypeError: httpProxy.createProxyServer is not a function at Proxy.start (C:\tools\runners\run-proxy.js:40:28) at Runner.start (C:\tools\runners\run-all.js:119:16) at Object.exports.run (C:\tools\runners\run-all.js:322:10) at Command.doRunCommand as func at C:\tools\cli\main.js:1410:23 ```
2016/09/28
[ "https://Stackoverflow.com/questions/39757948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6057000/" ]
the definitive solution is: remove folder "http-proxy" under c:\users\username\node\_modules
Try to change directory to the root of your new project, then run meteor. ``` $ cd my/directory/root $ meteor ```
16,019,401
I'm not entirely sure when it happened, but attempting to run homebrew on my OSX Mountain Lion machine now yields a strange error: `/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- checksums (LoadError)` This was noticed after a failed attempt to install RVM with the command: `\curl -L https://get.rvm.io | bash -s stable --ruby` ``` % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 184 100 184 0 0 136 0 0:00:01 0:00:01 --:--:-- 155 100 13145 100 13145 0 0 6879 0 0:00:01 0:00:01 --:--:-- 6879 Please read and follow further instructions. Press ENTER to continue. Downloading RVM from wayneeseguin branch stable % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 124 100 124 0 0 433 0 --:--:-- --:--:-- --:--:-- 551 100 3263k 100 3263k 0 0 1245k 0 0:00:02 0:00:02 --:--:-- 1467k Installing RVM to /Users/mike/.rvm/ Adding rvm PATH line to /Users/mike/.bashrc /Users/mike/.zshrc. Adding rvm loading line to /Users/mike/.bash_profile /Users/mike/.zprofile. * WARNING: You have RUBYOPT set in your current environment. This may cause rubies to not work as you expect them to as it is not supported by all of them If errors show up, please try unsetting RUBYOPT first. # RVM: Shell scripts enabling management of multiple ruby environments. # RTFM: https://rvm.io/ # HELP: http://webchat.freenode.net/?channels=rvm (#rvm on irc.freenode.net) # Cheatsheet: http://cheat.errtheblog.com/s/rvm # Screencast: http://screencasts.org/episodes/how-to-use-rvm # In case of any issues run 'rvm requirements' or read 'rvm notes' Installation of RVM in /Users/mike/.rvm/ is almost complete: * To start using RVM you need to run `source /Users/mike/.rvm/scripts/rvm` in all your open shell windows, in rare cases you need to reopen all shell windows. # Mike Greiling, # # Thank you for using RVM! # I sincerely hope that RVM helps to make your life easier and # more enjoyable!!! # # ~Wayne rvm 1.19.5 (stable) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/] Searching for binary rubies, this might take some time. No binary rubies available for: osx/10.8/x86_64/ruby-2.0.0-p0. Continuing with compilation. Please read 'rvm mount' to get more information on binary rubies. Installing requirements for osx, might require sudo password. Skipping `brew update` make sure your formulas are up to date. RVM autolibs is now configured with mode '2' => 'check and stop if missing', please run `rvm autolibs enable` to let RVM do its job or run and read `rvm autolibs [help]` or visit https://rvm.io/rvm/autolibs for more information. Missing required packages: automake, libtool, pkg-config, libyaml, readline, libxml2, libxslt, libksba, openssl, sqlite. RVM autolibs is now configured with mode '2' => 'check and stop if missing', please run `rvm autolibs enable` to let RVM do its job or run and read `rvm autolibs [help]` or visit https://rvm.io/rvm/autolibs for more information. There were package installation errors, make sure to read the log. Check Homebrew requirements https://github.com/mxcl/homebrew/wiki/Installation ``` I'm unsure if it was this failed attempt to install RVM that borked my default ruby installation or if homebrew itself is corrupted in some way, but I'd like to get homebrew and osx's native ruby install working again if possible. It may come down to a terminal PATH setting or something, but I'm new to this and have no idea where to start.
2013/04/15
[ "https://Stackoverflow.com/questions/16019401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1447303/" ]
You need to read the output: > > RVM autolibs is now configured with mode '2' => 'check and stop if missing', > please run `rvm autolibs enable` to let RVM do its job or run and read `rvm autolibs [help]` > > > If you were following instructions from [rvm site installation instructions](https://rvm.io/rvm/install) it would have worked: ``` \curl -#L https://get.rvm.io | bash -s stable --autolibs=3 --ruby ```
Try: ``` rvm get head && rvm reload ``` to update your rvm install
24,669,486
**HTML** ``` <input type="text" value="" id="ip1" class="ip1" /> <input type="button" value="Add" class="bt1" id="bt1"> </br> <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> </select> ``` **JQUERY** ``` $(document).ready(function(e) { $(".bt1").click(function(){ var opt = $("#ip1").val(); }); }); ``` Hi friends here i want to add value from text box to select option using jquery, i got the value from textbox but don't know how to insert, help me.
2014/07/10
[ "https://Stackoverflow.com/questions/24669486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3820063/" ]
you can do like this: **HTML:** ``` <select id="List"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> </select> ``` **JQUERY:** ``` $(".bt1").click(function(){ var opt = $("#ip1").val(); $('#List') .append($("<option></option>") .attr("value",opt ) .text(opt)); }); ``` [**FIDDLE DEMO**](http://jsfiddle.net/Z35r9/)
``` $(document).ready(function (e) { $(".bt1").click(function () { var opt = $("#ip1").val(); $('select').append(' <option value="' + opt + '">' + opt + '</option>') }); }); ``` [DEMO](http://jsfiddle.net/J2QVN/1/)
15,626,393
Ok It's simple. I just want to add 1 to a number every time trought the use of `+=` operator! So i go in prompt just like this: ``` C:\Users\fsilveira>SET teste=000007 C:\Users\fsilveira>ECHO %teste% 000007 C:\Users\fsilveira>SET /A teste+=1 8 C:\Users\fsilveira> ``` Wow nice. Seems to be working just fine. From the behaviour of the last one, if I use the same operator again, it should just add one to eight right? So I guess I will have 9? But here is what's happening: ``` C:\Users\fsilveira>SET teste=000008 C:\Users\fsilveira>ECHO %teste% 000008 C:\Users\fsilveira>SET /A teste+=1 1 C:\Users\fsilveira> ``` What? 8 + 1 is 1 ? o\_O When it comes to the number 8 it does not work how it should (or how I believe it's suppose to) I'm going insane over here. Please some one could help me and explain to me what's happening? I really dont know! Regards, Filipe
2013/03/25
[ "https://Stackoverflow.com/questions/15626393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521864/" ]
When prefixing with 0 it is intrepeated as an octal number. And 00008 is not a valid octal number. You can see the effect of this by the following: ``` C:\Users>SET teste=000020 C:\Users>ECHO %teste% 000020 C:\Users>SET /A teste+=1 17 ``` where `00020` in octal is `16` in decimal.
You can avoid this by removing leadig zeros: ``` C:\>set teste=000008 C:\>echo %teste% 000008 C:\>for /f "tokens=1*delims=0" %i in ("$0%teste%") do @set teste=%j C:\>set /a teste+=1 9 ```
24,745,396
I'm trying to run an SSIS package in Visual Studio 2012. When I click the "Start" button I get this very odd error in a popup from Visual Studio: ``` Method not found: 'Boolean Microsoft.SqlServer.Dts.Design.VisualStudio2012Utils.IsVisualStudio2012ProInstalled()'. (Microsoft.DataTransformationServices.VsIntegration) ``` Clicking on the show technical information, I get this stack trace: ``` =================================== Failed to start project (Microsoft Visual Studio) =================================== Method not found: 'Boolean Microsoft.SqlServer.Dts.Design.VisualStudio2012Utils.IsVisualStudio2012ProInstalled()'. (Microsoft.DataTransformationServices.VsIntegration) ------------------------------ Program Location: at Microsoft.DataTransformationServices.Project.DataTransformationsPackageDebugger.LaunchVsDebugger(IVsDebugger iVsDebugger, DataTransformationsProjectConfigurationOptions options) at Microsoft.DataTransformationServices.Project.DataTransformationsPackageDebugger.ValidateAndRunDebugger(Int32 flags, IOutputWindow outputWindow, DataTransformationsProjectConfigurationOptions options) at Microsoft.DataTransformationServices.Project.DataTransformationsProjectDebugger.LaunchDtsPackage(Int32 launchOptions, ProjectItem startupProjItem, DataTransformationsProjectConfigurationOptions options) at Microsoft.DataTransformationServices.Project.DataTransformationsProjectDebugger.LaunchActivePackage(Int32 launchOptions) at Microsoft.DataTransformationServices.Project.DataTransformationsProjectDebugger.LaunchDtsPackage(Int32 launchOptions, DataTransformationsProjectConfigurationOptions options) at Microsoft.DataTransformationServices.Project.DataTransformationsProjectDebugger.Launch(Int32 launchOptions, DataTransformationsProjectConfigurationOptions options) ``` Has anyone ever seen this error before or know what the issue might be? A bit of googling turned up absolutely nothing for me. I was able to happily develop and run SSIS packages from Visual Studio 2012 without any issues just a couple days ago (I did reboot my PC over the weekend and some windows updates were installed) ETA: I was able to find a couple very recent technet posts about this [here](http://social.msdn.microsoft.com/Forums/sqlserver/en-US/edfbbb0b-717f-4f4f-b458-fa4b0c1a5006/ssis-package-wont-debug-in-vs2012?forum=sqlintegrationservices) and [here](http://social.technet.microsoft.com/Forums/en-US/b7aff86e-564e-4a35-adb7-e48aebb7a09c/fail-to-start-project?forum=sqlintegrationservices) so I suspect this was something that broke in an update over the weekend. One post says he solved the issue by reinstalling, but of course I'd rather not go that route if I don't have to.
2014/07/14
[ "https://Stackoverflow.com/questions/24745396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65070/" ]
1. Open the Developer Command Prompt for VS212 as Administrator 2. execute the command `cd "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PrivateAssemblies"` 3. execute the command `gacutil /if Microsoft.SqlServer.Dts.Design.dll` 4. restart Visual Studio Source msdn [Fail to start project](http://social.technet.microsoft.com/Forums/en-US/b7aff86e-564e-4a35-adb7-e48aebb7a09c/fail-to-start-project?forum=sqlintegrationservices) **For visual Studio 2013** execute the command `cd "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies"` in point 2 and then execute point 3 and 4.
The following is the command we have to use to resolve the issue: > > "C:\Program Files\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\gacutil.exe" /if "C:\Program Files\Microsoft Visual Studio 11.0\Common7\IDE\PrivateAssemblies\Microsoft.SqlServer.Dts.Design.dll" > > > Make sure that your dll file and `Gacutil.exe` file locations are correct. It may be different in other systems. **Note**: You should open your *“Command Prompt”* as an administrator to run the above command.
42,548,714
I'm trying to put json into recyclerview but it gives me the "unable to parse dara" error! this is my json response : > > {"action":"true","error":"","data":[{"\_id":"58ad8d8ca49d0e11e21c4504","store\_name":"firstStore","store\_view":0,"store\_textposition":null}]} > > > And there is where i'm getting the error"Shops\_parser.java" : ``` public class Shops_Parser extends AsyncTask<Void,Void,Boolean> { Context c; String jsonData; RecyclerView rv; ProgressDialog pd; ArrayList<String> shops = new ArrayList<>(); public Shops_Parser(Context c, String jsonData, RecyclerView rv) { this.c = c; this.jsonData = jsonData; this.rv = rv; } @Override protected void onPreExecute() { super.onPreExecute(); pd=new ProgressDialog(c); pd.setMessage("PARSING JSON"); pd.show(); } @Override protected Boolean doInBackground(Void... voids) { return parse(); } @Override protected void onPostExecute(Boolean isParsed) { super.onPostExecute(isParsed); pd.dismiss(); if(isParsed) { ShopsAdapter adapter = new ShopsAdapter(c,shops); rv.setAdapter(adapter); } else { Toast.makeText(c,"Unable to Parse data",Toast.LENGTH_SHORT).show(); } } private boolean parse() { try { JSONArray ja = new JSONArray(jsonData); JSONObject jo; shops.clear(); for(int i=0;i<ja.length();i++) { jo=ja.getJSONObject(i); String store_name = jo.getString("store_name"); shops.add(store_name); } return true; } catch (JSONException e) { e.printStackTrace(); return false; } } } ``` What's wrong with it?
2017/03/02
[ "https://Stackoverflow.com/questions/42548714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6354359/" ]
Your root element is a json object. Parse the object first then get the json array ``` try { JSONObject obj = new JSONObject(jsonData); JSONArray ja = obj.getJsonArray("data"); JSONObject jo; shops.clear(); for(int i=0;i<ja.length();i++) //................ ```
Use below code to parse your json Response: ``` private void parse(String jsonData) { try { JSONObject jsonObject = new JSONObject(jsonData); String action = jsonObject.optString("action"); String error = jsonObject.optString("error"); JSONArray dataArray = jsonObject.getJSONArray("data"); shops.clear(); for(int i=0;i<dataArray.length();i++) { JSONObject jsonObject1 = dataArray.getJSONObject(i); String _id = jsonObject1.optString("_id"); String store_name = jsonObject1.optString("store_name"); String store_view = jsonObject1.optString("store_view"); String store_textposition = jsonObject1.optString("store_textposition"); shops.add(store_name); } } catch (JSONException e) { e.printStackTrace(); } } ```
927,894
I want to practice programming code for future hardware. What are these? The two main things that come to mind is 64bits and multicore. I also note that cache is important along and GPU have their own tech but right now i am not interested in any graphics programming. What else should i know about? -edit- i know a lot of these are in the present but pretty soon all cpus will be multicore and threading will be more important. I consider endians (big vs little) but found that not to be important and already have a big endian CPU to test on.
2009/05/29
[ "https://Stackoverflow.com/questions/927894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
64 bits and multicore are the present not the future. About the future: Quantum computing or something like that?
I agree with Oli's answere (+1) and would add that in addition to 64-bit environments, you look at multi-core environments. The industry is getting pretty close to the end of the cycle of improvements in raw speed. But we're seeing more and more multi-core CPUs. So parallel or concurrent programming -- which is rilly rilly hard -- is quickly becoming very much in demand. How can you prepare for this and practice it? I've been asking myself the same same question. So for, it seems to me like functional languages such as [ML](http://www.smlnj.org/), [Haskell](http://haskell.org/), [LISP](http://en.wikipedia.org/wiki/Lisp_programming_language), [Arc](http://arclanguage.org/), [Scheme](http://groups.csail.mit.edu/mac/projects/scheme/), etc. are a good place to begin, since truly functional languages are generally free of side effects and therefore very "parallelizable". [Erlang](http://erlang.org/) is another interesting language. Other interesting developments that I've found include * The [Singularity](http://www.se-radio.net/podcast/2008-03/episode-88-singularity-research-os-galen-hunt) Research OS * Transactional Memory and Software Isolated Processes * The many Software Engineering Podcast episodes on concurrency. (Here's [the first one](http://www.se-radio.net/podcast/2006-04/episode-12-concurrency-pt-1).) * This article from ACM Queue on "[Real World Concurrency](http://queue.acm.org/detail.cfm?id=1454462)"
17,292,783
Where I can find GPX files that I can import into my iOS Simulator? The iOS Simulator only contains static locations around the world and walk / bike / car drive simulations. This is not good enough for unit testing or other specific use cases. This is the for GPX file: <http://www.topografix.com/GPX/1/1/gpx.xsd> How can I simulate a movement along some custom route in Simulator or Xcode, cause it's needed in ios mobile development?
2013/06/25
[ "https://Stackoverflow.com/questions/17292783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1317394/" ]
You can go to <https://github.com/doronkatz/GFXLocations> which is a github repository of some cities (for Australia). You can generate new ones and contribute back to that.
The ideal and fastest solution (with accuracy), is to: 1. Create a Path via Google Earth 2. Save the path to an .kml file (on your desktop) 3. Open the .kml and copy all the geolocation points (notably the long, lat, elvations) 4. Paste it in TextMate or similar 5. Use this RegEx Find & Replace: Find: `(.*?),(.*?),0` (there is a space at the end of this regex) Replace: `<wpt lat="$2" lon="$1" />` 6. Add to the begining and to the end, and save it as a .gpx 7. Use that gpx file in Xcode after running the App in debug: "Simulate Location" add the GPX, then select it again to start the simulation of the path you made.
7,329,840
I wrote a small code of C. ``` #include<stdio.h> int main() { int a = 0; printf("Hello World %llu is here %d\n",a, 1); return 0; } ``` It is printing the following ouput > > Hello World 4294967296 is here -1216225312 > > > With the following warning on compilation > > prog.cpp: In function ‘int main()’: > > > prog.cpp:5: warning: format ‘%llu’ expects type ‘long long unsigned int’, but argument 2 has type ‘int’ > > > I know i need to cast the int to long long unsigned int, but i could not understand the fact that why the later values got corrupted. Thanks in advance
2011/09/07
[ "https://Stackoverflow.com/questions/7329840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/534087/" ]
The format you passed to `printf()` leads it to expect 12 bytes on the stack, but you only push 8 bytes. So, it reads 4 bytes you didn't push, and gives you unexpected output. Make sure you pass what `printf()` expects, and heed your compiler's warnings.
According to given format, printf reads memory region 64 bit length, which contains a and 1 together, an prints 4294967296. Then it reads some junk from the next 32 bits and prints -1216225312.
121,220
I am presently writing an article about a certain class of discrete probability distributions, and I want to mention that the distribution is relatively obscure compared to other common distributions. As an indicator of its relative obscurity, I would like to mention the fact that this class of distributions does not have its own [Wikipedia](https://en.wikipedia.org/wiki/Main_Page) page, whereas other common distributions (e.g., the [binomial](https://en.wikipedia.org/wiki/Binomial_distribution), [Poisson](https://en.wikipedia.org/wiki/Poisson_distribution), [hypergeometric](https://en.wikipedia.org/wiki/Hypergeometric_distribution), etc.) do have their own pages. **My question:** What is the proper way to cite this evidence? Presumably I will be citing the fact that I have performed a *search* of Wikipedia at a certain time, and that I found pages for various common discrete distributions, but no page for the one that is the subject of my paper. **What I am NOT asking:** I am well aware of the reasons that academic papers do not usually cite Wikipedia as a source. In this instance I only intend to cite it as an indicator of the fact that a topic is sufficiently obscure that no-one has created a page for it. As such, I am not seeking answers on the general objections to citations to Wikipedia (which I am already familiar with).
2018/12/07
[ "https://academia.stackexchange.com/questions/121220", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/87026/" ]
> > What is the proper way to cite this evidence? Presumably I will be citing the fact that I have performed a search of Wikipedia at a certain time, and that I found pages for various common discrete distributions, but no page for the one that is the subject of my paper. > > > You can prove that a particular page didn't exist, for instance, by accessing a particular page (e.g., [obscure\_distributions](https://en.wikipedia.org/wiki/Obscure_distributions)) and recording raw result data (which will be authenticated). See [my answer](https://academia.stackexchange.com/questions/120062/is-there-any-ways-to-document-google-search-results-in-a-research-paper/120064#120064) regarding a similar question for further details. That said, this is probably overkill, and you should probably be doing something [completely different](https://academia.stackexchange.com/a/121246/22768) anyhow.
I think you could really just handle it in article text itself. ("I searched" or "a search was done".) I would maybe mention a few details (date of the search, English Wikipedia, what different versions of the name you searched on). I don't think you have to go crazy about the details if it is just a minor point. You could put details down into a FOOTNOTE ("a" or "b", not a numbered ENDNOTE citation). This gives a little more backup for you, without having to derail the flow of the discussion. You could even consider to just put some [short] description into the endnote citation itself. I have seen people put things like "personal communication" or "Superbowl commercial 2005" or the like into endnotes. Obviously follow formatting strictly when citing normal sources, but if there is some rationale why you need to do something slightly differently, most editors/journals will be fine. The point after all is to communicate. P.s. Practical advice: Do a Google search of Wiki rather than using the Wiki search engine (it is miserable, too literal). Also if there is more than one name for whatever it is, than search under all the names. Don't want to look stupid if there is a page on it but under a different name. P.s.s. More practical advice: consider to do a search in Google science or Webofscience or the like to compare how often the funky distribution is returned versus more common ones (normal, etc.) It gives more of a comparison than just the yes/no has a Wiki page or not. You can also look at Google Trends for prevalence on the web (compare to other terms). I believe you can do the same thing even for book text. See below for an example in field I know: <http://2.bp.blogspot.com/-hC819n9EoFM/UfkIFielYMI/AAAAAAAAAlw/wgwD7GDqfqQ/s1600/screenshot_12.jpg>
22,826,067
I have read the MSDN but, I could not understand this concept. Correct me if I am wrong, > > A innerexception will be used in hand with current exception. > > > Inner exception will occur first and then the current exception will occur (if there is an exception) that is the reason why `InnerException` is checked against `null`. In order to retain inner exception we have to pass it as a parameter. Am I right with this?
2014/04/03
[ "https://Stackoverflow.com/questions/22826067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2526236/" ]
An inner exception is the exception that caused the current exception. It is used in cases when you want to surface a different exception than the one that your code caught but you don't want to throw away the original context. In order for a new exception to have information about a previous one, like you said, you pass it as constructor parameter to the new one. *Usually*, a null inner exception means that the current exception is root cause of the exceptional situation.
Exception objects are read only by the time you get to a `catch` block, sometimes your code can't do anything to handle the exception, but it can add more information by creating a new exception and wrapping the originally thrown exception inside of it. This makes it so you can add information but not be required to copy field by field every piece of information from the original exception (which may not even be possible if you don't know the type of exception that will be thrown). Here is a slightly modified snippet from a project of mine that uses a bit of everything dealing with Exceptions. ``` private void SomeFunction(string username, string password) { try { try { _someObject.DoSpecialPrivilegedFunction(username, password); } catch (UnauthorizedAccessException ex) { throw new UserUnauthorizedException(username, "DoSpecialPrivilegedFunction", ex); } catch (IOException ex) { throw new UserModuleActionException("A network IO error happend.", username, "DoSpecialPrivilegedFunction", ex); } //Other modules } catch (Exception ex) { //If it is one of our custom expections, just re-throw the exception. if (ex is UserActionException) throw; else throw new UserActionException("A unknown error due to a user action happened.", username, ex); } } //elsewhere [Serializable] public class UserUnauthorizedException : UserModuleActionException { private const string DefaultMessage = "The user attempted to use a non authorized module"; public UserUnauthorizedException() : base(DefaultMessage) { } public UserUnauthorizedException(string message) : base(message) { } public UserUnauthorizedException(string message, Exception innerException) : base(message, innerException) { } public UserUnauthorizedException(string username, string module, Exception innerException = null) : base(DefaultMessage, username, module, innerException) { } protected UserUnauthorizedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class UserModuleActionException : UserActionException { private readonly string _module; public UserModuleActionException() { } public UserModuleActionException(string message) : base(message) { } public UserModuleActionException(string message, Exception innerException) : base(message, innerException) { } public UserModuleActionException(string message, string username, string module, Exception innerException = null) : base(message, username, innerException) { _module = module; } protected UserModuleActionException(SerializationInfo info, StreamingContext context) : base(info, context) { } public virtual string Module { get { return _module; } } public override string Message { get { string s = base.Message; if (!String.IsNullOrEmpty(_module)) { return s + Environment.NewLine + String.Format("Module: {0}", _module); } return base.Message; } } } [Serializable] public class UserActionException : Exception { private readonly string _username; public UserActionException() { } public UserActionException(string message) : base(message) { } public UserActionException(string message, Exception innerException) : base(message, innerException) { } public UserActionException(string message, string username, Exception innerException = null) : base(message, innerException) { _username = username; } protected UserActionException(SerializationInfo info, StreamingContext context) : base(info, context) { } public override string Message { get { string s = base.Message; if (!String.IsNullOrEmpty(_username)) { return s + Environment.NewLine + String.Format("Username: {0}", _username); } return base.Message; } } public virtual string Username { get { return _username; } } } ```
2,674,205
> > What does the below expression converge to and why? > $$ \cfrac{2}{3 -\cfrac{2}{3-\cfrac{2}{3-\cfrac2\ddots}}}$$ > > > Setting it equal to $ x $, you can rewrite the above as $ x = \dfrac{2}{3-x} $, which gives the quadratic equation $x^2 - 3x + 2 = 0 $, and the roots are $ 1 $ and $2 $, both positive. How do we know which to reject?
2018/03/02
[ "https://math.stackexchange.com/questions/2674205", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
You can look at the stability of the solutions. You start with some $x\_0$ close to one of your solutions, and check if $$x\_1=\frac{2}{2-x\_0}$$ is closer to that solution. So if $x\_0=1+\epsilon$, where $|\epsilon|\ll 1$, we have $$x\_1=\frac{2}{3-(1+\epsilon)}=\frac{2}{2-\epsilon}\approx\left(1+\frac{\epsilon}{2}\right)$$ This is closer to $1$ than $x\_0$, so the solution is stable. We repeat the procedure for $x\_0=2+\epsilon$. $$x\_1=\frac{2}{3-(2+\epsilon)}\approx2(1+\epsilon)=2+2\epsilon$$ This $x\_1$ is further from $2$ than $x\_0$, so the solution is not stable.
In fact this fraction is the limit of the following sequence$$x\_{n+1}=\dfrac{2}{3-x\_n}\\x\_0=\dfrac{2}{3}$$now if $0<x\_n<1$ we have $$2<3-x\_n<3\to\\\dfrac{2}{3}<x\_{n+1}=\dfrac{2}{3-x\_n}<1$$therefore for all $n$ we have $$0.66<x\_n<1$$ ant then the limit is $1$.
6,969,604
This is code from Crockford's JavaScript: The Good Parts. ``` var results = []; var walkDOM = function (node,func) { func(node); //What does this do? node = node.firstChild; while(node) { walkDOM(node,func); node = node.nextSibling; } }; ``` I understand the code except for `func(node)`. I guess the point is to pass `node` as a parameter in function `func`, but how will the browser understand it this way? `node` and `func` could be anything--so when the function is called it could read like this: ``` walkDOM(document.body,function(att) { node.getAttribute(att); results.push(node); }); ``` When `func` is passed, `walkDOM` will process function(att) {...}(document.body)--which wouldn't make any sense. So why has Crockford chosen to include func(node)?
2011/08/06
[ "https://Stackoverflow.com/questions/6969604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/858962/" ]
The `func` that's in the ``` func(node) ``` line is what is typically known as a *callback function*. It a function that is available for use by the `walkDOM` function. It might make sense with a more verbose function name: ```js var results = []; var walkDOM = function (node, iCanBeCalledOnANode) { iCanBeCalledOnANode(node); // Will be called on every DOM element node = node.firstChild; while(node) { walkDOM(node,func); node = node.nextSibling; } }; ``` Hope this clears things up for you.
Crockford's code is passing a callback to walkDOM which can be used in many ways to process the arguments passed to it. An example could be a method which returns the count of all DOM elements with the specified tagName: ``` var getTagNameCount = function(tagName) { var count = 0; walkDOM(document.body, function(node) { if (node.tagName === tagName) { count++; } }); return count; }; ```
13,158,226
I have a `textbox` which needs only accept numbers (can be decimal values) and negative values. Currently I have something like this in `KeyPress` event ``` if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') { e.Handled = true; } ``` What else I should do in order to allow negative values? Thanks
2012/10/31
[ "https://Stackoverflow.com/questions/13158226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/925222/" ]
Hook up the Validating event, like so: ``` private void myTextBox_Validating(object sender, CancelEventArgs event) { decimal d; if(!decimal.TryParse(myTextBox.Text, out d) { event.Cancel = true; //this.errorProvider1.SetError(myTextBox, "My Text Box must be a negative number."); //optional return; } if(d >= 0) { event.Cancel = true; //this.errorProvider1.SetError(myTextBox, "My Text Box must be a negative number."); //optional return; } } ```
Something like: ``` var regex = new Regex("^[-]?\d+(\.\d+)?$", RegexOptions.Compiled); Match m = regex.Match(textbox.Text + e.KeyChar); e.Handled = m.Success; ``` **Edit**: It allows any real number now
817,044
This screenshot in the [Chrome Developer Documentation](https://developer.chrome.com/devtools/docs/network#resource-network-timing) shows very detailed information on what takes how long to fulfill a HTTP request: ![enter image description here](https://i.stack.imgur.com/70ndB.png) When I look that information up on Chrome 37 I only see a summary of this information: ![enter image description here](https://i.stack.imgur.com/Vk4Fg.png) Is there any way to enabled this detailed view? Or is the screenshot from the documentation just from an older version of Chrome and the level of detail was reduced in newer versions? It would be really helpful to track down why my requests take this long before they are even sent to the server.
2014/09/26
[ "https://superuser.com/questions/817044", "https://superuser.com", "https://superuser.com/users/83407/" ]
Performance is fine for pretty much every Linux Distro. If you want to run a server, choose one of the typical server distros. Debian, Ubuntu LTS, CentOS maybe Open SUSE
Based on your requirements Debian or Fedora will probably be your best choices as these distributions will hang on to old hardware support where Arch or Ubuntu may not. Almost any popular Linux distribution can be a server and will run will be performant on old CPUs and small amounts of ram. Debian, Fedora and Arch make minimal installs quite easy while CentOS and Ubuntu aren't as easy. However some distros such as CentOS can be a preinstalled container that is minimal.
6,915,013
I have to use the wakelock (yes I shouldn't for the obvious reasons but I'm being paid to do it so I don't have a choice lol) my question is very simple: when I leave the app onPause or onStop, is the wake lock of the app automatically released ? I want to avoid the user closing his app and the wake lock is still on for some weird reason. I'm having an issue with my current system where the app is calling up the release wake lock through a message handler (because its coming from another thread) and this happens "too late" and the app crashes because it does no longer have the reference to the wake lock. I might not be very clear but the main question here is : do I have to worry about the wake lock of my app affecting the phone outside the life cycle of the app. cheers Jason
2011/08/02
[ "https://Stackoverflow.com/questions/6915013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440336/" ]
Wake lock DEFINITELY affects your device even if you application is NOT in foreground ! That's actually the whole point of acquiring wake locks So, make sure you ONLY use wake locks when you have no other option, and if you don't need wake lock when your app is in background, make sure to release wake lock in onPause() method ! This will drastically affect your device 's performance and BATTERY !
When your application is no longer the focus the wake lock is cancelled, only when your application is the focus is the wake lock in affect.
32,366,942
Using the row id to call the particular row values from two columns and display in edittext. For that I had posted the below code that I tried so far. **ActivityList.java:** ``` public class ActivityList extends Activity { SQLiteDatabase db = null; EditText editId, editCheck, editCity; ActionBar actionBar; Button search; SharedPreferences mPrefs; Cursor c1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); setContentView(R.layout.list_activity); editCheck = (EditText) findViewById(R.id.editCheck); editId = (EditText) findViewById(R.id.editId); editCity = (EditText) findViewById(R.id.editCity); search = (Button) findViewById(R.id.search); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); Boolean welcomeScreenShown = mPrefs.getBoolean("k", false); db=openOrCreateDatabase("Check", MODE_PRIVATE, null); db.execSQL("create table if not exists CheckPoint (ID INTEGER PRIMARY KEY AUTOINCREMENT,STATE VARCHAR, PLACE VARCHAR)"); if (!welcomeScreenShown) { db.execSQL("INSERT INTO CheckPoint(STATE ,PLACE) values('Eden Garden','Kolkatta');"); SharedPreferences.Editor editor = mPrefs.edit(); editor.putBoolean("k", true); editor.commit(); } c1 = db.rawQuery("select * from CheckPoint ", null); search.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (editId.getText().toString().equals("")) { show("Enter Id Number"); } else if (editId.getText().toString() != null) { if (c1.getCount() > 0) { c1.moveToFirst(); do { String cp = c1.getString(1); String cy = c1.getString(2); editCheck.setText(cp); editCity.setText(cy); } while (c1.moveToNext()); } } } }); } public void show(String str) { Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } } ``` **list\_activity.xml:** ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:id="@+id/editId" android:layout_width="108dp" android:layout_height="wrap_content" android:ems="10" /> <Button android:id="@+id/search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="50dp" android:text="Button" /> </LinearLayout> <EditText android:id="@+id/editCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:ems="10" /> <EditText android:id="@+id/editCity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:ems="10" /> </LinearLayout> ``` **Database:** [![enter image description here](https://i.stack.imgur.com/RvUQo.png)](https://i.stack.imgur.com/RvUQo.png) With the help of sqlite browser I had added the second row and third row datas and stored in my application. **Edit:** My issue is,If I search the id 2,it display the row 1 id values.I need to display the row 2 id values.By the way,If I search the row 3 id,it have to display the row 3 state and place in edittext. Anyone can help me with this.Thank You.
2015/09/03
[ "https://Stackoverflow.com/questions/32366942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3960700/" ]
I think you should use sqlquery to search the db with the id. Ex: `"select * from CheckPoint WHERE id=2"` ``` else if (editId.getText().toString() != null) { c1 = db.rawQuery("select * from CheckPoint WHERE id=" + editId.getText().toString(), null); if (c1.getCount() > 0) { if (c1.moveToFirst()) { String cp = c1.getString(1); String cy = c1.getString(2); editCheck.setText(cp); editCity.setText(cy); } } } ```
**MainActivity.java:** ``` btnSearch.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (editId.getText().toString().equals("")) { show("Enter Id Number"); } else if (editId.getText().toString() != null) { Cursor c1 = db.getData(Integer.parseInt(editId.getText().toString())); if (c1.getCount() > 0) { c1.moveToFirst(); do { String cp = c1.getString(1); String cy = c1.getString(2); editName.setText(cp); editNumber.setText(cy); } while (c1.moveToNext()); } } } }); ``` **DatabaseHandler.java:** ``` public Cursor getData(int id){ SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null ); if(res != null && res.moveToFirst()) { res.getString(res.getColumnIndex(KEY_NAME)); res.getString(res.getColumnIndex(KEY_PH_NO)); return res; } return res; } ```
51,699
I'm a beginning flute player. When I play, I often- but not always- have a "shh" sound along with it. I noticed that it usually starts out pretty quiet when I start practicing, but after I play for about an hour it gets totally out of control. And since I usually play for an hour or more in one setting, that is a major problem. I've tried changing my lip shape and tilting my flute back and forth, and I found there's a spot where it doesn't sound as bad as the other spots, but the shh sound almost never fully goes away. Anybody know how to help with this?
2016/12/30
[ "https://music.stackexchange.com/questions/51699", "https://music.stackexchange.com", "https://music.stackexchange.com/users/-1/" ]
Check out [this thread on fluteland.com](https://www.fluteland.com/board/viewtopic.php?t=6178). Notably, it's mentioned that this is a 'by-individual-musician' issue... Also, this nice gentleman is beautifully demonstrating body position, fingering, etc. on a wooden flute with no hiss: Your ultimate answer here, as you may find in other places on this SE, is: practice, practice, practice. As play becomes second nature, and your instrument becomes an extension of your body, this problem will likely solve itself. Keep it up!
Have proper posture and make sure you play the correct note.
40,492
In what ways may I monetize a website which offers free and accurate real time Bitcoin exchange and BTC market meta data? In this particular case the purpose and the business model the website was built for is a longer term proposition. In the meantime how can this website be enhanced to return at least some revenue while not substantially diminishing the intrinsic value of the content? About the content one recent user said "Wow – I went through most or all of the site, I can see you have a lot of thought into this, and a very nice informative site it is." I am brainstorming for a complete array of all possible - and legal - options. Any idea in its kernel form could be what I need "how may I get paid with this website?" - so add your answer now :)
2015/09/11
[ "https://bitcoin.stackexchange.com/questions/40492", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/29340/" ]
One way in which I have seen many such websites monetize their services is to release paid APIs. There would be people willing to pay to use your APIs (for trading, news services, Apps etc) if the data is better than the ones that are freely available. On top of this you can try the usual stuff, ads and referrals and such things on your website.
Generally, there are two sources of income available when you monetize a site; the site user pays you or, a third-party pays you. You can use either or both of them. ### The site user pays you: You must offer something of value for the site user to pay you. Subscription services or access to something of value. * You could start a newsletter with related content, (paid) offers of value and premium extension articles. Subscribe to the [Windows Secrets](https://windowssecrets.com/) newsletter for a great example of how this can work. EDIT: *Since December they no longer seem to have the free newsletter. I think this is their mistake.* * You could have a premium access section of your website, it can be independent or linked to the premium content of your newsletter or, it could be an API. * Some websites only give the current information to subscribers, everyone else gets information hourly for free. This may work for market data. ### Third-party pays you When a third-party pays you, you give them something of value. For a website this is essentially for access to your site users but may also include for access to metrics or, subscriber details. * You could install on-site advertising from one (or more than one) of many sources, you are generally paid per-click or per-view. * You could setup referral programs. You could setup an entire page dedicated to quality 'Partner Programs' and earn from the referrals. Partner program articles often make for great newsletter content, one or two depending per newsletter amongst the other articles. * You could opt-in sell (subscriber accepts third-party offers) qualified leads from your site-subscriber and/or newsletter-subscriber lists. * You could sell advertising space in your online and/or email newsletter. ### The other option You could voice for donations. This is effectively voluntary-pay-for-content. "This site cost money to operate, if you appreciate this service please consider a donation..." Or, a donation banner drive with email-out. Wikipedia and Internet Archive both use this strategy to good effect. To do any sort of email-out you need a list. People can be very creative with how they call for payment, I have seen website signup processes with a voluntary payment as a part of the web signup. Whatever you choose, I would recommend that you take the time to develop a quality regular newsletter, whether it is email or online, free, paid or, partial paid. This builds your reputation as an authority in your field and builds report with your site users.
34,111,807
Currently my code iterates through each `<li>` within a `<td>` cell and applies a class to the `<li>`. I've now added `<a>` tags in between each `<li>` and am having problems accessing the `<a>`. I essentially want to add a class to each `<a>` tag rather than the `<li>`. **HTML** ``` <td style='padding: 0;' bgcolor='#FAFAFA'> <ul class='doctorList'> <li id='1'><a style='text-decoration: none;'>Curly</a></li> <li id='2'>Larry</li> <li id='3'>Moe</li> </ul> </td> ``` **JavaScript** ``` function mapBookedAppointmentsToCalendar() { var bookedAppointmentsArray = <?php echo json_encode($mappingIdArray) ?>; var table = document.getElementById("tbl_calendar"); for (var i = 0, row; row = table.rows[i]; i++) { for (var j = 0, col; col = row.cells[j]; j++) { var li = col.querySelectorAll("li"); for (var k = 0; k < li.length; k++) { for (var a = 0; a < bookedAppointmentsArray.length; a++) { if (li[k].id == bookedAppointmentsArray[a]) { li[k].className = "colorRed booked"; break; } else { li[k].className = "colorGreen"; } } } } } } ```
2015/12/05
[ "https://Stackoverflow.com/questions/34111807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5330854/" ]
Did you try using the query selector to find those `<a>` ? ``` var li = col.querySelectorAll("#tbl_calendar li a"); for (var k = 0; k < li.length; k++) { for (var a = 0; a < bookedAppointmentsArray.length; a++) { if (li[k].id == bookedAppointmentsArray[a]) { li[k].className = "colorRed booked"; break; } else { li[k].className = "colorGreen"; } } } ```
You don't need to use `table` to access it. Just keep in mind `getElementsByClassName` method: ``` u = document.getElementsByClassName('doctorList'); for (i = 0; i < u.length; i++){ l = u[i].getElementsByTagName('li'); for (j = 0; j < l.length; j++){ l[j].className = 'red'; } } ``` Checkout this [demo](http://jsbin.com/vadusoveki)
322,057
I described someones voice as being **shrill** but I think that relates to the voice being particularly high pitched. If when someone speaks and it invokes an uneasy feeling in others, how would you describe it? The uneasy feeling isn't necessarily from what they are saying but rather the tone, pitch, repetitiveness, etc. I could generalize and say they are annoying or irritating but that isn't necessarily the case. Is there a word that is more accurate for this? **So if someone talking can be uncomfortable to listen to how would you describe their voice?** **Example use could be:** * Blimey, your voice is quite ***word here*** * Woah, be quiet for a second, when you speak you're quite ***word here***
2016/04/27
[ "https://english.stackexchange.com/questions/322057", "https://english.stackexchange.com", "https://english.stackexchange.com/users/63120/" ]
"Distressing": *causing anxiety, sorrow or pain; upsetting.* "Unsettling": *causing one to feel anxious or uneasy; disturbing.* "Agitating": *make (someone) troubled or nervous.*
***aggravating*** > > : arousing displeasure, impatience, or anger. > > > [M-W](http://www.merriam-webster.com/dictionary/aggravating) > > >
819
Хочу написать предложение со словом "завсегдатай" во множественном числе. Никак не соображу, как правильно написать. "И тогда эти посетители станут завсегдата...." ????
2012/01/16
[ "https://rus.stackexchange.com/questions/819", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/239/" ]
Завсегдатаями (полицаями, самураями и т. д.).
В случае возникновения подобных вопросов, можно обратиться к словарям, содержащим формы слов, например [к этому](http://dic.academic.ru/dic.nsf/dic_forms/18414/завсегдатай) или [к этому](http://ru.wiktionary.org/wiki/завсегдатай).