pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
9,704,131 | 0 | <p>You can make new union case values based on existing value of the same union case using Reflection. In order to achieve this just add instance member <code>Same</code> to your discriminated union, which first derives specific union case from the instance <code>self</code> and then constructs a new instance by the same union case, but now populated with <code>newVal</code>:</p> <pre><code>open Microsoft.FSharp.Reflection type Currency = | Dollar of int | Euro of int member self.Same newVal : Currency = FSharpValue.MakeUnion(fst (FSharpValue.GetUnionFields(self, typeof<Currency>)), [|newVal|]) |> unbox </code></pre> <p>Now applying it to <code>lowPrice</code> value below</p> <pre><code>let lowPrice = Euro(100) let highPrice = lowPrice.Same 200 </code></pre> <p>you'll get <code>highPrice : Currency = Euro 200</code></p> |
31,280,140 | 0 | <p>As @CBroe points out, this isn't supported by the Facebook Graph API. (It can be done using <a href="https://developers.facebook.com/docs/reference/fql/" rel="nofollow">FQL</a>, but that's deprecated and won't be supported for much longer).</p> <p>That said, with some creativity (and a bit extra code) a similar effect can be achieved by combining a couple of queries. </p> <p>In my application, I perform a query with the following parameters:</p> <ul> <li><code>until=2015-07-07</code> (or whatever the <code>since</code> date would have been)</li> <li><code>fields=updated_time</code> (to keep the query fast and the payload small)</li> <li><code>limit=5000</code> (or some similarly large page size, as I'm only grabbing one field)</li> </ul> <p>I then evaluate each post that has an <code>updated_time</code> greater than the would-be <code>since</code> date, and throw those posts into a queue to download the entirety of the post content. </p> <blockquote> <p><em>Note:</em> If you're dealing with content where there are frequent updates on past content, you'd likely want to use the Graph API's <a href="https://developers.facebook.com/docs/graph-api/making-multiple-requests" rel="nofollow">Batch Requests feature</a>, as opposed to downloading each post individually.</p> </blockquote> <p>So, for example, if the <code>until</code> (and, thus, <code>since</code>) date is <code>2015-07-07</code> and the <code>updated_time</code> on a post is <code>2015-10-15</code>, then I know that post was created prior to <code>2015-07-07</code> but updated afterwards. It won't get picked up in a <code>since</code> query, but I can easily download it individually to synchronize my cache.</p> |
34,850,189 | 0 | Kendo Sort not working <p>i have implemented a kendo grid as shown below , paging works without any issues but sort not work. Could you please help</p> <p>CSHTML</p> <pre><code><div class="panel"> <div id="CsHistory" class="row"> <div class="col-lg-12 col-md-12 col-sm-12" style="float:none; margin-left:auto; margin-right:auto; margin-top: 10px; margin-bottom: 10px;"> @using PC.Cmgr.Claims.Domain.Models; @using PC.Cmgr.Claims.Domain.Common; @using PC.Cmgr.Models; @using System.Linq; @(Html.Kendo().Grid<CsAuditTrailViewModel> () .HtmlAttributes(new { style = "width:auto; height:auto; text-center;margin-right: 30px;margin-left: 30px; " }) .Name("AllCsHistory") .Columns(columns => { columns.Bound(o => o.CsAuditTrailId).Title("CsAuditTrailId"); }) .ToolBar(toolBar => { }) .Resizable(resize => resize.Columns(false)) .Reorderable(reorder => reorder.Columns(true)) .Sortable() .Pageable(pageable => pageable .Refresh(true) .PageSizes(true) .ButtonCount(5)) .DataSource(dataSource => dataSource .Ajax() .Batch(true) .ServerOperation(true) .Model(model => { model.Id(o => o.CsAuditTrailId); }) .Read(read => read.Action("GetCHistoryByClaimId", "Claims", new { ClaimId = Model.Claim.ClaimId })) .Events(events => { events.Sync("sync_handler"); } ) ) ) </div> </div> </code></pre> <p></p> <p>Controller</p> <pre><code> public async Task<ActionResult> GetCsHistoryByClaimId([DataSourceRequest] DataSourceRequest request, Guid ClaimId) { var CsHistory = await _CsHistoryProxy.GetCsHistoryByClaimId(ClaimId); var rawData = new ConcurrentBag<CsAuditTrailViewModel>(); var gridData = new List<CsAuditTrailViewModel>(); Parallel.ForEach(CsHistory, (x) => { rawData.Add( new CsAuditTrailViewModel { CsAuditTrailId = x.CsAuditTrailId, NewData = x.NewData, OldData = x.OldData, UpdateDate = x.UpdateDate, UserId = x.UserId }); }); ViewData["total"] = rawData.Count(); // Apply paging if (request.Page > 0) { gridData = rawData.Skip((request.Page - 1) * request.PageSize).ToList(); } gridData = gridData.Take(request.PageSize).ToList(); var result = new DataSourceResult() { Data = gridData, Total = (int)ViewData["total"] }; return Json(result); } </code></pre> |
35,113,212 | 0 | <p>It means that header "header.h" is included in more than one compilation unit.</p> <p>In this case variable GAMESTATE is defined in each module that includes the header.</p> <p>You should declare the variable without its definition in the header the following way</p> <pre><code>extern Gamestate GAMESTATE; </code></pre> <p>and then for example in main.cpp define it like</p> <pre><code>Gamestate GAMESTATE = MENU; </code></pre> |
9,879,479 | 0 | Optimization stops prematurely (MATLAB) <p>I'm trying my best to work it out with fmincon in MATLAB. When I call the function, I get one of the two following errors:</p> <p>Number of function evaluation exceeded, or</p> <p>Number of iteration exceeded.</p> <p>And when I look at the solution so far, it is way off the one intended (I know so because I created a minimum vector).</p> <p>Now even if I increase any of the tolerance constraint or max number of iterations, I still get the same problem. </p> <p>Any help is appreciated.</p> |
11,983,857 | 0 | SQL query to select max value of a varchar field <p>I want to select the max value of a varchar field and increment its value by 1 retaining its original format .. </p> <p>Customer ID for ex. : <code>CUS0000001</code> is the value </p> <p>add 1 to it and then enter it into the database along with other details.</p> <p>So the result should be like <code>CUS0000002</code> ..</p> <p>This is what I have tried and in fact achieved what I want .. </p> <p>But is this the best way to do it ?? </p> <pre><code>SELECT CONCAT('CUS', RIGHT(CONCAT('000000', CONVERT((CONVERT(MAX(RIGHT(customer_id, 7)) , UNSIGNED) + 1), CHAR(10))), 7)) AS customer_id FROM customer_master </code></pre> |
11,251,170 | 0 | <p>What user is your ssh daemon running as? Presumably System. That user doesn't have authority to map network drives, as far as I recall. Can you not just do this on the Linux box directly using samba?</p> |
3,769,939 | 0 | <p>It is necessary to call ActionBarAdvisor.register() to make the save action available. For example:</p> <pre><code>public class MyActionBarAdvisor extends ActionBarAdvisor { public MyActionBarAdvisor(IActionBarConfigurer configurer) { super(configurer); } protected void makeActions(final IWorkbenchWindow window) { register(ActionFactory.SAVE.create(window)); } } </code></pre> <p>Given the addition to plugin.xml in the question, the built-in save handler will now be invoked for any active editor.</p> |
25,546,637 | 0 | ldap ObjectSID string to hex <p>I can't figure out how to search in an ldap directory by objectsid string:</p> <pre><code>$string = 'S-0-1-23-4567890123-4567890123-456789012-3456' $ds = ldap_connect('xxxx', xxx); ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); $r = ldap_bind($ds, $bind_rdn, $bind_password); $filter = "(objectSid=$string)"; $sr = ldap_search($ds, $dn, $filter); $users = ldap_get_entries($ds, $sr); </code></pre> <p>Then i read somewhere you should pass it as hex value: /00/00/....</p> <pre><code>$s = preg_replace('/../','\\\\$0',bin2hex($string)); </code></pre> <p>But still no result. If i pass objectSid=* ass filter, i get all results, so i know the query is working :).</p> <p>Thx!</p> |
19,487,550 | 0 | <p>You can force a numerical sorting when converting your text data type to a numeric one. Use an explicit or this implicit cast</p> <pre><code> ORDER BY cnumber * 1 ASC </code></pre> |
1,470,983 | 0 | PDF ZOOMING is fading the text <p>i successfully download the pdf file and it's working fine. But the problem is zooming . when i m zooming the clarity is not as clear as originally. need help..</p> <p>thanks in advance.</p> <p>--- goeff. </p> |
4,083,966 | 0 | ASP.NET pages never stop loading <p>We have a problem with many of our website written C# ASP.NET. The problem is that often a C# page will never fully load from the server. The page content itself load fine but Images but more annoying Scripts (Javascript) seam to hang and never come down and depending on the content it might lock up the page on Ajax Postback.</p> <p>This problem is not limited to a single server as it happens on development machines as well as pre production and production servers.</p> <p>The development machine are just using the inbuilt VS IIS Instance.</p> <p>All pages that have this problem use ASP.NET Update Panels with varying versions of AJAX Toolkit.</p> <p>Thanks</p> |
11,884,852 | 0 | <p>Do something like that in a method, perhaps initDatabase or something: (the reason is the answer of trojanfoe, I just want to add some code snippets)</p> <pre><code>NSString *databaseName = @"bd_MyObjects.sqlite"; // Get the path to the documents directory and append the databaseName NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName]; // Check if the SQL database has already been saved to the users phone, if not then copy it over BOOL success; // Create a FileManager object, we will use this to check the status // of the database and to copy it over if required NSFileManager *fileManager = [NSFileManager defaultManager]; // Check if the database has already been created in the users filesystem success = [fileManager fileExistsAtPath:databasePath]; // If the database already exists then return without doing anything if(success) return; // If not then proceed to copy the database from the application to the users filesystem // Get the path to the database in the application package NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName]; // Copy the database from the package to the users filesystem [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil]; </code></pre> |
28,946,463 | 0 | Counters do not update <p>This is a first for me. I have started using GUIDE and after mild cussing I have hit rock bottom. I have setup a counter in a m-file but for some reason it does not update. Could you please help me. The counter is called num.</p> <pre><code>function ack = streamSensor_1_2_3(hObject, handles) if handles.fileID.BytesAvailable == 0 fprintf(handles.fileID, 'P') display('yes'); %get data from active receiver stations for l = 1:3 data_cm(l,:) = fscanf(handles.fileID, ' %f ' ); display(data_cm); set(handles.uitable1, 'data', data_cm); end %solve perpendicular view [at, bt, ct] = flatPlane(data_cm(:,2), data_cm(:,3), data_cm(:,4)) [xr, yr] = reposit(at, bt, ct); D_angle = dangle(data_cm(:,2), data_cm(:,3), data_cm(:,4), 'deg'); display(handles.num); comet(handles.axes3, handles.num, D_angle); handles.num = handles.num +1 ; %plot knee angle plot3(handles.axes1, data_cm(:,2), data_cm(:,3), data_cm(:,4)); plot(handles.axes2, xr, yr); ylim(handles.axes2,[-1.2 1.2]); xlim(handles.axes2,[-1.2 1.2]); ack = 1; else ack = 0; end guidata(hObject, handles); </code></pre> <p>I have declared this variable in the opening function</p> <pre><code>function Knee_DepressAngle_GUI_OpeningFcn(hObject, eventdata, handles, varargin) % Choose default command line output for Knee_DepressAngle_GUI handles.output = hObject; handles.num = 0; % Update handles structure guidata(hObject, handles); ...........etc. </code></pre> <p>And the function is called from a button press. This is later going to be a continuously called function so a counter based on the button press information will not work.</p> <pre><code>function printOnce_Callback(hObject, eventdata, handles) display(streamSensor_1_2_3(hObject, handles)); guidata(hObject, handles); </code></pre> |
38,042,222 | 0 | How to accelerate PHP execution by using cached result? <p>I'm using PHP-FPM 5.6 version.</p> <p>php -v shows there's OPcache in place.</p> <p>I have a PHP script that's accepting parameters and giving me same <code>2.2k</code> HTML output all the time.</p> <p>The script execution does not involve any connectivity to MySQL.</p> <p>In Chrome Developer Tools, I'm seeing an execution time of <code>900ms</code>.</p> <p>I find that this is relatively slow.</p> <p>I would like to shorten this execution time.</p> <p>Given that OPcache is in place with this version of PHP, can I use it to cache the result of my PHP script execution for a faster response time?</p> <p>Or if there's an alternative approach?</p> <p>Any configuration to be tweaked in <code>php.ini</code>, <code>/etc/php.d/10-opcache.ini</code> or <code>/etc/php-fpm.d/www.conf</code>?</p> <p>And how do I purge the cached result when needed?</p> |
32,534,703 | 0 | <p>You can store then wherever makes sense. The catch is that when you <code>source</code> them, you need to either already be in that directory before running the initial <code>mysql</code> command, because <code>source</code> only looks in the current directory -- that's why they aren't found, not because you put them in the "wrong" place, if that's what you're thinking may be the problem.</p> <p>Or, use the full path, e.g.:</p> <pre><code>mysql> source /home/melissa/myscript.sql </code></pre> |
30,531,592 | 0 | <p>You can use parameters only once in a query</p> <pre><code>$sql1="SELECT @rownum := @rownum + 1 Rank, q.* FROM (SELECT @rownum:=0) r,(SELECT * ,sum(`number of cases`) as tot, sum(`number of cases`) * 100 / t.s AS `% of total` FROM `myTable` CROSS JOIN (SELECT SUM(`number of cases`) AS s FROM `myTable` where `type`=:criteria and `condition`=:diagnosis) t where `type`=:criteria2 and `condition`=:diagnosis2 group by `name` order by `% of total` desc) q"; $stmt = $dbh->prepare($sql1); $stmt->execute(array(':criteria' => $search_crit, ':diagnosis' => $diagnosis, ':criteria2' => $search_crit, ':diagnosis2' => $diagnosis)); </code></pre> |
9,473,326 | 0 | <p>I personally verified that for domain classes there is a big hit in terms of performances.</p> <p>While trying to solve a performance issue, I found this blog entry <a href="http://blog.oio.de/2010/08/05/updated-grails-domain-class-creation-performance-avoid-named-parameters-in-loops-with-many-iterations/" rel="nofollow">Grails Domain Class Creation Performance</a>, changed from map style constructor invocation and gained a factor on ten when creating a lot of new instances (not to be persisted BTW). </p> <p>I'm using grails 2.01, so the problem (?) is still there.</p> |
20,093,495 | 0 | <p>The following can work. You can google for them and see how they work.</p> <pre><code>driver.findElement(By.id("id")); driver.findElement(By.cssSelector("cssSelector")); driver.findElement(By.name("name")); driver.findElement(By.linkText("linkText")); driver.findElement(By.partialLinkText("partialLinkText")); driver.findElement(By.className("className")); driver.findElement(By.xpath("xpath")); </code></pre> <p>I am sure some of them will be useful. Please let me know if you want more info. The easiness of using them is in the order which i have mentioned.</p> |
25,749,239 | 0 | <p>You have created list of exceptions, i.e. list that can hold instances of exceptions. But you try to add there <code>class</code> instead. </p> <p>the following will work </p> <pre><code>List<Exception> ex = new ArrayList<Exception>(); ex.add(new NotFoundException()); </code></pre> <p>(obvioously if your <code>NotFoundException</code> has default constructor; otherwise use appropriate contructor). </p> <p>The following will work too: List> ex = new ArrayList>(); ex.add(NotFoundException.class);</p> <p>now it depends what do you really need. </p> |
32,058,169 | 0 | <p>One is to INNER JOIN Table B onto Table A by ID's. You will have 3 records returned from Table B. If you ORDER those records by the COLX</p> <pre><code>SELECT ,a.ID ,a.Col1 ,a.Col2 ,a.Col3 ,b.COLX FROM TableA AS a INNER JOIN TABLE_B AS b on b.A_ID = a.id ORDER BY b.COLX DESC </code></pre> <p>Then another way is joining a sub query of Table B that also has a sub query that filters Table B records to only the records with the highest RANK. </p> <p>That way you can bring in COLX values from the highest RANK records from Table B that match the records of Table A. </p> <p>I think at least...</p> <pre><code>SELECT a.ID ,a.Col1 ,a.Col2 ,a.Col3 ,b.COLX FROM TableA a INNER JOIN ( SELECT a.A_ID ,a.RANK ,a.COLX FROM TABLE_B a INNER JOIN ( SELECT A_ID, ,MAX(RANK) AS [RANK] -- Highest Rank FROM TABLE_B GROUP BY A_ID ) AS b ON b.A_ID = a.A_ID AND b.RANK = a.RANK ) AS b on b.A_ID = a.id ORDER BY a.ID ASC </code></pre> |
41,018,667 | 0 | <p>You can use HttpClient class to create an object and make <code>get</code> or <code>put</code> requests for your restful API. You may need to pass the API key or secret in the get parameters in the request or add these as Http headers for your HttpClient object.</p> |
1,263,878 | 0 | <p>If your regex engine has lookbehind assertions then you can just add a "(?<!\.)" before the "@".</p> |
37,947,315 | 0 | <pre><code> ((MainActivity)getActivity()).mDrawerToggle.setDrawerIndicatorEnabled(false); ((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); getActivity().getSupportFragmentManager().beginTransaction() .add(R.id.frame, new DetailFragment())//here add add fragment on stack .addToBackStack(null) .commit(); </code></pre> |
22,792,860 | 0 | <pre><code><?php if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $q_cat = get_query_var('cat'); $cat = get_category($q_cat); $catName = $cat->cat_ID; $category = new WP_Query(); query_posts( array( 'post_type' => 'producto', 'paged' => $paged, 'cat' => $catName ) ); if ( have_posts() ) : $count = 0; while ( have_posts() ) : the_post(); $count++; get_template_part('content', get_post_format()); endwhile; else: ?> <?php _e('sorry no posts', 'siddharta naranjo') ?> <?php endif; ?> </code></pre> |
9,910,853 | 0 | <p>Android reserves the right to kill any application or component that isn't visible to the user (even those can be killed, but it's a rare occurrence). Most often, this is due to memory pressure, and the system kills applications to free up resources.</p> <p>If you have a long-running process that runs in the background and it should run continuously, your best bet is to make it a <a href="http://developer.android.com/reference/android/app/Service.html#startForeground%28int,%20android.app.Notification%29" rel="nofollow">foreground service</a>. This will put the service at a higher priority than a background service, and should be interrupted less by the system.</p> <p>However, unless your service NEEDS to run in the foreground, you should implement your service to gracefully handle being torn down and built up by the system, since it usually kills the service for a good reason. Forcing your service into the foreground might increase the risk of hurting overall device performance, and it does force the presence of a persistent notification in the notification bar, which annoys some users (at least me).</p> |
18,028,548 | 0 | <p>Just put that in your hosts file and you won't have to worry about DNS.</p> <p>But really, doesn't it make more sense to use an ENV var?</p> |
13,659,262 | 0 | <p><code>CR</code> represents the regular Viginere ciphertext, <code>CM</code> the modified Viginere ciphertext</p> <pre><code>CR[i] = (P[i] + K[i]) mod 26 CM[i] = (P[i] + K[i] + CM[i-1]) mod 26 = (CR[i] + CM[i-1]) mod 26 </code></pre> <p>Now simply solve for the original ciphertext <code>CR</code></p> <pre><code>CR[i] = (CM[i] - CM[i-1]) mod 26 </code></pre> <p>Once you have the regular ciphertext, break it as usual.</p> |
8,593,533 | 0 | <p>This is a fairly common problem.</p> <p>One often used solution is to have pipes as a communication mechanism from worker threads back to the I/O thread. Having completed its task a worker thread writes the pointer to the result into the pipe. The I/O thread waits on the read end of the pipe along with other sockets and file descriptors and once the pipe is ready for read it wakes up, retrieves the pointer to the result and proceeds with pushing the result into the client connection in non-blocking mode.</p> <p>Note, that since pipe reads and writes of less then or equal to <code>PIPE_BUF</code> are atomic, the pointers get written and read in one shot. One can even have multiple worker threads writing pointers into the same pipe because of the atomicity guarantee.</p> |
6,860,743 | 0 | <p>Why not store the values in the list and in the map the key -> index mapping?</p> <p>so for getEntry you only need on lookup (in the list which should be anyway faster than a map) and for remove you do not have to travers the whole list. Syhnronization happens so.</p> |
866,626 | 0 | <p>For UNIX, <code>man setitimer</code>.</p> |
30,010,264 | 0 | <p>I'm just messing around with the Gdriv.es service and the link you posted. Thanks for sending me down the rabbit-hole... </p> <p>Google Drive folders seem to either have 28 or 72 character long ids. Most of your product subfolders have the 28 character id format. Interestingly, there are some other folders that show up in your posted link that don't if you go in a different way to the same folder <a href="https://drive.google.com/drive/folders/0ByX-7AGzNtLkfnJDcC0tRm5xcE9aYlp3akljS3p4OWxpeDNId0FlaEdONFVTak0xeld4NGc" rel="nofollow">https://drive.google.com/drive/folders/0ByX-7AGzNtLkfnJDcC0tRm5xcE9aYlp3akljS3p4OWxpeDNId0FlaEdONFVTak0xeld4NGc</a></p> <p>Going through my own drive, what I'm seeing is that all of the older folders I have from 2009 and earlier have the 72 character id format. Folders from 2012 are 28 character ids. Unfortunately, I don't have anything in mine between summer 2009 and 2012.</p> <p>A quick twitter search shows a <a href="https://twitter.com/vivekhaldar/status/275090459867635713" rel="nofollow">Dec 2012 tweet</a> that kind of looks like an announcement.</p> <p>My guess is there was some sort of API change with Google Drive from the 72 to the 28 character ids before then, and Gdriv.es doesn't support the old format. Maybe if your root folder was created before that change, you could create a new root folder and shift your content over?</p> |
12,942,911 | 0 | Octopress, github pages, CNAME domain and google website search <p>My <a href="http://www.convalesco.org" rel="nofollow">blog</a> was successfully transferred to <a href="http://octopress.org" rel="nofollow">octopress</a> and github-pages. My problem though is that website's search uses <a href="https://encrypted.google.com/search?q=test&q=site%3awww.convalesco.org" rel="nofollow">google search</a> but the result of 'search' as you can see, are pointing to the old (wordpress) links. Now these links have change structure, following default octopress structure.</p> <p>I don't understand why this is happening. Is it possible for google to have stored in it's DB the old links (my blog was 1st page for some searches, but gathered just 3.000 hits / month... not much by internet's standards) and this will change with time, or is it something I'm able to change somehow?</p> <p>thanks.</p> |
25,455,197 | 0 | <pre><code>mysql_insert_id(); </code></pre> <p>That's it :)</p> |
9,473,396 | 0 | <p>Well, there are <code>splay trees</code> and <code>AVL Trees</code> that does what you are asking for but those are limited to a max of 2 children per node. You could try modifying them. The problem could be <code>Form a tree which is as wide as possible</code>.</p> |
22,470,118 | 0 | <p>You are not passing any parameters to the query.</p> <p>Instead of:</p> <pre><code>cur.execute('INSERT INTO report_table (id, date, time, status) VALUES (id, date, time, status)') </code></pre> <p>create a parameterized query:</p> <pre><code>cur.execute("""INSERT INTO report_table (id, date, time, status) VALUES (%(id)s, %(date)s, %(time)s, %(status)s)""", {'id': id, 'date': date, 'time': time, 'status': status}) </code></pre> <p>There are other fixes you should apply to the code:</p> <ul> <li>define <code>db</code> and <code>cursor</code> variables before the loop so that you don't need to connect to the database and open a cursor on every iteration</li> <li>you should properly close the cursor and connection objects</li> <li>instead of calling <code>INSERT</code> database query on each iteration step, consider gathering the data into a list and then insert once after the loop</li> </ul> <p>Hope that helps.</p> |
5,448,806 | 0 | Syntax for naming foreign keys <p>Using:</p> <pre><code>ALTER TABLE dbo.Table1Name ADD FOREIGN KEY (colname) REFERENCES dbo.Table2Name (colname) </code></pre> <p>I get a foreign key with a name like: FK___colname__673F4B05</p> <p>I want it to be named: FK_Tabl1Name_Table2Name, </p> <p>...so that it will be easy to read when browsing the DB structure in SSMS. I know I can go back into the GUI and do this, but I want to be able to script it.</p> <p>So What's the SQL sytnax for adding a name to the FK? Nothing I've found online seems to bother with this.</p> |
29,281,643 | 0 | <pre><code>DataTable dttable = new DataTable(); dttable = gettable(dtgreater, dtcurrentdate); public DataTable gettable(List<DateTime> objct1, DateTime objct2) { DataTable data=null; sql = "select library_issue.STUDENTCODE,library_issue.studentname,library_book.bookname,library_issue.issuedate,library_issue.returndate from library_issue join library_book on library_book.book_id = library_issue.book_id where library_issue.returndate ='" + objct1[j].ToString("dd/MM/yyyy") + "'"; ds = obj.openDataset(sql, Session["SCHOOLCODE"].ToString()); Label1.Text = (ds.Tables[0].Rows.Count).ToString(); for (int j = 0; j < dtgreater.Count; j++) { if(data.Columns.count==0) { data = new DataTable(); data.Columns.Add("STUDENTCODE", typeof(int)); data.Columns.Add("Studentname", typeof(string)); data.Columns.Add("Bookname", typeof(string)); data.Columns.Add("Issuedate", typeof(string)); data.Columns.Add("Returndate", typeof(string)); data.Columns.Add("NO of Days Exceeded", typeof(string)); } for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { TimeSpan ts = objct1[j] - objct2; Label1.Text = ts.ToString("dd"); data.Rows.Add(ds.Tables[0].Rows[i]["STUDENTCODE"], ds.Tables[0].Rows[i]["studentname"], ds.Tables[0].Rows[i]["bookname"], ds.Tables[0].Rows[i]["issuedate"], ds.Tables[0].Rows[i]["returndate"], ts.ToString("dd")); } return data; } </code></pre> |
24,512,566 | 0 | <p>I recommend looking over this documentation for the <a href="https://developer.apple.com/library/ios/documentation/AddressBookUI/Reference/ABNewPersonViewController_Class/Reference/Reference.html" rel="nofollow">ABNewPersonViewController</a> class. </p> <p>The setup I would use is to setup an IBAction to your "Add Contact" button. The IBAction can create an instance of the New Person VC.</p> <p>If you need to predefine some of the fields for the new contact, you will need to create an ABRecordRef and set the properties you want to be in the new contact. Then set the New Person VC's <code>displayedPerson</code> property to this record.</p> <p>At the end of the method, you can call `[self.navigationController presentViewController: newPersonVC];</p> <p>This may be possible in a storyboard, but I have always found it easier to do in code. </p> <p>Hopefully this will help.</p> |
19,410,010 | 0 | <p>Yes, of course this is possible. You can either use a 3D array:</p> <pre><code>byte[][][] array = new byte[w][h][3]; array[0][0][0] = 123; array[0][0][1] = 234; array[0][0][2] = 125; </code></pre> <p>Or use a 2D array of ints. ints are 4 bytes, which is enough for your requirements:</p> <pre><code>int[][] array = new int[w][h]; array[0][0] = (123 << 16) | (234 << 8) | (125); </code></pre> |
13,353,544 | 0 | Ruby, Tor and Net::HTTP::Proxy <p>My apologies in advance if this is a noobish doubt: I want to use a proxy in my Ruby code to fetch a few web pages. And I want to be sneaky about it! So I am using Tor.</p> <p>I have Tor running, and I am able to use Net::HTTP.get(uri) as usual. But I can't figure out how to use Net::HTTP::Proxy to fetch the uri. I also can't figure out how using Tor will help make my fetches anonymous. </p> <p>Any help is greatly appreciated. Please don't just add a <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html#method-c-Proxy">link to the ruby-doc page for Net::HTTP::Proxy</a>. If I had understood that, I would not be asking this here :-)</p> <hr> <p>Another easy way to do this is using <a href="http://socksify.rubyforge.org/">SOCKSify</a>, but in this case, I receive the following error:</p> <p><code>/usr/lib/ruby/gems/1.9.2-p290/gems/socksify-1.5.0/lib/socksify.rb:189:in 'socks_authenticate': SOCKS version not supported (SOCKSError)</code></p> <p>I have never done any network programming before. Any guidance about this will also be very helpful. Thanks :-)</p> |
27,939,800 | 0 | <p>Try attribute <code>colorControlActivated</code>:</p> <p>themes.xml</p> <p></p> <pre><code><style name="CET" parent="Theme.AppCompat.Light.NoActionBar"> <item name="windowActionBar">false</item> <item name="colorPrimary">@color/primary</item> <item name="colorPrimaryDark">@color/primary_dark</item> <item name="colorAccent">@color/accent</item> <item name="colorControlActivated">#a32b30</item> </style> </code></pre> <p></p> |
39,626,771 | 0 | Batch file not keeping variables <p>Why doesn't the below batch file keep variables when CMD.exe terminates</p> <pre><code>@echo off cmd /c "set var=hi" if defined var (echo var is defined ("var=%var%")) else (echo var isn't defined) pause exit </code></pre> <p>Is there any way to use CMD /c, whilst keeping variables? and why doesn't CMD /c keep variables?</p> |
20,534,760 | 0 | <p>You can use Householder elimination to get the QR decomposition of <code>delta0</code>. Then the determinant of the Q part is +/-1 (depending on whether you did an even or odd number of reflections) and the determinant of the R part is the product of the diagonal elements. Both of these are easy to compute without running into underflow hell---and you might not even care about the first.</p> |
7,245,634 | 0 | Deactivate line feed with css of tag p <p>Hello I'm defining a css style and I have a problem with the tag p. I am defining a style p tag and I get a line feed but I would like to deactivate its Line feed instead. How to do that?</p> |
18,784,882 | 0 | <p>A similar problem and its solution is <a href="http://stackoverflow.com/questions/12920225/text-selection-in-divcontenteditable-when-double-click">here</a>, I am surprised for finding it in the second day of search considering my offensive search yesterday. Any better solution is welcomed, since even this one cannot bypass text selection at first double click.</p> |
30,224,228 | 0 | <p>The wiki page says to use a "Java source files", not "Interface Builder Storyboard files" as your screen capture shows. You also need to define an output file, or Xcode ignores the rule (since it doesn't generate anything).</p> <p>I just verified that adding a Java source file to a 6.3.1 project works with the wiki page's instructions. Be sure that your app is selected in the "Add to targets:" when adding the Java source file.</p> <p>Project: <img src="https://i.stack.imgur.com/jt1af.png" alt="enter image description here"></p> <p>Build log: <img src="https://i.stack.imgur.com/KPaiz.png" alt="enter image description here"></p> |
23,733,985 | 0 | <p>Use ng-class and call a function on your controller that does the check:</p> <pre><code>$scope.getClass = function(text) { return text.slice(-1) === '!' ? 'error':''; } </code></pre> <p><a href="http://jsfiddle.net/hHdfF/" rel="nofollow"><h2>Fiddle</h2></a></p> <p>Update: </p> <pre><code><div ng-class="(message.text.slice(-1) === '!' ? 'error':'')">{{message.text}}</div> </code></pre> |
34,999,434 | 0 | maven-release-plugin deploying SNAPSHOT <p>I have a Maven project and now want to release it with the maven-release-plugin. Unfortunately after executing <code>mvn release:prepare</code> the git tag contains the old version number (1.0-SNAPSHOT) and when deploying to artifactory the SNAPSHOT version is used instead of the desired release version.</p> <p>I already found <a href="https://issues.apache.org/jira/browse/MRELEASE-812" rel="nofollow">this</a> bug, but all suggested solutions are not working for me.</p> <p>I'm using:</p> <ul> <li>Apache Maven 3.3.9</li> <li>git version 2.7.0 (German)</li> </ul> <p>I already tried several versions of the release plugin (2.4, 2.5.3, 2.5.1) but none woked. Does anyone have a fix for that problem?</p> <p><strong><em>EDIT1:</em></strong> The current pom.xml</p> <pre><code><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mygroupid</groupId> <artifactId>myartifact</artifactId> <version>1.0-SNAPSHOT</version> <!-- [...] --> <scm> <url>http://url/to/gitlab</url> <connection>scm:git:git@gitlab:group/repo.git</connection> <developerConnection>scm:git:git@gitlab:group/repo.git</developerConnection> <tag>HEAD</tag> </scm> <!-- [...] --> <distributionManagement> <!-- [...] --> </distributionManagement> </project> </code></pre> |
13,252,265 | 0 | <p>You could animate the footer with <a href="http://api.jquery.com/fadeIn/" rel="nofollow">fadeIn()</a> and <a href="http://api.jquery.com/fadeOut/" rel="nofollow">fadeOut()</a> jQuery effects.</p> <pre><code>$(window).scroll(function() { if($(document).scrollTop() > 100) $('#footer').fadeIn(); else $('#footer').fadeOut(); }); </code></pre> <p>If you dig deep enough into these effects you will find that both uses <a href="http://api.jquery.com/animate/" rel="nofollow">animate()</a> effect with opacity.</p> |
20,703,092 | 0 | <p>Look for sources titled "C for Scientists" or "C for engineers". The first google hit contains answers to your questions: (<a href="http://www2.warwick.ac.uk/fac/sci/physics/current/teach/module_home/px270/week2/week_2a.pdf" rel="nofollow">http://www2.warwick.ac.uk/fac/sci/physics/current/teach/module_home/px270/week2/week_2a.pdf</a>).</p> <hr> <p>Have also a look at (<a href="http://sccn.ucsd.edu/labinfo/computer-faq/Numerical_Recipes.html" rel="nofollow">http://sccn.ucsd.edu/labinfo/computer-faq/Numerical_Recipes.html</a>), your paths may be different.</p> |
25,404,286 | 0 | <p>use the <a href="https://metacpan.org/pod/Time::Moment" rel="nofollow">Time::Moment</a> CPAN module:</p> <pre><code>use Time::Moment; my $data = 0x0FA89EEB0F; my $seconds = $data >> 8; # Right shift to remove fractional second. my $milliseconds = 10 * ( $data & 0xff ); # Hundredths to Milli my $tm = Time::Moment->new( year => 2000, month => 1, day => 1 ); #base datetime my $tm2 = $tm->plus_seconds($seconds)->plus_milliseconds($milliseconds); print $tm2, "\n"; #<-- prints: 2008-04-28T14:42:51.150Z </code></pre> |
1,102,547 | 0 | Working with Dreamweaver and ASP.NET - is this recommended? <p>I am a ASP.NET 3.5 web developer using VS 2008. I just started at a new company and there are alot of Web Designers here (never worked with Web Designers before). They all use Dreamweaver CS3 and PhotoShop (something i know nothing about).</p> <p><strong>What I would like to know is the following:</strong></p> <ul> <li>Would they have problems opening my ASP.NET pages in Dreamweaver? ( I heard they might not be able to ).</li> <li>What about when i use MasterPages? Will they be able to open my pages when i use MasterPages, or must i stay away from MasterPages?</li> </ul> <p>Thanks in advance!</p> |
4,402,288 | 0 | <p>I'm not an expert in hard real-time scheduling, but this is what your algorithm sounds like to me.</p> <p>It bears very strong resemblance with what happens in aerospace systems. Your system looks more flexible, but basically it all grinds down to knowing in advance that you have the resources to run the tasks that you need to run.</p> <p>Critical embedded aerospace systems prefer to be deterministic, but as a protection against potential flaws (tasks can run longer than allocated, if let), the tasking engine will interrupt those tasks to let other taks complete. Any free cycle left can sometimes be used to complete the interrupted tasks, or the task is deemed to have failed.</p> <p>Note that you can only fail tasks that are not critical, so you must construct your critical tasks carefully, or have a priority system whereby critical tasks have a chance to complete no matter what.</p> <p>You're now back to square one: you need to make sure that the ressources are sufficient to run the tasks required in advance.</p> <p>hth,<br> asoundmove.</p> |
6,699,850 | 0 | <p>maybe you think about such declaration (I think this is it):</p> <pre><code>public abstract class AbstractEventBuffer<E extends BufferedEvent<?>> </code></pre> <p>or:</p> <pre><code>public abstract class AbstractEventBuffer<T, E extends BufferedEvent<T>> </code></pre> <p>or</p> <pre><code>public abstract class AbstractEventBuffer<E extends BufferedEvent<? extends Object>> </code></pre> <p>or such:</p> <pre><code>public abstract class AbstractEventBuffer<BufferedEvent> { </code></pre> <p>?</p> |
11,890,124 | 0 | Java nio server client asynchonous <p>I made a server myself using java nio and a selector. I can receive the data and answer directly from the client if needed.</p> <p>But now I want a thread that will process data, and anytime it will send data to each client.</p> <p>So how can I do that? Also how to keep in memory all channels to write the data to each client ?</p> <p>If you need I can post the part of my code with java nio.</p> |
21,586,688 | 0 | callback function with underscore _.each() <p>I'm trying to implement an _.each() (that I wrote) inside another function and I keep getting "undefined" returned to me. I'm trying to use _.each() to apply a test function to an array. I know this a simple callback syntax issue, but its perplexing me. </p> <p>thanks in advance from a noob.</p> <p>here's my function:</p> <pre><code>_.filter = function(collection, test) { _.each(collection, test()); }; </code></pre> <p>this returns 'undefined'</p> <p>this is the array i'm passing as 'collection':</p> <pre><code>[1, 2, 3, 4, 5, 6] </code></pre> <p>this is the function i'm passing as 'test': </p> <pre><code>function (num) { return num % 2 !== 0; } </code></pre> <p>here's my _.each():</p> <pre><code>_.each = function(collection, iterator) { if( Object.prototype.toString.call( collection ) === '[object Array]' ) { for (var i=0; i<collection.length; i++){ iterator(collection[i], i, collection); } } else if (typeof collection === 'object'){ for (var i in collection){ iterator(collection[i], i, collection) } } else if (typeof collection === 'int'){ console.log('int') } }; </code></pre> |
15,665,391 | 0 | <p>Unescaped quotes inside quotes</p> <p>This</p> <pre><code>$sql = pg_query("SELECT title FROM books WHERE ownedby=("$user_id")"); </code></pre> <p>Should be</p> <pre><code>$sql = pg_query("SELECT title FROM books WHERE ownedby='$user_id'"); </code></pre> <p>Or</p> <pre><code>$sql = pg_query("SELECT title FROM books WHERE ownedby=\"$user_id\""); </code></pre> |
36,397,864 | 0 | <p>A claim from website A will not be sent to website B.</p> <p>This could work this way: </p> <ol> <li>A users logs on to site A (using credentials from B2C)</li> <li>User saves info into B2C (using Graph API)</li> <li>Redirect to Site B</li> <li>User logs on to site B (this can occur without prompting the user, same B2C)</li> <li>Claim are created for site B, but they can contain values set during step 2</li> </ol> <p>graph API: <a href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/" rel="nofollow">https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/</a> <hr /> If the info is already in the B2C directory, the example is even more simple, create 2 sites: <a href="https://azure.microsoft.com/nl-nl/documentation/articles/active-directory-b2c-devquickstarts-web-dotnet/" rel="nofollow">https://azure.microsoft.com/nl-nl/documentation/articles/active-directory-b2c-devquickstarts-web-dotnet/</a></p> <p>Create a custom attribute to store the information: <a href="https://azure.microsoft.com/nl-nl/documentation/articles/active-directory-b2c-reference-custom-attr/" rel="nofollow">https://azure.microsoft.com/nl-nl/documentation/articles/active-directory-b2c-reference-custom-attr/</a></p> <ul> <li>Create a B2C custom attribute: </li> <li>Create 2(both) B2C Applications</li> <li>Create a single B2C sign-in policy using the custom attribute and add it to the claims</li> <li>Use the same policy in both applications, both should see the same claim</li> </ul> |
23,625,044 | 0 | <p>It is a package to be able to use <code>async</code> and <code>await</code> in .NET 4.0 projects.</p> <p>But be aware. I encountered the problem where these libraries cannot be used in .NET 4.5 projects. But this was before the initial release of .NET 4.5. Therefore this problem might be resolved.</p> |
17,667,578 | 0 | <p>you're not using Stage3D. If you use Starling, ND2D or write your own Stage3D wrapper you'll be able to get better performance.</p> <p>You can also take a look at Jackson Dunstan's blog, this post is especially helpful: <a href="http://jacksondunstan.com/articles/2279" rel="nofollow">http://jacksondunstan.com/articles/2279</a></p> |
30,768,030 | 0 | minecraft forge doesnt seem to call postInit <p>I am writing an addon to the minecraft mod Thaumcraft, specifically one that adds aspects to blocks based on the contents of a file. This is for Minecraft 1.7.10</p> <p>The code runs the preInit method, everything goes fine. However, the game crashes on the postInit method. I cannot figure out why it crashes</p> <p>Here is the stacktrace from the crash report:</p> <pre><code>---- Minecraft Crash Report ---- // I'm sorry, Dave. Time: 6/10/15 5:40 PM Description: Initializing game java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(Unknown Source) at polymer.aspectadder.AspectAdder.decodeValues(AspectAdder.java:105) at polymer.aspectadder.AspectAdder.postInit(AspectAdder.java:64) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at cpw.mods.fml.common.FMLModContainer. handleModStateEvent(FMLModContainer.java:513) at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.common.eventbus.EventSubscriber. handleEvent(EventSubscriber.java:74) at com.google.common.eventbus.SynchronizedEventSubscriber. handleEvent(SynchronizedEventSubscriber.java:47) at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322) at com.google.common.eventbus.EventBus. dispatchQueuedEvents(EventBus.java:304) at com.google.common.eventbus.EventBus.post(EventBus.java:275) at cpw.mods.fml.common.LoadController. sendEventToModContainer(LoadController.java:208) at cpw.mods.fml.common.LoadController. propogateStateMessage(LoadController.java:187) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.common.eventbus.EventSubscriber. handleEvent(EventSubscriber.java:74) at com.google.common.eventbus.SynchronizedEventSubscriber .handleEvent(SynchronizedEventSubscriber.java:47) at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322) at com.google.common.eventbus.EventBus. dispatchQueuedEvents(EventBus.java:304) at com.google.common.eventbus.EventBus.post(EventBus.java:275) at cpw.mods.fml.common.LoadController. distributeStateMessage(LoadController.java:118) at cpw.mods.fml.common.Loader.initializeMods(Loader.java:694) at cpw.mods.fml.client.FMLClientHandler. finishMinecraftLoading(FMLClientHandler.java:288) at net.minecraft.client.Minecraft.func_71384_a(Minecraft.java:541) at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:867) at net.minecraft.client.main.Main.main(SourceFile:148) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) at net.minecraft.launchwrapper.Launch.main(Launch.java:28) A detailed walkthrough of the error, its code path and all known details is as follows: --------------------------------------------------------------------------- ------------ -- Head -- Stacktrace: at java.lang.String.substring(Unknown Source) at polymer.aspectadder.AspectAdder.decodeValues(AspectAdder.java:105) at polymer.aspectadder.AspectAdder.postInit(AspectAdder.java:64) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at cpw.mods.fml.common.FMLModContainer. handleModStateEvent(FMLModContainer.java:513) at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.common.eventbus.EventSubscriber. handleEvent(EventSubscriber.java:74) at com.google.common.eventbus.SynchronizedEventSubscriber. handleEvent(SynchronizedEventSubscriber.java:47) at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322) at com.google.common.eventbus.EventBus. dispatchQueuedEvents(EventBus.java:304) at com.google.common.eventbus.EventBus.post(EventBus.java:275) at cpw.mods.fml.common.LoadController. sendEventToModContainer(LoadController.java:208) at cpw.mods.fml.common.LoadController. propogateStateMessage(LoadController.java:187) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.common.eventbus.EventSubscriber. handleEvent(EventSubscriber.java:74) at com.google.common.eventbus.SynchronizedEventSubscriber. handleEvent(SynchronizedEventSubscriber.java:47) at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322) at com.google.common.eventbus.EventBus. dispatchQueuedEvents(EventBus.java:304) at com.google.common.eventbus.EventBus.post(EventBus.java:275) at cpw.mods.fml.common.LoadController. distributeStateMessage(LoadController.java:118) at cpw.mods.fml.common.Loader.initializeMods(Loader.java:694) at cpw.mods.fml.client.FMLClientHandler. finishMinecraftLoading(FMLClientHandler.java:288) at net.minecraft.client.Minecraft.func_71384_a(Minecraft.java:541) -- Initialization -- Details: Stacktrace: at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:867) at net.minecraft.client.main.Main.main(SourceFile:148) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) at net.minecraft.launchwrapper.Launch.main(Launch.java:28) </code></pre> <p>The file had the following line in it:</p> <p>minecraft:sponge=WATER,WATER,WATER,VOID,VOID,CROP</p> <p>This should add 3 WATER aspects, 2 VOID aspects, and 1 CROP aspect.</p> <p>Here is my code:</p> <pre><code>package polymer.aspectadder; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import java.util.Set; import java.util.logging.Logger; import net.minecraft.item.Item; import thaumcraft.api.ThaumcraftApi; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; @Mod(modid = "aspectadder", name = "Aspect Adder", version = "1.0,minecraft 1.7.10", dependencies="required-after:Thaumcraft") public class AspectAdder { /* * A mod that allows the adding of Thaumcraft aspects to items, blocks, * or entities (enchantments may be added one day :D) * This is done through a config file. * * This is an example of how to add an aspect to something, in this case * adding 3 telum and 2 instrumentum to a Tinker's Construct Battleaxe * * tconstruct:battleaxe=WEAPON,WEAPON,WEAPON,TOOL,TOOL */ public static Logger log = Logger.getLogger("Aspect Adder"); static String pathOfClass = AspectAdder.class.getProtectionDomain() .getCodeSource().getLocation().getPath(); static String pathOfInstall = pathOfClass.substring(0, pathOfClass.indexOf("mods")); //back up to the install folder static String path = pathOfInstall.concat("config/aspectadder").substring(6); @EventHandler public void preInit(FMLPreInitializationEvent event){ if(System.getProperty("os.name").startsWith("Windows")){ path.replaceAll("/", "\\\\"); } log.info("Creating a file at " + path + " if one does not exist."); try { new File(path).mkdirs(); new File(path + File.separator + "entries.txt").createNewFile(); } catch (IOException e) { e.printStackTrace(); } } @EventHandler public void init(FMLInitializationEvent event){ } @EventHandler public void postInit(FMLPostInitializationEvent event){ decodeValues(readFile()); } static Properties readFile(){ Properties p = new Properties(); File f = new File(path + File.separator + "entries.txt"); FileInputStream inStream; try { inStream = new FileInputStream(f); p.load(inStream); inStream.close(); } catch (FileNotFoundException fnfe) { try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } // do nothing, since we handled this at lines 39-44 // this catch clause is just here so the code runs // plus, the file is blank anyways if it wasn't there } catch (IOException ioe) { ioe.printStackTrace(); } return p; } static void decodeValues(Properties p){ Set<Object> keySet= p.keySet(); Object[] keys = new Object[p.size()]; int dex = 0; for(Object o : keySet){ keys[dex] = o; dex++; } for(int i = 0; i < keys.length; i++){ String key = keys[i].toString(); Item item = GameRegistry.findItem( key.toString().substring(0, key.indexOf(":")), key.toString().substring(key.indexOf(":") + 1)); //these are modID and item name, without the colon addAspects(item, p.getProperty(key)); } } static void addAspects(Item item, String aspects) { log.info("Adding Aspects: " + aspects + " to " + item.getUnlocalizedName()); AspectList list = new AspectList(); int commaIndex = 0; int i = 0; do{ String aspect = aspects.substring(commaIndex + 1, aspects.substring(commaIndex + 1).indexOf(",")); commaIndex = aspects.substring(commaIndex + 1).indexOf(","); list.add(Aspect.getAspect(aspect), 1); i++; log.info("Attempting to add " + Aspect.getAspect(aspect).getTag() + " (" + aspect.toLowerCase() + ") to " + item.getUnlocalizedName()); }while(commaIndex < aspects.lastIndexOf(",")); ThaumcraftApi.registerObjectTag(item.getUnlocalizedName(), list); } } </code></pre> <p>So you don't have to count all those lines, the crash seems to be caused by this section of the code:</p> <pre><code> for(int i = 0; i < keys.length; i++){ String key = keys[i].toString(); Item item = GameRegistry.findItem( //the following line is the one in the crash report key.toString().substring(0, key.indexOf(":")), key.toString().substring(key.indexOf(":") + 1)); //these are modID and item name, without the colon addAspects(item, p.getProperty(key)); } </code></pre> |
9,786,736 | 1 | How to read through collection in chunks by 1000? <p>I need to read whole collection from MongoDB ( collection name is "test" ) in Python code. I tried like </p> <pre><code> self.__connection__ = Connection('localhost',27017) dbh = self.__connection__['test_db'] collection = dbh['test'] </code></pre> <p>How to read through collection in chunks by 1000 ( to avoid memory overflow because collection can be very large ) ? </p> |
23,207,215 | 0 | Free scrolling and parallax issue (jQuery Scroll Path + Parallax) <p>in a project where I need to build something like the famous parallax-powered Mario Kart Wii Experience site, which also comes with horizontal and vertical scroll (if you haven't seen it, here it is: <a href="http://www.nintendo.com.au/gamesites/mariokartwii/#home" rel="nofollow">http://www.nintendo.com.au/gamesites/mariokartwii/#home</a>)</p> <p>For the scrolling effect, I grabbed the JQuery Scroll Path plugin (website here: <a href="http://joelb.me/scrollpath/" rel="nofollow">http://joelb.me/scrollpath/</a>), and it seems to suit my needs concerning the free scrolling. </p> <p>The problem comes when I try to include some plugin to generate the parallax effect. I tried several plugins (including Stellar.js, jInvertScroll, Parallax.js, Parallax-JS), but none of them seem to work properly. I assume that there's some kind of relationship between the custom scroll that comes with the Scroll Path plugin and the need of the parallax plugins of working with the navigator scroll to make the effect work.</p> <p>I searched in Google for some similar situation (i.e., implementing Scroll Path with some parallax plugin) but I didn't find anyone in my current situation, and it seems that the Scroll Path plugin isn't maintained anymore.</p> <p>Any idea for making it work would be appreciated!</p> <p>PS: Sorry for the grammar mistakes, I'm still in process of learning english.</p> |
8,981,820 | 0 | clueTip is a jQuery plugin for displaying stylized tooltips |
36,665,346 | 0 | <p>Two notes: such more complex query conditions cannot be written using symbols, you have to use string notation instead. And, secondly, a scope does not need to have a parameter, your <code>latest</code> scope is one of them, as you simply compare the <em>database</em> <code>created_at</code> time with the current time shifted by 5 days. So, the correct scope should be something like:</p> <pre><code>scope :latest, -> { where("created_at >= ?", Time.now - 5.days) } </code></pre> <p>and you call it simply:</p> <pre><code>@workers = Worker.company_id(@company.id).latest </code></pre> |
8,923,120 | 0 | <p><a href="https://github.com/codegram/rack-webconsole" rel="nofollow">https://github.com/codegram/rack-webconsole</a></p> <p>Or you could simply pass the Ruby code to the server via post and call <a href="http://www.ruby-doc.org/core-1.9.2/Kernel.html#method-i-eval" rel="nofollow">eval</a> <code>eval(CODE)</code>.</p> <p>You should note that especially the second way is very insecure since it gives the executing code complete access to your system.</p> <p>If this really has to be done "<a href="http://ruby-doc.org/docs/ProgrammingRuby/taint.html" rel="nofollow">Locking Ruby in the Safe</a>" could help secure it.</p> <p>EDIT:</p> <p>For syntax highlighting take a look at <a href="http://codemirror.net/" rel="nofollow">Code Mirror</a> and <a href="http://ace.ajax.org/" rel="nofollow">ACE</a>. Both are decent source code editors with ruby support.</p> |
21,677,171 | 0 | <p>If you're using 11g or later version of Oracle, the easiest way to transpose rows into columns is PIVOT operator (<a href="http://www.oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1.php" rel="nofollow">documentation</a>). For example, consider this query - it'll give you the table of all roles and privileges with corresponding values for them:</p> <pre><code>SELECT * FROM (SELECT fj.role_name, fj.priv_name, DECODE(rp.val,1,'YES',0,'NO','-') VAL FROM (SELECT r.id role_id, r.name role_name, p.id priv_id, p.name priv_name FROM ROLE r, PRIVILEGE p) fj LEFT JOIN ROLE_PRIV rp ON fj.role_id = rp.role_id AND fj.priv_id = rp.priv_id) PIVOT (MAX(VAL) FOR PRIV_NAME IN (list_of_privileges)) ORDER BY ROLE_NAME </code></pre> <p>But there is a catch with such solution: you need to name each privilige in IN clause (or use XML keyword, but it'll mess up the result), but, considering that list of priviliges supposed to change not so frequently, it shouldn't be a problem. The following example:</p> <pre><code>WITH ROLE AS (SELECT 1 ID, 'ROLE1' NAME FROM DUAL UNION SELECT 2 ID, 'ROLE2' NAME FROM DUAL UNION SELECT 3 ID, 'ROLE3' NAME FROM DUAL), PRIVILEGE AS (SELECT 1 ID, 'READ' NAME FROM DUAL UNION SELECT 2 ID, 'WRITE' NAME FROM DUAL UNION SELECT 3 ID, 'EXECUTE' NAME FROM DUAL), ROLE_PRIV AS (SELECT 1 ROLE_ID, 1 PRIV_ID, 1 VAL FROM DUAL UNION SELECT 1 ROLE_ID, 2 PRIV_ID, 0 VAL FROM DUAL UNION SELECT 2 ROLE_ID, 1 PRIV_ID, 1 VAL FROM DUAL UNION SELECT 2 ROLE_ID, 2 PRIV_ID, 0 VAL FROM DUAL UNION SELECT 3 ROLE_ID, 1 PRIV_ID, 0 VAL FROM DUAL UNION SELECT 3 ROLE_ID, 3 PRIV_ID, 1 VAL FROM DUAL) SELECT * FROM (SELECT fj.role_name, fj.priv_name, DECODE(rp.val,1,'YES',0,'NO','-') VAL FROM (SELECT r.id role_id, r.name role_name, p.id priv_id, p.name priv_name FROM ROLE r, PRIVILEGE p) fj LEFT JOIN ROLE_PRIV rp ON fj.role_id = rp.role_id AND fj.priv_id = rp.priv_id) PIVOT (MAX(VAL) FOR PRIV_NAME IN ('READ','WRITE','EXECUTE')) ORDER BY ROLE_NAME </code></pre> <p>Will give you the following result:</p> <pre><code>ROLE_NAME 'READ' 'WRITE' 'EXECUTE' ROLE1 YES NO - ROLE2 YES NO - ROLE3 NO - YES </code></pre> <p>If you're using the earlier version of Oracle, you can consider alternative solutions (<a href="http://asktom.oracle.com/pls/apex/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:31263576751669#76663048528720" rel="nofollow">like this one</a>).</p> <hr> <p>Well, if you can't use PIVOT operation, the simplest way to get the desired output would be this query:</p> <pre><code>SELECT p.name, DECODE((SELECT VAL FROM ROLE_PRIV rp WHERE rp.role_id = (SELECT ID FROM ROLE r WHERE r.name = :ROLE_NAME) AND rp.priv_id = p.id), 1, 'YES', 0, 'NO', '-') :ROLE_NAME FROM PRIVILEGE p </code></pre> <p>You can add addtional roles to this query by just adding another column. For example, take a look at this query:</p> <pre><code>WITH ROLE AS (SELECT 1 ID, 'ROLE1' NAME FROM DUAL UNION SELECT 2 ID, 'ROLE2' NAME FROM DUAL UNION SELECT 3 ID, 'ROLE3' NAME FROM DUAL), PRIVILEGE AS (SELECT 1 ID, 'READ' NAME FROM DUAL UNION SELECT 2 ID, 'WRITE' NAME FROM DUAL UNION SELECT 3 ID, 'EXECUTE' NAME FROM DUAL), ROLE_PRIV AS (SELECT 1 ROLE_ID, 1 PRIV_ID, 1 VAL FROM DUAL UNION SELECT 1 ROLE_ID, 2 PRIV_ID, 0 VAL FROM DUAL UNION SELECT 2 ROLE_ID, 1 PRIV_ID, 1 VAL FROM DUAL UNION SELECT 2 ROLE_ID, 2 PRIV_ID, 1 VAL FROM DUAL UNION SELECT 3 ROLE_ID, 1 PRIV_ID, 0 VAL FROM DUAL UNION SELECT 3 ROLE_ID, 3 PRIV_ID, 1 VAL FROM DUAL) SELECT p.name, DECODE((SELECT VAL FROM ROLE_PRIV rp WHERE rp.role_id = (SELECT ID FROM ROLE r WHERE r.name = 'ROLE1') AND rp.priv_id = p.id), 1, 'YES', 0, 'NO', '-') ROLE1, DECODE((SELECT VAL FROM ROLE_PRIV rp WHERE rp.role_id = (SELECT ID FROM ROLE r WHERE r.name = 'ROLE2') AND rp.priv_id = p.id), 1, 'YES', 0, 'NO', '-') ROLE2, DECODE((SELECT VAL FROM ROLE_PRIV rp WHERE rp.role_id = (SELECT ID FROM ROLE r WHERE r.name = 'ROLE3') AND rp.priv_id = p.id), 1, 'YES', 0, 'NO', '-') ROLE3 FROM PRIVILEGE p </code></pre> <p>It will provide you result for three roles.</p> <hr> <p>Something like this should work:</p> <pre><code>SELECT p.name, DECODE((SELECT COUNT(1) FROM ROLE_PRIV rp WHERE rp.role_id = (SELECT ID FROM ROLE r WHERE r.name = 'ROLE1') AND rp.priv_id = p.id), 0, 'NO', 'YES') ROLE1 FROM PRIVILEGE p </code></pre> |
34,641,471 | 0 | How can I assign int values to const char array in my blackjack game, C <p>I'm working on a blackjack game in C. I have three functions, one to fill the deck, one for shuffling the cards and one for dealing the cards. My problem is that I don't know how to give my cards an integer value, I need that to see who wins. I would be very grateful for some input on how to solve this.</p> <pre><code>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "func.h" /*fill deck with 52 cards*/ void fillDeck(Card * const Deck, const char *suit[], const char *deck[]){ int s; for (s = 0; s < 52; s++){ Deck[s].suits = deck[s % 13]; Deck[s].decks = suit[s / 13]; } return; } #include <stdio.h> #include <stdlib.h> #include <string.h> #include "func.h" /*shuffle cards*/ void shuffle(Card * const Deck){ int i, j; Card temp; for (i = 0; i < 52; i++){ j = rand() % 52; temp = Deck[i]; Deck[i] = Deck[j]; Deck[j] = temp; } return; } #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "func.h" /*deal cards*/ void deal(const Card * const Deck, int size, int size_1, int size_2){ int i, j, length; char anotherCard[2]; char name1[30]; char name2[30]; printf("Name player one > "); scanf("%s", name1); printf("Name player two > "); scanf("%s", name2); printf("\nWelcome %s and %s, lets begin!\n\n", name1, name2); getchar(); printf("%s's card:\n", name1); for (i = 0; i < size; i++){ printf("%5s of %-8s%c", Deck[i].decks, Deck[i].suits, (i + 1) % 2 ? '\t' : '\n'); } printf("\n%s's card:\n", name2); for (i = 2; i < size_1; i++){ printf("%5s of %-8s%c", Deck[i].decks, Deck[i].suits, (i + 1) % 2 ? '\t' : '\n'); } printf("\nDealer card:\n"); for (i = 4; i < size_2; i++){ printf("%5s of %-8s%c", Deck[i].decks, Deck[i].suits, (i + 1) % 2 ? '\t' : '\n'); } return; } #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "func.h" int main(void){ Card allCards[52]; const char *suits[] = { "spades", "hearts", "diamonds", "clubs" }; char *decks[] = { "ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king" }; int *values[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 }; srand(time(NULL)); fillDeck(allCards, suits, decks, values); shuffle(allCards); deal(allCards, 2, 4, 6); getchar(); return 0; } /*func.h*/ struct card{ const char *suits; const char *decks; }; typedef struct card Card; void fillDeck(Card * const Deck, char *suit[], char *deck[]); void shuffle(Card * const Deck); void deal(const Card * const Deck, int size, int size_1, int size_2); #endif </code></pre> |
2,869,472 | 0 | <p>As long as you are inside the <code>EnumTest</code> class, you can access the <code>LEN</code> field by simply writing:</p> <pre><code>int len = RecordType1.LEN; </code></pre> <p>From the outside, it's still difficult.</p> |
7,842,194 | 0 | <p><a href="http://pubs.opengroup.org/onlinepubs/007904975/functions/atoi.html" rel="nofollow"><code>atoi()</code></a> should do what you want to, although a more robust implementation would use <a href="http://pubs.opengroup.org/onlinepubs/007904975/functions/strtol.html" rel="nofollow"><code>strtol()</code></a>.</p> |
482,882 | 0 | <p>Another potential problem is where your databinding is happening - I don't see a DataSource in your code-in-front, so I guess you're databinding in the code-behind.</p> <p>If you are doing the databind on postback, and after the first onChange event has fired, it's quite likely that the databind event is reseting the checkbox's status, and so causing the event to fire again.</p> |
1,071,106 | 0 | Do web apps encrypt passwords during login when integrated security is enabled within IIS? <p>I have always enabled integrated security on my web apps inside IIS with the assumption that the passwords that are requested on the client end will always be transmitted securely (encrypted) to my authentication server (AD/LSA). Am I correct on my assumption? The reason I have always assumed this is 'coz I always think of them as being very similar to authenticating a windows client with an AD in which case the client & server will either employ NTLM or Kerberos for authentication where the passwords are always encrypted.</p> |
11,741,777 | 0 | <p>If you are using a BroadcastReceiver to receive incoming calls, you have to use <code>SipManager.getCallId(incomingCallIntent)</code> inside your 'onReceive()' method.</p> |
16,210,560 | 0 | <p><a href="https://pypi.python.org/pypi/xlrd" rel="nofollow">xlrd</a> has support for .xlsx files, and this <a href="http://stackoverflow.com/a/9897909/1452002">answer</a> suggests that at least the beta version of xlrd with .xlsx support was quicker than openpyxl. </p> <p>The current stable version of Pandas (11.0) uses openpyxl for .xlsx files, but this has been changed for the next release. If you want to give it a go, you can download the dev version from <a href="https://github.com/pydata/pandas" rel="nofollow">GitHub</a></p> |
37,493,136 | 0 | I am currently developing a script in PERL it works but I would like to append the contents to the CSV file whenever the script is executed <pre><code>print "Enter number of days: "; my $var = <STDIN>; my $SQL = "COPY (SELECT * FROM Parent WHERE StartDate < NOW() - INTERVAL '$var days') TO '/home/username/Desktop/new1.csv' WITH CSV"; my $sth = $dbh->prepare($SQL); my $rv1 = $dbh->do($SQL) or die $DBI::errstr; </code></pre> |
24,941,367 | 0 | <blockquote> <p>however I'm trying to deduce whether or not there is something interfering with the response in between the client an server.</p> </blockquote> <p>So you want to take a look what headers etc were sent even though the server is not sending the required <em>Access-Control-Allow-Origin</em> header along with the response?</p> <p>With <em>Google Chrome</em>, you can turn off some security features by launching it with the flag <code>--disable-web-security</code>, opening the browser up like this this will let you debug what you're asking about, but <strong>it won't prevent that error message for other people</strong>, you'd still need to fix it</p> <p>With <strong><em>your browser</em></strong> in this mode, you'll now be able to see the requests without the error being thrown, so be able to inspect them as normal</p> <hr> <p>An example of how you might open the browser like this from the <em>cmd</em> on a <em>Windows 7 (x64)</em> machine</p> <pre class="lang-sh prettyprint-override"><code>start "" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "--disable-web-security" </code></pre> <p>For more, see <a href="http://stackoverflow.com/a/19317888/1615483"><strong>here</strong></a></p> <hr> <p><strong>Don't run <em>Chrome</em> like this for normal web browsing</strong></p> |
33,332,700 | 0 | <p>If you look at Pascal's triangle as a matrix, and you want to find the complexity of building that matrix up to size <code>n x k</code>, then the big-oh of that will be <code>O(n*k)</code>. Obviously you can't get better than that, because that's the size of the matrix.</p> <p>How do we get that? Use the following simplified recurrence for combinations:</p> <pre><code>C(n, k) = C(n - 1, k) + C(n - 1, k - 1) </code></pre> <p>Computing just a single combination has the same complexity (if using memoization).</p> |
1,636,474 | 0 | How to use shared array between function calls in objective C <p>I have one array. I want that array to retain its value between function calls of from single class function.</p> <p>I have function that is called every time page is loaded. </p> <p>This function displays all the data stored in array right from application launches.</p> <p>Thanks in advance.</p> |
38,510,941 | 0 | <p>You can loop through your array elements and add <code><tr></code> to them for each row.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ["<td>200</td><td>I3</td><td>NAME NAME 1</td><td>EXTRA 1</td>", "<td>100</td><td>I2</td><td>NAME NAME 2</td><td>EXTRA 2</td>"]; var str = ""; var table = document.getElementById("myTable"); for(var i = 0; i < arr.length; i++) str += "<tr>"+arr[i]+"</tr>"; table.innerHTML = str;</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><table id="myTable"></table></code></pre> </div> </div> </p> |
38,721,983 | 0 | <p>Assuming you want the 10 most recent eve_Dates for each customer.</p> <p><strong>untested</strong> I'm thinking the correlated subquery will generate a result set for each customer, but I'm not positive about that.</p> <p>I don't think you were limiting to the 10 records because you had no join on date.</p> <pre><code>select t1.EVE_DATE, t1.CUSTID, SUM(t1.ATTENDENCE) as PRESENCE, TRUNCATE((AVG(t1.LECTURE_DUR))/(1000),2) as LECTURE_DUR from MY_TABLE t1 left join ( select CUSTID, eve_date from MY_TABLE t2 where t1.EVE_DATE = t2.EVE_DATE order by t2.CUSTID, t2.eve_Date desc limit 10 ) t3 on t1.CUSTID = t3.CUSTID t1.Eve_Date = T3.Eve_Date where t1.SUBJECT= 'PHYSICS' and t1.EVE_DATE >= '2015-01-01' and t1.EVE_DATE <= '2016-01-01' and t1.CUSTID <> '' group by t1.EVE_DATE, t1.CUSTID order by t1.EVE_DATE </code></pre> |
38,014,372 | 0 | <p>Try This code </p> <pre><code> #include <stdio.h> int main() { int i, repeatName; // ints char firstName[50]; // array to store users name // get first name from user printf("Please enter your first name: "); scanf("%s", firstName); // get amount of times user would like to repeat name printf("How many times would you like to repeat your name?: "); scanf("%i", &repeatName); // tell user name has to be repeated at last one if (repeatName < 1) { printf("The name has to be repeated at least one (1) time. Try again: "); scanf("%i", &repeatName); } // for loop to repeat name 'x' number of times for (i = 1; i <= repeatName; i++) { printf("Line %d Your name %s \n",i,firstName); } } </code></pre> |
10,420,354 | 0 | <p>You're confused about what first and second mean. In this expression:</p> <pre><code>"([^$]*(\\$[A-Za-z][A-Za-z0-9_]*))+" ^_______________________________^ this part </code></pre> <p>is the first parenthesizes subexpression and </p> <pre><code>"([^$]*(\\$[A-Za-z][A-Za-z0-9_]*))+" ^________________________^ this part </code></pre> <p>is the second. If a parenthesized subexpression gets used more than once as part of a <code>*</code>, <code>?</code>, <code>+</code>, or <code>{}</code> repetition operator, it's the last match that counts.</p> <p>If you want to match an arbitrary number of instances, than rather than using the <code>+</code> on the end of your regex, you simply need to call <code>regexec</code> multiple times, and use the ending offset of the previous run as your new starting point.</p> |
22,090,033 | 0 | Link on my website to facebook message a page <p>I would like to embed a link that will open site visitor's browser with their facebook account in "New Message" writing mode with the "to:" field already pointing to my Facebook page.</p> <p>Is there a way to do this?</p> <p>It's a wordpress site, so if there is already a plugin that can do this I'd be happy to know which (without asking the visitor for permissions to a facebook app).</p> <p>Thanks!</p> |
39,505,018 | 0 | <p>Its not an error, It is a warning.</p> <p>It means that you have called the method <code>calculateTip()</code> which return Bool value. But you have not used this result anywhere.</p> <p>To suppress this warning just to this:</p> <pre><code>print(calculateTip()) </code></pre> <p>Now you are printing the output of the method, means the output is used now!</p> |
3,609,408 | 0 | <p>Why would you want to create a Collection but then specify that it should be empty?</p> <p>You can just instantiate the PriorityQueue with <code>Math.max(1, data.size())</code></p> |
8,632,267 | 0 | accessing data of a GridView on button click <p>I am having a gridview with some columns and a template field column that contains a button and I want to call a procedure on button click, however I want to pass a value of a column to the procedure but I am getting an error, here is the action listener of the button: (column name in the gridview is team_ID) error: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control. error line: int team_ID = Convert.ToInt32(Eval("team_ID"));</p> <pre><code>protected void Button1_Click(object sender, EventArgs e) { string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString(); SqlConnection conn = new SqlConnection(connStr); SqlCommand cmd = new SqlCommand("join_team", conn); cmd.CommandType = CommandType.StoredProcedure; int team_ID = Convert.ToInt32(Eval("team_ID")); string email = Session["email"].ToString(); cmd.Parameters.Add(new SqlParameter("@team_ID", team_ID)); cmd.Parameters.Add(new SqlParameter("@myemail", email)); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } </code></pre> |
16,549,700 | 0 | <p>Just add the <code>focus()</code> trigger after the value is set, like so:</p> <pre><code>$('#social-url').val("http://www.twitter.com/").focus(); </code></pre> <p>Here's how I'd do it:</p> <pre><code>$(document).ready(function() { $('select').on('change', function() { $('#social-url').val("http://www." + this.value.toLowerCase() + ".com/") .focus(); }); }); </code></pre> <p><a href="http://jsfiddle.net/dgUrj/4/"><strong>FIDDLE</strong></a></p> |
15,835,080 | 0 | Chrome Extension - Run content script only when button is clicked <p>I've had a good look, but I can't seem to find and answer to this question (well, one that works for me anyway).</p> <p>I've made a Chrome extension that should run the code that's in my content script on click of the icon only, but it always runs as soon as the page loads. Is there a way to prevent this from happening? None of the possible strings I can enter for run_at really cater for this.</p> <p>Here is example code in both scripts:</p> <p>Content Script:</p> <pre><code>function runIt() { console.log('working'); } runIt(); </code></pre> <p>background.js:</p> <pre><code>chrome.browserAction.onClicked.addListener(function(activeTab) { chrome.tabs.executeScript(null, {file: "content.js"}); }); </code></pre> <p>It will log 'working' as soon as the page loads, and for each button click after that. Is there a way to stop it running as soon as the page loads?</p> <p>Thanks in advance for all contributions.</p> |
6,423,121 | 0 | <p>simply you can do this --</p> <p>there are so many option or answer available for this. one of these is as follow--</p> <pre><code>select case when b.c_1 = 1 then b.col1 else null end col1, b.col2 col2, b.col3 col3 from ( select distinct col1,col2,col3, rownum() over(partition by col1) c_1 from table_name )b </code></pre> <p>now assume / modify above query - </p> <p>table_name is the table name col1 , col2 and col3 is your table's column name.</p> <p>just modify this query as per your table name and structure and see..</p> <p>it would be your required solution.</p> |
17,751,637 | 0 | Dynamic Dropdown menu - PHP <p>First of all, I am new to mysqli and prepare statements so please let me know if you see any error. I have this static drop down menu : <img src="https://i.stack.imgur.com/BJwtZ.png" alt="enter image description here"></p> <p>HTML code:</p> <pre><code><ul class="menu sgray fade" id="menu"> <li><a href="#">Bike</a> <!-- start mega menu --> <div class="cols3"> <div class="col1"> <ol> <li><a href="#">bikes</a></li> <li><a href="#">wheels</a></li> <li><a href="#">helmets</a></li> <li><a href="#">components</a></li> </ol> </div> <div class="col1"> <ol> <li><a href="#">pedals</a></li> <li><a href="#">GPS</a></li> <li><a href="#">pumps</a></li> <li><a href="#">bike storage</a></li> </ol> </div> <div class="col1"> <ol> <li><a href="#">power meters</a></li> <li><a href="#">hydratation system</a></li> <li><a href="#">shoes</a></li> <li><a href="#">saddles</a></li> </ol> </div> </div> <!-- end mega menu --> </li> </code></pre> <p></p> <p>I want to make a dynamic dropdown menu. I managed to show the <code>$categoryName</code> and the <code>$SubCategoryName</code> with this function:</p> <pre><code>function showMenuCategory(){ $db = db_connect(); $query = "SELECT * FROM Category"; $stmt = $db->prepare($query); $stmt->execute(); $stmt->bind_result($id,$categoryName,$description,$pic,$active); while($stmt->fetch()) { echo'<li><a href="#">'.$categoryName.'</a> <!-- start mega menu --> <div class="cols3"> <div class="col1"> <ol>'; $dba = db_connect(); $Subquery = "SELECT * FROM Subcategory WHERE CategoryId = '".$id."'"; $Substmt = $dba->prepare($Subquery); $Substmt->execute(); $Substmt->bind_result($Subid,$CatId,$SubCategoryName,$SubDescription); while($Substmt->fetch()) { echo' <li><a href="#">'.$SubCategoryName.'</a></li>'; } echo' </ol> </div> <!-- end mega menu --> </li>'; } } </code></pre> <p>The only problem is that it returns all the subcategories on the the same <code><div class="col1"></code>:</p> <p><img src="https://i.stack.imgur.com/9ChgN.png" alt="enter image description here"></p> <p>what I would like to obtain is count the subcategories and if the result is more than 4 return the other items in the second and third column. </p> <p>UPDATE***: thanks to the answer below now the menu looks like this:</p> <p><img src="https://i.stack.imgur.com/mqKp4.png" alt="enter image description here"></p> <p>thanks!</p> |
1,398,344 | 0 | <p>Aside from changing your entity name, your options are really limited to name-aliasing and/or fully-qualifying the two colliding names, as you are already doing.</p> <p>My personal preference would be fully-qualifying both type names throughout the source. Your current approach is a mix of both aliasing and qualifying. You can also alternatively alias both types to something like:</p> <pre><code>using EntityImage = myCMS.Entities.Image; using DrawingImage = System.Drawing.Image; </code></pre> |
23,097,162 | 0 | <p>As suggested in the comments, the Array <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="nofollow">filter</a> method should give you what you want. Here's a start:</p> <pre><code>var filteredFilms = films.filter(function(film) { return parseInt(film.duration) > 150 && film.genre === 'Crime'; }); </code></pre> |
1,725,514 | 0 | Help me remove a Singleton: looking for an alternative <p>Background: I have some classes implementing a subject/observer design pattern that I've made thread-safe. A <code>subject</code> will notify it's <code>observers</code> by a simple method call <code>observer->Notified( this )</code> if the <code>observer</code> was constructed in the same thread as the notification is being made. But if the <code>observer</code> was constructed in a different thread, then the notification will be posted onto a <code>queue</code> to be processed later by the thread that constructed the <code>observer</code> and then the simple method call can be made when the notification event is processed.</p> <p>So… I have a map associating threads and queues which gets updated when threads and queues are constructed and destroyed. This map itself uses a mutex to protect multi-threaded access to it. </p> <p>The map is a singleton. </p> <p>I've been guilty of using singletons in the past because "there will be only one in this application", and believe me - I have paid my penance!</p> <p>One part of me can't help thinking that there really will be only one queue/thread map in an application. The other voice says that singletons are not good and you should avoid them. </p> <p>I like the idea of removing the singleton and being able to stub it for my unit tests. Trouble is, I'm having a hard time trying to think of a good alternative solution.</p> <p>The "usual" solution which has worked in the past is to pass in a pointer to the object to use instead of referencing the singleton. I think that would be tricky in this case, since observers and subjects are 10-a-penny in my application and it would very awkward to have to pass a queue/thread map object into the constructor of every single observer.</p> <p>What I appreciate is that I may well have only one map in my application, but it shouldn't be in the bowels of the subject and observer class code where that decision is made.</p> <p>Maybe this is a valid singleton, but I'd also appreciate any ideas on how I could remove it.</p> <p>Thanks.</p> <p>PS. I have read <a href="http://stackoverflow.com/questions/1300655/whats-alternative-to-singleton">What's Alternative to Singleton</a> and <a href="http://googletesting.blogspot.com/2008/08/where-have-all-singletons-gone.html" rel="nofollow noreferrer">this article</a> mentioned in the accepted answer. I can't help thinking that the ApplicationFactory it just yet another singleton by another name. I really don't see the advantage.</p> |
32,433,237 | 0 | <p>If you have associative array than You can use php built in function <code>extract()</code>. </p> <p>Example:</p> <pre><code>$abc = array('var1'=>2, 'var2'=>4, 'var3'=>6); extract($abc); echo $var1.$var2.$var3; //Outputs 246 </code></pre> |
36,406,419 | 0 | <p>u can use isEnabled() to verify whether it is enabled or disable.it returns boolean .if it returns true the element is enabled if it returns false the element is disabled.</p> |
40,701,314 | 0 | <p>You called a method that basically calls another method of the same signature </p> <pre><code>@Override public String userSignIn(String email, String password, String authType) throws Exception { login(email, password, authType, new OnLoginResponseCallback() { @Override </code></pre> <p>Instead, wherever you would call <code>userSignIn</code>, you call <code>login</code>, and pass in that anonymous class. You can't return from these inner methods, because that isn't how callbacks work. You use the parameters of the interface methods to "continue" your logic. Like, do login, callback to the main function with some user info, use this info to make a new request, have a callback waiting for that data, that passes back data to some other method. It's all <code>void</code> methods calling other methods. No <code>return</code> statements </p> <p>Although, in Javascript, you can read this </p> <p><a href="http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function">How to return value from an asynchronous callback function?</a></p> |
33,371,936 | 0 | <p>No, a static method cannot call a non-static method.</p> <p>Consider that you have objects <code>a</code> and <code>b</code>, both instances of <code>Currency</code>. <code>currencyValidator</code> exists on those two objects. Now <code>store()</code> belongs to the class <code>Currency</code> itself, not one of those objects. So, in <code>Currency.store()</code>, how does it know which object to call <code>currencyValidator()</code> on? The simple answer is it doesn't so it can't. This is one of the pitfalls of using static methods and one of the reasons people often urge against them.</p> <p>Regardless, you can get around this by passing <code>a</code> into <code>Currency.store()</code>, and calling <code>a.currencyValidator()</code> instead.</p> |
1,195,551 | 0 | <p>I understand your concern. Even for trusted sources, PHP provides more access than is necessary to the whole environment of the web request. Even if the scripters are trusted and even if they can only harm themselves with a scripting error, a more constrained scripting environment would be easier for them to use and easier for you to support.</p> <p>You want something that can be sandboxed off, that can only access resources you explicitly assign to its scope, and that executes in a "play within a play" runtime environment rather than in PHP's own.</p> <p>One approach is to use a web templating language for user-submitted scripts. These provide a certain amount of control (variable assignment for example), and close off other options, for example you can't write an infinite loop. I've used Velocity for this purpose in Java applications; I think something like Smarty might work in PHP, but I don't have direct experience of using it for that purpose. </p> <p>Another approach, if what the scripts are required to do is constrained by the domain, is to implement a Domain Specific Language (DSL). I mentioned that in <a href="http://stackoverflow.com/questions/1171485/interpret-text-input-as-php/1172023#1172023">this answer</a>.</p> <p>Apart from that, I don't know of any pure-PHP implementations of scripting languages. It's something I'd be interested in myself.</p> |
364,590 | 0 | <p>Of additional interest is probably how good of a fit the line is. For that, use the Pearson correlation, here in a PHP function:</p> <pre><code>/** * returns the pearson correlation coefficient (least squares best fit line) * * @param array $x array of all x vals * @param array $y array of all y vals */ function pearson(array $x, array $y) { // number of values $n = count($x); $keys = array_keys(array_intersect_key($x, $y)); // get all needed values as we step through the common keys $x_sum = 0; $y_sum = 0; $x_sum_sq = 0; $y_sum_sq = 0; $prod_sum = 0; foreach($keys as $k) { $x_sum += $x[$k]; $y_sum += $y[$k]; $x_sum_sq += pow($x[$k], 2); $y_sum_sq += pow($y[$k], 2); $prod_sum += $x[$k] * $y[$k]; } $numerator = $prod_sum - ($x_sum * $y_sum / $n); $denominator = sqrt( ($x_sum_sq - pow($x_sum, 2) / $n) * ($y_sum_sq - pow($y_sum, 2) / $n) ); return $denominator == 0 ? 0 : $numerator / $denominator; } </code></pre> |
Subsets and Splits