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
4,207,709
I am using Windows 7 64bit and I am trying to get my computer to detect my HTC Desire, but it's not picking it up. I have everything available installed through the Android Updater and I have got my phone running through Ubuntu, so it is definitely a problem with Windows. Does anyone know what's wrong or how to get it working or both? * I am using Windows 7 64 bit * I have a HTC Desire running Stock 2.2 (Froyo) that works with USB Debugging on my Ubuntu machine * Windows does detect that my phone is plugged in. It shows as a mass storage device. * I have all the available things installed via the Android Updater.
2010/11/17
[ "https://Stackoverflow.com/questions/4207709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348261/" ]
Had this problem on Windows 7 x64 and uninstalling in device manager then selecting manual install gave an error (something like: ensure driver is 64-bit compatible). Resolved as follows: 1. Connect phone 2. Run [USBDeview](http://www.nirsoft.net/utils/usb_devices_view.html) as Administrator 3. Sort by Serial Number 4. Select all devices with Serial Number starting HT 5. Uninstall selected devices 6. Disconnect/reconnect phone 7. Windows will try, and fail, to install device, ignore that and... 8. Install driver via Device Manager: 1. Open Device Manager (**Start**->**My Computer**, right click->**Manage**->**Device Manager**) 2. Under Other, you should see a device with a yellow warning called **ADB** or **Android Phone**; right click -> **Update driver software...** 3. Click **Browse my computer for driver software** 4. Click **Let me pick from a list of device drivers on my computer** 5. Select **Show all devices**, click **Next** 6. Click **Have disk...** 7. Browse to android sdk install directory and find the usb\_driver directory (mine is in extras\google) 8. Select **android\_winusb.inf** and click **OK** 9. Select **Android Composite ADB Interface** and click **Next** 10. When the Update Driver Warning appears click **Yes** (Props to craigcrawford1988 on <http://android.modaco.com/topic/309154-adb-device-driver-installation-failed-on-window-7-x64/>)
I had a similar problem of not being able to launch the Android app from Eclipse on real phone and not in AVD. Once I installed HTC Sync, it did the magic and I was able to use real phone. Cheers, Madhu
8,271
I wanted to carry out a two-way ANCOVA for my data. However, SPSS isn't liking that I have only one IV. I have * One IV: Group (3 levels, i.e. 2 experimental groups and a control group), * One DV: outcome measure (2 levels, i.e. time 1 and time 2), * One covariate (I have checked and this demographic continuous variable moderately correlates with the DV). Please could someone help as to whether I am missing something in terms of putting this into SPSS?
2011/03/14
[ "https://stats.stackexchange.com/questions/8271", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/-1/" ]
I am guessing that you have your data in wide format. This seems to be causing you confusion because in wide format it is less obvious that "time" is your second independent variable. One option in SPSS for doing what it sounds like you want to do: 1. `Analyze -- GLM -- Repeated Measures` 2. Enter time as repeated measures factor with two levels 3. Enter `Group` as a between subjects factor 4. Enter the dependent variable (presumably represented as two variables in SPSS as your two times points) 5. Enter your `covariate` in the covariate box For more information, see [Andy Field's SPSS Repeated Measures tutorial](http://www.statisticshell.com/repeatedmeasures.pdf). However, given that repeated measures ANOVA already controls for individual differences in some respect, you may want to think about the meaning of including a time-invariant covariate in such a model. See here for a [discussion of the issues related to covariates in repeated measures ANOVA](http://www.psyc.bbk.ac.uk/research/DNL/stats/Repeated_Measures_ANCOVA.html).
Set it up as a regular regression, they are mathematically equivalent, just make sure your non-continuous variables are defined appropriately (as categorical or whatever) to SPSS.
33,842,521
I have an ASP.NET application running on a dedicated server "Windows Server 2012 R2". The site uses SSL encryption throughout, the certificate is correctly installed on the server and shows as valid when accessed through different browsers. I now want to send emails through my application, to do this I set up an SMTP server following the instructions in this article. <http://www.vsysad.com/2014/09/setup-and-configure-smtp-server-on-windows-server-2012/> After setting up the SMTP server as specified above, I can send emails using powershell, and they are sent without issue. However, when I do the same through my application I get the following error ``` Exception Type: System.Security.Authentication.AuthenticationException Exception: The remote certificate is invalid according to the validation procedure. Stack Trace: at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception) at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result) at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Mail.SmtpConnection.Flush() at System.Net.Mail.EHelloCommand.Send(SmtpConnection conn, String domain) at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpClient.Send(MailMessage message) at EmailSender.SendMailSingleRecipient(String recipient, String subject, String message) ``` The code to send the email from my application is very simple as you can see below. ``` MailMessage mailMessage = new MailMessage(); mailMessage.From = new MailAddress("no-reply@mysite.com"); mailMessage.To.Add("myemail@email.com"); mailMessage.Subject = "subject" mailMessage.Body = "message" SmtpClient smtpClient = new SmtpClient("localhost", 25); smtpClient.Send(mailMessage); ``` I have seen the same issue reported many times, but no answer which solves the issue for me. Could someone explain the reason behind this error and possible causes/solutions.
2015/11/21
[ "https://Stackoverflow.com/questions/33842521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321152/" ]
I managed to find a solution to my original question. Instead of sending directly from my application, I set up my SMTP server to use a pickup directory instead. The application code is very simple now, specifying the delivery method and pickup directory can also be moved into the configuration file. ``` SmtpClient client = new SmtpClient("localhost", 25); client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; client.PickupDirectoryLocation = @"C:\inetpub\mailroot\Pickup"; client.Send(mail); ``` Another advantage with this approach is that the generation of emails from the application can be tested without setting up SMTP on a development machine. By looking in the pickup directory you can determine if the application is working correctly. Using this approach on my live server, I receive the email almost as soon as I send it from my application so the performance is very good.
this may be the reson SMTP service on the server is not using the same certificate as https. The [diagnostic steps I had read here](http://blogs.msdn.com/b/jpsanders/archive/2009/09/16/troubleshooting-asp-net-the-remote-certificate-is-invalid-according-to-the-validation-procedure.aspx?Redirected=true)
1,718,412
I have a small question: how do I find out what type a C++ pointer is? I often use a small function in my console programs to gather input, which looks something like this: ``` void query(string what-to-ask, [insert datatype here] * input) ``` I would like to create a generic form, using a void pointer, but I can't cin a void pointer, so how to I find out it's type so I can cast it?
2009/11/11
[ "https://Stackoverflow.com/questions/1718412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144734/" ]
If you control the datatype yourself, I would probably make a class/struct that contains an enum of all of the data types you care about and pass that. You could then query the passed in pointer for it's datatype, and then cast appropriately. IE ( pseudo code warning - treating this as a struct for now. ) ``` class MyDataType { enum aDataType type; void * myData; } void query( string whatToAsk, MyDataType * pdata) { switch ( pdata.type) { case integer: int * workInt = (int * ) pdata; do whatever you want to to get the data break; case someFunkyObject: someFunkyObject pob = (SomeFunkyObject *) pdata; Do whatever you want with the data. etc. } } ```
If I understand what you're asking then the usual way to do this is to create an interface class that supports `query(string what-to-ask)` and then instead of using a void pointer just pass a pointer to the interface. Then you can call query() on that instance.
1,088,793
What is a culture-invariant way of constructing a string such that the Javascript Date() constructor can parse it and create the proper date object? I have tried these format strings which don't work (using C# to generate the strings): ``` clientDate.ToString(); // gives: "11/05/2009 17:35:23 +00:00" clientDate.ToString("MMM' 'dd', 'yyyy' 'h':'mm':'ss' 'tt"); // works on an English server // but on a French server, gives: "mai 11, 2009 5:35:23" // Javascript won't parse that. clientDate.ToString("MM'-'dd'-'yyyy' 'HH':'mm':'ss") // gives: 05-11-2009 17:35:23 ``` What is the universal format??
2009/07/06
[ "https://Stackoverflow.com/questions/1088793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111934/" ]
[According to MDC](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/parse): > > Given a string representing a time, `parse` returns the time value. It accepts the IETF standard ([RFC 1123](https://www.rfc-editor.org/rfc/rfc1123) Section 5.2.14 and elsewhere) date syntax: `"Mon, 25 Dec 1995 13:30:00 GMT"`. It understands the continental US time-zone abbreviations, but for general use, use a time-zone offset, for example, `"Mon, 25 Dec 1995 13:30:00 GMT+0430"` (4 hours, 30 minutes east of the Greenwich meridian). If you do not specify a time zone, the local time zone is assumed. GMT and UTC are considered equivalent. > > > If you can’t generate this format using english locale, try to use [Date.UTC](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/UTC)
If you want a locale-independent format Javascript can parse, you can use `2013-03-31T16:36:57+0900`. It works at least in Node.js and Chrome, so I suspect it's standard.
140
What properties should I look for in a good wire for building a wire antenna? Could anyone recommend something specific for me?
2013/10/22
[ "https://ham.stackexchange.com/questions/140", "https://ham.stackexchange.com", "https://ham.stackexchange.com/users/106/" ]
Because of the skin effect, which causes most of the electric current to be concentrated around the outer surface of the wire at high frequencies, larger gauge wire is needed for RF than for an equivalent DC current. As a general rule of thumb, 16 gauge is sufficient up to 100 watts, but 12 would be ideal. Any system exceeding 100 watts really needs to have the actual current and skin effect calculated, and that is dependent on frequency and also somewhat on antenna type. Since most antennas are used outdoors, you must use outdoor-rated wire. You can use uninsulated wire, but it is much better to use insulated wire for safety purposes if there is any chance that someone could come in contact with the wire while you are transmitting. If you are using insulated wire, make sure the insulation code (which is printed along the wire) has a "W" in it - it stands for water-resistant. Some examples are XHH **W**, SOO **W**, or TH **W** N. Stranded copper or copper clad aluminum are the most common - copper clad aluminum is somewhat stronger and has the more conductive copper on the outside, where the current is concentrated. Stranded wire is ideal for flexibility and ease of soldering and crimping.
Be sure that the wire that you use is acceptable legally as well as physically. In any place were the National Electric Code (NEC), that is used in much of the United States, is enforced as law the minimum size of wire that can be used for an amateur radio transmitting antenna is number fourteen American Wire Gauge (14AWG). For people in other parts of the world that is equivalent to 1.63mm diameter or 2.08 square mm. If you use a smaller gauge in such an area subject to that code than any harm that might result from the antenna failing and falling into contact with people or things is entirely on you. For the sake of those who may be able to make direct use of the information the applicable section of the NEC is > > ARTICLE 810 Radio and Television Equipment > > > III. Amateur Transmitting and Receiving Stations — Antenna Systems > > > 810.52 Size of Antenna. > > Antenna conductors for transmitting and receiving stations shall be of a size not less than given in Table 810.52. > > > The table requires 14 gauge for lengths up to 150 feet with larger gauges for longer lengths dependent on the type of wire used. The important thing to know is that fourteen gauge is the smallest size of wire permitted for a amateur radio antenna and that there are no exceptions to permit a smaller gauge for any reason in areas were the NEC is enforced as law.
13,326,877
I have very simple code that includes ImageButton with OnClickListener that points to another Activity, the click on the ImageButton doesn't fire the onClick (The same problem was with Button) : ``` public class ToolsActivity extends Activity { private ImageButton btnCamera; final Context context = ToolsActivity.this; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tools); this.btnCamera = (ImageButton) findViewById(R.id.cameraButton); this.btnCamera.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(context,MainActivity.class); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_tools, menu); return true; } ``` XML: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="16dp" android:paddingRight="16dp" > <ImageButton android:id="@+id/cameraButton" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:background="@drawable/btncamera" android:contentDescription="@string/desc" /> ```
2012/11/10
[ "https://Stackoverflow.com/questions/13326877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315264/" ]
I can't see anything wrong with the code. If it works with a regular button my guess is that you maybe have to set `android:clickable="true"` in the xml (you can also do it in code).
I opened new Android project and copy paste may code, and it works, I guess something with the project was damaged.
24,792,301
I'm trying to use [this](http://iphone2020.wordpress.com/2012/10/01/uitableview-tricks-part-2-infinite-scrolling/) method to implement an infinitely scrolling `UITableView` The core logic of the solution is: 1. To increase the tableview content by a factor of 3, so that we make the 3 copies of the content laid one after another vertically. 2. Whenever the top end of the scroll is reached, move the the scroll offset back to start of the 2nd copy 3. When the bottom end of the scroll is reached, we move the scroll offset back to the start of the 2nd copy minus the height of the tableview, so that we end up showing the same content as we are now. This means that a single cell insert or delete actually results in three inserts or deletes. Because my table's datasource is populated by an `NSFetchedResultsController` it causes an Assertion Failure. > > The number of rows contained in an existing section after the update (12) must be equal to the number of rows contained in that section before the update (15), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). > > > Is there some way to stop the program from crashing in these cases? I'd really appreciate any help/pointers. Thanks.
2014/07/16
[ "https://Stackoverflow.com/questions/24792301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3846979/" ]
Another possible workaround is to create a simple `DataTransfromer` and attach it to the required field. Example: ``` <?php namespace Interprac\Bundle\UtilityBundle\Form\DataTransformer; use Symfony\Component\Form\DataTransformerInterface; class NullToEmptyTransformer implements DataTransformerInterface { /** * Does not transform anything * * @param string|null $value * @return string */ public function transform($value) { return $value; } /** * Transforms a null to an empty string. * * @param string $value * @return string */ public function reverseTransform($value) { if (is_null($value)) { return ''; } return $value; } } ``` Attach the transformer to a single field: ``` $nameSuffix = $builder->create('name_suffix', 'choice', array( 'label' => 'Name Suffix', 'choices' => PR::getSMSFSuffixes(), ))->addModelTransformer(new NullToEmptyTransformer()); $builder->add($nameSuffix); ```
1. Do not use empty\_data option. 2. And use the placeholder attribute. 3. Ex: ``` array( 'label' => 'textExample', 'required' => false, 'disabled' => false, 'read_only' => true, 'attr' => array('placeholder' => 'DefaultValue') ) ```
3,114,696
I have multiple user types in a system that shows each user different views and templates of the stored information, often based on whether they are logged in and what current\_user.user\_type is. As a result, I have lots of this: ``` #controller @project = Project.find(params[:id]) if current_user.user_type == "Company" redirect_to :controller => "companies", :action => "home" elsif current_user.user_type == "Contractor" @contractor = Contractor.find(current_user.user_type_id) redirect_to :controller => "contractors", :action => "home" elsif current_user.user_type == "Customer" redirect_to :controller => "companies", :action => "list" end ``` This is my first Rails project and I am pretty sure this is poor design. What are simple clean ways of doing this in a better way?
2010/06/24
[ "https://Stackoverflow.com/questions/3114696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341583/" ]
If you're having **a lot** of code like this, is a code smell that your controller is really serving multiple purposes. Assuming your controller is something like InfoController, which is a REST view for some Info model, ask yourself: * What is the central piece of your actions, the data or the user who access it? * Are you taking decisions based on who requests the actions? (Like saving, deleting, etc) * Can these decisions be taken in the Info model, rather than in the controller? To me, seems like you should create different controllers for each model, and make just one redirect per action. In your views, you can use things like [polymorphic\_paths](http://apidock.com/rails/ActionController/PolymorphicRoutes/polymorphic_url) to link up to your controllers. If you decide not to do this, I'd just put that code in a `case` statement instead of an `if`.
Can also use constraints as seen here: [User-centric Routing in Rails 3](http://collectiveidea.com/blog/archives/2011/05/31/user-centric-routing-in-rails-3/) ``` root :to => "companies#home", :constraints => UserTypeConstraint.new("Company") ``` Or scoped routes as seen here: [Use lambdas for Rails 3 Route Constraints](http://intridea.com/posts/use-lambdas-for-rails3-route-constraints) ``` scope :constraints => lambda{|req| !req.session[:company_user_id].blank? } do # all company routes end ```
11,448,307
I'm having a bit of a problem trying to import data from a CSV and have a couple of questions on it that I haven't managed to solve myself yet. First off here's my code to help put things in perspective (tidied it up a bit, removing CSS and DB connection): ``` <body> <div id="container"> <div id="form"> <?php $deleterecords = "TRUNCATE TABLE tablename"; //empty the table of its current records mysql_query($deleterecords); //Upload File if (isset($_POST['submit'])) { if (is_uploaded_file($_FILES['filename']['tmp_name'])) { echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>"; echo "<h2>Displaying contents:</h2>"; readfile($_FILES['filename']['tmp_name']); } //Import uploaded file to Database $handle = fopen($_FILES['filename']['tmp_name'], "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $import="INSERT into importing(text,number)values('$data[0]','$data[1]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); print "Import done"; //view upload form } else { print "Upload new csv by browsing to file and clicking on Upload<br />\n"; print "<form enctype='multipart/form-data' action='upload.php' method='post'>"; print "File name to import:<br />\n"; print "<input size='50' type='file' name='filename'><br />\n"; print "<input type='submit' name='submit' value='Upload'></form>"; } ?> </div> </div> </body> ``` It's basically an adaptation of an example I have found after many many attempts at various methods. My CSV has two columns of data, the first one being text and the second is integers The table in the database also has two columns, the first called "text" and the second "number" So the questions I have are: 1. the text being uploaded is just being displayed as 0 in every field and i'm not sure why 2. I keep reading about data ending up enclosed in "", if that happens how would I sort it? 3. how can I ignore the first X lines of the CSV for headers etc? 4. is the data format changed throughout this process or is it ready for me to use in a graph? e.g. would a decimal stay a decimal once placed in the database? I think that covers everything, thanks in advance for any help! EDIT: Just done a test of 10,000 record uploading and got the error: "Fatal error: Maximum execution time of 30 seconds exceeded" any thoughts?
2012/07/12
[ "https://Stackoverflow.com/questions/11448307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1520179/" ]
``` set_time_limit(10000); $con = mysql_connect('127.0.0.1','root','password'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("db", $con); $fp = fopen("file.csv", "r"); while( !feof($fp) ) { if( !$line = fgetcsv($fp, 1000, ';', '"')) { continue; } $importSQL = "INSERT INTO table_name VALUES('".$line[0]."','".$line[1]."','".$line[2]."')"; mysql_query($importSQL) or die(mysql_error()); } fclose($fp); mysql_close($con); ```
i think the main things to remember about parsing csv is that it follows some simple rules: a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns [have a read of this post](http://php-addict.com/upload-import-csv-mysql-database-php/) to see what i am talking about it's actually very easy to do once you have the hang of it and becomes very useful.
21,379,444
I'm looking for a data structure that behaves like this: 1. Last in, first out 2. Upon iteration the first item is the item that was last in (LCFS - last come, first served) 3. When max capacity is reached, the 'oldest' item(s) need(s) to be dropped It sounds like a `Queue` would do the trick, but that structure is FIFO. Sounds like I need a LIFO-like queue. Any ideas what I should use?
2014/01/27
[ "https://Stackoverflow.com/questions/21379444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/201482/" ]
.Net has a LIFO "queue" structure called [`Stack<T>`](http://msdn.microsoft.com/en-us/library/3278tedw%28v=vs.110%29.aspx), although this does not fulfill your third constraint (e.g. size constrained). It wouldn't be too difficult to achieve this by means of containment. However... if you want to throw away the oldest items in your stack, it might be better to use a circular buffer. This might be implemented as follows: ``` class OverflowingStack<T> { private T[] items; private int currentIndex; private int count; public OverflowingStack(int size) { this.items = new T[size]; this.currentIndex = 0; this.count = 0; } public void Push(T item) { items[currentIndex] = item; currentIndex++; currentIndex %= items.Length; count++; count = count > items.Length ? items.Length : count; } public T Pop() { if (count == 0) throw new Exception("stack is empty"); currentIndex--; while (currentIndex < 0) {currentIndex += items.Length;} count--; return items[currentIndex]; } } ``` I'll leave the additional interface implementations to you, but you get the idea.
I would recommend to use the `Stack` class [MSDN Stack Class](http://msdn.microsoft.com/de-de/library/system.collections.stack%28v=vs.110%29.aspx)
747,303
I'm trying to use `parallel` and `ack` together to do some searching in parallel. However, `ack` seems to insist on using `stdin` if it finds itself in a pipe, even if you give it files to search: ``` $ echo hello > test.txt $ ack hello test.txt hello $ echo test.txt | xargs ack hello hello $ echo test.txt | parallel ack hello {} # ack thinks it should be searching stdin: $ echo test.txt | parallel ack -f {} - # even though parallel is indeed passing test.txt: $ echo test.txt | parallel --dry-run ack hello {} ack hello test.txt ``` What do I need to do to get `ack` and `parallel` to play nicely?
2014/04/28
[ "https://superuser.com/questions/747303", "https://superuser.com", "https://superuser.com/users/70130/" ]
This happens on the current dev branch as well (`9cc2407`). The reason for this is that when standard input is a pipe, ack tries to be helpful and assumes you're trying to search that input stream. We've not seen this behavior before, so I've brought it up on the ack developers mailing list. In the meantime, you can use `--nofilter` to override ack's default behavior.
The problem is due to this line in `ack`: ``` $is_filter_mode = -p STDIN; ``` So these two situations are treated differently in `ack`: ``` cat file | ack ... ack < file ... ``` The workaround for you seem to be to add a `cat`: ``` echo test.txt | parallel cat {} \| ack hello ``` This works in `ack` 2.12.
1,971,246
I recently wrote a piece of code that looked a bit like this: ``` IEnumerable<DTO.Employee> xEmployee = from e in xDoc.Descendants("Employee") where int.Parse(e.Attribute("Id").Value) == emp.Id select new DTO.Employee { Id = (int)e.Attribute("Id"), LastName = (string)e.Element("LastName"), FirstName = (string)e.Element("FirstName"), Email = (string)e.Element("Email") }; ``` However, I am confused about the casting to an int in the where clause. First, I'd written something like ``` where (int)(e.Attribute("Id").Value) == emp.Id ``` which didn't compile. Why can I do a explicit cast on (e.Attribute("Id")), but can 't I do this on (e.Attribute("Id").Value)?
2009/12/28
[ "https://Stackoverflow.com/questions/1971246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/237462/" ]
Check out the explicit operator overloads of the [XAttribute](http://msdn.microsoft.com/en-us/library/system.xml.linq.xattribute.op_explicit.aspx) class. ``` public static explicit operator int(XAttribute attribute); ```
There is an [explicit conversion from `XAttribute` to `int`](http://msdn.microsoft.com/en-us/library/bb358993.aspx) - but there's no explicit conversion from `string` (the type of `XAttribute.Value`) to `int`.
12,639,914
I am using javascript method window.open to get the reference to the other windows of mine service. The main idea is that if I use window.open('', name ) and window with given name exsists then I get the reference to it (and if it is from same domain I can comunicate with it). If it does not the new window has url 'about:blank'. So if it is about:blank I am closing it. That works on every browser except Opera... When I am calling window.open with empty string as first argument on every browser if the window with this name exsits I will get refenrence to it and nothing more. But not on Opera - there the URL of this window will be changed to about:blank. Are there any way to workaround this on Opera?
2012/09/28
[ "https://Stackoverflow.com/questions/12639914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507549/" ]
``` string uri = "file:\\C:\Users\...\...\App_Code\ClassDiagram.cd"; string localPath = new Uri(uri).LocalPath; ``` OR ``` @'C:\Users\...\...\App_Code\ClassDiagram.cd' ``` OR ``` 'C:\\Users\\...\\...\\App_Code\\ClassDiagram.cd' ``` uper three way to solution of you problem
Please see my full answer to a related post on stackoverflow for more details [here](https://stackoverflow.com/questions/18391113/cannot-load-classdiagram-cd-on-visual-studio-uri-formats-are-not-supported/28463971#28463971). Under "WEBSITE", select "Use Visual Studio Development Server..." and then try right clicking on your solution (or App\_Code worked for me too) and select "View Class Diagram" again.
6,390,297
I have downloaded a javascript script and one of the first line is : ``` qq = qq || {}; ``` What does it mean?
2011/06/17
[ "https://Stackoverflow.com/questions/6390297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
It checks `qq` for a pre-existing [truthy value](http://11heavens.com/falsy-and-truthy-in-javascript) or else (`||`) sets it as an empty object (`{}`). In essence, it's purpose is to quickly ensure that any further references to qq will not be undefined, so you can check for properties of the object without your script breaking due to the fact that the variable isn't even a valid object in the first place.
Explanation: ``` qq = qq || {}; // ^^ is equal to iself, but if it does not exist, // then it is equal to an empty object ``` For example: ``` for(var i = 0; i < 5; i++){ qq = qq || {}; qq[i] = 'something!'; } ``` Fiddle: <http://jsfiddle.net/maniator/dr5Ra/>
13,799,533
**FINAL EDIT - ANSWER** : Thanks for your help everyone. In the end it came down to some htaccess problems in changing the url names and for some odd reason, even when referencing the root (./ajax) it didn't like it. I don't know why still, but it just didn't. When I hard-coded the whole URL in, it worked. Ridiculous - thanks for your help everyone. Everyday is a school day.... I can not figure out for the life of me why this is erroring - can someone please cast a second pair of eyes over this - it's probably something really stupid, thanks in advance for the help: **EDIT** Stupidly I was putting the wrong URL in - HOWEVER... Now I have put the correct URL in, the site just hangs and crashes. Any ideas please? **EDIT 2** Just to add even more detail to this post, the "LOADING..." div appears, so the ajax definitely starts, and then the page crashes and becomes unresponsive. I have added extra validation to ensure that the PHP file exists. It does. The PHP file is simply echoing out a h1 tag. This is a complete enigma as I was doing a similar ajax request on a home server yesterday and it worked fine. **EDIT 3** Thank you for everyone's input and help on this so far. Upon further testing, I have removed the data property from the JQuery AJAX request and it STILL becomes completely unresponsive and crashes. Could this be server related? I'm really running out of ideas... HTML: ``` <input id="pc" class="sfc" name="ProdCat[]" type="checkbox" value=""> <input id="psc" class="sfc" name="ProdSubCat[]" type="checkbox" value=""> <input id="bf" class="sfc" name="BrandFil[]" type="checkbox" value=""> ``` JQuery: ``` $('input[type="checkbox"]').change(function(){ var name = $(this).attr("name"); var ProdCatFil = []; var ProdSubCatFil = []; var BrandFil = []; // Loop through the checked checkboxes in the same group // and add their values to an array $('input[type="checkbox"]:checked').each(function(){ switch(name) { case 'ProdCatFil[]': ProdCatFil.push($(this).val()); break; case 'ProdSubCatFil[]': ProdSubCatFil.push($(this).val()); break; case 'BrandFil[]': BrandFil.push($(this).val()); break; } }); $("#loading").ajaxStart(function(){ $(this).show(); $('.content_area').hide(); }); $("#loading").ajaxStop(function(){ $(this).hide(); $('.content_area').show(); }); $.ajax({ type: "GET", url: '../ajax/ajax.php', data: 'ProdCatFil='+ProdCatFil+'&ProdSubCatFil='+ProdSubCatFil+'&BrandFil='+BrandFil, success: function(data) { $('.content_area').html(data); } }).error(function (event, jqXHR, ajaxSettings, thrownError) { $('.content_area').html("<h2>Could not retrieve data</h2>"); //alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])'); }); }); ``` PHP (just to prove it's working): ``` echo '<h1>TEST TEST TEST </h1>'; ```
2012/12/10
[ "https://Stackoverflow.com/questions/13799533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312839/" ]
From the commments: To be specific, the problem is that Java's open file operation triggers the OS operation that runs the virus scan, and the solution is to add Java to the list of trusted processes
The problem you have is mostly caused by JNI you are using. As your code wait during constructor for FileInputSream(String). That veryfie the existance of passed path and call a method `private native void open(String)`. Then openJDK implementation of [FileInputSream#open(String)](http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/0a5b87833562/src/share/native/java/io/FileInputStream.c) look like: ``` JNIEXPORT void JNICALL Java_java_io_FileInputStream_open(JNIEnv *env, jobject this, jstring path) { fileOpen(env, this, path, fis_fd, O_RDONLY); } ``` This move us to [io\_util\_md.c](http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/1ad7fbef48d0/src/windows/native/java/io/io_util_md.c) and method `jlong winFileHandleOpen(JNIEnv *env, jstring path, int flags)` You can analyse the code there. --- At this point you have various options. * Check the different JDK * Write a C code, to creaete onw JNI method. * Check the differnet file system.
665,903
I need to create a new db in **SQL Server**, and move some data from an **Oracle** db to this SQLServer db; I read that this function can be implemented by using **SSIS** or the **SQL Server Migration Assistant for Oracle**; I wonder if someone can point me to a tutorial or a document where I can see how this task is performed step by step The data moved from the **Oracle** db is updated on a day basis, so the data moved has to be updated regularly.
2009/03/20
[ "https://Stackoverflow.com/questions/665903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Have you looked at the [SQL Server Migration Assistant for Oracle](http://www.microsoft.com/sqlserver/2005/en/us/migration-oracle.aspx)? [Step by step document on how to use it](http://download.microsoft.com/download/e/c/8/ec8d5025-7ef7-4dcc-a9f3-9c297cf5350e/SSMAOracle.docx).
How about this: <http://aspalliance.com/947_building_a_sql_server_2005_integration_services_package_using_visual_studio_2005> and this: <http://msdn.microsoft.com/en-us/library/ms169917.aspx>
590,968
I have vdi with quite a number of snapshots taken from it - say, 50 or 70 snapshots. I want to have one plain vdi with a current state. These snapshots take way too much disk space and are not needed as snapshots. I know that if I call ``` VBoxManage clonehd thedisk.vdi thedisk-full.vdi (50-70 times) VBoxManage clonehd {uuid-of-snapshot}.vdi thedisk-full.vdi --existing ``` I will get what I want. But it takes very very long time (more than 5 hours given my hardware and 16G initial disk size). And, of course, I tried `VBoxManage snapshot delete` and it is strange: doesn't work on stopped machine, can fail on running machine and when it fails once, it will fail all subsequent calls. Is there a way to make plain vdi from a number of snapshots - quicker? ``` $ VBoxManage --version 3.2.14r75509 ``` (asked it on [ServerFault](https://serverfault.com/questions/504676) but decided this place is more appropriate for this question)
2013/05/03
[ "https://superuser.com/questions/590968", "https://superuser.com", "https://superuser.com/users/129273/" ]
Found the solution. It is as simple as the last step from the commands I wrote here. I.e. ``` VBoxManage clonehd fullpath/{uuid-of-last-snapshot}.vdi thedisk-full.vdi ``` So I should clonehd only the last snapshot, not every snapshot from the chain. And it is thousands percent faster. The uuid can be found from `VBoxManage list hdds | grep VmName | tail` In the GUI (on Windows), select the VM, select *Snapshots* from the top right, right click on the snapshot you want, select *Clone...*, and select *Full Clone* in the dialog.
You can try to [export](http://www.virtualbox.org/manual/ch08.html#vboxmanage-export) to [OVF](https://en.wikipedia.org/wiki/Open_Virtualization_Format) and then [import](http://www.virtualbox.org/manual/ch08.html#vboxmanage-import) back the generated file. As explained [here](http://www.virtualbox.org/manual/ch01.html#ovf): > > OVF cannot describe snapshots that were taken for a virtual machine. As a result, when you export a virtual machine that has snapshots, only the current state of the machine will be exported, and the disk images in the export will have a "flattened" state identical to the current state of the virtual machine. > > > As result you will have a cloned VM with the current state without other snapshots.
37,945,958
Working with Spark dataframes imported from Hive, sometimes I end up with several columns that I don't need. Supposing that I don't want to filter them with ``` df = SqlContext.sql('select cols from mytable') ``` and I'm importing the entire table with ``` df = SqlContext.table(mytable) ``` does a `select` and subsequent `cache` improves performance/decrease memory usage, like ``` df = df.select('col_1', 'col_2', 'col_3') df.cache() df.count() ``` or is just waste of time? I will do lots of operations and data manipulations on `df`, like `avg`, `withColumn`, etc.
2016/06/21
[ "https://Stackoverflow.com/questions/37945958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307283/" ]
Try getting the information from the input fields with .val() and store it in arrays for AJAX querys or another process operations: JS example: ``` var key = []; var value = []; $("input").filter('.form1').each(function(){ key.push($(this).attr('id');); value.push($(this).val()); }); ``` You can also store the information in one array and split the key and the value like CVS with a semicolon.
Try this: ``` $('<div>').append($('#formId').clone()).html(); ``` I found it [here](https://stackoverflow.com/questions/652763/how-do-you-convert-a-jquery-object-into-a-string). **[Example](https://jsfiddle.net/myrluk3/ns9u6krz/1/)**.
56,684,215
In my application, I need to secure controller access with Spring Security In particular, I would like to allow / disallow the access to all controller methods to users based on grants. Here is an example of Controller: ``` @Controller @RequestMapping("${path.myapp}" + "/accounts") public class AccountsController extends AbstractCrudController<AccountsBean, Long> { ... } ``` In my application, each user has a list of functionalities (defined in a DB table that associates USER->FUNCTIONALITY). User has also a Role, but users with same roles could have the capability to use different functionalities. When application starts and user do login, I read all functionalities linked to user and I show/hide menu items properly. Here a bunch of the jsp: ``` <sec:authorize access="hasAnyRole('Anagrafica -> Accounts')" > <li id="accounts"><a href="${anagraficaPath}/accounts/index.html"><fmt:message key="menu.anagrafica.accounts"/></a></li> <li class="divider"></li> </sec:authorize> ``` How could I secure this Controller, to deny users that does not have the 'Anagrafica -> Accounts' functionality?
2019/06/20
[ "https://Stackoverflow.com/questions/56684215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1537580/" ]
you can use `Stream.from(from: Int, step: Int)` : ``` def generate(): Stream[Int] = { Stream.from(1, 2) } println(generate().take(10).toList) // this will print List(1, 3, 5, 7, 9, 11, 13, 15, 17, 19) ```
As you asked in a comment how to do this with Scala's `2.13` [`Stream.unfold`](https://www.scala-lang.org/files/archive/api/2.13.x/scala/collection/immutable/Stream$.html#unfold[A,S](init:S)(f:S=%3EOption[(A,S)]):CC[A]): ``` Stream.unfold(-1)(i => Some(i+2, i+2)) // immutable.Stream[Int] = Stream(1, <not computed>) ``` and to have a glance at what it actually does: ``` Stream.unfold(-1)(i => Some(i+2, i+2)).take(10).toList // List[Int] = List(1, 3, 5, 7, 9, 11, 13, 15, 17, 19) ``` Though I would recommend using [@nader.h solution](https://stackoverflow.com/a/56684331/9297144) Since we generate an infinite stream, the building function will only always return `Some` (`None` would mean stopping the iteration). The unfolding function, takes an initial state (here `-1`) and keeps updating this state (right part of the optional tuple (`i+2`)) while providing at each iteration the current state (left part of the optional tuple (in this case also `i+2`)) In other words, this starts with an initial state `-1`, and then, for each iteration, you add an element based on the current state (for the first iteration the state is `-1` and you produce `-1 + 2` - left part of the optional tuple) and you also modify the state for the next iteration (for the first iteration the state is `-1` and you produce `-1 + 2` as a new state - right part of the optional tuple).
26,811,101
I'll caveat this with the fact that I am not a Javascript expert. Not even close. That said, I'm using a [Javascript Polyfill](https://github.com/chuckcarpenter/REM-unit-polyfill/) to allow me to use rem units for text size on a web page and maintain IE8 compatibility: <http://www.joannecorryhair.co.uk/> The script is referenced on line 24: ``` <!--[if lt IE 9]> <script src="scripts/html5shiv.js"></script> <link rel="stylesheet" type="text/css" href="css/0.css" /> <link rel="stylesheet" type="text/css" href="css/600.css" /> <link rel="stylesheet" type="text/css" href="css/740.css" /> <script src="scripts/rem.js" type="text/javascript"></script> <![endif]--> ``` In IE8 only (even if I put this outside of the conditional meta tags), the console throws the following error and this script doesn't work (font spacing is all messed up): > > Origin <http://joannecorryhair.co.uk> not found in Access-Control-Allow-Origin header. > > > This works perfectly locally. I suspect this is something on the server config, as this is a very popular polyfill. Any help will be much appreciated. Thanks
2014/11/07
[ "https://Stackoverflow.com/questions/26811101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1824285/" ]
Note that Vagrant itself, in [the Vagrant::Util::Platform class](https://github.com/mitchellh/vagrant/blob/master/lib/vagrant/util/platform.rb) already implements a more advanced version of the platform checking logic in [the answer](https://stackoverflow.com/a/26889312) by [BernardoSilva](https://stackoverflow.com/users/1150700/bernardosilva). So in a Vagrantfile, you can simply use the following: ``` if Vagrant::Util::Platform.windows? then myHomeDir = ENV["USERPROFILE"] else myHomeDir = "~" end ```
When I read the original question according to me it is not how to find out on which OS vagrant it self runs, but which OS do the virtual machines to be provisioned have. That is why you want to run a different provision script depending on the diffent OSses of the new VMs, eg: "/vagrant/provisioning/only\_run\_this\_on\_${OS\_OF\_NEW\_VM}.sh". Unfortunately Vagrant does not have this capability (yet), so this is my solution: I define my VMs on top of my vagrant file: ``` cluster = { "control.ansible.RHEL76" => { :ip => "192.168.1.31", :type => 0, :cpus => 1, :mem => 1024, :box_image => "centos/7" }, "app01.ansible.RHEL76" => { :ip => "192.168.1.32", :type => 1, :cpus => 1, :mem => 1024, :box_image => "centos/7" }, "app02.ansible.RHEL76" => { :ip => "192.168.1.33", :type => 1, :cpus => 1, :mem => 1024, :box_image => "centos/7" }, "winserver" => { :ip => "192.168.1.34", :type => 2, :cpus => 1, :mem => 1024, :box_image => "mwrock/Windows2016" }, } ``` Then these conditions in my code can provision different ways depending on the OS of the VM's: ``` if "#{info[:box_image]}" == "mwrock/Windows2016" then puts "is_windows_host: #{info[:box_image]}" config.vm.provision : shell, inline => "/vagrant/provisioning/only_run_this_on_windows.psl" end if "#{info[:box_image]}" == "centos/7" then puts "is_linux_host: #{info[:box_image]}" config.vm.provision : shell, inline => "/vagrant/provisioning/only_run_this_on_linux.sh" end ``` By the way, only the ansible controller should have ansible installed, because in real life (yes the office) I do not use vagrant but an ansible controller, which I also want in my lab (OK Virtual Box on both my Windows 10 desktop as well as my Ubuntu laptop). I use a condition to test "type = 0" (which I use for a ansible "controller"). Only the ansible controller starts ansible\_local to provision the cluster of VMs with ansible. ``` if info[:type] == 0 then cfg.vm.provision "shell", inline: "if [ `which ansible` ] ; then echo \"ansible available\"; else sudo yum -y update; sudo yum -y install epel-release; sudo yum -y install ansible; fi" cfg.vm.provision "ansible_local" do |ansible| ansible.extra_vars = { ansible_ssh_user: 'vagrant' } ansible.inventory_path = "./production" ansible.playbook = "rhelhosts.yml" ansible.limit = "local" end # ansible_local ``` This is displayed during a vagrant provision: PS D:\Documents\vagrant\top> vagrant provision control.top.RHEL76 is\_linux\_host: centos/7 is\_linux\_host: centos/7 is\_linux\_host: centos/7 is\_windows\_host: mwrock/Windows2016 This is displayed during a vagrant provision: `PS D:\Documents\vagrant\ansible> vagrant provision control.ansible.RHEL76` `is_linux_host: centos/7` `is_linux_host: centos/7` `is_linux_host: centos/7` `is_windows_host: mwrock/Windows2016` `--- many more lines, not relevant ---` Have fun experimenting and deploying your multimachine / multi OS labs!
6,126,433
> > **Possible Duplicate:** > > [How can one close html tags in vim quickly](https://stackoverflow.com/questions/130734/how-can-one-close-html-tags-in-vim-quickly) > > > One of my favorite features of TextMate is the ability to type out a tag, say `<div>`, and press `⌥`+`⌘`+`.`, it will automatically insert the corresponding end tag, `</div>`. How can I do this in vim?
2011/05/25
[ "https://Stackoverflow.com/questions/6126433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
I use the [`xmledit`](http://www.vim.org/scripts/script.php?script_id=301) plugin for this. > > ...When in insert mode and you finish a tag (pressing '>') the > tag will be completed. If you press '>' twice it will complete the tag and > place the cursor in the middle of the tags on it's own line. > > >
I've not used TextMate so I'm not sure if this is quite the same thing but there is a vim plugin called snipmate that may help you out. <http://www.vim.org/scripts/script.php?script_id=2540>
38,640,339
For classic UI there is a option to set `defaultValue` for fields, this is shown to user when user first time opens the dialog after dragging the component. If user clears the value in dialog and saves, on editing the dialog, value of field is not shown again. For touch UI dialog, couldn't find the equivalent of `defaultValue`. There are following options 1. `emptyText` - But this is kind of placeholder text. If user wants to save form without entering value, this is not useful. 2. `value` - This shows the value when first time component is opened for authoring. But if user clears the value and saves. From the JCR structure the value is removed. But if user opens the dialog for editing, the value is again shown in the field, while this should be empty. If there a equivalent of `defaultValue` in touch UI dialog or any other way of handling this (may be listeners or something else)
2016/07/28
[ "https://Stackoverflow.com/questions/38640339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4920566/" ]
I'm planning to set a `select` field in the `design dialog` with `dropdown` for default values and then work with it in the cq-dialog with `value="${cqDesign.type}"`
Since `numberfield` is also mentioned in this discussion. I have got `value` working instead of `defaultValue` in granite UI. ``` <numberOfResults jcr:primaryType="nt:unstructured" sling:resourceType="granite/ui/components/coral/foundation/form/numberfield" fieldLabel="Number Of Results" required="{Boolean}true" value="10" name="./numberOfResults"/> ``` **Limitation** (snippet from mentioned thread): The `value` property values only persist if `jcr:created` and `jcr:lastModified` date is same for a component node in content. That means once component is authored, the dialog values will be fetched from save properties. Make this field mandatory if you wish to keep a value either default or authored value. That solves the problem of always populating it. **Thread** Refer <https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/defaultvalue-property-removed-in-coral-numberfield-in-aem-6-4/qaq-p/292673> for more details.
7,374,810
I have a Fundamental question in using Jquery with PHP when making ajax calls with respect to performance. Is it right to do a Get or a POST. Which is faster when using ajax calls. I know this question has got nothing to do with PHP though, but would like to understand the different view points. All I am trying to do is to pass variables to PHP and echo data using jquery. ``` $.post('request.php', { param1: value, param2:value }, function (data) { container.html(data); } if (isset($_POST['param1']) && isset($_POST['param2'])){ //Do some process on the server echo "server processed data"; } ``` What is best to use in this case? A `GET` or a `POST`
2011/09/10
[ "https://Stackoverflow.com/questions/7374810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/748546/" ]
`addEventListener` is a method of the DOM element. `fadeOut`, `fadeIn` and `delay` are jQuery methods. If you want to use the bind method, you need a jQuery object, so it would be like ``` $(audioElement).bind('ended', function() { $('span#pause').fadeOut('slow'); $('span#play').delay(1500).fadeIn('slow'); }); ```
addEventListener works on DOM elements, while bind works on jquery objects. The event handler contains JQuery code, but addEventListener is JavaScript. You could change it to: ``` $(audioElement).bind('ended', function() { $('span#pause').fadeOut('slow'); $('span#play').delay(1500).fadeIn('slow'); }); ``` This makes it 'full JQuery' (which is still JavaScript) :)
900,867
I create a button and set title as "Click here". When I press that button I want to get that button title and log it. Here's my code, where am I going wrong? ``` -(void)clicketbutton { UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeCustom]; [mybutton setTitle:@"Click here" forState:UIControlStateNormal]; [mybutton addTarget:self action:@selector(displayvalue:)forControlEvents:UIControlEventTouchUpInside]; } -(void)displayvalue:(id)sender { UIButton *resultebutton= [UIButton buttonWithType:UIButtonTypeCustom]; resultebutton=sender;// pls clear here.. my question here , it it possible or not. if possible how ? NSLog(@" The buttontitile is %@ ", [resultebutton.Title] // here also. } ```
2009/05/23
[ "https://Stackoverflow.com/questions/900867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/108639/" ]
Your displayvalue: method should look something like this: ``` -(void)displayvalue:(id)sender { UIButton *resultButton = (UIButton *)sender; NSLog(@" The button's title is %@.", resultButton.currentTitle); } ``` (Please check out the documentation in XCode, it would have given you the right answer.)
I know it's a bit of an old question, but this is probably the neatest way to resolve this one. ``` NSLog(@"The button title is: %@", [sender currentTitle]); ``` **Edit** I've just realised that this is depending on the fact that you have set the receiving parameter to `UIButton*`. Rather than using the default `id`, creating a `UIButton` object and casting `(id)sender` to that button. Cut out the middle man and just set the function signature to ``` -(void)buttonPressed:(UIButton*)sender{ NSLog(@"Button title: %@",sender.currentTitle); } ``` This is effectively casting the function parameter
239,722
I have generated a custom entity using Drupal Console. ``` drupal generate:entity:content ``` The entity doesn't have the permission `edit own content` which we usually have in node types etc... The entities `entity_name.permissions.yml` the file has the following enteries. ``` add company entities: title: 'Create new Company entities' administer company entities: title: 'Administer Company entities' description: 'Allow to access the administration form to configure Company entities.' restrict access: true delete company entities: title: 'Delete Company entities' edit company entities: title: 'Edit Company entities' access company overview: title: 'Access the Company overview page' view published company entities: title: 'View published Company entities' view unpublished company entities: title: 'View unpublished Company entities' ``` I tried understanding, how this is done in node. But in node types permission file also I couldn't find this permission entered.
2017/06/30
[ "https://drupal.stackexchange.com/questions/239722", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/3028/" ]
A little surprised how easy this was to fix; but it seems to be working. Console originally created permissions similar to what @esefwan posted and in MyEntityAccessConrtolHandler.php it created this code: ``` protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { /** @var \Drupal\reserve\Entity\MyEntityInterface $entity */ switch ($operation) { case 'view': if (!$entity->isPublished()) { return AccessResult::allowedIfHasPermission($account, 'view unpublished myentity'); } return AccessResult::allowedIfHasPermission($account, 'view published myentity'); case 'update': return AccessResult::allowedIfHasPermission($account, 'edit myentity entities'); case 'delete': return AccessResult::allowedIfHasPermission($account, 'delete myentity entities'); } // Unknown operation, no opinion. return AccessResult::neutral(); } ``` Looking at the code in node.module under node\_node\_access() i ended up modifying the above to this: ``` protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { /** @var \Drupal\reserve\Entity\ReserveReservationInterface $entity */ switch ($operation) { case 'view': if (!$entity->isPublished()) { $access = AccessResult::allowedIfHasPermission($account, 'view unpublished myentity'); } $access = AccessResult::allowedIfHasPermission($account, 'view published myentity'); break; case 'update': $access = AccessResult::allowedIfHasPermission($account, 'edit any myentity'); if (!$access->isAllowed() && $account->hasPermission('edit own myentity')) { $access = $access->orIf(AccessResult::allowedIf($account->id() == $entity->getOwnerId())->cachePerUser()->addCacheableDependency($entity)); } break; case 'delete': $access = AccessResult::allowedIfHasPermission($account, 'delete any myentity'); break; // Unknown operation, no opinion. default: $access = AccessResult::neutral(); } return $access; } ```
I added two additional permissions in my permissions.yml file (view own and edit own...) and altered the checkAccess by adding the following conditions in the switches. Everything was initially created by drush generate. ``` /** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { $uid = $entity->getOwnerId(); switch ($operation) { case 'view': if ($account->id() != $uid) { return AccessResult::allowedIfHasPermission($account, 'view company'); } elseif ($account->id() == $uid) { return AccessResult::allowedIfHasPermissions($account, ['view company, view own company'], 'OR'); } break; case 'update': if ($account->id() != $uid) { return AccessResult::allowedIfHasPermissions($account, ['edit company', 'administer company'], 'OR'); } elseif ($account->id() == $uid) { return AccessResult::allowedIfHasPermissions($account, ['edit own company', 'administer company', 'edit company'], 'OR'); } break; case 'delete': return AccessResult::allowedIfHasPermissions($account, ['delete company', 'administer company'], 'OR'); default: // No opinion. return AccessResult::neutral(); } }``` ```
25,180,021
I have two tables , table1 and table2 with the following structure Table1: ``` ID Location Date ---------------------------- 1 abc 2014-6-3 2 xyz 2013-6-5 ``` Table2: ``` ID Location Date ---------------------- 1 abc NULL 2 xyz NULL 3 hgf 2012-9-8 ``` I need to write a CTE to update the `Table2.Date` column with the values from `table1.Date` column based on the condition `where table1.location = table2.location` Can someone please help me with it as I am very new to the concept of CTE
2014/08/07
[ "https://Stackoverflow.com/questions/25180021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1315013/" ]
You can give an alias to the new value in the cte and then update the value using that alias: ``` WITH cte AS ( SELECT t2.Date ,t1.Date AS NewDate FROM #Table1 t1 JOIN #Table2 t2 ON t1.Location=t2.Location ) UPDATE cte SET Date=NewDate; ```
Problem Analysis : The Update using Common Table Expression is possible only when the updated record affects one base base and this is not possible when the update statement affects more than one base table. In the Above query, Update action is possible by using CTE. Solutions: ``` With Data(t2Date,t2Location,t1Date,t1Location) as ( Select t2.Date,t2.Location,t1.Date,t1.Location from Table_2 t2 Join Table_1 t1 ON t1.Location = t2.Location ) Update Data SET t2Date = t1Date where t1Location = t2Location ``` The output will be [![enter image description here](https://i.stack.imgur.com/Omacw.png)](https://i.stack.imgur.com/Omacw.png) Alternate Solution : we can also provide solution by a normal SQL Query without using CTE. ``` Update Table_2 t2 SET t2.Date = (select t1.Date From Table_1 t1 Where t1.Location = t2.Location) ```
30,138,017
I'm trying to play a bit with Firebase and Android. I have one `RegisterActivity`, and one `MainActivity`. My current flow is - start with `MainActivity` - check if user is registered, if not, call `RegisterActivity` - after registeration call `MainActivity`. I'm having trouble with where to put the `Firebase.setAndroidContext()` call. I have 2 questions: 1. Should I only call this function once in `Application` or once in each `Activty`? 2. If the answer for question 1 is only once, then where should I put it ? Thank you all, Giora.
2015/05/09
[ "https://Stackoverflow.com/questions/30138017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2649154/" ]
I do not know FireBase but i know Android.. A `Context` is a global information about an application environment. Your `Activity` is a `Context` so i am pretty sure `Firebase.getAndroidContext()` retrieves your Application `Context` which is `getApplicationContext()`, Since that seems sensible. > > Should I only call this function once in Application or once in each Activty? > > > call it whenever you need a `Context` with respects to FireBase codes- but i think will suit best if you call it in your `Application` class > > If the answer for question 1 is only once, then where should I put it ? > > > what if its not once? where do you call it? i guess you will call it anywhere you need `Context` right? so do that irrespective of question 1's answer, but you can fall on `Class.this` , `getBaseContext()` or `View.getContext()` anytime
You can do both. If you set it just once then it should be here. Anywhere else and your app will crash. Debugger will say that you have not setAndroidContext(): ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Firebase.setAndroidContext(this); // The rest of your code goes here ``` If you want to use for multiple activities then create a class that has the same name as the app, make sure that the class extends Application. ``` public class NameOfApp extends Application { @Override public void onCreate() { super.onCreate(); Firebase.setAndroidContext(this); } ``` } After that update the application tag in the manifest.xml file with the following: ``` android:name=".NameOfApp" ```
24,858,633
I have 4 columns `A`, `B`, `C`, `D`. In `A` I have some part numbers, and in `B` I have the quantity. In `C` I have almost the same part numbers but in `D` I have a different quantity. I need to make the difference between `D` & `B` (`D-B`) if the part number from `C` is found in `A`. The good results should be in `E` **Image:** ![](https://i.stack.imgur.com/m9amJ.png) I tried this formula but it's not to good one. ``` =IFERROR(IF(VLOOKUP(A2,C:C,1,FALSE)=A2,D4-B2),"NOT FOUND") ``` This formula is not good because I have to manually put `D4-B2`, `D2-B6`, `D6-B5`, and so on. I have 300 rows to make these differences and I thought maybe there is a formula to calculate this.
2014/07/21
[ "https://Stackoverflow.com/questions/24858633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3859315/" ]
I have a MacBook Air 2012 with 4GB of Ram. It worked well to run Eclipse and Android Studio. It's enough for development, and 8GB is better :)
The environment you have is good enough to run the [ADT](http://developer.android.com/tools/help/adt.html) (i.e. Eclipse + Android plugin). However, the default emulator that comes with ADT would run slow and may be choppy. But, as an alternative to this, you can use [Genymotion](http://www.genymotion.com/) which allows to run Android as a VirtualBox VM, which is much faster than the Android emulator. Also it has an Eclipse plugin, which works great. You will have to download and install [Virtualbox](https://www.virtualbox.org/) for this. **Source:** I have a Linux laptop (Dell) with 4 GB Ram, i5 processor (first generation) and 500Gb (non SSD) Harddisk which I bought in 2009, and I do Android development actively on it :). About J2EE, if you are planning to use it using IBM Websphere Server, then I suspect that your configuration might be slow. If you are going to use Tomcat, then it might work. I cannot be sure about this as I have never tried it. Good luck!
46,066,824
I encountered some problem when writing c++. The problem might be symplified as below. The function named as "test" return a pointer. And I tried to modify it but failed with error information. ``` void* test(){ void * p1; return p1} test() = new string(); ``` ERROR: expression must be a modifiable lvalue. In my case, p1 is not a local variable but a certain member of an object. And it failed too.
2017/09/06
[ "https://Stackoverflow.com/questions/46066824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8331937/" ]
@MikaelMello is correct that you cannot set the value of a function. Extending your code and @MikaelMello 's, you can take the pointer that your function returns and make it point to an object like this: ``` void* test(){ void * p1; return p1} ... void* voidPointer = test(); voidPointer = new string(); ```
the function `test` has a return type of `void *`, thus the expression `test()` is a rvalue, which cannot be assigned to. only lvalue can appear on the left of an assignment operator. see the [explanation](http://en.cppreference.com/w/cpp/language/value_category) of lvalue, rvalue, and others. I'm guessing you probably want to dereference a pointer and assign a new value to it. but if you really want to assign to a return value of a function, the return type must be a lvalue reference type. like ``` // this function returns a reference to a pointer void * &test (); test() = new string; ``` you really know what the code should mean, right? if you return a dangling reference and assign value to it, even the syntax has the correct type, the program is still not correct.
11,770,716
Python is my first language, and I am very new to it, so the answer may be very clear, but after many hours looking and experimenting, I am not sure what is causing the problem. An overview of the module: The DicePool module is meant to manage collections of "dice", stored as dictionary items. Each dictionary key (herein poolKey) has a list containing information about one "type" of dice, most importantly, a tuple describing its faces and an integer representing the quantity of "dice" type 'x' in the "pool." My specific question regards the Transfer method, which used to be two methods (send and receive, basically), but which I thought I could combine into one method. When the test code at the bottom runs, I'd like it to leave dp.dictPool[poolKey][1] == 0 and dp2.dictPool[poolKey][1] == 2. But in every attempt I've made, the values come out the same. Sorry I can't categorize this question better . . . I don't really know what the problem is. Anyway, one half of the Transfer method is supposed to run for the "sender" instance, and one half is supposed to run for the "receiver" instance. ``` import random class DicePool(object): def __init__(self): self.dictPool = {} def AddDice(self, poolKey, faces = 6, quant = 1, color = "white"): '''faces must be int or items 'a,b,c'; count must be int or def to 1''' try: #if count is not an integer, it defaults to 1 quant = int(quant) except: print("Quant is not an integer, defaulting to 1") quant = 1 try: #if faces is can be int, a list is built of numbers 1 to faces faces = int(faces) if faces < 2: #a 1 or 0-sided die breaks the program faces = 2 tempList = [] for i in range(1, faces+1): tempList.append(i) faces = tempList except: #if faces is not an integer, it is split into list items by "," faces = faces.split(",") if poolKey in self.dictPool.keys(): #if the key already exists in pool self.dictPool[poolKey][1] += quant #add to the quantity, else: #if the key does not already exist, set all attributes self.dictPool[poolKey] = [faces, quant, color] def Transfer(self, poolKey, targetPool, sendQuant, senderPool = None): '''targetPool must be DicePool instance''' if targetPool: self.dictPool[poolKey][1] -= sendQuant targetPool.Transfer(poolKey, None, sendQuant, self) else: try: self.dictPool[poolKey][1] -= sendQuant except: self.dictPool[poolKey] = senderPool.dictPool[poolKey] self.dictPool[poolKey][1] = sendQuant dp = DicePool() dp2 = DicePool() dp.AddDice("d6") dp.AddDice("d6") dp.Transfer("d6",dp2,2) print(dp.dictPool,dp2.dictPool) ```
2012/08/02
[ "https://Stackoverflow.com/questions/11770716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1570231/" ]
The problem is in this line: ``` self.dictPool[poolKey] = senderPool.dictPool[poolKey] ``` The values in your dictPools are lists. Here, you set one object's dictPool value to *the same list* as in the other one. Not a copy of the list, but the same list. So later if you add or subtract from that list, it will affect the other as well, because they are sharing one list object. Try doing `self.dictPool[poolKey] = senderPool.dictPool[poolKey][:]`. The `[:]` grabs the contents of the list rather than the list object iself.
Here is a version of the Transfer() method that seems to work as intended (more or less), although it's very clumsy looking: ``` def Transfer(self, poolKey, targetPool, sendQuant, senderPool = None): '''targetPool must be DicePool instance''' if isinstance(targetPool, DicePool): #valid target, so subtract dice here, then call Transfer on target temp = self.dictPool[poolKey][1:2][0] - sendQuant print("sent",sendQuant,"leaving",temp) targetPool.Transfer(poolKey, "Receiver", sendQuant, self) elif targetPool == "Receiver": #this executes if a DicePool is named as the targetPool of Transfer if poolKey in self.dictPool.keys(): self.dictPool[poolKey][1:2][0] += sendQuant else: self.dictPool[poolKey] = senderPool.dictPool[poolKey] self.dictPool[poolKey][1:2] = [sendQuant] print("now have",self.dictPool[poolKey][1:2][0]) pass else: print("Not a valid targetPool, apparently") ```
1,460
Is there a graph of known black holes, with their estimated mass in the X axis and their estimated radius in the Y axis? If so, where can we find it? I would like to know if a black whole with the whole estimated mass of our universe would have the estimated radius of our universe (which means our universe could be a black hole, that's why light can't escape it and it looks "finite").
2014/01/15
[ "https://astronomy.stackexchange.com/questions/1460", "https://astronomy.stackexchange.com", "https://astronomy.stackexchange.com/users/813/" ]
The [Schwarzschild radius](http://en.wikipedia.org/wiki/Schwarzschild_radius) of a black hole is probably the closest we can get to your question. $$ r\_s = (2G/c^2) \cdot m \mbox{, with }\ 2G/c^2 = 2.95\ \mbox{km}/\mbox{solar mass}. $$ This means, that the Schwarzschild radius for a given mass is proportional to that mass. The radius shouldn't be taken too literal in the physical sense, because space is highly non-euclidean close to a black hole. Present (light-travel) radius of the visible universe, as seen from the earth: $$13.81 \cdot 10^9\ \mbox{lightyears} = 13.81 \cdot 10^9 \* 9.4607 \* 10^{12}\ \mbox{km} = 1.3065\cdot 10^{23}\ \mbox{km}.$$ So we need $$1.3065\cdot 10^{23}\ \mbox{km} / 2.95\ \mbox{km} =4.429 \cdot 10^{22}$$ solar masses to get a black hole of the light-travel Schwarzschild radius of the visible universe, pretty close (by order of magnitude) to the number of stars estimated for the visible universe. The Wikipedia author(s) gets a similar result: "The observable universe's mass has a Schwarzschild radius of approximately 10 billion light years".
According to the standard [ΛCDM](http://en.wikipedia.org/wiki/%CE%9BCDM) cosmological model, the observable universe has a density of about $\rho = 2.5\!\times\!10^{-27}\;\mathrm{kg/m^3}$, with a cosmological consant of about $\Lambda = 1.3\!\times\!10^{-52}\;\mathrm{m^{-2}}$, is very close to spatially flat, and has a current proper radius of about $r = 14.3\,\mathrm{Gpc}$. From this, we can conclude that the total mass of the observable universe is about $$M = \frac{4}{3}\pi r^3\rho \sim 9.1\!\times\!10^{53}\,\mathrm{kg}\text{.}$$ Sine the universe at large is nonrotating and uncharged, it's natural to compare this to a Schwarzschild black hole. The Schwarzschild radius of such a black hole is $$R\_s = \frac{2GM}{c^2}\sim 44\,\mathrm{Gpc}.$$ Well! Larger that the observable universe. But the Schwarzschild spacetime has zero cosmological constant, whereas ours is positive, so we should instead compare this to a Schwarzschild-de Sitter black hole. The SdS metric is related to the Schwarzchild one by $$1-\frac{R\_s}{r}\quad\mapsto\quad1 - \frac{R\_s}{r} - \frac{1}{3}\Lambda r^2,$$ and for our values we have $9\Lambda(GM/c^2)^2 \sim 520$. This quantity is important because the black hole event horizon and the cosmological horizon become close in $r$-coordinate when it is close to $1$, a condition that creates a maximum possible mass for an SdS black hole for a given positive cosmological constant. For our $\Lambda$, that extremal limit gives $M\_\text{Nariai} \sim 4\!\times\!10^{52}\,\mathrm{kg}$, smaller than the mass of the observable universe. In conclusion, the mass of the observable universe cannot make a black hole. --- > > Well, we don't fully comprehend black matter, do we? And it was just "yesterday" that we discovered the "black energy", wasn't it? > > > If GTR with cosmological constant is right, we don't need to "fully comprehend" it to know its gravitational effect, which is what the calculation is based on. If GTR is wrong, which is of course quite possible, then we could be living in some analogue of a black hole. But then it's rather unclear what theory of gravity you wish for us to use to try to answer the question. There's no remotely competitive theory that's even approaching general acceptance. > > From the perspective of our huge ignorance, I think that 14.3Gpc and 44Gpc are not even one order of magnitude apart, which I consider a good approximation. > > > Actually, the point of that calculation was to show that it's at least *prima facie* plausible. The Schwarzschild radius calculation doesn't rule out the black hole--quite the opposite. However, it's also not appropriate for reasons I explained above. The more relevant one actually does have mass more than one order of magnitude apart, and shows inconsistency. So if GTR with Λ is correct, it's unlikely because the ΛCDM error bars aren't that bad. However, even if we still treat it as "close enough", that does not by itself imply what you want. The question of what kind of black hole all the mass of the observable universe would make, if any, is quite different from whether or not we're living in one. The black hypothetical needs to be larger still. The biggest point of uncertainly, though, is the cosmological constant, even if GTR is otherwise correct. If we're allowed to have very different conditions outside our hypothetical black hole, then we could still have one, but then we get into very speculative physics at best, and just complete guesswork at worst. So treat the above answer as conditional on the mainstream physics; if that's not what you want, then there can be no general answer besides "we don't know". And that's always a possibility, although not a very interesting one.
58,947,142
I cannot figure out what is causing the top margin (pink div) to be greater on top (while left, right, bottom are correct); I've specified padding:10px; on the container. Any ideas? Full page below, or try link here <https://codepen.io/joe-oli/pen/ZEEVKZz> **UPDATE** after too many rushed answers, along the lines of try this, try that... I am looking for an explanation as to why I have specified #wrapper {padding: 10px}, yet the pink child has a bigger padding on top. It should be 10px on top, bottom, left, right ! ``` <html> <head> <style> body { background: white; padding: 20px; font-family: Helvetica; } #wrapper { border: 1px dashed magenta; padding: 10px; position: relative; } .yellowBg { background-color: yellow !important; } #theModal { display: none; font-size: 30px; text-align: center; } .modal { display: block !important; z-index: 999; /* opacity: 0.4; */ background: rgba(10, 10, 10, 0.4); position: absolute; width: 100%; /* calc(100% - 10px) */ height: 100%; top: 0; left: 0; cursor: progress; } button { color: #fff; /* white */ background: #0084ff; /* blue */ border: none; border-radius: 5px; padding: 8px 14px; font-size: 15px; } </style> </head> <body> <div id="wrapper"> <div id="theModal">Loading...</div> <div style="background-color:hotpink;"> <p>Hello World !</p> <input placeholder="enter something" value="" /> <input placeholder="and something else" /> <select> <option>apples</option> <option>bananas</option> <option>oranges</option> </select> <br /> <br /> <button id="btnToggle">Click me often</button> <button id="btnDoAjax">Do Ajax call</button> </div> </div> </body> </html> ```
2019/11/20
[ "https://Stackoverflow.com/questions/58947142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90259/" ]
``` p{ margin:0 } ``` Use this line after theModal id this will fix this.
Try with this code: HTML: ``` <div id="wrapper"> <div id="theModal">Loading...</div> <div class="pink_div" style="background-color:hotpink;"> <p>Hello World !</p> <input placeholder="enter something" value="" /> <input placeholder="and something else" /> <select> <option>apples</option> <option>bananas</option> <option>oranges</option> </select> <br/> <br/> <button id="btnToggle">Click me often</button> <button id="btnDoAjax">Do Ajax call</button> </div> </div> ``` CSS: ``` body { background: white; padding: 20px; font-family: Helvetica; } #wrapper { border: 1px dashed magenta; padding:10px; position:relative; } .pink_div{ padding:10px; } .pink_div p{ margin-top:0; } .yellowBg { background-color:yellow !important; } #theModal { display:none; font-size: 30px; text-align:center; } .modal { display:block !important; z-index:999; /* opacity: 0.4; */ background: rgba(10, 10, 10, 0.4); position:absolute; width: 100%; /* calc(100% - 10px) */ height: 100%; top:0; left:0; cursor:progress; } button { color: #fff; /* white */ background: #0084ff; /* blue */ border: none; border-radius: 5px; padding: 8px 14px; font-size: 15px; } ```
107,472
I flagged a question as offensive, figuring that it may not get the 6 votes needed to shut it down, but it was the right thing to do (no, I won't point out which one, since that would derail the discussion of this issue, **this is not about the particular flag**). I got the following feedback on the flag page: ![Offensive Flag declined](https://i.stack.imgur.com/4lmkw.png) The message is also ***plainly wrong***, since `offensive` and `spam` flags should be used for those reasons, since the community alone with enough votes can deal with those issues. They do not need to be mod-targeted specifically, since it doesn't always require their intervention. I **did not** flag the moderator, I just flagged the post as offensive. If they don't want to fix it, then fine just leave it alone, but there is no reason to decline an offensively flagged post. If 5 others don't agree, then it will disappear on its own. The `offensive` and `spam` flags work that way, and shouldn't be declined.
2011/09/26
[ "https://meta.stackexchange.com/questions/107472", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/13295/" ]
> > I **did not** flag the moderator, I just flagged the post as offensive. If they don't want to fix it, then fine just leave it alone, but there is no reason to decline an offensively flagged post. > > > Yes, you did flag for a moderator. The fact that the community can vote to deal with spam/offensive flags without moderator intervention should not weaken spam/offensive flags. Those flags are, in my mind, *stronger* than regular flags because they make a stronger assertion about the post. They require my immediate attention. Allowing the community to deal with spam/offensive posts allows them to be dealt with *more quickly*. It doesn't mean moderators should let them sit in the queue until they eventually evaporate.
Moderators are also members of the community. If they happen across offensive and spam flags in the mod queue, it's up to their judgement and discretion to either nuke the steamroll or drive in the final nail with their blood diamond sledgehammer. Users are known to at times flag posts that are neither offensive nor spam. Letting them pile up to the point of a -100 EXP hit would be letting evil or misguided flags win. Moderators need the ability to decline these flags as they do with any other flag and may indeed require their intervention should the reasoning not gel.
10,847,031
I am trying to extract two sentences out of a bunch of paragraphs, and I am stuck... Basically, the paragraphs look like this: ``` <p class="some_paragraph">This is a sentence. Here comes another sentence. A third sentence.</p> <p class="some_paragraph">Another sentence here. Interesting information. Very interesting.</p> <p class="some_paragraph">This is a sentence. Here comes another sentence. A third sentence.</p> ``` What I need to do, is to find the two 'shortest' sentences out of all 9 sentences in these three paragraphs. The two extracted sentences have to be put into the following spans: ``` <span class="span1">Shortest sentence comes here</span> <span class="span2">Second shortest sentence comes here</span> ``` How do I do that?
2012/06/01
[ "https://Stackoverflow.com/questions/10847031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/921295/" ]
``` var snt = []; $('.some_paragraph').each(function() { var text = $(this).text(); text.replace(/[A-Z][^.]+\./g, function(s) { if (snt.length < 2) { snt.push(s); } else { snt[+(snt[0].length <= snt[1].length)] = s; } }); }); console.log(snt); // outputs the two shortest sentences /* creating two span with shortest sentences */ snt.map(function(el, i) { $('<span />', { class: "span" + (i+1), text: el }).appendTo($('body')); }); /** * Result: * * <span class="span1">Very interesting.</span> * <span class="span2">A third sentence.</span> */ ``` example fiddle : <http://jsfiddle.net/4La9y/2/> Just to be clear, this criptic statement `snt[+(snt[0].length <= snt[1].length)] = s;` means that if I already filled the array with two sentences, then the next you find will be stored in place of `snt[0]` if `snt[1]` is shortest and vice-versa
``` var smallest = 0; var smaller = 0; var bigger = 0; var smallest_sen; var smaller_sen; $('p.some_paragraph').each(function(){ plength = $(this).text().length; if(smallest == 0){ smallest = plength; smallest_sen = $(this).text(); }else if(smallest > plength){ smaller_sen = smallest_sen; smaller = smallest; smallest = plength; smallest_sen = $(this).text(); } }); alert(smallest_sen); alert(smaller_sen); ```
29,817,656
I am using glob to find directories inside the current one where my index file is. Inside it i am saving html pages extracted from EXCEL and they create folders directories ending in .files Is there a way to glob all directories but exclude those ending in .files? Here is my code as it's currently: ``` <?php // set to current directory $dir = ''; // directories only. ignore files, etc. foreach(glob($dir.'*', GLOB_ONLYDIR) as $folder){ // do not include wordpress directories if (($folder != '*') && ($folder != 'ΦΥΛΑΚΕΣ ΠΡΑΤΗΡΙΩΝ.files') && ($folder != 'wp-includes')) { // list directories and their links ?> <li><a href="<?php echo $dir."/files/".$folder;?>"><?php echo $folder;?></li> <?php } } ?> ``` EDIT: As you can see i can exclude specified folders but i want it to exclude automatically all folders ending in .files as i said.
2015/04/23
[ "https://Stackoverflow.com/questions/29817656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3785886/" ]
You could use the [substr](http://php.net/manual/en/function.substr.php)-function to do the following: ``` <?php // set to current directory $dir = ''; // directories only. ignore files, etc. foreach( glob( $dir.'*', GLOB_ONLYDIR ) as $folder ){ // do not include wordpress directories if( ($folder != '*') && (substr( $folder , -6 ) != '.files') && ($folder != 'wp-includes') ){ // list directories and their links ?> <li> <a href="<?php echo $dir."/files/".$folder;?>"><?php echo $folder;?></a> </li> <?php } } ?> ```
I am sorry for the message, I do not how to use it properly, I write it here ``` <?php $cur = getcwd(); chdir($dir); $src = glob("*",GLOB_ONLYDIR); chdir($cur); $nomatch = preg_grep("/.*\.files$|^wp\-includes$/i",$src,PREG_GREP_INVERT); foreach($nomatch as $folder) { ?> <li><a href="<?php echo $dir."/files/".$folder;?>"><?php echo $folder;?></li> <?php } ?> ```
44,441,070
Hello I need some inspiration, I have a waypoint class like so: ``` public class Waypoint<T> { } ``` and I would like to add all my waypoints to one list like so: ``` var w1 = new Waypoint<Item>(); var w2 = new Waypoint<Player>(); var waypoints = new List<Waypoint<?>>(); ``` Problem is, they are not all of the same Type. Is there a way that I can add different types to one list? Anybody know an easy workaround? Language: C# Kind regards, Venomous
2017/06/08
[ "https://Stackoverflow.com/questions/44441070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6655608/" ]
Instead of a generic base class, you could define Waypoint as an interface and have Item and Player implement it. That way you can have a list of IWaypoints like you want. ``` interface IWaypoint { Point GetPosition();//whatever a waypoint should do } class Item : IWaypoint { Point location; public Point GetPosition() { return location; } } class Player : IWaypoint { Point position; float movespeed; public Point GetPosition() { return position * movespeed; } } void main() { List<IWaypoint> waypoints = new List<IWaypoint>(); waypoints.Add(new Player()); waypoints.Add(new Item()); foreach (IWaypoint wp in waypoints) { Console.WriteLine(wp.GetPosition()); } } ```
Assuming you are coding in C#, there is no common base class for `Waypoint<Item>` and `Waypoint<Player>` except for `object` so the type of collection would be `List<object>` (or even `ArrayList`). Even if `Item` and `Player` both derived from the same base class, you wouldn't be able to define a `List<Waypoint<Base>>` and add both `Waypoint<Item>` and `Waypoint<Player>` objects to this list. `Waypoint<Item>` is not a derived type of `Waypoint<Base>` just because `Item` is a derived type of `Base`.
12,570,807
Instead of doing this, I want to make use of `string.format()` to accomplish the same result: ``` if (myString.Length < 3) { myString = "00" + 3; } ```
2012/09/24
[ "https://Stackoverflow.com/questions/12570807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41508/" ]
``` string.Format("{0:000}", myString); ```
You can also do : string.Format("{0:D3}, 3);
447,319
I have a 5 year old notebook computer. It uses Windows XP, and as you might know, this OS now has no support at all. It has a 1.60GHz, 0.98GB of RAM. What would you guys recommend me , in order for me to happily migrate from Windows XP to Ubuntu program. I appreciate in advance any help you can provide me regarding this matter. Regards
2014/04/13
[ "https://askubuntu.com/questions/447319", "https://askubuntu.com", "https://askubuntu.com/users/268247/" ]
Seeing the hardware you have (CPU: 1.6 GHz, RAM: 1 GB) I recommend to download Xubuntu or Lubuntu before testing Ubuntu. This is not related to which one is better but I am trying to make sure that the Ubuntu version works OK on your hardware. I also would recommend, like Devesh said, to wait until 14.04 is out (Which will happen next week on April 17, so the wait won't be long). Here's what each of them would look like once you have them installed: Lubuntu ======= Very lightweight Desktop environment (Lightweight meaning that it uses small amounts of RAM, CPU and HDD space). The menu, where all the apps can be found, is located in the same place as you have them in Windows XP. ![enter image description here](https://i.stack.imgur.com/X9qlZ.jpg) Xubuntu ======= Another lightweight Desktop environment. The menu can be found in the top left corner so instead of going down to the bottom right corner, you would go up. ![enter image description here](https://i.stack.imgur.com/R5JPQ.jpg) Ubuntu ====== This is the main Ubuntu distribution. It uses a bit more resources than the other two, but I have tried Ubuntu on computers with 512 MB of RAM and it has ran correctly. You would also need a good video card. Still, you would need to personally test this. From Booting time, to how fast apps opened, to how fast you can work and be productive with each Desktop environment. ![enter image description here](https://i.stack.imgur.com/sfmHL.jpg) You need to know that, independent of what Ubuntu flavor you decide to select, you can install from any of them, the other desktops to try out. What I mean with this is that, if you download Lubuntu, Xubuntu, Ubuntu, Kubuntu, Gnome Ubuntu or any Ubuntu official version, you can install from the Software Center (The application that manages installation of other apps and updates) any other Desktop environment. So you could have installed Xubuntu but you also wanted to try out Lubuntu, so you would go to the Software Center and download the `lubuntu-desktop` package. This would make your system have both, Xubuntu and Lubuntu. you can choose which one you want to use from the Login Screen. I would also invite you to read about [Start Ubuntu](https://wiki.ubuntu.com/StartUbuntu) which guides new Ubuntu users into this open source world. So with everything here said and taking your hardware into consideration my recommendations would be: * Download Xubuntu or Lubuntu first before trying Ubuntu * Download ONLY the 32 Bit version. The 64 Bit needs more RAM in order to perform better. * If you have a low graphics card I recommend staying with Xubuntu or Lubuntu only. * Remember that you can test other Desktop Environments (DE) from any of the other Ubuntu versions just by installing their appropriate package (`lubuntu-desktop` for Lubuntu, `xubuntu-desktop` for Xubuntu...) * Run the LiveCD/LiveDVD/LiveUSB which is a Live session of Ubuntu that does not install on your computer but runs directly from CD/DVD/USB. This way you can test out the DE and how it feels to you before even installing it on your system. * Remember that you can install Ubuntu alongside Windows XP. There is no need to eliminate Windows XP completely. At least while you get accustomed to how the DE looks, works and behaves. The Ubuntu installer will give you an option about installing alongside in case you want this or you can be a brave warrior and go straight to Ubuntu FTW!. * Remember to backup anything you want to save in case you want to format the whole system and install Ubuntu only. * Use the SEARCH option in Ask Ubuntu when you find a problem you can't solve. There are more than 3000 questions related to Windows XP and more than 2000 related to Windows XP and the installation procedures. So there is a sure bet you will find most of the issues solved already. So with all of this said, I applaud you and say: Welcome to Ubuntu my friend.
Since your configuration is a bit low, it would be getter if you go for the lighter version of Ubuntu called Lubuntu. its a light weight version of Ubuntu. It is a fast and lightweight operating system developed by a community of Free and Open Source enthusiasts. The core of the system is based on Linux and Ubuntu. It focus on speed and energy-efficiency. Because of this, Lubuntu has very low hardware requirements. So in my opinion this would be the better option for you. 1.download the .iso file from this link : <http://cdimage.ubuntu.com/lubuntu/releases/13.10/release/> 2.Then install this by burning the iso to a DVD or installing via pen drive.here's the link for the software you will need if you plan to do so: <http://www.pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/> Hope this helps
17,596,827
The following connects the js client to all the existent hubs: ``` $.connection.hub.start({ transport: 'longPolling' }).done(function () {}); ``` Is there some way to connect to some particular hub instead? If not, what is the point of "OnConnected()" and "OnDisconnected()" being in EVERY hub? if all of them are going to be called anyway. I'm asking this because there is a particular html (something like a news feed) in which I want to handle notifications from one hub (when news are posted, this view should handle and show them appearing). I'm going to use groups but seems more natural to separate this in hubs.
2013/07/11
[ "https://Stackoverflow.com/questions/17596827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1387588/" ]
You only subscribe to hubs that you have client side events associated with. So lets say you had two hubs: 1. **hubA** 2. **hubB** In your client if you have: ``` var hubA = $.connection.hubA; hubA.client.foo = function() {}; $.connection.hub.start(); ``` You will only be subscribed to events on hubA (not hubB).
You can choose to use or not use the connection events in any hubs you create. You certainly can separate your code into logical sections using hubs, no harm in that.
25,642,691
I'm developing an Android app on my Nexus 5 device (~445 ppi) and I'm using Roboto Light as the font for a few sections in the application. When displayed in my device, the Roboto Light text looks clean and crisp, however when testing the app on device with screens that have a lower pixel density, Roboto Light looks pretty bad (bolder fonts look OK). What is the best and quickest way to tell my app to use Roboto Light on high-density screens and another font on low-density ones? My first idea was to create different `values` directories (values-mdpi, values-hdpi, values-xhdpi...), place a `strings.xml` in each one with the same key and assign it the font's filename I wish to use for each density, and then load the font using that string... however that looks a bit complicated and I was wondering if there is an easier way.
2014/09/03
[ "https://Stackoverflow.com/questions/25642691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1989647/" ]
DisplayMetrics metrics = getResources().getDisplayMetrics(); int densityDpi = (int)(metrics.density) depends on your density you can set font type to textview and other controls like below code use Typeface font = Typeface.createFromAsset(getAssets(), "/fonts/Avenir.ttf"); textView.setTypeface(font);
You could do this programmatically by > > float density = getResources().getDisplayMetrics().density; > > > This will give you: > > > 0.75 - ldpi > > > 1.0 - mdpi > > > 1.5 - hdpi > > > 2.0 - xhdpi > > > 3.0 - xxhdpi > > > 4.0 - xxxhdpi > > > [Source](https://stackoverflow.com/a/10948031/3249477) > > > Then check the density and act accordingly: ``` if (density >= 2.0) { textView.setTypeface(Typeface.SANS_SERIF); } else { textView.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD); } ```
3,830,833
I (mostly) use git to download and compile various projects from their source code, keeping my source in `/usr/local/src` and installing the binaries in `/usr/local/bin`. Following the building procedure, usually with `./configure && make && make install`, I'm left with a lot of cruft that ends up as 'new' files in my local git repository. To my understanding, `make clean`, `make distclean` and possibly also (?) `./configure clean` are thinkable procedures in order to trash most leftover files. But in specific scenarios (see example below) I'm left clueless what thing to do in order to "stay clean", such as I was prior to the installation... A recent example – installing jscoverage (via *git svn*) from <http://svn.siliconforks.com/jscoverage/trunk> jscoverage: The building instructions for this project prompted me to use **./bootstrap.sh** `&& make && make install`. In this case, after compiling and installing was finished, I tried all of the aforementioned cleanup commands (by random), but didn't manage to get rid of everything. To wrap my question up: Is there any all-mighty, superior cleaning strategy that I haven't grasped? How do you approach this cleanup issue when using a VCS such as git, in a typical workflow where you 1.) download – 2.) build – 3.) pull updates from upstream repository – 4.) build once again – and so forth?
2010/09/30
[ "https://Stackoverflow.com/questions/3830833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/63984/" ]
1. First, you can NOT hide command line arguments. They will still be visible to other users via `ps aux` and `cat /proc/$YOUR_PROCESS_PID/cmdline` at the time of launching the program (before the program has a chance to do run-time changes to arguments). Good news is that you can still have a secret by using alternatives: 2. Use standard input: ``` mySecret='hello-neo' printenv mySecret | myCommand ``` 3. Use a dedicated file if you want to keep the secret detached from the main script (note that you'd be recommended to use full disc encryption and make sure the file has correct `chmod` permissions): ``` cat /my/secret | myCommand ``` 4. Use environment variables ([with caveats](https://security.stackexchange.com/questions/197784/is-it-unsafe-to-use-environmental-variables-for-secret-data)). If your program can read them, do this: ``` mySecret='hello-neo' myCommand ``` 5. Use temporary file descriptor: ``` myCommand <( mySecret='hello-neo' printenv mySecret ) ``` In the last case your program will be launched like `myCommand /dev/fd/67`, where the contents of `/dev/fd/67` is your secret (`hello-neo` in this example). --- In all of the above approaches, be wary of leaving the command in bash command history (`~/.bash_history`). You can avoid this by either running the command from a script (file), or by interactively prompting yourself for password each time: ``` read -s secret s=$secret printenv s | myCommand # approach 2 myCommand <( s=$secret printenv s ) # approach 3 secret=$secret myCommand # approach 4 export secret && myCommand # another variation of approach 4 ```
If the secret doesn't change between executions, use a special configuration file, `".appsecrets"`. Set the permissions of the file to be read-only by owner. Inside the file set an environment variable to the secret. The file needs to be in the home directory of the user running the command. ``` #!/bin/bash #filename: .appsecrets set SECRET=polkalover ``` Load the config file so the environment variable gets set. ``` . ~/.appsecrets ``` What I've seen done: **1)** `echo $SECRET | command` works if the command prompts for the password from stdin AND if 'echo' is a builtin of your shell. We were using Korn. **2)** `password=$ENV{"SECRET"};` works if you have control of the code (e.g. in perl or C++) **3)** `. ./.app.config #sets the environment variables isql -host [host] -user [user] -password <<SECRET ${SQLPASSWORD} SECRET` works if the command can accept the secret from std-in. One limitation is that the `<<`string has to be the last argument given to the command. This might be troublesome if there is a non-optional arg that has to appear after -password The benefit of this approach is you can arrange it so the secret can be hidden in production. Use the same filename in production but it will be in the home directory of the account that runs the command in production. You can then lock down access to the secret like you would access to the root account. Only certain people can 'su' to the prod account to view or maintain the secret while developers can still run the program because they use their own '.appsecret' file in their home directory. You can use this approach to store secured information for any number of applications, as long as they use different environment variable names for their secrets. **(WRONG WAY)** One old method I saw the DBAs use was to set SYBASE to `"/opt/././././././././././././././././././././././././././././././././././sybase/bin"`. So their commandlines were so long the ps truncated it. But in linux I think you might be able to sniff out the full commandline from /proc.
1,106,339
An easy problem, but for some reason I just can't figure this out today. I need to resize an image to the maximum possible size that will fit in a bounding box while maintaining the aspect ratio. Basicly I'm looking for the code to fill in this function: ``` void CalcNewDimensions(ref int w, ref int h, int MaxWidth, int MaxHeight); ``` Where w & h are the original height and width (in) and the new height and width (out) and MaxWidth and MaxHeight define the bounding box that the image must fit in.
2009/07/09
[ "https://Stackoverflow.com/questions/1106339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65070/" ]
Based on Eric's suggestion I'd do something like this: ``` private static Size ExpandToBound(Size image, Size boundingBox) { double widthScale = 0, heightScale = 0; if (image.Width != 0) widthScale = (double)boundingBox.Width / (double)image.Width; if (image.Height != 0) heightScale = (double)boundingBox.Height / (double)image.Height; double scale = Math.Min(widthScale, heightScale); Size result = new Size((int)(image.Width * scale), (int)(image.Height * scale)); return result; } ``` I might have gone a bit overboard on the casts, but I was just trying to preserve precision in the calculations.
Tried Mr. Warren's code, but it didn't produce reliable results. For example, ``` ExpandToBound(new Size(640,480), new Size(66, 999)).Dump(); // {Width=66, Height=49} ExpandToBound(new Size(640,480), new Size(999,50)).Dump(); // {Width=66, Height=50} ``` You can see, height = 49 and height = 50 in another. Here's mine (based version of Mr. Warren's code) without the discrepancy and a slight refactor: ``` // Passing null for either maxWidth or maxHeight maintains aspect ratio while // the other non-null parameter is guaranteed to be constrained to // its maximum value. // // Example: maxHeight = 50, maxWidth = null // Constrain the height to a maximum value of 50, respecting the aspect // ratio, to any width. // // Example: maxHeight = 100, maxWidth = 90 // Constrain the height to a maximum of 100 and width to a maximum of 90 // whichever comes first. // private static Size ScaleSize( Size from, int? maxWidth, int? maxHeight ) { if ( !maxWidth.HasValue && !maxHeight.HasValue ) throw new ArgumentException( "At least one scale factor (toWidth or toHeight) must not be null." ); if ( from.Height == 0 || from.Width == 0 ) throw new ArgumentException( "Cannot scale size from zero." ); double? widthScale = null; double? heightScale = null; if ( maxWidth.HasValue ) { widthScale = maxWidth.Value / (double)from.Width; } if ( maxHeight.HasValue ) { heightScale = maxHeight.Value / (double)from.Height; } double scale = Math.Min( (double)(widthScale ?? heightScale), (double)(heightScale ?? widthScale) ); return new Size( (int)Math.Floor( from.Width * scale ), (int)Math.Ceiling( from.Height * scale ) ); } ```
8,339,030
I have an array like ``` Array ( [select_value_2_1] => 7 ) ``` I want to explode index into `Array ([0]=select_value, [1]=2, [2]=1)`
2011/12/01
[ "https://Stackoverflow.com/questions/8339030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/685713/" ]
Or if you want to split the keys as in your example, use a more complex function: ``` foreach ($array as $key=>$value) { $key_parts = preg_split('/_(?=\d)/', $key); } ```
``` <?php $arr=array("select_value_2_1" => 7); $keys= array_keys($arr); $key=$keys[0]; $new_arr=explode("_",$key); print_r($new_arr); ?> ```
140,916
I have 30 years of professional experience as a software engineer and I'm at the point in my career where I can volunteer lots of time. I have helped with several childhood cancer organizations over the years but mostly was pulled into raising money. At this point in my life, I would like to help with a closer connection to the research aspect in either finding a cure, better medicines/trials, or similar. I do not have experience in the sciences, bioinformatics, etc. but I am willing to learn. Where do I best find researchers in the field of childhood cancer (which I know very well is many different cancers) who might be looking for the help of a software developer?
2019/12/01
[ "https://academia.stackexchange.com/questions/140916", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/116861/" ]
I work in a biomedical field and most of us are awful programmers. We tend to be more interested in getting the underlying back-end algorithm to work than worrying about the front-end, comments, documentation, version control, unit tests, etc. My suggestion, would be to look through the web pages at a nearby university and see if you can identify someone doing something you think is interesting, preferably something computational. Then email the PI explaining your skills and experience and that you would like to volunteer to help people with their programming and that you could help people move to the next level of using tools like version control and work with them on documentation and the front end.
I can't speak specifically to cancer in children but drug design is a highly computer-oriented field. Drugs are designed, tested and analysed using computational chemistry before they are produced in a lab. The tools for this work are largely written by academics who produce great underlying theory but don't usually have the training in CS to write great code. You could dive into the ecosystems of some of these programs and submit pull requests but realistically the authors are looking for new features not architectural changes. They are often open-source with active slack channels so it may be worth popping in. PSI4, OpenForceField, RDKit all spring to mind as large, open-source, growing codebases in computational chemistry/bioinformatics. If you want to get heavily involved, in the UK we have the [RSE](https://rse.ac.uk/who/) (research software engineers). There may be similar posts wherever you're based.
496,173
How can i uninstall a program in Windows 8 in desktop without going to the start screen?
2012/10/30
[ "https://superuser.com/questions/496173", "https://superuser.com", "https://superuser.com/users/168834/" ]
1. Open the **Computer** in **File Explorer**. 2. Click **Computer** on the **Ribbon** and select **Uninstall or change a program** ![enter image description here](https://i.stack.imgur.com/shF5G.png)
You can access the control panel from the File Explorer browsing your Computer, then **Uninstall a program**. Uninstalling a program is quite similar to in Windows 7. From the start screen, just go to **Control Panel > More settings > Programs and Features**, and select the program to Uninstall. If you know where the uninstaller for a program is, you can also find it directly using the File Explorer. To uninstall a Metro/Modern UI application, right-click the application, and click Uninstall from the menu that pops up.
6,260,475
I can't google the ~ operator to find out more about it. Can someone please explain to me in simple words what it is for and how to use it?
2011/06/07
[ "https://Stackoverflow.com/questions/6260475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/747871/" ]
One usage of the ~ (Tilde) I have seen was getting boolean for .indexOf(). You could use: `if(~myArray.indexOf('abc')){ };` Instead of this: `if(myArray.indexOf('abc') > -1){ };` [JSFiddle Example](http://jsfiddle.net/mmuv1hwt/1/) --- Additional Info: [The Great Mystery of the Tilde(~)](http://www.joezimjs.com/javascript/great-mystery-of-the-tilde/) Search Engine that allows special characters: [Symbol Hound](http://symbolhound.com/)
It's a tilde and it is the bitwise NOT operator.
49,185,133
I have a Pandas data frame with multiple columns whose types are either float64 or strings. I'm trying to use `to_csv` to write the data frame to an output file. However, it outputs big numbers with scientific notion. For example, if the number is 1344154454156.992676, it's saved in the file as 1.344154e+12. How to suppress scientific notion for `to_csv` and keep the numbers as they are in the output file? I have tried to use `float_format` parameter in the `to_csv` function but it broke since there are also columns with strings in the data frame. Here are some example codes: ``` import pandas as pd import numpy as np import os df = pd.DataFrame({'names': ['a','b','c'], 'values': np.random.rand(3)*100000000000000}) df.to_csv('example.csv') os.system("cat example.csv") ,names,values 0,a,9.41843213808e+13 1,b,2.23837359193e+13 2,c,9.91801198906e+13 # if i set up float_format: df.to_csv('example.csv', float_format='{:f}'.format) ValueError: Unknown format code 'f' for object of type 'str' ``` How can I get the data saved in the csv without scientific notion like below? ``` names values 0 a 94184321380806.796875 1 b 22383735919307.046875 2 c 99180119890642.859375 ```
2018/03/09
[ "https://Stackoverflow.com/questions/49185133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1317643/" ]
The float\_format argument should be a str, use this instead ``` df.to_csv('example.csv', float_format='%f') ```
> > For python 3.xx (tested on 3.6.5 and 3.7): > > > [Options and Settings](https://pandas.pydata.org/pandas-docs/stable/options.html) [For visualization of the dataframe pandas.set\_option](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html#pandas.set_option) ``` import pandas as pd #import pandas package # for visualisation fo the float data once we read the float data: pd.set_option('display.html.table_schema', True) # to can see the dataframe/table as a html pd.set_option('display.precision', 5) # setting up the precision point so can see the data how looks, here is 5 df = pd.DataFrame({'names': ['a','b','c'], 'values': np.random.rand(3)*100000000000000}) # generate random dataframe ``` Output of the data: =================== ``` df.dtypes # check datatype for columns [output]: names object values float64 dtype: object ``` ### Dataframe: ``` df # output of the dataframe [output]: names values 0 a 6.56726e+13 1 b 1.63821e+13 2 c 7.63814e+13 ``` ### And now write *to\_csv* using the *float\_format='%.13f'* parameter ``` df.to_csv('estc.csv',sep=',', float_format='%.13f') # write with precision .13 ``` ### file output: ``` ,names,values 0,a,65672589530749.0703125000000 1,b,16382088158236.9062500000000 2,c,76381375369817.2968750000000 ``` ### And now write *to\_csv* using the *float\_format='%f'* parameter ``` df.to_csv('estc.csv',sep=',', float_format='%f') # this will remove the extra zeros after the '.' ``` ### file output: ``` ,names,values 0,a,65672589530749.070312 1,b,16382088158236.906250 2,c,76381375369817.296875 ``` [For more details check pandas.DataFrame.to\_csv](http://pandas.pydata.org/pandas-docs/version/0.19.1/generated/pandas.DataFrame.to_csv.html)
38,957,978
In the below example, I have a simple `<table>` with a checkbox inside it. I have click events on the td, tr and checkbox. I want to be able to click the checkbox and stop the bubbling to the td and tr. A simple "event.stopPropagation()" works great. The problem is that if I want to connect a `<label>` to the checkbox using "htmlFor", the events won't stop bubbling when the label is clicked (even though it still works as expected with the checkbox itself is clicked). And even more strangely, the bubbling seems to happen in a weird order (as in Checkbox click is received last!). Here's the code: ``` var Hello = React.createClass({ func1(e){ console.log('tr was clicked') }, func2(e){ console.log('td was clicked') }, func3(e){ e.stopPropagation(); console.log('Checkbox was clicked') }, render: function() { return <table> <tbody> <tr onClick={this.func1}> <td onClick={this.func2}> <input id="thing" type="checkbox" onClick={this.func3} /> <label htmlFor="thing"> label for checkbox</label> </td> </tr> </tbody> </table>; } }); ReactDOM.render( <Hello name="World" />, document.getElementById('container') ); ``` ...And here's the Fiddle: <https://jsfiddle.net/69z2wepo/52785/> (View the console for the click events)
2016/08/15
[ "https://Stackoverflow.com/questions/38957978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1809053/" ]
The `label` doesn't have a click handler of it's own, and can't stop propagation, so when you click the `label` normal event bubbling takes place. This means that all the parent's event handlers are invoked in the correct order. In addition, because of the `htmlFor`, the `checkbox` click handler is also triggered, but not as part of the event bubbling. To solve the problem, add a separate click handler to the `label` that only includes `.stopPropgation()` ([demo](https://jsfiddle.net/5wzbb77L/)): ``` var Hello = React.createClass({ func1(e){ console.log('tr was clicked') }, func2(e){ console.log('td was clicked') }, func3(e){ e.stopPropagation(); console.log('Checkbox was clicked') }, stopLabelPropagation(e) { e.stopPropagation(); }, render: function() { return <table> <tbody> <tr onClick={this.func1}> <td onClick={this.func2}> <input id="thing" type="checkbox" onClick={this.func3} /> <label htmlFor="thing" onClick={ this.stopLabelPropagation }>label for checkbox</label> </td> </tr> </tbody> </table>; } }); ReactDOM.render( <Hello name="World" />, document.getElementById('container') ); ```
Try wrapping with a span and add `evt.stopPropagation()` to span's onClick ``` <span onClick={evt => evt.stopPropagation()}> <input id="thing" type="checkbox" onClick={this.func3} /> <label htmlFor="thing"> label for checkbox</label> </span> ```
5,891,312
I have Entity Relationship Model (ERD) where entities `IndividualCategory` and `TeamCategory` relate to entity `Category`. Now I want to create tables in Oracle DB. I started like this: ``` CREATE TABLE Category( category_id INT PRIMARY KEY, ... ); CREATE TABLE Individual_category( category_id INT CONSTRAINT fk_cat_indivcat REFERENCES Category(category_id), ..., CONSTRAINT pk_indivgamecat PRIMARY KEY (category_id) ); CREATE TABLE Team_category( category_id INT CONSTRAINT fk_cat_teamcat REFERENCES Category(category_id), ..., CONSTRAINT pk_teamcat PRIMARY KEY (category_id) ); ``` This combination of *Foreign key* and *Primary key* constraints assures that for every `Individual_category` there will be corresponding record in `Category` "super" table (or "parent" table ?). And there will be only one `IndividualCategory` record for particular `Category` record. Same for `Team_category`. To enforce inheritance I need one more constraint: A constraint that assures that for every record in `Category` there will be either record in `IndividualCategory` (X)OR a record in `TeamCategory` but not both. How do I create such constraint ? --- **EDIT:** This is what I meant by 'inheritance in E-R model'. This is from my DB teacher's slides (they call it "Entity sub-type" there but they sometimes call it just inheritance):![enter image description here](https://i.stack.imgur.com/UqavU.png)
2011/05/05
[ "https://Stackoverflow.com/questions/5891312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/311865/" ]
A completely different way to do this using deferrable constraints: ``` CREATE TABLE Category( category_id INT PRIMARY KEY, team_category_id INT, individual_category_id INT, ... ); CREATE TABLE Individual_category( individual_category_id INT PRIMARY KEY, category_id INT NOT NULL, ..., ); CREATE TABLE Team_category( team_category_id INT PRIMARY KEY, category_id INT NOT NULL, ..., ); ``` Make sure a `Category` is a TeamCategory xor an IndividualCategory: ``` alter table Category add constraint category_type_check check ( (team_category_id is null and individual_category_id is not null) or (team_category_id is not null and individual_category_id is null) ); ``` Create deferrable integrity constraints so that one can insert a Category and Team/Individual\_Category within the same transaction; otherwise, you couldn't insert a Category before the TeamCategory/IndividualCategory, and vice-versa. A catch-22. ``` alter table category add constraint category_team_fk foreign key (team_category_id) references team_category (team_category_id) deferrable initially deferred; alter table category add constraint category_individual_fk foreign key (individual_category_id) references individual_category (individual_category_id) deferrable initially deferred; alter table individual_category add constraint individual_category_fk foreign_key (category_id) references category (category_id) deferrable initially deferred; alter table team_category add constraint team_category_fk foreign_key (category_id) references category (category_id) deferrable initially deferred; ```
ERD inheritance is a classic example of the gen-spec design pattern. There are numerous articles on how to design gen-spec in a relational DBMS like Oracle. you can find some of them by doing a Google search on "generalization specialization relational modeling". Much of what you will see in these articles has already been outlined by other responses to this question. This topic has surfaced many times in SO. For a sample prior discussion, [click here](https://stackoverflow.com/questions/3879806/data-modeling-question/3880673#3880673). The main feature of the classic solution is that the specialized tables have an id column that is both a primary key and a foreign key that references the id column of the generalized table. In this manner, the subentities do not acquire an identity of their own. The feature you really need to watch out for is the constraint that implements disjunction. Not all of the articles enforce this rule in their presented solution.
8,875,854
I am an experienced C++ programmer but new to Java. I have an algorithm that does some string manipulation and I want to terminate a string in the middle. Say, I want to do something like this ``` String str("hello, world"); char[] str2 = str.toCharArray(); //pass str2 to some function myFunc(str2); ... //inside myFunc, I decide to terminate str2 at position 3, so I did //str2[3] = 0 //then it returns, how can I construct an String type variable from str2 that includes chars before the '\0'? //String str3 = new String(str2), doesn't work ``` I can write my own C-liked `strlen`. However I would like to know what is the elegant way of doing it in Java. Also, it is hard to find document about type `char[]`. Whenever I Google, I can only find document on "char" instead of "char[]". I am thinking char[] may have methods liked `substr` or `strlen`. Thanks for any suggestion!
2012/01/16
[ "https://Stackoverflow.com/questions/8875854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903083/" ]
In Java, `char[]` and `String` are completely different. Forget the association from C, As far as you're concerned for now, they're not connected in any way. (For completeness, that `String` objects hold a `final char[]` representing the string (and it's *not* null-terminated), which you can obtain as you did in your example. Don't do that until you're clear on the difference.) You call all your methods on the string. But remember, in Java, `String`s are immutable - if you have a String, it will *always* be the same. You can assign a new String object to a variable, but the old string won't change (until all references are gone and it gets GC'd, of course). This is important to remember when you *are* trying to get a new string, like this. Once you've figured out how long you want your string, use `.substring()`. So your example should look something like this: ``` // Remember in Java no object is statically allocated. String str1 = "Hello, World"; int indexToCutAt = myFunc(str1); // We can't change str1, so we'll need to store the new string. String str2 = str1.substring(0,indexToCutAt); ```
Use java **substring** method [String#substring()](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring%28int%29) ``` str3 = str.substring(0, 3); ```
41,602,495
I want to inject some HTML to another HTML page dynamically like this : ``` <div id="jwplayer-player"> ... </div> ``` In the parent HTML page, there is CSS rules for DIV as generic (This is sample , may be different according to the page) : ``` div { margin-top: 15px; line-height: 200%; white-space: normal; } ``` How do I execlude my injected DIVs from being affected by them. The player is injected as follows : ``` <div id ="vid-player-container" class="player-container"></div> <script type="text/javascript"> document.write('<script type="text/javascript" src="some.site.com/jwplayer/jwplayer.js" ></script>'); document.write('<script type="text/javascript" src="some.script.com/player_style1.js"></script>'); </script> ``` If I try it alone outside those parent pages, works perfectly. So the key is isolating the injected code from being affected by the parent site, note that iFrame is not an option for me.
2017/01/11
[ "https://Stackoverflow.com/questions/41602495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4189602/" ]
I think you could use the ShadowDOM to achieve what you are trying to do. <https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM> It is designed to allow you to separate your components in this way, and provides isolation of CSS and JavaScript for the encapsulated DOM. ``` var shadow = document.querySelector('#container').attachShadow({mode: 'open'}); shadow.innerHTML += '<p>I am text in the injected code</p>' ``` For example: <https://jsfiddle.net/rn46rfgx/> If you inspect element on your page, you should be able to see the isolation: [![enter image description here](https://i.stack.imgur.com/a05HL.png)](https://i.stack.imgur.com/a05HL.png) *Disclaimer* : Whilst this probably works for you, I'm not sure if it is the **correct** way to do this or if it's a bit of a "hack" - I hope others will comment on this answer with their thoughts on this! Also, I'm not sure if the browser support will be adequate for you, you can check here: <http://caniuse.com/#feat=shadowdom>
Try ``` #jwplayer-player { margin-top: initial; line-height: initial; white-space: initial; } ``` It will change all those rules to its initial values - default. I am not sure if it will work in this case.
1,634,995
hey there could someone please help me determine the complexity?. An example given in my class was *bubble sort* ``` int main() { int a[10] = {10,9,8,7,6,5,4,3,2,1}; int i,j,temp; for (j=0;j<10;j++) { for (i=0;i<9;i++) { if (a[i] > a[i+1]) { temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } } } for (i=0;i<10;i++) { printf("%d ",a[i]); } } ``` which had a complexity of O(n^2) because it had two loops of O(n) hence O(n) x O(n). --- and they said quicksort has an complexity of O(nlog(n)) .. why is this? is it because as it goes around a loop it divides a number? -thanks
2009/10/28
[ "https://Stackoverflow.com/questions/1634995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197793/" ]
The previous answers describe quicksort and its running time pretty well, but I want to comment on the worst-case running time. It is true that quicksort in general is O(n log n) in the average case (given a random permutation of inputs) and O(n^2) in the worst case. However, quicksort in general doesn't specify which element to partition around at every step, so the O(n^2) case arises when you pick any element (usually the first or the last) as the pivot without regard to its relation to other elements in the list. You can implement quicksort to run in worst-case O(n log n) by choosing the pivot wisely. One method is to find the median in O(n) time. (See <http://en.wikipedia.org/wiki/Selection_algorithm#Linear_general_selection_algorithm_-_.22Median_of_Medians_algorithm.22>) Then if you always partition around the median, the number of times any element is examined is at most O(log n), so that the total running time is O(n log n).
Contrary to the opinion of all people here, the complexity of your program is O(1). You haven't defined what n is. I know, my answer seems a bit daft, but in practice it is often more important to find the bounds of your problem than the complexity of the algorithm. If your dataset will never be bigger than a given size, you may better use a simpler method which has good enough performance/behaviour.
14,651,187
*I´ve read a lot of posts about this but all of them were to limit the number digits to show them(NSString) .In my case I have:* I compare two double values(wich are the "same"), each of them got from different mathematical operations. For example: (4.800000 and 4.800000) double result1=4.800000, result2=4.800000 //compare the results: ``` if(result1==result2){ msg.text=@"well done!!"; }else if(result1>result2){ msg.text=@"continue your work"; } ``` "I´m working with money (4,80€)" In the msg label i get "continue your work" message, not the "well done". I don´t even know if the comparison is done in a correct way. I think that the best idea would be to limit 4.800000 to 4.80 in order to delete small values and get a exact comparison.(how could i do this?) I DONT WANT to limit the number to two digits just to PRINT the solution, I want to WORK with that number.
2013/02/01
[ "https://Stackoverflow.com/questions/14651187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479793/" ]
Generally speaking, you want a thread pool to service requests. A typical structure will start with a single thread that does nothing but queue up incoming requests. Since it doesn't do very much, it's typically pretty easy for one thread to keep up with the maximum speed of the network. That puts the items into some sort of concurrent queue. Then you have a pool of other threads reading items from the queue, doing what's needed, then depositing the result in another queue (and repeating, and repeating until the servers shuts down). Finally, you have another single thread that just takes items from the result queue, and sends replies out to the clients.
select or poll or epoll These are facilities on \*nix systems to aggregate multiple event sources (connections) into a single waiting point. The server adds the connections to a data structure, and then waits by calling select etc. It gets woken up when stuff happens on any of these connections, figures out which one, handles it, and then goes back to sleep. See manual for details. There are several higher level libraries built on top of these mechanisms, that make programming them somewhat easier e.g. libevent, libev etc.
11,055,897
For our app, we use the following code to check for internet connection whenever the app user is trying to post a message. When we test the feature, it works fine when turning on the airplane mode. Then when we turn off the airplane mode, the call to connected still returns NO. What could be the reason for that? Do we need extra "setup" in the order in order to get it right? such as listen to network state change notifications? ``` + (BOOL)connected { Reachability *hostReach = [Reachability reachabilityForInternetConnection]; NetworkStatus netStatus = [hostReach currentReachabilityStatus]; return !(netStatus == NotReachable); } ```
2012/06/15
[ "https://Stackoverflow.com/questions/11055897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180862/" ]
Apple Engineers have suggted that completely relying on Rechability. From a [SO post](https://stackoverflow.com/questions/12490578/should-i-listen-for-reachability-updates-in-each-uiviewcontroller#12490864) (source of blockquote) ``` On a WWDC talk this year the Apple engineer on stage recommended users to never base the application internet access on the Reachability example app status. Often reachability doesn't provide a complete information (it is based on a complex mechanism) and the suggestion provided by the engineer was this: 1. try to do your internet connection, whatever it is the Reachability status; then set your UI hint based on success/fail result 2. if it fails due to networking issue, then register to Reachability and retry again when Reachability gives the green light; this is needed when you want to recover automatically from the fail condition 3. in any case give the user the possibility to "force a retry", whatever is the Reachability status. If it succeeds, reset your UI hint immediately. ``` What I have done ? Every time I need to make a connection for example ``` NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://myadress.com"]]]; [self performSelectorOnMainThread:@selector(responseHandler:) withObject:data waitUntilDone:TRUE]; - (void)responseHandler:(NSData *)responseData { if(!responseData) { ReachabilityController *reachability = [[ReachabilityController alloc] init]; [reachability checkReachability]; return; } // you handle your data } ``` What is happening there is, the reachability will only be tested if the connection was failed. I have made a generic ReachabilityController that only deals with the reachability. I did it so, such that i could make calls from all the other controllers every time i make a request. My ReachabilityController.m looks like ``` -(void) checkReachability { Reachability* internetAvailable = [Reachability reachabilityForInternetConnection]; NetworkStatus netStatus = [internetAvailable currentReachabilityStatus]; NSString *messageText; if (netStatus == NotReachable) { messageText = [NSString stringWithFormat:@"Internet access not available"]; } else { Reachability *netReach = [Reachability reachabilityWithHostName:host]; NetworkStatus hostStatus = [netReach currentReachabilityStatus]; if (hostStatus == NotReachable) { messageText = [NSString stringWithFormat:@"Host Unreachable"]; } else { messageText = [NSString stringWithFormat:@"Problem with remote service"]; } } NSLog(@"%@", messageText); } ``` It won't crash your app, As you are handling the "nil" data parameter yourself and finally you are determining the cause. hope this helps! UPDATE: Apple may reject your app if you show a false message about the Internet Connectivity. They are very serious about their reputation with the iphone. If the internet connectivity is available but if your app reports that internet connectivity is unavailable, **It will be considered very serious**
You're using some kind of *convenience constructor* to check for reachability - this will not work. One of best examples of how to use reachability is found here on SO: <https://stackoverflow.com/a/3597085/653513> Or so what EricS suggests and don't use reachability at all - it's a viable option.
3,032,768
I have made an out-of-browser **silverlight** application which I want to **automatically update** every time there is a **new .xap file** uploaded to the server. When the user right-clicks the application and clicks on **Updates**, the default is set to "**Check for updates, but let me choose whether to download and install them**": [![alt text](https://i.stack.imgur.com/p1RCo.png)](https://i.stack.imgur.com/p1RCo.png) (source: [deviantsart.com](http://www.deviantsart.com/upload/uhjdal.png)) This leads me to believe that it is possible to make my Silverlight application automatically **detect** if there is a new .xap file present on the server, and if there is, the Silverlight client **will automatically** ask the user if he would like to install it. * This however is not the case. I upload a new .xap file and the Silverlight application **does nothing**. * Even if I add this to my **App.xaml.cs**: -- ``` private void Application_Startup(object sender, StartupEventArgs e) { this.RootVisual = new BaseApp(); if (Application.Current.IsRunningOutOfBrowser) { Application.Current.CheckAndDownloadUpdateAsync(); } } ``` and update the .xap file, the Silverlight application **does nothing**. * [This information](https://learn.microsoft.com/en-us/previous-versions/windows/silverlight/dotnet-windows-silverlight/dd730310(v=vs.95)) enabled me to check if there is an update and if so, tell the user to restart the application, but when he restarts the application, **nothing happens**: -- ``` private void Application_Startup(object sender, StartupEventArgs e) { this.RootVisual = new BaseApp(); if (Application.Current.IsRunningOutOfBrowser) { Application.Current.CheckAndDownloadUpdateAsync(); Application.Current.CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(Current_CheckAndDownloadUpdateCompleted); } } void Current_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e) { if (e.UpdateAvailable) { MessageBox.Show("An application update has been downloaded. " + "Restart the application to run the new version."); } else if (e.Error != null && e.Error is PlatformNotSupportedException) { MessageBox.Show("An application update is available, " + "but it requires a new version of Silverlight. " + "Visit the application home page to upgrade."); } else { //no new version available } } ``` **How do I make my Silverlight application check, each time it starts, if there is a new .xap file, and if there is, pass control to the Silverlight client to ask the user if he wants to download it, as the above dialogue implies is possible?**
2010/06/13
[ "https://Stackoverflow.com/questions/3032768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
The first dialog is about how updates to Silverlight itself are installed and has nothing to do with your application. Using the CheckAndDownloadUpdateAsync the new XAP should be downloaded automatically. Acording to the doc there is no way to prevent the new version from being installed one you call CheckAndDownloadUpdateAsync.
You might get what you're wanting by incorporating an external version control check. have it look to see if the version that's installed and the version on the server is different. If it's different ask the user if they want to update. If they choose yes, then invoke `CheckAndDownloadUpdateAsync();` otherwise skip it if they choose no or if the version is the same. there are many ways to do your own versioning checks. Including static readonly properties that are populated @ build time and have some kind of similar result on an http request. You could use the webclient to grab a response from the server and compare that with the currently loaded version of the application. You can incorporate a method on the callback to go to show a message that tells the user to restart the app.
9,241,054
My Android app has a tab bar that uses an Intent to launch the content in each tab, as in Android's API Demos [example](http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/Tabs3.html). I've put an AndEngine activity under one of the tabs. My first question is: is this a reasonable idea? Or if I'm using AndEngine, is it better to implement my app's whole UI in AndEngine? Assuming I'm not already onto a non-starter, the specific problem I've run up against is as follows. This AndEngine activity - the one I've incorporated in my tab-based app - is a simplified version of the AndEngine PinchZoom [example](https://github.com/nicolasgramlich/AndEngineExamples/blob/GLES2/src/org/andengine/examples/PinchZoomExample.java). It works well until you switch away from the tab and then back again. At that point, the view reappears, but you can't scroll or zoom any more. Here's my activity class. Let me know if you want to see the tab bar class too. As you can see, I've tried to switch off the various listeners and detectors when the user leaves the tab, and switch them back on when they return. But I've established, using a breakpoint, that `onSceneTouchEvent` isn't called when I touch the screen after returning to the tab. Is something intervening and capturing my touch events? Or is there something that goes inactive and needs to be brought back to life? I've also [posted](http://www.andengine.org/forums/gles2/what-s-the-right-way-to-integrate-zoom-with-a-tab-bar-t6847.html) this question on the AndEngine forums. **Edit:** Thanks for your suggestions, Guillaume. You're right that `onResumeGame` isn't called when the user returns to the tab. I thought I'd checked that, but I must have confused myself by putting the scrollable graphic under two tabs at once. The `onResume` method is called at that point, while `onCreateGame` isn't. I've therefore changed the code so that the touch detectors are switched on in `onResume`. This method is definitely being called when I want it to be, so I guess that's progress, but `onSceneTouchEvent` still isn't being triggered when I touch the screen after returning to the tab. The updated code is below, with the changes marked as `// NEW`. ``` public class HomeActivity extends SimpleBaseGameActivity implements IOnSceneTouchListener, IScrollDetectorListener, IPinchZoomDetectorListener { private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 628; private boolean mInitialised = false; // NEW private Scene mScene; private ZoomCamera mZoomCamera; private ITexture mTexture; private ITextureRegion mGrassTextureRegion; private SurfaceScrollDetector mScrollDetector; private PinchZoomDetector mPinchZoomDetector; private float mPinchZoomStartedCameraZoomFactor; @Override public EngineOptions onCreateEngineOptions() { this.mZoomCamera = new ZoomCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mZoomCamera); if (MultiTouch.isSupported(this)) { if (MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText( this, "MultiTouch detected, but your device has problems distinguishing between " + "fingers.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!", Toast.LENGTH_LONG).show(); } return engineOptions; } @Override public void onCreateResources() { try { this.mTexture = new BitmapTexture() { @Override protected InputStream onGetInputStream() throws IOException { return getAssets().open("gfx/background_grass.png"); } }.load(this.getTextureManager()); this.mGrassTextureRegion = TextureRegionFactory.extractFromTexture(mTexture); } catch (IOException e) { Debug.e(e); } } @Override public Scene onCreateScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setOnAreaTouchTraversalFrontToBack(); this.mScene.setBackground(new Background(0.09804f, 0.6274f, 0.8784f)); // Calculate the coordinates for the sprite, so it's centered on the // camera. final float centerX = (CAMERA_WIDTH - this.mGrassTextureRegion.getWidth()) / 2; final float centerY = (CAMERA_HEIGHT - this.mGrassTextureRegion.getHeight()) / 2; // Create the sprite and add it to the scene. final Sprite grass = new Sprite(centerX, centerY, this.mGrassTextureRegion, this.getVertexBufferObjectManager()); this.mScene.attachChild(grass); enableTouchDetectors(); // NEW mInitialised = true; // NEW return this.mScene; } @Override public void onPause() { this.mScene.setTouchAreaBindingOnActionDownEnabled(false); this.mScene.setOnSceneTouchListener(null); this.mPinchZoomDetector = null; this.mScrollDetector = null; super.onPause(); } // NEW method @Override public void onResume() { super.onResume(); // If returning to the tab, switch the touch detectors back on. if (mInitialised) { enableTouchDetectors(); } } // This method has been removed since Guillaume's answer. // @Override // public void onResumeGame() { // super.onResumeGame(); // this.mScrollDetector = new SurfaceScrollDetector(this); // this.mPinchZoomDetector = new PinchZoomDetector(this); // this.mScene.setOnSceneTouchListener(this); // this.mScene.setTouchAreaBindingOnActionDownEnabled(true); // } @Override public void onScrollStarted(final ScrollDetector pScollDetector, final int pPointerID, final float pDistanceX, final float pDistanceY) { } @Override public void onScroll(final ScrollDetector pScollDetector, final int pPointerID, final float pDistanceX, final float pDistanceY) { final float zoomFactor = this.mZoomCamera.getZoomFactor(); this.mZoomCamera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY / zoomFactor); } @Override public void onScrollFinished(final ScrollDetector pScollDetector, final int pPointerID, final float pDistanceX, final float pDistanceY) { } @Override public void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent) { this.mPinchZoomStartedCameraZoomFactor = this.mZoomCamera.getZoomFactor(); } @Override public void onPinchZoom(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor) { this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor); } @Override public void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor) { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { this.mPinchZoomDetector.onTouchEvent(pSceneTouchEvent); if (this.mPinchZoomDetector.isZooming()) { this.mScrollDetector.setEnabled(false); } else { if (pSceneTouchEvent.isActionDown()) { this.mScrollDetector.setEnabled(true); } this.mScrollDetector.onTouchEvent(pSceneTouchEvent); } return true; } // NEW method private void enableTouchDetectors() { this.mScrollDetector = new SurfaceScrollDetector(this); this.mPinchZoomDetector = new PinchZoomDetector(this); this.mScene.setOnSceneTouchListener(this); this.mScene.setTouchAreaBindingOnActionDownEnabled(true); } } ```
2012/02/11
[ "https://Stackoverflow.com/questions/9241054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]
you've set up your rails code so that it requires a call to `/hotels.json` in order to return json, but your backbone code is calling `/hotels` only. the easiest way to fix this is to have a separate api for json data, than for html pages. for example: `/hotels` returns html and `/api/hotels` return json. see Ryan Bate's Railscasts for an example of this (paid) <http://railscasts.com/episodes/323-backbone-on-rails-part-1> another option would be to change your Backbone models / collections so that they append the ".json" to the end of your urls. for example: ``` Backbone.Model.extend({ url: function(){ var url; if (this.isNew()){ url = "/hotels/" + this.id + ".json"; } else { url = "/hotels.json"; } return url; } }); ``` There are likely other options as well. These are just two that came up off the top of my head.
When your javascript application runs on a different domain, port or protocol than your server, strange things will happen. This is called Same Origin Policy. Just load the javascript from your rails server and everything will be fine.
34,280,094
In pandas.fillna, ``` method : {‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill gap ``` How can I fill values both backward and forward? None of the options seem to do this
2015/12/15
[ "https://Stackoverflow.com/questions/34280094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/308827/" ]
It seems very simple and there may be a quicker way, but simply chaining the two, like so ``` df.fillna(method='ffill').fillna(method='bfill') ``` This will fill forwards first and then backwards.
It depends on the precise result you are looking for and where are the NaNs in your dataframe. In the following situation you will see that only using two succesive `fillna` calls will actually pad the dataframe with values. The `interpolate` functions both fall short. ``` # Modules # import pandas from six import StringIO # Define # df = """ C | Y | S AA | 10 | NaN AA | 11 | NaN AA | 12 | 52 AA | 13 | 53 AA | 14 | 54 AA | 15 | NaN AA | 16 | NaN""" df = StringIO(df.replace(' ','')) df = pandas.read_csv(df, sep="|", header=0) # Show # print(df) print('------------') # This doesn't work (no propagation) # df['S'] = df['S'].interpolate(method='nearest') print(df) print('------------') # This work partially (propagation forward only) # df['S'] = df['S'].interpolate(method='pad') print(df) print('------------') # This works (propagation in both directions) # df['S'] = df['S'].fillna(method='ffill').fillna(method='bfill') print(df) print('------------') ```
72,316,073
Let's say I have 3 lists. Two of them are basic lists while the last one is an observable. The issue is I now want to merge a non-observable list into the observable one. Right now I do something like this but I feel like it's "against observables' nature" ``` listToMerge = [] listObs$: BehaviorSubject<[]> = new BehaviorSubject([]); listObsCopy = [] ``` I already added some elements in the listObs with the next method ``` listObs$.next(someStuff); listObsCopy = somestuff; ``` Here is my attempt to merge them. ``` listToMerge = listObsCopy.concat(someOtherStuff); listObs$.next(listToMerge as any); ```
2022/05/20
[ "https://Stackoverflow.com/questions/72316073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18710595/" ]
Issue <http://github.com/aspnet/Logging/issues/441> is closed and MS officially recommends to use 3rd party file loggers. Please see answers from: [How to log to a file without using third party logger in .Net Core?](https://stackoverflow.com/questions/40073743/how-to-log-to-a-file-without-using-third-party-logger-in-net-core)
A little different approach, but if you're using Datadog consider just writing to the Windows Event Viewer ``` public void WriteToEventLog(string sLog, string sSource, string message, EventLogEntryType level) { if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog); EventLog.WriteEntry(sSource, message, level); } ``` Then with Datadog: ``` - type: windows_event channel_path: System source: System service: eventlog log_processing_rules: - type: exclude_at_match name: exclude_information_event pattern: ^.*[Ll]evel.*Information.* ```
520,755
I'm designing a PCB with 4 layers, but I've seen different recommendations about layer distribution. I'm considering that: Top layer - Signal + short traces of VCC 2nd layer - Signal 3rd layer - VCC 4th layer - GND Can I fill all area around with ground in each plane and place several vias to connect grounds across the layers? Can I have the VCC layer filled with ground plane? The circuit has a nordic + lora radio in one module castellation. Output antenna has a connector over the module already, so no need to design microstrip lines. What is the minimum recommended power trace width for a 3.3 V and 150 mA maximum? Shall I have very large traces in 3rd layer and not filled with ground around?
2020/09/09
[ "https://electronics.stackexchange.com/questions/520755", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/262643/" ]
Your stackup is a poor choice in most cases. Most 4 layer stackups are like ``` Top thin insulator Mid 1 Thick insulator Mid 2 Thin insulator Bottom. ``` So your stackup places your signal traces far away from any reference plane. The most common arrangement would be to use mid1 for ground and mid 2 for power, this means that all signal traces are close to a reference plane, but it has the downside that you can't just couple the two reference planes directly with a via, but instead they can only be coupled through a capacitor. This impacts signal integrity when a signal changes planes. Another option would be to use both mid1 and mid2 for ground. This would allow better signal integrity on reference plane changes, but would mean your power would need to be routed on a signal layer. It can make sense to swap the layers around, for example if you want EMI shielding on the bottom then you might put the ground on the bottom, ground or power on mid1 and signals on top and mid2 but you should generally always have one signal layer and one power/ground layer in each pair.
Signal, Ground, Power, Signal is the most common 4 layer board stack up. In many cases when this is used the power plane acts like a return plane for the signals on the bottom layer. Ideally not all the layers are equally spaced depending on what you are trying to accomplish. **Remember engineering is always a trade of something for something else.** Something to ask yourself is how important is the decoupling of your 3.3V to Ground? Is it most important to protect your wireless signal from radiation? See the link below for some 4 layer board combinations and the trade offs. <http://www.hottconsultants.com/techtips/pcb-stack-up-2.html>
170,259
I have webex installed on ubuntu 12.04 with wine as per the instructions at [this link](http://my.opera.com/rembrant/blog/2011/11/16/installing-webex-player-on-ubuntu-11-04-arf). I'm able to open .arf files but the video is not showing up. This is the output i get when i open the application using terminal ``` wine: Call from 0x7b839cf2 to unimplemented function msvcp90.dll.??0?$basic_stringstream@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QAE@H@Z, aborting ``` EDIT : i'm trying to play an .arf file - the file works fine on windows but on my setup in ubuntu it is not working.
2012/07/31
[ "https://askubuntu.com/questions/170259", "https://askubuntu.com", "https://askubuntu.com/users/22589/" ]
1. Install WINE 2. Download the MSI installer from the webex web-site <http://www.webex.com/play-webex-recording.html> 3. Right click on it and install using WINE 4. Run the player from the terminal wine "/home/username/.wine/drive\_c/Program Files (x86)/WebEx/WebEx/500/nrplay.exe"
The tool does not like any *whitespace*, neither in the directory path where it is residing nor the MP4 directory. The directory path and filename of the file to be converted must not contain any whitespace either. So no whitespace anywhere -)
5,521,518
I have been searching for over an hour and I can not for the life of me figure out how to search a string variable starting on the right. What I want to do is to get the last folder of a path (right before the file name), In VB6 I would do something like this: ``` Dim s As String s = "C:\Windows\System32\Foo\Bar\" Debug.Print Mid(s, InStrRev(Left(s, Len(s) - 1), "\") + 1) ``` Here is what I tried so far: ``` string s = "C:\\Windows\System32\\Foo\\Bar\\"; s = agencyName.Substring(s.LastIndexOf("\\") + 1) ```
2011/04/02
[ "https://Stackoverflow.com/questions/5521518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/100283/" ]
Presumably you want to ignore the last `\` in the string, because your VB code is searching all but the last character. Your C# code isn't working because it's searching the whole string, finding the `\` as the last character in the string, causing your substring to return nothing. You have to tell `LastIndexOf` to start at the character before the last one just as you did in VB. I think the equivalent to your VB code would be: ``` s = s.Substring(s.LastIndexOf("\\", s.Length - 2) + 1) ```
``` var fullPath = @"C:\foo\bar\file.txt"; var folderName = new FileInfo(fullPath).Directory.Name; //folderName will be "bar" ``` Edit: Clarified example
251,204
I want to fade out an element and all its child elements after a delay of a few seconds. but I haven't found a way to specify that an effect should start after a specified time delay.
2008/10/30
[ "https://Stackoverflow.com/questions/251204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
``` setTimeout(function() { $('#foo').fadeOut(); }, 5000); ``` The 5000 is five seconds in milliseconds.
I use this pause plugin I just wrote ``` $.fn.pause = function(duration) { $(this).animate({ dummy: 1 }, duration); return this; }; ``` Call it like this : ``` $("#mainImage").pause(5000).fadeOut(); ``` Note: you don't need a callback. --- **Edit: You should now use the [jQuery 1.4. built in delay()](http://api.jquery.com/delay/) method. I haven't checked but I assume its more 'clever' than my plugin.**
49,500,213
I'm trying to join my `users` table with my `jobs` table based on a mapping table `users_jobs`: Here is what the `users` table looks like: ``` users |--------|------------------| | id | name | |--------|----------------- | | 1 | Ozzy Osbourne | | 2 | Lemmy Kilmister | | 3 | Ronnie James Dio | | 4 | Jimmy Page | |---------------------------| ``` `jobs` table looks like this: ``` |--------|-----------------| | id | title | |--------|-----------------| | 1 | Singer | | 2 | Guitar Player | |--------------------------| ``` And `users_jobs` table looks like this: ``` |--------|-------------|-------------|---------------|-------------| | id | user_id | job_id | column3 | column4 | |--------|-------------|-------------|---------------|-------------| | 1 | 1 | 1 | 0 | 1 | | 2 | 2 | 1 | 1 | 0 | | 3 | 3 | 1 | 0 | 1 | | 4 | 4 | 2 | 1 | 0 | |----------------------|-------------|---------------|-------------| ``` For example, let's say the ozzy does a query. Here is what should expect: ``` |--------|------------------|------------|--------- | | id | name | column3 | column4 | |--------|----------------- |------------|----------| | 1 | Ozzy Osbourne | 0 | 1 | | 2 | Lemmy Kilmister | 1 | 0 | | 3 | Ronnie James Dio | 0 | 1 | |---------------------------|------------|----------| ``` Basically, he can only see the job in which he is registered (role) and the users included. I tried to do this: ``` SELECT u1.*, uj1.colum3, uj1.column4 FROM users AS u1 JOIN users_jobs AS uj1 ON uj1.user_id = 1 JOIN jobs AS j1 ON j1.id = up1.job_id WHERE uj1.job_id = 1 ``` Any help would be great!
2018/03/26
[ "https://Stackoverflow.com/questions/49500213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6454033/" ]
I found a solution. Using @stackFan approach adding an `EXISTS` clause to make sure that the user is in. ``` SELECT u.id, u.column3 , u.column4 FROM users u INNER JOIN user_jobs uj on u.id = uj.user_id INNER JOIN jobs j on j.id = uj.job_id WHERE uj.job_id = <job-ID> AND EXISTS ( SELECT * FROM users_jobs AS uj WHERE uj.job_id = <job-ID> AND uj.user_id = <user-ID> ); ```
Try `LEFT JOIN`. It will display all users, whether they have job or not. ``` SELECT u.id, u.name, uj.colum3, uj.column4 FROM users AS u LEFT JOIN users_jobs uj ON uj.user_id = u.id LEFT JOIN jobs j ON j.id = uj.job_id ```
28,780,675
please read my code ask solution how to create folder public class CameraActivity extends ActionBarActivity { ``` private static final int ACTION_TAKE_IMAGE = 1; Button btnImage; ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); imageView = (ImageView)findViewById(R.id.imageView); btnImage= (Button) findViewById(R.id.buttonCapture); btnImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent takeVideoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(takeVideoIntent, ACTION_TAKE_IMAGE); } }); } ``` @onActivityResult start ``` @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { try { AssetFileDescriptor imageAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r"); FileInputStream fis = imageAsset.createInputStream(); File root=new File(Environment.getExternalStorageDirectory(),"/Vipul/RecordImage/"); if (!root.exists()) { System.out.println("No directory"); root.mkdirs(); } File file; file=new File(root,"IMG_"+System.currentTimeMillis()+".jpg" ); FileOutputStream fos = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = fis.read(buf)) > 0) { fos.write(buf, 0, len); } fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } if(requestCode == ACTION_TAKE_IMAGE && resultCode == RESULT_OK){ Bundle bundle = data.getExtras(); Bitmap imageBitmap = (Bitmap) bundle.get("data"); imageView.setImageBitmap(imageBitmap); } } } ``` this code work 2.3 capture Image but work and not create folder not store in my specific folder please ask your answer
2015/02/28
[ "https://Stackoverflow.com/questions/28780675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4565853/" ]
try this code ``` public class CameraActivity extends ActionBarActivity { // private static final int ACTION_TAKE_IMAGE = 1; Button btnImage; ImageView imageView; File image; String picturePath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); imageView = (ImageView) findViewById(R.id.imageView); btnImage = (Button) findViewById(R.id.buttonCapture); btnImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE); //Create folder File imagesFolder = new File( Environment.getExternalStorageDirectory(), "Vipul/image"); imagesFolder.mkdirs(); //Asign name for image String fname = "Pic-" + System.currentTimeMillis() + ".png"; image= new File(imagesFolder, fname); Uri uriSavedImage = Uri.fromFile(image); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage); //launch camera app with result code (forResult) startActivityForResult(cameraIntent, 1); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1 && resultCode == RESULT_OK) { Bitmap bitmap; BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); picturePath=image.getAbsolutePath(); bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bitmapOptions); imageView.setImageBitmap(bitmap); } } } ``` final solution
To use different name for image everytime you can use method getTimeInMillis() as `Calendar mCalendar = Calendar.getInstance(); String n = ""+mCalendar.getTimeInMillis(); String fname = "Pic-" + n.substring(5) + ".png"; //Asign name for image File image = new File(imagesFolder, fname); Uri uriSavedImage = Uri.fromFile(image);`
2,426,230
I'm trying to port the following Java snippet to Scala. It takes a list of `MyColor` objects and merges all of the ones that are within a delta of each other. It seems like a problem that could be solved elegantly using some of Scala's functional bits. Any tips? ``` List<MyColor> mergedColors = ...; MyColor lastColor = null; for(Color aColor : lotsOfColors) { if(lastColor != null) { if(lastColor.diff(aColor) < delta) { lastColor.merge(aColor); continue; } } lastColor = aColor; mergedColors.add(aColor); } ```
2010/03/11
[ "https://Stackoverflow.com/questions/2426230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111777/" ]
I'm assuming that you somehow have your colors arranged in the list such that colors "close" in color space (i.e. with a low `diff` value) are adjacent in the list. Then I'd use a fold: ``` val unmergedColors: List[MyColor] = ... val mergedColors = (Nil:List[MyColor] /: unmergedColors)( (list,c) => { list match { case oldc :: rest if (oldc.diff(c) < delta) => oldc.merge(c) :: rest case _ => c :: list } }).reverse ``` Here, I'm assuming that `merge` is altered to take return a new color that is the previous two merged (so that your colors are immutable); otherwise, you'd `oldc.merge(c) ; list` in the first case. Let's see what's going on here. We start with an empty list for the new colors. Then, for each color in the unmerged list, we have two cases: * The merged list has a head, and the color of the head is within delta of the color we're testing. In that case, merge the head and the new color, and pass along the saved list with the new head. * Otherwise, add the new color to the front of the growing list and pass it along. Finally, since we're using these as stack operations, we finish off by reversing the list.
I'd try folding: ``` def merge(lotsOfColor: List[MyColor], delta: Double): List[MyColor] = lotsOfColor.tail.foldLeft((List(lotsOfColor.head), lotsOfColor.head)) { case ((mergedColors, lastColor), aColor) if (lastColor diff aColor) < delta => (mergedColors, lastColor merge aColor) case ((mergedColors, _), aColor) => (aColor :: mergedColors, aColor) }._1.reverse ``` Or, slightly different, ``` def merge(lotsOfColor: List[MyColor], delta: Double): List[MyColor] = lotsOfColor.tail.foldLeft((List(lotsOfColor.head), lotsOfColor.head)) { case ((mergedColors, lastColor), aColor) => if ((lastColor diff aColor) < delta) (mergedColors, lastColor merge aColor) else (aColor :: mergedColors, aColor) }._1.reverse ``` There's also another cool trick using ListBuffer in Scala, to avoid the reverse at the end: ``` import scala.collection.mutable.ListBuffer def merge(lotsOfColor: List[MyColor], delta: Double): List[MyColor] = lotsOfColor.tail.foldLeft((ListBuffer(lotsOfColor.head), lotsOfColor.head)) { case ((mergedColors, lastColor), aColor) if (lastColor diff aColor) < delta => (mergedColors, lastColor merge aColor) case ((mergedColors, _), aColor) => mergedColors += aColor (mergedColors, aColor) }._1.toList ```
5,929,765
I am trying to order by lowest however this sql term below order's by highest number ``` SELECT * FROM questions ORDER BY question_ref DESC LIMIT 1; ``` Any help would be appreciated
2011/05/08
[ "https://Stackoverflow.com/questions/5929765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/393273/" ]
Use `ASC` instead of `DESC`: ``` SELECT * FROM questions ORDER BY question_ref ASC LIMIT 1; ```
Using ascending rather than descending ordering should do the trick: `SELECT * FROM questions ORDER BY question_ref ASC LIMIT 1;`
1,110,404
So, if I try to remove elements from a Java *HashSet* while iterating, I get a *ConcurrentModificationException*. What is the best way to remove a subset of the elements from a *HashSet* as in the following example? ``` Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i < 10; i++) set.add(i); // Throws ConcurrentModificationException for(Integer element : set) if(element % 2 == 0) set.remove(element); ``` Here is a solution, but I don't think it's very elegant: ``` Set<Integer> set = new HashSet<Integer>(); Collection<Integer> removeCandidates = new LinkedList<Integer>(); for(int i = 0; i < 10; i++) set.add(i); for(Integer element : set) if(element % 2 == 0) removeCandidates.add(element); set.removeAll(removeCandidates); ``` Thanks!
2009/07/10
[ "https://Stackoverflow.com/questions/1110404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can manually iterate over the elements of the set: ``` Iterator<Integer> iterator = set.iterator(); while (iterator.hasNext()) { Integer element = iterator.next(); if (element % 2 == 0) { iterator.remove(); } } ``` You will often see this pattern using a `for` loop rather than a `while` loop: ``` for (Iterator<Integer> i = set.iterator(); i.hasNext();) { Integer element = i.next(); if (element % 2 == 0) { i.remove(); } } ``` As people have pointed out, using a `for` loop is preferred because it keeps the iterator variable (`i` in this case) confined to a smaller scope.
you can also refactor your solution removing the first loop: ``` Set<Integer> set = new HashSet<Integer>(); Collection<Integer> removeCandidates = new LinkedList<Integer>(set); for(Integer element : set) if(element % 2 == 0) removeCandidates.add(element); set.removeAll(removeCandidates); ```
71,550,031
I'm having trouble understanding how to properly end a firestore trigger. From what I read from [this](https://stackoverflow.com/questions/69931652/returning-null-from-firebase-cloud-function-background-triggers) and [this](https://stackoverflow.com/questions/59561961/do-i-need-to-explicitly-end-firebase-cloud-functions-triggered-by-firestore-ev), it seems you should only return null to end a function if there's no async code such as to quickly end if a condition isn't met. When I return null in my scenario below, it seems to work fine. Is there a better practice for what I'm doing that I'm missing? I need to log my own custom error message which why I need the catch. I know I could return Promise.all here instead of null in the try block, but this is just sudo code for my scenario. ``` export const delacc = functions.auth.user().onDelete(async (user) => { const userUID = user.uid; try{ await admin.firestore().collection("users").doc(userUID).delete(); await admin.firestore().collection("spam").doc(userUID).delete(); await admin.firestore().collection("photos").doc(userUID).delete(); return null; }catch(error){ functions.logger.error(error) return null } }); ```
2022/03/20
[ "https://Stackoverflow.com/questions/71550031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17483742/" ]
First, select the Pictures you want by ids list: ``` var pictures = _dbContext.Pictures .Where(s => ids.Contains(s.Id)); ``` Second, calculate the IsAnnotated field with foreach - this is not a case of 'select', this is an update case. (Convert to 'List' for using the ForEach linq function, you can use the foreach statement instead): ``` pictures.ToList().ForEach(a => a.IsAnnotated = _dbContext.Annotations.Any(x => x.PictureId == a.Id)); ```
You can do something like this. ``` Var pictures = _dbcontext.Pictures.Where(x=> IDs.Contains(x.id)); var annotations = await pictures.Join(_dbContext.annotation, pic => pic.id, ann => ann.pictureId, (pic, ann) => new { Annotation = ann.IsAnnotated }.ToListAsync(); ``` Or instead an anonymous type you can pass a model if you want. Sorry if it's not readable but I wrote it from my phone!!
438,312
Let $W\_t$ be a Wiener process with $W\_0=0$, and let $L=\{at+by=c\}$ be a line with $c/b<0$ (i.e. the line crosses the $Y$-axis below $0$). Assume that $W\_t$ stayed above $L$ up to time $T$. What is the PDF of $W\_T$ under this assumption? Does it have a closed form?
2023/01/11
[ "https://mathoverflow.net/questions/438312", "https://mathoverflow.net", "https://mathoverflow.net/users/64302/" ]
The problem can be restated as follows: > > For a real $a>0$ and a real $b$, let > $$X\_t:=a+bt+W\_t$$ > for real $t\ge0$, where $W$ is a standard Wiener process. Let > $$\tau:=\inf\{t>0\colon X\_t=0\}.$$ > For a real $t>0$, find the joint distribution of $X\_t$ and $\tau$. > > > The answer is well known: $$P(X\_t\in dx,\tau>t)=f\_t(x-a-bt)(1-e^{-2ax/t})\,1(x>0)\,dx, \tag{1}\label{1}$$ where $f\_t$ is the pdf of $W\_t$. A derivation of this formula can be found [here](https://works.bepress.com/iosif-pinelis/24/).
As I mentionned in my comment, there is an ambiguity in the statement of you question. Anyway, if $B$ is a standard one dimensional Brownian motion, if $\lambda$ is a real number, then $(B\_t-\lambda t)$ is a diffusion. The joint distribution of its position and its current minimum at time $T$ can be derived from <http://www.numdam.org/item/AIHPB_1987__23_2_179_0.pdf> And there are probably more elementary methods to get this distribution. This provides an answer.
616,254
Background: I'm attempting to derive the Friedmann Equations in Mathematica. The code works with the FLRW metric employing natural units where c=1. However, to insure the calculation works for all cases, I'm inputting other versions of known metrics see if the result are still correct. When I switch from natural units, space negative:$$d\tau^2=\text{d}t^2-a(t)^2\left(\dfrac{\text{d}r^2}{1-kr^2}+r^2(\text{d}\theta^2+\text{sin}^2\theta\text{d}\phi^2)\right)$$to SI units, space positive:$$d\tau^2=i^2c^2dt^2+ a(t)^2\left(\dfrac{\text{d}r^2}{1-kr^2}+r^2(\text{d}\theta^2+\text{sin}^2\theta\text{d}\phi^2)\right)$$I get some strange results coming from the Perfect Fluid tensor calculation. I believe it has to do with the interpretation of the velocity vector in the formula found [here](https://en.wikipedia.org/wiki/Perfect_fluid). When working with space negative natural units, we have:$$U^\mu=\{1,0,0,0\}$$$$T^{\mu\nu}=\left(\rho+p\right)U^\mu U^\nu-p\space g^{\mu\nu}$$$$T^{\mu\nu}= \begin{bmatrix} \rho&0&0&0 \\ 0&\frac{p-k p r^2}{\dot a^2}&0&0\\ 0&0&\frac{p}{r^2a^2}&0\\ 0 & 0 & 0 & \frac{p\space Csc^2 \theta}{r^2a^2} \end{bmatrix}$$ When I'm working with the second metrics in SI units, we have: $$U^\mu=\{c,0,0,0\}$$$$T^{\mu\nu}=\left(\rho+\frac{p}{c^2}\right)U^\mu U^\nu-p\space g^{\mu\nu}$$$$T^{\mu\nu}= \begin{bmatrix} p+\frac{p}{c^2}+c^2\rho&0&0&0\\ 0&\frac{p(-1+k\space r^2)}{\dot a^2}&0&0\\ 0&0&-\frac{p}{r^2a^2}&0\\ 0&0&0&-\frac{p\space Csc^2 \theta}{r^2a^2} \end{bmatrix}$$The $T^{00}$ term appears to screw up the results from this point on. Oddly, if I go back to using $U^0=1$, then $T^{00}=\frac{2p}{c^2}+\rho$ the calculations work again inasmuch as the pressure cancels out of the first Friedmann equation. However, doing this this appears to be mixing SI units with natural units unless $U$ is interpreted as a basis vector. So here's my question: **How is the velocity vector of the fluid interpreted for this tensor?** It appears from my experimentation that it should be a basis vector, not the actual velocity (that is, ${e\_\mu}$ instead of $U^\mu$), but the notation indicates that we're dealing with the actual velocity vector of the fluid. A perfect fluid should have no motion, so the velocity vector should be $\{c, 0, 0, 0\}$ I would think. What have I got wrong? **EDIT:** In this [post](https://physics.stackexchange.com/questions/411934/stress-energy-tensor-for-a-perfect-fluid-in-general-relativity), the author gives an example and seems to be using the velocity vectors, $U$, as basis vectors during the addition of the two tensors. Is this right?
2021/02/21
[ "https://physics.stackexchange.com/questions/616254", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/260164/" ]
A conceptual error: The parallel axis theorem is used to find the inertial moment about an **rotating axis** which is not the CM. In this problem, the disk is not rotating about the CM (for rock and disc joint system) but it rotates around the center of disk. Therefore, it should be think in decomposing the motion into motion of the center of the disk around the CM, and the rotation around the center of disk. $$ L\_{disc-total} = L\_{disc-around-CM} + L\_{disc-rotation-around-disc-center}. $$ Therefore, in the beginning, the rock and disk are both not moving w.r.t the CM (between rock and disk center: $$ L\_i = 0 + 0 + \frac{1}{2} mR^2 \omega\_0. $$ In the final motion, the rock is rotating around the CM, and the disc center is also rotating around the CM, in order to keep the center of mass fixed. Besides, the disc has additional rotation about the disc center. All these rotations are of a same frequence $\omega\_f$ for syncronization. $$ L\_f = L\_{rock} + L\_{disc} = L\_{rock} + \left( L\_{disc-center} + L\_{disk-rotation} \right),\\ = \frac{1}{4}mR^2 \omega\_f +\left( \frac{1}{4}mR^2 \omega\_f + \frac{1}{2}mR^2 \omega\_f\right) \\ = mR^2 \omega\_f. $$ Then applying $L\_i = L\_f$, render $$ \omega\_f = \frac{1}{2} \omega\_0. $$
This problem has a major difference from many similar textbook problems dealing with the conservation of angular momentum. In many of the textbook problems the axis of rotation of the disk about its center of mass (CM) is fixed by a constraining force/torque and does not move. If that were the case here, the axis of rotation would not move when the stone is placed (and moves) on the disk. The problem would be addressed considering angular momentum of the disk/stone about the fixed axis of rotation. Here, the disk is on a frictionless table and its axis of rotation can move, but is always perpendicular to the table surface. The problem is best evaluated considering the angular momentum about the center of mass of the disk/stone system. Denote the center of mass of the system consisting of the disk and the stone as CMS (center of mass of system). Due to conservation of linear momentum the CMS does not move. To keep CMS fixed as the stone moves (rotates on the disk), the CM of the disk moves and rotates about the CMS. Also, the disk rotates about its own CM, and the stone rotates about the CMS. Angular momentum is conserved. The overall motion is as quantified in an earlier answer by @ytlu.
205,593
I'am trying to check whether a user is logged-in or not; with `\Drupal::currentUser()->id()` I am getting the user ID for the anonymous user (i.e. 0), even though I'm logged in. How can I resolve this? I'm just calling this function in the `.module` file, and it is not run from cron. I am using the following code. ``` use Drupal\Core\Session\UserSession; use Drupal\Core\Session\AccountInterface; $user = \Drupal::currentUser(); if ($user->isAuthenticated()) { echo 'logged-in'; } else { echo 'guest'; } ``` [![enter image description here](https://i.stack.imgur.com/Id90O.png)](https://i.stack.imgur.com/Id90O.png)
2016/06/29
[ "https://drupal.stackexchange.com/questions/205593", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/62722/" ]
Try this. ``` use Drupal\Core\Session\AccountInterface; function mymodule_function() { $account = \Drupal::currentUser(); if ($account->isAuthenticated()) { // User is logged in. } } ``` Refer the below Link for more details <https://www.drupal.org/node/2017231>
It appears that the code in the original post is not in any function, it's just in the global spec of whichever file it's in, so the current user probably hasn't been loaded yet.
49,836,702
The situation is that when I modify a `Card` view background from a program then the corner radius of the `Card` view reset. But why? *(I don't think I need to provide any other information (code, picture of the result, etc.), because I think it's clear enough to understand. If you need more information then you should write down in a comment.)*
2018/04/14
[ "https://Stackoverflow.com/questions/49836702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9377499/" ]
I found a solution to the question. I needed to retrieve the background of the view and set its color, then I assigned the new background to the view. ``` Drawable backgroundOff = v.getBackground(); //v is a view backgroundOff.setTint(defaultColor); //defaultColor is an int v.setBackground(backgroundOff); ``` *(This answer helped: <https://stackoverflow.com/a/18394982/9377499>)*
Same problem and fix the problem this way At first, create the shape named in Drawable "shape\_background\_cardview" and this add below code ``` <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/gray500" /> <corners android:radius="5dp" /> </shape> ``` step second, set the shape to the background CardView yourself ``` yourCardView.setBackgroundResource(R.drawable.shape_background_cardview); ``` GoodLuck
39,722,694
In my conversion program I am using a dictionary to gives names to specific rows read from a pre defined text file. Then creating a multidimensional array named "Rows" an error occurs: > > An item with the same key has already been added. > > > The following piece of code is written: ``` Dictionary<string, int> rows = new Dictionary<string, int>(); // The file "read.txt" is being read string[] lines = File.ReadAllLines("read.txt"); int[] array = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // In this section each line is being read and the spacing is removed foreach (string s in lines) { string[] arr = s.Split(' '); // This line ables the program to differ between variables and numbers. for (int i = 0; i < arr.Length; i++) { array[i] = Convert.ToInt32(arr[i]); // arr is now converted into a Int. rows.Add("array" + i, array[i]); } } ``` Then debugging the error occurs then the loop is ended. Why does the error appear and how do I fix it?
2016/09/27
[ "https://Stackoverflow.com/questions/39722694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6822608/" ]
If you have multiple lines, you will start at `"array" + i` == `array0` again. That item has already been added to the dictionary, hence the exception. You have to keep in mind to number the lines too, so maybe you should format it like `"array" + "line" + lineNumber + "row" + i` or so.
You probably want to associate *multiple* int's to the key in the dictionary. A Dictionary won't do for this, but rather a ``` Dictionary<string, List<int>> or Dictionary<string, HashSet<int>> ``` If you are using ("array" + i) as key, an int would do it. Initializing an array with many 0's is not very nice, rather use new int[n]. With these small changes, here is my updated version: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StackOverflow { class Program { static void Main(string[] args) { Dictionary<string, HashSet<int>> rows = new Dictionary<string, HashSet<int>>(); // The file "read.txt" is being read string[] lines = new string[] { "1", "2", "1 2"}; //File.ReadAllLines("read.txt"); // In this section each line is being read and the spacing is removed foreach (string s in lines) { string[] arr = s.Split(' '); // This line ables the program to differ between variables and numbers. int[] array = new int[arr.Length]; for (int i = 0; i < arr.Length; i++) { array[i] = Convert.ToInt32(arr[i]); // arr is now converted into a Int. string key = "array" + i; if (!rows.ContainsKey(key)) rows.Add(key, new HashSet<int>()); rows[key].Add(array[i]); } } foreach (string key in rows.Keys) { Console.WriteLine($"{key}: {String.Join(", ", rows[key])}"); } } } } ``` Many further improvements are possible.
303,864
My system (Debian squeeze) uses anti-aliasing for fonts, which is fine for the most part. However, I would like to disable it for terminal fonts in xterm and urxvt (rxvt-unicode), and can't get that to work. I tried using `antialias=false`, like explained e.g. in the [urxvt man page](http://linux.die.net/man/1/urxvt) (search for "antialias"), but it does not have any effect: ``` urxvt -fn "xft:Deja Vu Sans Mono:pixelsize=10:antialias=false" ``` I get exactly the same font rendering, no matter if I use `antialias=true` or `false`. The font face and size I specify do have an effect, so urxvt apparently processes the option. Same result with xterm (using `-fa`), or when putting `Xft*antialias: false` into my X resources (as proposed in [How can I turn off font-antialiasing only for gnome-terminal, but not for other applications?](https://superuser.com/questions/130267/how-can-i-turn-off-font-antialiasing-only-for-gnome-terminal-but-not-for-other-a)). What am I doing wrong? Is there some other setting? **Edit:** Just found out that I *can* disable anti-aliasing in `/etc/fonts/local.conf`: ``` <match target="font"> <edit name="antialias" mode="assign"> <bool>false</bool> </edit> </match> ``` Still, I don't understand why `antialias=false` is not respected in a font spec.
2011/06/29
[ "https://superuser.com/questions/303864", "https://superuser.com", "https://superuser.com/users/5026/" ]
Usually xterm does not apply antialiasing to fonts. However, I think some windowmanagers like compiz generally apply antialias to windows, hence your problem would be your window manager, not your terminal emulator. Try checking your window manager for antialiasing and try disabling it.
xterm actually work with font antialiasing like below. > > ~/.Xdefaults > > > ``` !xterm font antialiasing variant xterm*faceName: DejaVu Sans Mono:size=10:antialias=true xterm*font: 7x13 !rxvt-unicode fontantialiasing variant URxvt*font: xft:DejaVu Sans Mono:pixelsize=12:antialias=true:hinting=true URxvt*boldFont: xft:DejaVu Sans Mono:bold:pixelsize=12:antialias=true:hinting=true ``` As I investigated simple rxvt (without unicode) doesn't support font antialiasing. The reason why I prefer xterm today (2015) is lesser amount of memory consumed by xterm when is opened then urxvt. Rxvt consumes even lesser amount of memory then xterm, but it doesn't support font antialiasing.
18,308,972
I am using PlayN to build a game involving stone a user has to move in a physic world (with gravity etc.) I want the user to be able to manipulate directly the stones using the touch pad and give them a velocity by dragging and throwing them. For now I have an implementation where every stone is on his own layer and I have a listener on the stone layer that would deactivate the physics for this stone body (when the user grabs it) and reactivate once the drag is finished. The problem is the listener callback seems to be executed with a delay meaning that many frames are displayed before reactivation of the physics engine is taken into account leading to delay in the stone falling after the user stopped the grabbing. Are there other approaches for such behaviors ? Am I missing something ? Thanks ! ``` layer.addListener(new Pointer.Adapter() { @Override public void onPointerStart(Event event) { suspendPhysik = true; getBody().setActive(!suspendPhysik); } @Override public void onPointerEnd(Event event) { suspendPhysik = false; getBody().setActive(!suspendPhysik); long deltatime = System.currentTimeMillis() - prevTimestamp; Vec2 velocity = new Vec2((event.x() * NewGame.physUnitPerScreenUnit - prevX) / deltatime, (event.y() * NewGame.physUnitPerScreenUnit - prevX) * NewGame.physUnitPerScreenUnit / deltatime); getBody().setLinearVelocity(velocity); } @Override public void onPointerDrag(Event event) { x = event.x() * NewGame.physUnitPerScreenUnit; y = event.y() * NewGame.physUnitPerScreenUnit; setPos(event.x() * NewGame.physUnitPerScreenUnit, event.y() * NewGame.physUnitPerScreenUnit); } });` ```
2013/08/19
[ "https://Stackoverflow.com/questions/18308972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2534331/" ]
Found an interesting presentation about playN. <http://playn-2011.appspot.com/slides/index.html#34> In the example the author uses following code: ``` touch().setListener(new Touch.Adapter() { @Override public void onTouchStart(Event[] touches) { // Process touch events into a zoom start position. } @Override public void onTouchMove(Event[] touches) { // Update zoom based on touches. } }); ``` This link contains the docs for the Touch.Adapter <http://docs.playn.googlecode.com/git/javadoc/playn/core/Touch.Adapter.html#Touch.Adapter()> So try this: ``` layer.addListener(new Touch.Adapter() { @Override public void onTouchStart(Touch.Event[] touches) { suspendPhysik = true; getBody().setActive(!suspendPhysik); } @Override public void onTouchMove(Touch.Event[] touches) { suspendPhysik = false; getBody().setActive(!suspendPhysik); long deltatime = System.currentTimeMillis() - prevTimestamp; Vec2 velocity = new Vec2((touches[0].x() * NewGame.physUnitPerScreenUnit - prevX) / deltatime, (event.y() * NewGame.physUnitPerScreenUnit - prevX) * NewGame.physUnitPerScreenUnit / deltatime); getBody().setLinearVelocity(velocity); } @Override public void onTouchMove(Touch.Event[] touches) { x = touches[0].x() * NewGame.physUnitPerScreenUnit; y = touches[0].y() * NewGame.physUnitPerScreenUnit; setPos(x * NewGame.physUnitPerScreenUnit, y * NewGame.physUnitPerScreenUnit); } }); ```
The best way I found to handle this type of problem is actually to use a MouseJoint in Box2d. Suspending the physic is not the correct approach as it breaks the simulation (among other things, the body will not be taken into account for collisions) I will post some links I found explaining the different possible approaches...
14,369,032
I can compile from the command line by running **vcvarsall.bat**, then running **cl.exe** with my source file as the only argument. The problem is that just running **cl.exe** without first setting up the environment using the aforementioned batch file causes errors due to "missing libraries". I can picture a couple of workarounds to this, for example creating a batch file in my project directory that includes **vcvarsall.bat** and does all the compiling. That seems to me to be a very cumbersome and inflexible solution though. I would much prefer to be able to compile and run any C or C++ file from Vim like one would in Unix: ``` :nnorebind <F5> :! g++ %<CR> ``` I don't want to add the pile of paths that **vcvarsall.bat** adds to the environment permanently though. I don't know how to phrase my question any better than this: How do I set up Vim to be able to use the Visual Studio 2010 C++ compiler?
2013/01/16
[ "https://Stackoverflow.com/questions/14369032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388916/" ]
You can update environment variables from within Vim. For instance, to add "c:\foo" to the start of your PATH: ``` let $PATH='c:\\foo;'.$PATH ``` I copied the relevant portions of my vcvars\*.bat file to my vimrc: ``` if !exists("visual_studio_paths_added") let visual_studio_paths_added = 1 let $PATH="C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\BIN;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\Tools;C:\\Windows\\Microsoft.NET\\Framework\\v3.5;C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\VCPackages;C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\bin;".$PATH let $INCLUDE="C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\ATLMFC\\INCLUDE;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\INCLUDE;C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\include;".$INCLUDE let $LIB="C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\ATLMFC\\LIB;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\LIB;C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\lib;".$LIB let $LIBPATH="C:\\Windows\\Microsoft.NET\\Framework\\v3.5;C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\ATLMFC\\LIB;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\LIB;".$LIBPATH endif ``` Adapt as needed given your version of Visual Studio and installation directory. In my case, I put this in a function. I call `:vcvars` when I want to work with Visual Studio. But you could just have those changes always included.
Expanding on the comment by David Rodríguez - dribeas, and seeing how `vcvarsall.bat` accepts parameters, I found it helpful to have the following file in my source trees: `vc.bat`: ``` call "%VS100COMNTOOLS%\..\..\VC\vcvarsall.bat" amd64 & %* ``` Adjust MSVS version and platform as appropriate, or make them additional parameters if you like. The `%VS...COMNTOOLS%` environment variable is set by the MSVC installer, which makes the above independent of the actual installation path. This allows me to run any `<command>` in the proper MSVC environment by running it as: ``` vc.bat <command> ``` If called without parameters, it will just set the environment for the current shell without executing any further commands. If you want to go one step further, there is [CMake](http://www.cmake.org), a meta-buildsystem that allows you to generate Unix Makefiles, MSVC solutions and several other buildfile types from a single (CMake syntax) configuration. One of the buildfile types supported on Windows are *NMake Makefiles*... and `nmake <target>` on Windows handles just about as well as `make <target>` does on Unix.
161,977
It seems like I am only able to centre my zoom around the camera and no longer with the object I've made. I can't even really zoom in that far at all anymore either. This is my first time trying to make something on Blender so I am very unfamiliar with the program, but none of the suggestions for solutions I've found online have been of any help. (Also I am on a MacBook)
2019/12/27
[ "https://blender.stackexchange.com/questions/161977", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/86010/" ]
Welcome to Blender! Have you tried changing the camera lock settings? Press `N` to bring up the sidebar. On the right-hand side of the sidebar, press the *View* tab then expand the *View Lock* options. Here, you can toggle locking to the 3D cursor, to View, or to an object. If you would like your view to always rotate around the selected object, press, in the top left corner, press *Edit* > *Preferences.* Open the *Navigation* tab, and check *Orbit around selection.* Please note that your viewport will still rotate around the 3D cursor if that option is checked in the sidebar mentioned above. PS: If you're looking for a good beginner's tutorial series, check out the [Donut Tutorial series by BlenderGuru](https://www.youtube.com/playlist?list=PLjEaoINr3zgEq0u2MzVgAaHEBt--xLB6U)
This sounds like it would be solved with the "Show Active" action. You can select the object you want to zoom into and execute the "Show Active" command. To use Show Active, hit full stop (.) on the number pad. Since you're on a Macbook and probably don't have a number pad, you should make sure you have "emulate numpad" selected in Preferences>interface>input. Usually, you hit a controller to indicate you're entering numpad emulation, then you use the numbers across the top of your keyboard. (I don't know what controller yours is set to, sometimes it's [backspace], sometimes it's [/].) You can also create your own keymap options on "keymap" in the same interface tab and assign the "Show Active" action to a particular keystroke. Good luck.
7,641,013
I have added some testers to my Facebook application while it is still in Sandbox mode. I have already added them as testers within a group called testers. However, they are having issues accessing the application directly (while logged in) and the APPs page. Do these testers need a developer ID to access my application in Sandbox mode?
2011/10/03
[ "https://Stackoverflow.com/questions/7641013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54627/" ]
Problem solved on my end. Apparently when you add people as testers they don't get a "Developer App" invite like people added as developers do, so the testers need to make sure they are approved for the Developer App at <https://developers.facebook.com/apps>. Then they should be able to get to your sandboxed app and approve its permissions. The reason for the fact that some people could access it and others not in my case from my group, was that the ones that could access it from the group had already at some point in their past approved the developer app unknown to me. So it seems all users of my group can now access the sandboxed app, but they have to allow the dev app first.
No, I don't think they do. I have recently added a friend as a tester and they do not have a developer ID/added the developer application. My app is still in sandbox mode and is an iframe app btw.
35,910,001
In my magento website, whenever i am trying to view the product details page,its not loading the product details page properly,after the Product Image its not displaying anything. [![enter image description here](https://i.stack.imgur.com/6tHx8.png)](https://i.stack.imgur.com/6tHx8.png)
2016/03/10
[ "https://Stackoverflow.com/questions/35910001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6041121/" ]
In order to invoke a controller method from the directive you need to create a "reference" function with `&` scope configuration: ``` .directive('radio', () => { return { restrict: 'E', replace: true, templateUrl: 'radio', scope: { data: '=', onupdate: '&' } }; }) ``` Then from directive template you need to call it like this: ``` ng-click="onupdate({data: $parent.data});" ``` And finally the usage of the radio directive becomes: ``` <radio onupdate="vm.save(data)" data="model.myradio1" /> ```
Hello I stick to your **question title** '*how to call controller function from directive*'. I've made an example that uses a `<select>` element and calls the controller function `$scope.filterHall()` to send the selected object, whenever the user changes value. **Directive** (i get the changeHall function and i call it into the template,see below ): ``` .directive('eventHallsList', function($timeout, $log, $http, $compile) { return { restrict: 'AE', replace: true, scope: { changeHall: '&', items: '=', model: '=' }, templateUrl: 'mytemplate.tpl.html', link: function(scope, element, attrs) { } } }); ``` **Template:** **Into the select element everytime the user selects a value, i call the `changeHall()` which is bind to the controller's function `$scope.filterHall()` , and it pass the object.** ``` <select style="color:#337ab7" ng-change="changeHall({value:model})" ng-model="model" ng-options="item as item.name for item in items"> <option value=""> choose hall</option> </select> ``` live example : <http://plnkr.co/edit/iCS0blQjceA4tIIb8bUV?p=preview> Hope helps, good luck.
69,894,036
I have a dataframe where columns are numneri ``` asd <- data.frame(`2021`=rnorm(3), `2`=head(letters,3), check.names=FALSE) ``` But when I reference the columns names as variable, it is returning error ``` x = 2021 asd[x] Error in `[.data.frame`(asd, x) : undefined columns selected ``` Expected output ``` x = 2021 asd[x] 2021 1 1.5570860 2 -0.8807877 3 -0.7627930 ```
2021/11/09
[ "https://Stackoverflow.com/questions/69894036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16935119/" ]
Use `deparse` ``` asd[,deparse(x)] [1] 1.3445921 -0.3509493 0.5028844 asd[deparse(x)] 2021 1 1.3445921 2 -0.3509493 3 0.5028844 ```
If the value is numeric, just convert to character with `as.character` - column/row names attributes are all `character` values ``` asd[as.character(x)] 2021 1 -0.4438473 2 -0.8904154 3 -0.9319593 ```
29,142
How could one put, in a single word, language that has multiple meanings at once?
2011/06/09
[ "https://english.stackexchange.com/questions/29142", "https://english.stackexchange.com", "https://english.stackexchange.com/users/9607/" ]
There's also [polysemous](http://dictionary.reference.com/browse/polysemous) or [polysemantic](http://dictionary.reference.com/browse/polysemantic), both of which mean "having many meanings."
you do it [ostensibly](http://www.wordnik.com/words/ostensibly/) > > "So maybe there’s a legal convention > concerning how definitions such as > this are to be > circumscribed/overridden/whatever by > the common English meaning however > vague by comparison of the term > ostensibly being defined?" *— The > Volokh Conspiracy » **Hate Crimes and > Double Jeopardy:*** > > > I just realized that if your word has at least two meanings at the same time that you might be referring to something [ironic](http://www.wordnik.com/words/ironic) > > > ``` > –adjective > Both coincidental and contradictory in a humorous or > poignant and extremely improbable way. > > ``` > > *It is ironic that Einstein, who was > such a revolutionary young man, was > reduced to irrational denial of > quantum mechanics in his later years.* > > >
52,552,143
This question is related to [Applying Cost Functions in R](https://stackoverflow.com/questions/42372821/applying-cost-functions-in-r/42374307) I would like to know how to save the coefficients generated for each iteration of `optim`. `trace=TRUE` enables me to get the coefficients for each iteration printed, **but how can I save them**? Example code: ``` set.seed(1) X <- matrix(rnorm(1000), ncol=10) # some random data Y <- sample(0:1, 100, replace=TRUE) # Implement Sigmoid function sigmoid <- function(z) { g <- 1/(1+exp(-z)) return(g) } cost.glm <- function(theta,X) { m <- nrow(X) g <- sigmoid(X%*%theta) (1/m)*sum((-Y*log(g)) - ((1-Y)*log(1-g))) } X1 <- cbind(1, X) df <- optim(par=rep(0,ncol(X1)), fn = cost.glm, method='CG', X=X1, control=list(trace=TRUE)) ``` Which outputs: > > > ``` > Conjugate gradients function minimizer > Method: Fletcher Reeves > tolerance used in gradient test=2.00089e-11 > 0 1 0.693147 > parameters 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 > 0.00000 0.00000 0.00000 0.00000 > i> 1 3 0.662066 > parameters -0.01000 -0.01601 -0.06087 0.14891 0.04123 0.03835 -0.01898 > 0.00637 0.02954 -0.01423 -0.07544 > i> 2 5 0.638548 > parameters -0.02366 -0.03733 -0.13803 0.32782 0.09034 0.08082 -0.03978 > 0.01226 0.07120 -0.02925 -0.16042 > i> 3 7 0.630501 > parameters -0.03478 -0.05371 -0.19149 0.43890 0.11960 0.10236 -0.04935 > 0.01319 0.10648 -0.03565 -0.20408 > i> 4 9 0.627570....... > > ``` > > And `df`does not contain any information on the coefficients, but only displays the final coefficients and the final cost: ``` str(df) ``` > > > ``` > List of 5 > $ par : num [1:11] -0.0679 -0.1024 -0.2951 0.6162 0.124 ... > $ value : num 0.626 > $ counts : Named int [1:2] 53 28 > ..- attr(*, "names")= chr [1:2] "function" "gradient" > $ convergence: int 0 > $ message : NULL > > ``` > >
2018/09/28
[ "https://Stackoverflow.com/questions/52552143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1993932/" ]
``` ## use `capture.output` to get raw output out <- capture.output(df <- optim(par=rep(0,ncol(X1)), fn = cost.glm, method='CG', X=X1, control=list(trace=TRUE))) ## lines that contain parameters start <- grep("parameters", out) param_line <- outer(seq_len(start[2] - start[1] - 1) - 1, start, "+") ## parameter message param_msg <- gsub("parameters", "", out[param_line]) ## parameter matrix (a row per iteration) param <- matrix(scan(text = param_msg), ncol = length(df$par), byrow = TRUE) ## inspect output (rounded to 2-digits for compact display) head(round(param, 2)) # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] # [1,] 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 # [2,] -0.01 -0.02 -0.06 0.15 0.04 0.04 -0.02 0.01 0.03 -0.01 -0.08 # [3,] -0.02 -0.04 -0.14 0.33 0.09 0.08 -0.04 0.01 0.07 -0.03 -0.16 # [4,] -0.03 -0.05 -0.19 0.44 0.12 0.10 -0.05 0.01 0.11 -0.04 -0.20 # [5,] -0.04 -0.07 -0.23 0.51 0.14 0.11 -0.05 0.01 0.14 -0.04 -0.22 # [6,] -0.05 -0.08 -0.25 0.55 0.14 0.12 -0.05 0.01 0.16 -0.04 -0.23 tail(round(param, 2)) #[23,] -0.07 -0.10 -0.30 0.62 0.12 0.13 -0.03 -0.01 0.21 -0.04 -0.21 #[24,] -0.07 -0.10 -0.30 0.62 0.12 0.13 -0.03 -0.01 0.21 -0.04 -0.21 #[25,] -0.07 -0.10 -0.30 0.62 0.12 0.13 -0.03 -0.01 0.21 -0.04 -0.21 #[26,] -0.07 -0.10 -0.30 0.62 0.12 0.13 -0.03 -0.01 0.21 -0.04 -0.21 #[27,] -0.07 -0.10 -0.30 0.62 0.12 0.13 -0.03 -0.01 0.21 -0.04 -0.21 #[28,] -0.07 -0.10 -0.30 0.62 0.12 0.13 -0.03 -0.01 0.21 -0.04 -0.21 ## one way to visualize the search steps matplot(param, type = "l", lty = 1, xlab = "iterations") ``` [![](https://i.stack.imgur.com/Oxrvf.jpg)](https://i.stack.imgur.com/Oxrvf.jpg)
So, the other solution works... but involves parsing the response inside the trace. Here's an approach that gives you access to the objects directly. (And would be general in any other optimization function that doesn't allow you to easily show a text trace): (This works because you can assign inside of an environment from within a function) EDIT: This adds another row every time cost.glm is run, not just every time the trace is evaluated. Also added the conversion to the matrix format used by the other solution. ``` set.seed(1) X <- matrix(rnorm(1000), ncol=10) # some random data Y <- sample(0:1, 100, replace=TRUE) # Implement Sigmoid function sigmoid <- function(z) { g <- 1/(1+exp(-z)) return(g) } # Create environment to store output # We could also use .GlobalEnv params_env <- new.env() # Initialize parameters object params_env$optim_run <- list() cost.glm <- function(theta,X) { # Extend the list by 1 and insert theta inside the given environment # This can be done more efficiently by # extending several at a time, but that's easy to add. n <- length(params_env[['optim_run']]) params_env[['optim_run']][[n + 1]] <- theta m <- nrow(X) g <- sigmoid(X%*%theta) (1/m)*sum((-Y*log(g)) - ((1-Y)*log(1-g))) } X1 <- cbind(1, X) df <- optim(par=rep(0,ncol(X1)), fn = cost.glm, method='CG', X=X1, control=list(trace=TRUE)) # View list of all param values print(params_env$optim_run) # Return as same format as other solution param <- do.call(rbind, params_env[['optim_run']]) matplot(param, type = "l", lty = 1, xlab = "iterations") ``` [![As we can see, there are more jumps in this set as cost.glm explores the space](https://i.stack.imgur.com/AqEKx.png)](https://i.stack.imgur.com/AqEKx.png)
52,419,505
On my script I need to match two words after a specific command executed. I need to greep on **karaf-ids** and **DEPLOYED** I used `grep -F` but it don't match exactly the first word and the second after ``` #helm ls NAME REVISION UPDATED STATUS CHART NAMESPACE cantankerous-abalone 1 Mon Sep 3 14:54:53 2018 FAILED karaf-0.0.215 karaf hissing-albatross 1 Mon Sep 3 14:57:14 2018 FAILED karaf-0.0.215 karaf karaf-ids 1 Thu Sep 20 08:18:28 2018 DEPLOYED karaf-ids-0.0.339 karaf-ids ``` I continue to searching for a solution ...
2018/09/20
[ "https://Stackoverflow.com/questions/52419505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9923968/" ]
``` awk '$1 == "karaf-ids" && $8 == "DEPLOYED"' ``` prints any line which matches these criteria. If that's not what you want, add something like `{ print $3, $4, $5, $6, $7 }` to print just the date, for example.
If you need to match two words (word1 AND word2) with `grep` you have 2 choices: If the order of words is known: ``` $ grep word1.*word2 file ``` or if the order is unknown: ``` $ grep word1 file | grep word2 ``` In your case they both work. If you want to use a list of words to search from file (`grep -F`), you can't use `grep`, use awk: ``` $ awk ' NR==FNR { a[$0] next } { for(i in a) if($0!~i) next }1' list file ``` Output on your data: ``` karaf-ids 1 Thu Sep 20 08:18:28 2018 DEPLOYED karaf-ids-0.0.339 karaf-ids ``` All of the solutions will fail for partial matches.
20,710,766
I have a website for my business coded entirely in HTML. No CSS at all. The problem is that every page except my index.html home page is scaling the text (on android) and reflowing it so that it is a readable size on the page. So my question is: how would I go about making my website display properly on mobile devices using only HTML?
2013/12/20
[ "https://Stackoverflow.com/questions/20710766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1527258/" ]
``` ?modestbranding=1&autohide=1&showinfo=0&controls=0 autohide=1 ``` is something that I never found... but it was the key :) I hope it's help
To remove you tube **`controls`** and **`title`** you can do something like this ```html <iframe width="560" height="315" src="https://www.youtube.com/embed/zP0Wnb9RI9Q?autoplay=1&showinfo=0&controls=0" frameborder="0" allowfullscreen ></iframe> ``` [code with output](https://jsfiddle.net/umanguSp/pt5gcv2r/) `showinfo=0` is used to remove title and `&controls=0` is used for remove controls like **volume**,**play**,**pause**,**expend**.
48,095,622
I have a tab system which uses some Javascript to switch tabs. I want them to fade in and out when you switch tabs. The JS at the moment just removes and adds the clicked tab the user chooses. I have made the fade in JS kind of work however it does not remove tabs. ```js $(document).ready(function() { $('ul.tabs li').click(function() { var tab_id = $(this).attr('data-tab'); $('ul.tabs li').removeClass('current'); $('.tab-content').removeClass('current'); $(this).addClass('current'); $("#" + tab_id).addClass('current'); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="container"> <div class="col-md-6"> <ul class="tabs"> <li class="tab-link current" data-tab="tab-1">Tab One</li> <li class="tab-link" data-tab="tab-2">Tab Two</li> <li class="tab-link" data-tab="tab-3">Tab Three</li> <li class="tab-link" data-tab="tab-4">Tab Four</li> </ul> </div> <div class="col-md-6"> <div id="tab-1" class="tab-content current"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </div> <div id="tab-2" class="tab-content"> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div> <div id="tab-3" class="tab-content"> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> <div id="tab-4" class="tab-content"> Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </div> </div> </div> <!-- container --> ```
2018/01/04
[ "https://Stackoverflow.com/questions/48095622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8113906/" ]
`AbstractQueuedSynchronizer` provides lots of `public` methods and it is very unlikely that all of them make sense as part of your own `public` API. Exposing those unwanted methods can distract from the your actual API or even harm the stability of your code. Even worse, the API of this class could evolve, providing even more methods, you can’t know beforehand whether they are suitable for your use case. Note that a lot of the concurrency tools of the `java.util.concurrent` package use this class internally, without exposing all of the AQS methods. Also, using `AbstractQueuedSynchronizer` internally allows you to switch to another class, e.g. Java 6 introduced `AbstractQueuedLongSynchronizer`, while in Java 5 there was only `AbstractQueuedSynchronizer`, and some of the classes of the `java.util.concurrent` might have switched since then, without you noticing.
AbstractQueuedSynchronizer is a framework that provides blocking mechanish for FIFO like structures. You can see many blocking structures extending this class's functionality to implement locking mechanism. For example you can see ReentrantLock class providing fair/unfair locking through Sync class which extends AQS. Regarding internal classes, it's a case of Composition. The internal classes exist only exists to help their parent class. I hope it helps.
14,749,404
I change the content of an UIView by clicking of some UIButtons. (Buttons and UIView are included in the same UIScrollView) For Example: Case 1: I add content and raise the height of the View and the ScrollView. Case 2: I remove content and reduce the height of the View and the ScrollView. At both cases i set the scroll position: ``` [newsScrollView setContentOffset:CGPointMake(0,240) animated:YES]; ``` At Case 1 it worked fine and the ScrollView shows the right content, but at case 2 it scroll at the bottom of the ScrollView. Does someone knows where 's the mistake?
2013/02/07
[ "https://Stackoverflow.com/questions/14749404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862913/" ]
Almost all money in the world IS "purely representative of your money, its just a value in a database"! The next part of money is the paper money which in a sense real in that it's physical but it can become worthless at any time if the government who backs the paper goes belly up. After that comes physical stuff like gold, but that's extremely impractical. So basically what I'm saying is that web apps that handle money just have values in a database! The ones that are properly written take great care to test and validate the code that handles "money" and of course uses database transactions like hoang already said to avoid duplicating money or losing money in the system. I hope this answer makes you a little less confortable with how money is handled in the modern world :P
It boils down to a secure token that can be trusted, I can issue a cheque for an amount and send it to you, you go to the bank and get that honoured/paid A cheque can be "written" (I use the term loosely, because it can also be a barcode or an encrypted code) in any way (Bullet cases have been used and honoured) So all it really is is a promise "I promise to pay the bearer"
17,502,337
I have a problem...what's a nondeterministic procedure? I have this exercise Provide a nondeterministic procedure for the following language: L = {: G=(V,E) has an Indipendent Set I s.t. |I| >= k and the vertices V\I form a Hamilton cycle} Thanks!
2013/07/06
[ "https://Stackoverflow.com/questions/17502337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2057119/" ]
A non-deterministic procedure or function is a procedure that for a given input value will *not* always produce the same output. For example: DateTime.GetCurrent would be non-deterministic. Random.Next() would be non-deterministic. Math.Sin() would hopefully be deterministic. If you enter the same value 10 times you will get the same result 10 times.
A non-deterministic function can rely on an "oracle". In your example, the oracle would produce the set `I` and the function only needs to check whether it has specified properties, i.e. `I` is independent, `|I| >= k` and `V\I` forms a Hamilton cycle.
34,019,990
In my app/views/phrases/\_forms.html.erb, I have a button with an id which I want to show or hide a particular section with id preview-section. ``` <%= button_tag(type: 'button', class: "btn btn-default", id: 'preview-button') do %> Preview <% end %> <section id="preview-section"> Some Content </section> ``` I'm not sure where to place the jquery in the rails app. ``` $('#preview-button').click(function () { alert("Preview button was clicked"); }); ```
2015/12/01
[ "https://Stackoverflow.com/questions/34019990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3561894/" ]
Pre-standard C had no `void*` but only `char*`, so you had to cast all parameters passed. If you come across ancient C code, you might therefore find such casts. [Similar question with references](https://stackoverflow.com/questions/32652213/why-does-the-book-say-i-must-cast-malloc). When the first C standard was released, the prototypes for malloc and free changed from having `char*` to the `void*` that they still have today. And of course in standard C, such casts are superfluous and just harm readability.
Here is another alternative hypothesis. We are told that the program was written pre-C89, which means it can't be working around some kind of mismatch with the prototype of `free`, because not only was there no such thing as `const` nor `void *` prior to C89, there was no such thing as a *function prototype* prior to C89. `stdlib.h` itself was an invention of the committee. If the system headers bothered to declare `free` at all, they would have done it like this: ``` extern free(); /* no `void` return type either! */ ``` Now, the key point here is that the absence of function prototypes meant the compiler did *no argument type checking*. It applied the default argument promotions (the same ones that still apply to variadic function calls) and that was it. Responsibility for making the arguments at each callsite line up with the callee's expectations lay *entirely* with the programmer. However, this still doesn't mean it was necessary to cast the argument to `free` on most K&R compilers. A function like ``` free_stuff(a, b, c) float *a; char *b; int *c; { free(a); free(b); free(c); } ``` should have been compiled correctly. So I think what we've got here is a program written to cope with a buggy compiler for an unusual environment: for instance, an environment where `sizeof(float *) > sizeof(int)` and the compiler *wouldn't* use the appropriate calling convention for pointers unless you cast them at the point of the call. I am not aware of any such environment, but that doesn't mean there wasn't one. The most probable candidates that come to mind are cut-down "tiny C" compilers for 8- and 16-bit micros in the early 1980s. I also wouldn't be surprised to learn that early Crays had problems like this.
710,393
I have read this question: [![enter image description here](https://i.stack.imgur.com/iuEcV.png)](https://i.stack.imgur.com/iuEcV.png) <http://hyperphysics.phy-astr.gsu.edu/hbase/Forces/funfor.html> > > So , in a nutshell, it is the fitting of data with a specific standard model that organizes the particle interactions in line with four forces. > > > [How do physicists compare the relative strengths of the four forces?](https://physics.stackexchange.com/questions/516169/how-do-physicists-compare-the-relative-strengths-of-the-four-forces) We do have data, because we do know how fast the galaxies are flying apart, and this is in mainstream physics accounted for to the existence of dark energy. Is there a way to put dark energy into this table and somehow match its strength compared to the other forces?
2022/05/24
[ "https://physics.stackexchange.com/questions/710393", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/132371/" ]
As mentioned in the other answer, we can take $\mathbf{q}$ to point in the $z$-direction: $$\int \frac{d^3k}{(2\pi)^3} \theta(k\_F - k)(\mathbf{k}\cdot\mathbf{q})^n = \int d\Omega\int\_{0}^{k\_F}\frac{dkk^2}{8 \pi^3} (kq\cos{\theta})^n$$ $$=\frac{q^n}{4\pi^2}\int\_{-1}^{1}\cos^n\theta ~d(\cos\theta)\int\_{0}^{k\_F}k^{n+2}dk$$ $$=\frac{q^n [1+(-1)^n]}{4\pi^2(n+1)(n+3)}k\_F^{n+3}$$
The integral is spherically symmetric so we can put $\mathbf{q}$ along the $z$-axis: $$\int \frac{d^3k}{(2\pi)^3} \theta(k\_F - k)(\mathbf{k}\cdot\mathbf{q})^n = \int d\Omega\int\_{0}^{k\_F}\frac{k^2dk}{8 \pi^3} (kq\cos{\theta})^n$$ the integral then factorizes $$\frac{q^n}{4\pi^2}\int\_{-1}^{1}\cos^n\theta ~d(\cos\theta)\int\_{0}^{k\_F}k^{n+2}dk$$ which is simply $$\frac{q^n [1+(-1)^n]}{4\pi^2(n+1)^2}k\_F^{n+3}$$
419,016
I faced a strange problem with the following circuit. [![The circuit](https://i.stack.imgur.com/OfjRX.png)](https://i.stack.imgur.com/OfjRX.png) I'm using some buck converters and an Arduino. The buck converter (Vout = 5.25v) is for a USB charger (up to 2 Amps). Well, I think the circuit itself has no problem, but in fact there is a problem due to electrostatic charges. Let's suppose that I touch the open-state USB cable with some electrostatic charge (caused by friction of my clothes). Then the Arduino's voltage is influenced in this situation. I coded the Arduino to respond to the voltage fluctuation of the circuit and the Arduino tells me the fluctuation has occurred. If the electrostatic charge is big enough, Arduino reboots! I know the electrostatic charge causes the problem, but how can I cease the problem? Some intuitions for the solution will be appreciated. This just occurs very few times but I don't like this. If I can do, I want to solve this problem. * USB is used with Dedicated Charger Port (DCP) mode.
2019/01/26
[ "https://electronics.stackexchange.com/questions/419016", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/208458/" ]
The conventional way to deal with externally applied ESD is to protect the circuit with TVS diodes and ESD clamp devices. There are a plethora of these types of devices in the market including a slew of them designed specifically for USB applications.
Use apparel that grounds you before using any kind of electronics. I personally screwed up a monitor while disassembling it because of electrostatic charge. The easiest thing to do is touching grounded metal pieces every few minutes. If that's irritating, buy an ESD mat to stand on. Also, I bought a device that I can wear on my wrist and attach a wire to a grounded metal. I don't remember what it's called though. I'll update it after going back home.
27,003
I am starting to write some functions while studying how to program in C. In this small function I take a string as an argument and print it out in reverse order. ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { int aLen = argc; char *sWord = argv[aLen - 1]; char *reversed; int sLen = strlen(sWord); int i = 0; reversed = reversed + sLen; // offset pointer to the length of string while (i <= sLen) { if (sWord[i] != '\0') { // check if character is null-terminator *reversed = sWord[i]; // if not, let reversed correct address } // equal letter. i++; reversed--; } printf("%s reversed is:%s\n", sWord, reversed); return 0; } ``` I was hoping to get some tips on best practice or corrections on any errors.
2013/06/04
[ "https://codereview.stackexchange.com/questions/27003", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/17028/" ]
Your code has a number of issues, the main one being that it doesn't work. If you want to reverse a string in place then I suggest you write a function just for that, separate from `main`. The function will need a temporary variable and will, for example: ``` swap first and last characters swap 2nd and 2nd-from-last characters swap 3rd and 3rd-from-last characters etc ``` To swap the characters pointed to by `a` and `b`, you would do ``` char temp = *a; *a = *b; *b = *temp; ``` or if you have a pointer and a length: ``` char temp = a[0]; a[0] = b[len]; b[len] = temp; ``` So your reversal function needs to contain one of these sequences in a loop and the loop must arrange `a` and `b` to point to the correct places. For example, here is a reverse function: ``` static char* reverse(char *str) { char *s = str; char *end = s + strlen(s) - 1; for (; s < end; ++s, --end) { char ch = *end; *end = *s; *s = ch; } return str; } ``` --- Then in `main` all you do is call the reverse function with the desired string: ``` printf("'%s'\n", reverse(argv[1])); ``` Of course it is best to check that `argv[1]` exists first (remember that argv[0] is the program name and argc is always greater than or equal to 1): ``` if (argc == 2) { printf("'%s' reversed is ", argv[1]); printf("'%s'\n", reverse(argv[1])); } ``` --- Notes: In your code, `aLen` and `sWord` are unnecessary. And `reversed` is not initilaised but is then used in ``` reversed = reversed + sLen; // See the EDIT below ``` In the line ``` int sLen = strlen(sWord); ``` `strlen` returns the length as a `size_t`, not `int` **EDIT** When you declare a variable local to a function, the compiler sets aside a space on the stack. It does **not** write anything there unless you declare the initial value for the variable. So in your code, `reserved` contains whatever happens to be at that location on the stack and, as `reserved` is a pointer, it therefore points to some unknown (unplanned) location in memory. If you are **unlucky** that location will be writeable, your accesses 'work' and you won't see the problem (or not immediately - in a larger program you will probably encounter strange behaviour later on while the code is executing because your accesses have overwritten something important); if you are **lucky** and the location is unwritable you will see the problem the first time you run the program. The moral is always to initialise variables, just to be safe. Zero (NULL) is a good value for pointers. With C99 you are not restricted to defining them at the start of a function, so it is often best to define a variable only at the point where you need it and have a useful value with which to initialise it.
You need to allocate storage for the reversed string using `malloc` unless that's changed in the last twenty years and place a `'\0'` string terminator at the end. ``` char *reversed = malloc(sLen + 1); reversed[sLen] = '\0'; ``` Also, you're writing to cells 1 .. `sLen` when you should be writing to 0 .. `sLen - 1`.
10,869,484
This has been asked a lot, but I'm after more specific answers. I'm designing/developing a suite of applications that are dependent on communicating with a agent and a manager. They will be communicating commands (from manager to agent) and statistics (agent to manager). At the moment, this suite of applications will only run on the Windows platform, but eventually should scale out to other systems. Some places where this application would be used might not want to install a great load of applications across their systems, and some might not want the manager side sitting there sucking up juice (analysis!) and therefore might want it in the cloud. So, I know that I can use .Net TCP sockets, which seems to have good raw performance and allows me a great deal of flexibility. I also know that I could use Windows Communication Foundation, which seems like naturally a better choice. But, seeing as I'm sending commands and receiving statistics, I could just use Powershell to connect remotely and use the plethora of commands available from what would be the server, ruling out writing a client application full stop. Bearing in mind that these applications (client especially) should just sit there, be quiet, do their job and not interfere with general operations, which would you suggest to be better? If you need more clarification I'll be happy to do so! Thanks.
2012/06/03
[ "https://Stackoverflow.com/questions/10869484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/421023/" ]
Does this snippet give the output you want? (It is compileable and executeable) ``` import java.util.ArrayList; import java.util.List; public class SO { static ArrayList<Integer> specs = new ArrayList<Integer>(); static int[] i; public static void main(String[] args) throws Exception { specs.add(5); //for(int i=0 to 5; i++) specs.add(7); specs.add(9); specs.add(2); specs.add(8); specs.add(9); i = new int[specs.size()]; printMe(0, specs, i); } static void printMe(int depth, List<Integer> _specs, int[] i) { if (_specs.isEmpty()) { System.out.println(printI(i)); return; } else { for (int j = 0; j < _specs.get(0); j++) { i[depth] = j + 1; // + 1 since you seems to want to go from 1 and not 0 printMe(depth + 1, _specs.subList(1, _specs.size()), i); } } } static String printI(int[] i) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < i.length; j++) { sb.append(i[j]); if (j < i.length - 1) { sb.append(" "); } } return sb.toString(); } } ```
You can try this : ``` public static void loops(ArrayList<Integer> specs, int idx, StringBuilder res){ if(idx==specs.size()-1){ for (int i = 0; i < specs.get(idx); i++) { System.out.println(i+" "+res); } } else{ for(int i=0;i<specs.get(idx);i++){ res.insert(0,i+" "); loops(specs,idx+1,res); res.delete(0, 2); } } } ``` And call with : ``` ArrayList<Integer> specs= new ArrayList<Integer>(); specs.add(5); //for(int i=0 to 5; i++) specs.add(7); specs.add(9); specs.add(2); specs.add(8); specs.add(9); loops(specs,0, new StringBuilder()); ```
52,078,391
I have the following code from a tutorial on youtube (im just getting started with react native): ``` import React, {Component} from 'react'; import { Text, StyleSheet, View, TextInput, ScrollView, TouchableOpacity} from 'react-native'; type Props = {}; export default class Main extends Component<Props> { render() { return ( <View style={styles.container}> <Veiw style={styles.header}> <Text style={styles.headerText}> Todo List </Text> </Veiw> <ScrollView style={style.ScrollContainer}> </ScrollView> <Veiw style={style.footer}> <TextInput styles={styles.TextInput} placeholder='>Todo' placeholder = 'white' underlineColorAndroid = 'transparent'> </TextInput> </Veiw> </View> ); } } ``` but when i run this on my android emulator i get the following error message: ReferrenceError can't find variable: Veiw I know that the error is prity clear, but i imported Veiw in the start of the app, so why isn't it registered?
2018/08/29
[ "https://Stackoverflow.com/questions/52078391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9231880/" ]
This is just a typo, this happens sometimes, just change "Veiw" to "View". Since you are new to React Native you can always head over to the [official documentation](https://facebook.github.io/react-native/docs/view) and be sure that the components you are working with actually exist when importing them (the official components are always imported in the "import 'react-native'" line). All of these are official components of React Native: ``` import { Text, StyleSheet, View, TextInput, ScrollView, TouchableOpacity} from 'react-native'; ``` In the docs you will always find the components, their props, and how they can be used. Also there are some useful guidelines there, I suggest you start with them as well.
I believe you spelt 'view' wrong, Try this: ``` import React, {Component} from 'react'; import { Text, StyleSheet, View, TextInput, ScrollView, TouchableOpacity} from 'react-native'; type Props = {}; export default class Main extends Component<Props> { render() { return ( <View style={styles.container}> <View style={styles.header}> <Text style={styles.headerText}> Todo List </Text> </View> <ScrollView style={style.ScrollContainer}> </ScrollView> <View style={style.footer}> <TextInput styles={styles.TextInput} placeholder='>Todo' placeholder = 'white' underlineColorAndroid = 'transparent'> </TextInput> </View> </View> ); } } ```
46,484,989
I'm trying to design the database schema with the ability to both private chat and group chat. Here's what I've got so far: [![enter image description here](https://i.stack.imgur.com/qnLFa.png)](https://i.stack.imgur.com/qnLFa.png) So - the theory is that even if the user is just in a one on one private chat, they are still assigned a 'roomID', and each message they send is to that `room`. To find out all the rooms they are involved in, I can SELECT a list from the table `participants` to find out. This is okay, However it feels to me that the `room` table is slightly redundant, in that I don't really need a room name, and I could leave it out and simply use the `participants` table and `SELECT DISTINCT roomID FROM particpants` to find out the individual rooms. Can anyone explain to me a better structure or why I should keep the room table at all?
2017/09/29
[ "https://Stackoverflow.com/questions/46484989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1445985/" ]
Your schema looks perfectly fine, you might see the others (including myself today) came with more or less the same structure before ([Storing messages of different chats in a single database table](https://stackoverflow.com/q/39810106/1657819), [Database schema for one-to-one and group chat](https://stackoverflow.com/q/35788610/1657819), [Creating a threaded private messaging system like facebook and gmail](https://stackoverflow.com/questions/6420264/creating-a-threaded-private-messaging-system-like-facebook-and-gmail)). I'd really like to note that your visual representation is the best of all, it's so easy to understand and follow :) In general, I think having "room" ("chat", "conversation") makes sense even if you have no specific properties at the moment (as it might be `name`, `posting_allowed`, `type` (i.e. if you reuse the similar structure not only for private messages and chats but i.e. to public posts with comments) and so on. Single table with the single index ID should be super fast and have close to zero overhead, however it will allow extension quite easily without need to modify all existing code (i.e. one day you decide to add a `name` to chats). Keeping the roomID logic "hidden" inside `participants` table will not be transparent and neither efficient (i.e. when you need to find next ID of the chat), I wouldn't recommend that.
I think you may need to refine your domain model a little - without that, it's hard to say whether your schema is "right". Taking Slack as a model (note - I haven't done a huge amount of research on this, so the details may be wrong), you might say that your system has "chats". A chat can be public - i.e. listed for all users to see and join - or private - i.e. not listed for all users, and only available by invitation. Public chats must have a "name" attribute. Private chats may or may not have a name attribute. A chat can have 2..n participants. All 1-1 chats start as private by default. It is possible to change a private chat to a public chat. In that case, you have an inheritance/specialisation relationship - "private" and "public" are subtypes of "chat". The relational model is notoriously bad at dealing with inheritance; there are lots of [related](https://stackoverflow.com/questions/1567935/how-to-do-inheritance-modeling-in-relational-databases) [questions](https://stackoverflow.com/questions/3579079/how-can-you-represent-inheritance-in-a-database?rq=1) on SO.
171,975
In Harry Potter and the Half-Blood Prince, Ollivander is missing and his shop is closed. In Harry Potter and the Deathly Hallows, Bellatrix gets a new wand ([somehow](https://scifi.stackexchange.com/questions/171969/whose-wand-did-bellatrix-use-at-the-battle-of-hogwarts)) and: > > Voldemort / Death Eaters have taken over Hogwarts > > > Since Ollivander's is closed, how are new first years entering Hogwarts acquiring wands? Book 7 does show some measure of wand legislation under the new regime. Does the Ministry have possession of all of Ollivander's wands and only release one to first years/replacements after verification of blood status, or do the Death Eaters have them all or a cache of some (see the Bellatrix question linked above)?
2017/10/16
[ "https://scifi.stackexchange.com/questions/171975", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/55637/" ]
Even though Olivander's Shop is an important part of the Harry Potter story, it's not reasonable to assume all wands were distributed through that shop alone. There would be other shops around the world, and as with the Weasley family, there would be hand-me-downs. And of course there must be some number of other wizards around the world who actually craft the wands in the first place.
What do you think the Ministry of Magic under Voldemort's control was doing with the wands of [Muggle-borns](http://harrypotter.wikia.com/wiki/Muggle-born) that were sentenced to Azkaban? > > The Commission punished anyone who could not prove to have wizarding heritage for this alleged action, sentencing them to Azkaban. > > > ... or were punished [less severly](http://harrypotter.wikia.com/wiki/Muggle-Born_Registration_Commission)? > > Furthermore, their "interviews" were shams, fully intent on sending innocent Muggle-borns to Azkaban, or stripping them of their wands and jobs, leaving them impoverished. > > > As discussed at [How do the Azkaban escapees get their wands back?](https://scifi.stackexchange.com/questions/66732/how-do-the-azkaban-escapees-get-their-wands-back) Wands don't just vanish when one is sentenced to Azkaban. And since the muggle-borns were unable to keep their wands, there is an ever-growing inventory of potentially available wands for new First Years. (I don't have definitive evidence that wands were recycled in this way. I doubt we will ever know. So many records from that period were poorly recorded, poorly filed, or were destroyed ...)
11,446,395
I am working on some large web projects at work, and a lot of HTML ID's and Classnames are being used. When I create something new in one of those huge projects, naming new ID's and classes can be frustrating, because I always end up with something like `#subprojectname_title` , `.subprojectname_editor` to make sure that I don't overwrite any classes and ID's that have previously been written for the "parent" project, and to make sure I dont inherit the previously written styles. I always have to write `subprojectname` whenever I create a new class or id for that subproject, and thats quite annoying. I'm looking for suggestions on how I can make my selectors shorter, without having to reset the style to make sure I dont inherit from the previous selector, and without messing with the previously written styles (overwriting them, changing their names).
2012/07/12
[ "https://Stackoverflow.com/questions/11446395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/561545/" ]
I have a simple solution for this in my projects. I use "unique" names for globally effective styles and "common" names for local scope. i.e. My site.css uses names such as "defaultList" or "defaultWhiteButton", where as my pageX.css uses "list" and "button". I never make use of IDs for my selectors, since IDs are used (in my purposes) for all programmatic behavior and not cosmetic. I make use of classes only in my CSS. I hope this helps.
Instead of .subproject\_thingie1 and .subproject\_thingie2 everywhere I usually go for adding a root class or id to differentiate between projects/pages. That way you can have global styling maintained on all pages on the same class names while being able to add specific rules for specific pages. But as always, the best solution depends on how well the existing project is written.
44,742,705
``` #include <stdio.h> void fun(int *i) { (*i) = (*i) + 1; } int main() { int pskills[] = { 10, 20, 30, 40, 50 }; int i, *ptr ; ptr = pskills; for (i = 0; i < 4; i++) { fun(ptr++); printf("%d\n", *ptr); } return 0; } ``` After I compile the code, the results are: ``` 20 30 40 50 ``` However, based on my understanding, the output should be: ``` 11 21 31 41 ``` I am confused. Can anybody help me understand this?
2017/06/25
[ "https://Stackoverflow.com/questions/44742705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8210760/" ]
In the first pass, you pass a pointer to `pskills[0]` to `fun` (incrementing `10` to `11`), but you increment `ptr` before the `printf`, so you print `pskills[1]` (`20`). In short, you incremented `ptr` too soon. You want ``` fun(ptr); printf("%d\n", *ptr); ++ptr; ``` or ``` fun(ptr); printf("%d\n", *(ptr++)); ```
You are increasing the pointer before you print the content `fun(ptr++);`. You want to increase the content, then print, then increase the pointer. ``` #include <stdio.h> void fun(int *i) { (*i) = (*i) + 1; } int main(void) { int pskills[] = { 10, 20, 30, 40, 50 }; int i, *ptr ; ptr = pskills; for ( i = 0 ; i <4 ; i++ ) { fun(ptr); // first increase content, without increasing the pointer printf ("%d\n", *ptr ) ; // then print content, before increasing ptr++; // THEN increase the pointer } return 0; } ``` Output: ``` 11 21 31 41 ``` Bingo! As desired. (I notice that you expect only 4 values, which matches your loop. The array has 5 entries, but you obviously are aware of that.)
1,003,823
Find the last two digits of $3^{2002}$. How should I approach this question using modulo? I obtained 09 as my answer however the given answer was 43. My method was as follows: $2002\:=\:8\cdot 250+2$ $3^{2002}=\:3^{8\cdot 250+2}\:=\:3^{8\cdot 250}\cdot 3^2$ The last two digits is the remainder when divided by 100. Thus we need to compute the sum mod 100. $3^8\equiv 61\:\left(mod\:100\right)$ Thus, $3^{2002}=\:3^{8\cdot 250+2}\:=\:3^{8\cdot 250}\cdot 3^2$ $\equiv 61^{250}\cdot 9\:\equiv 61^{5\cdot 50}\cdot 9\equiv \:9\:\left(mod\:100\right)$ Therefore my answer would be 09. Am I doing it the right way? Thanks in advanced
2014/11/03
[ "https://math.stackexchange.com/questions/1003823", "https://math.stackexchange.com", "https://math.stackexchange.com/users/177860/" ]
Observe that $\text{gcd(3,100)} = 1$, by Euler totient formula: $3^{\phi(100)} \cong 1(\mod 100)$. But $\phi (100) = 100\left(1-\dfrac{1}{2}\right)\left(1-\dfrac{1}{5}\right) = 40$. Thus: $3^{40} \cong 1(\mod 100)$. So $3^{2002} = (3^{40})^{50}\cdot 3^2 \cong 1\cdot 9(\mod 100) \cong 9(\mod 100)$. Thus the remainder is $9$ as claimed.
Using [Carmichael function](http://en.wikipedia.org/wiki/Carmichael_function), $\lambda(100)=20$ As $(3,100)=1$ and $2002\equiv2\pmod{20},$ $$\implies3^{2002}\equiv3^2\pmod{100}$$ --- $$3^{2002}=(3^2)^{1001}=9^{1001}=(10-1)^{10001}$$ $$=-1+\binom{1001}110\pmod{100}\equiv10010-1\equiv9$$
23,253,609
I am asking this question because I'm unsure of the best way to solve my problem. Problem: I have a pre-populated drop down list of 1,000 or so numbers. I need to limit which numbers appear in the drop down based on which user is using the drop down. Solution I thought of: 1. Hide all numbers with jQuery 2. Use jQuery / AJAX to call a database, passing a userID 3. DB returns a list of values based on the userID 4. Show options in drop down that have same values as numbers returned from the DB Lets say this is my **HTML**: ``` <select> <option>Please Select..</option> <option value="101"> CC 101 </option> <option value="102"> CC 102 </option> <option value="103"> CC 103 </option> <option value="104"> CC 104 </option> <option value="105"> CC 105 </option> <option value="106"> CC 106 </option> </select> ``` And this is my **DB table**: ``` ======================= | User1 | 101 | | User2 | 101 | | User2 | 102 | | User2 | 103 | | User3 | 103 | ======================= ``` I need to figure out, for example, how to pass user2 and then return 101,102,103. I only know basic js/jQuery, and I am not very experienced with DBs, so I am welcome to any suggestions that can help me accomplish my end goal. EDIT/NOTE: As dumb as this sounds.... Security is not a huge deal here. This will be used on an internal company website, where if a user felt the need to hack around and select a different number, it really wouldn't matter that much. I also don't foresee any of the employees of the company having the desire/need/want to select a different option than they are allowed. Also, the list ***must*** be pre-populated then numbers hidden. Its the way the platform I am using is set up, so I have to use show/hide, or something similar.
2014/04/23
[ "https://Stackoverflow.com/questions/23253609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007416/" ]
I would go only with steps 2-3 of your approach; however, I would not store the numbers in the way you showed. A better approach would be to store them in a table called user\_value -or something like that-: ``` user_id | value ---------+------- user1 | 101 user1 | 102 user2 | 101 ``` Just because you can then easily add/remove/update values in the future as opposed to having to parse the comma-delimited value. I would avoid using jQuery to simply "hide" things because Javascript can be disabled by the user and he may end up submitting whatever value he wants (visible or invisible) - Never trust user input. In conclusion do this: 1. Use jQuery / AJAX to call a database, passing a userID 2. DB returns a list of values based on the userID 3. populate the dropdownlist with the values returned from the database. 4. Validate the form on the server side to make sure that the value submitted is present in the `user_value` table.
i think a good way to do it would be using JSON for all users. prepare a json array for users with options and render it based on users to populate options. eg. ``` var user1 = '["101","102","103"]'; ```